Debian Codegraph @

resources/resource_transformers/js/js_integration_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package js_test
15
16 import (
17 "os"
18 "path/filepath"
19 "runtime"
20 "strings"
21 "testing"
22
23 qt "github.com/frankban/quicktest"
24 "github.com/gohugoio/hugo/common/paths"
25 "github.com/gohugoio/hugo/htesting"
26 "github.com/gohugoio/hugo/hugolib"
27 "github.com/gohugoio/hugo/internal/js/esbuild"
28 )
29
30 func TestBuildVariants(t *testing.T) {
31 c := qt.New(t)
32
33 mainWithImport := `
34 -- hugo.toml --
35 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
36 disableLiveReload = true
37 -- assets/js/main.js --
38 import { hello1, hello2 } from './util1';
39 hello1();
40 hello2();
41 -- assets/js/util1.js --
42 import { hello3 } from './util2';
43 export function hello1() {
44 return 'abcd';
45 }
46 export function hello2() {
47 return hello3();
48 }
49 -- assets/js/util2.js --
50 export function hello3() {
51 return 'efgh';
52 }
53 -- layouts/home.html --
54 {{ $js := resources.Get "js/main.js" | js.Build }}
55 JS Content:{{ $js.Content }}:End:
56
57 `
58
59 c.Run("Basic", func(c *qt.C) {
60 b := hugolib.Test(c, mainWithImport, hugolib.TestOptOsFs())
61
62 b.AssertFileContent("public/index.html", `abcd`)
63 })
64
65 c.Run("Edit Import", func(c *qt.C) {
66 b := hugolib.Test(c, mainWithImport, hugolib.TestOptRunning(), hugolib.TestOptOsFs())
67
68 b.AssertFileContent("public/index.html", `abcd`)
69 b.EditFileReplaceFunc("assets/js/util1.js", func(s string) string { return strings.ReplaceAll(s, "abcd", "1234") }).Build()
70 b.AssertFileContent("public/index.html", `1234`)
71 })
72
73 c.Run("Edit Import Nested", func(c *qt.C) {
74 b := hugolib.Test(c, mainWithImport, hugolib.TestOptRunning(), hugolib.TestOptOsFs())
75
76 b.AssertFileContent("public/index.html", `efgh`)
77 b.EditFileReplaceFunc("assets/js/util2.js", func(s string) string { return strings.ReplaceAll(s, "efgh", "1234") }).Build()
78 b.AssertFileContent("public/index.html", `1234`)
79 })
80 }
81
82 // Issue #15173.
83 func TestBuildDataArtifacts(t *testing.T) {
84 t.Parallel()
85
86 files := `
87 -- hugo.toml --
88 baseURL = "https://example.org/"
89 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
90 -- assets/js/main.js --
91 import { hello } from './util';
92 hello();
93 -- assets/js/util.js --
94 export function hello() {
95 return 'abcd';
96 }
97 -- layouts/home.html --
98 {{ with resources.Get "js/main.js" | js.Build (dict "minify" true "sourcemap" "external") }}
99 COUNT: {{ len .Data.Artifacts }}
100 {{ range .Data.Artifacts }}
101 ARTIFACT: {{ .RelPermalink }}|{{ .Permalink }}|{{ .MediaType.Type }}
102 {{ end }}
103 {{ end }}
104 {{ with resources.Get "js/main.js" | js.Build }}
105 COUNT2: {{ len .Data.Artifacts }}
106 {{ end }}
107 `
108
109 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
110 b.AssertFileContent("public/index.html",
111 "COUNT: 1",
112 "ARTIFACT: /js/main.js.map|https://example.org/js/main.js.map|application/source-map",
113 "COUNT2: 0",
114 )
115 b.AssertFileExists("public/js/main.js.map", true)
116 }
117
118 func TestBuildWithModAndNpm(t *testing.T) {
119 if !htesting.IsCI() {
120 t.Skip("skip (relative) long running modules test when running locally")
121 }
122
123 c := qt.New(t)
124
125 files := `
126 -- hugo.toml --
127 baseURL = "https://example.org"
128 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
129 [module]
130 [[module.imports]]
131 path="github.com/gohugoio/hugoTestProjectJSModImports"
132 -- go.mod --
133 module github.com/gohugoio/tests/testHugoModules
134
135 go 1.16
136
137 require github.com/gohugoio/hugoTestProjectJSModImports v0.10.0 // indirect
138 -- package.json --
139 {
140 "dependencies": {
141 "date-fns": "^2.16.1"
142 }
143 }
144
145 `
146 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
147 cfg.Verbose = true
148 }))
149
150 b.AssertFileContent("public/js/main.js", `
151 greeting: "greeting configured in mod2"
152 Hello1 from mod1: $
153 return "Hello2 from mod1";
154 var Hugo = "Rocks!";
155 Hello3 from mod2. Date from date-fns: ${today}
156 Hello from lib in the main project
157 Hello5 from mod2.
158 var myparam = "Hugo Rocks!";
159 shim cwd
160 `)
161
162 // React JSX, verify the shimming.
163 b.AssertFileContent("public/js/like.js", filepath.FromSlash(`@v0.10.0/assets/js/shims/react.js
164 module.exports = window.ReactDOM;
165 `))
166 }
167
168 func TestBuildWithNpm(t *testing.T) {
169 if !htesting.IsCI() {
170 t.Skip("skip (relative) long running modules test when running locally")
171 }
172
173 c := qt.New(t)
174
175 files := `
176 -- assets/js/included.js --
177 console.log("included");
178 -- assets/js/main.js --
179 import "./included";
180 import { toCamelCase } from "to-camel-case";
181
182 console.log("main");
183 console.log("To camel:", toCamelCase("space case"));
184 -- assets/js/myjsx.jsx --
185 import * as React from 'react'
186 import * as ReactDOM from 'react-dom'
187
188 ReactDOM.render(
189 <h1>Hello, world!</h1>,
190 document.getElementById('root')
191 );
192 -- assets/js/myts.ts --
193 function greeter(person: string) {
194 return "Hello, " + person;
195 }
196 let user = [0, 1, 2];
197 document.body.textContent = greeter(user);
198 -- hugo.toml --
199 disablekinds = ['taxonomy', 'term', 'page']
200 -- content/p1.md --
201 Content.
202 -- data/hugo.toml --
203 slogan = "Hugo Rocks!"
204 -- i18n/en.yaml --
205 hello:
206 other: "Hello"
207 -- i18n/fr.yaml --
208 hello:
209 other: "Bonjour"
210 -- layouts/home.html --
211 {{ $options := dict "minify" false "externals" (slice "react" "react-dom") "sourcemap" "linked" }}
212 {{ $js := resources.Get "js/main.js" | js.Build $options }}
213 JS: {{ template "print" $js }}
214 {{ $jsx := resources.Get "js/myjsx.jsx" | js.Build $options }}
215 JSX: {{ template "print" $jsx }}
216 {{ $ts := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "inline")}}
217 TS: {{ template "print" $ts }}
218 {{ $ts2 := resources.Get "js/myts.ts" | js.Build (dict "sourcemap" "external" "TargetPath" "js/myts2.js")}}
219 TS2: {{ template "print" $ts2 }}
220 {{ define "print" }}RelPermalink: {{.RelPermalink}}|MIME: {{ .MediaType }}|Content: {{ .Content | safeJS }}{{ end }}
221 -- package.json --
222 {
223 "scripts": {},
224
225 "dependencies": {
226 "to-camel-case": "1.0.0"
227 }
228 }
229 `
230
231 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall())
232
233 b.AssertFileContent("public/js/main.js", `//# sourceMappingURL=main.js.map`)
234 b.AssertFileContent("public/js/main.js.map", `"version":3`, "! ns-hugo") // linked
235 b.AssertFileContent("public/js/myts.js", `//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJz`) // inline
236 b.AssertFileContent("public/index.html", `
237 console.log(&#34;included&#34;);
238 if (hasSpace.test(string))
239 var React = __toESM(__require(&#34;react&#34;));
240 function greeter(person) {
241 `)
242
243 checkMap := func(p string, expectLen int) {
244 s := b.FileContent(p)
245 sources := esbuild.SourcesFromSourceMap(s)
246 b.Assert(sources, qt.HasLen, expectLen)
247
248 // Check that all source files exist.
249 for _, src := range sources {
250 filename, ok := paths.UrlStringToFilename(src)
251 b.Assert(ok, qt.IsTrue)
252 _, err := os.Stat(filename)
253 b.Assert(err, qt.IsNil, qt.Commentf("src: %q", src))
254 }
255 }
256
257 checkMap("public/js/main.js.map", 5)
258 }
259
260 func TestBuildError(t *testing.T) {
261 c := qt.New(t)
262
263 filesTemplate := `
264 -- hugo.toml --
265 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
266 -- assets/js/main.js --
267 // A comment.
268 import { hello1, hello2 } from './util1';
269 hello1();
270 hello2();
271 -- assets/js/util1.js --
272 /* Some
273 comments.
274 */
275 import { hello3 } from './util2';
276 export function hello1() {
277 return 'abcd';
278 }
279 export function hello2() {
280 return hello3();
281 }
282 -- assets/js/util2.js --
283 export function hello3() {
284 return 'efgh';
285 }
286 -- layouts/home.html --
287 {{ $js := resources.Get "js/main.js" | js.Build }}
288 JS Content:{{ $js.Content }}:End:
289
290 `
291
292 c.Run("Import from main not found", func(c *qt.C) {
293 c.Parallel()
294 files := strings.Replace(filesTemplate, "import { hello1, hello2 }", "import { hello1, hello2, FOOBAR }", 1)
295 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs())
296 b.Assert(err, qt.IsNotNil)
297 b.Assert(err.Error(), qt.Contains, `main.js:2:25": No matching export`)
298 })
299
300 c.Run("Import from import not found", func(c *qt.C) {
301 c.Parallel()
302 files := strings.Replace(filesTemplate, "import { hello3 } from './util2';", "import { hello3, FOOBAR } from './util2';", 1)
303 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs())
304 b.Assert(err, qt.IsNotNil)
305 b.Assert(err.Error(), qt.Contains, `util1.js:4:17": No matching export in`)
306 })
307 }
308
309 // See issue 10527.
310 func TestImportHugoVsESBuild(t *testing.T) {
311 c := qt.New(t)
312
313 for _, importSrcDir := range []string{"node_modules", "assets"} {
314 c.Run(importSrcDir, func(c *qt.C) {
315 files := `
316 -- IMPORT_SRC_DIR/imp1/index.js --
317 console.log("IMPORT_SRC_DIR:imp1/index.js");
318 -- IMPORT_SRC_DIR/imp2/index.ts --
319 console.log("IMPORT_SRC_DIR:imp2/index.ts");
320 -- IMPORT_SRC_DIR/imp3/foo.ts --
321 console.log("IMPORT_SRC_DIR:imp3/foo.ts");
322 -- assets/js/main.js --
323 import 'imp1/index.js';
324 import 'imp2/index.js';
325 import 'imp3/foo.js';
326 -- layouts/home.html --
327 {{ $js := resources.Get "js/main.js" | js.Build }}
328 {{ $js.RelPermalink }}
329 `
330
331 files = strings.ReplaceAll(files, "IMPORT_SRC_DIR", importSrcDir)
332
333 b := hugolib.Test(c, files, hugolib.TestOptOsFs())
334
335 expected := `
336 IMPORT_SRC_DIR:imp1/index.js
337 IMPORT_SRC_DIR:imp2/index.ts
338 IMPORT_SRC_DIR:imp3/foo.ts
339 `
340 expected = strings.ReplaceAll(expected, "IMPORT_SRC_DIR", importSrcDir)
341
342 b.AssertFileContent("public/js/main.js", expected)
343 })
344 }
345 }
346
347 // See https://github.com/evanw/esbuild/issues/2745
348 func TestPreserveLegalComments(t *testing.T) {
349 t.Parallel()
350
351 files := `
352 -- assets/js/main.js --
353 /* @license
354 * Main license.
355 */
356 import * as foo from 'js/utils';
357 console.log("Hello Main");
358 -- assets/js/utils/index.js --
359 export * from './util1';
360 export * from './util2';
361 -- assets/js/utils/util1.js --
362 /*! License util1 */
363 console.log("Hello 1");
364 -- assets/js/utils/util2.js --
365 //! License util2 */
366 console.log("Hello 2");
367 -- layouts/home.html --
368 {{ $js := resources.Get "js/main.js" | js.Build (dict "minify" false) }}
369 {{ $js.RelPermalink }}
370 `
371
372 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
373
374 b.AssertFileContent("public/js/main.js", `
375 License util1
376 License util2
377 Main license
378
379 `)
380 }
381
382 // Issue #11232
383 func TestTypeScriptExperimentalDecorators(t *testing.T) {
384 t.Parallel()
385 files := `
386 -- hugo.toml --
387 disableKinds = ['RSS','sitemap','taxonomy','term']
388 -- tsconfig.json --
389 {
390 "compilerOptions": {
391 "experimentalDecorators": true,
392 }
393 }
394 -- assets/ts/main.ts --
395 function addFoo(target: any) {target.prototype.foo = 'bar'}
396 @addFoo
397 class A {}
398 -- layouts/home.html --
399 {{ $opts := dict "target" "es2020" "targetPath" "js/main.js" }}
400 {{ (resources.Get "ts/main.ts" | js.Build $opts).Publish }}
401 `
402 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
403 b.AssertFileContent("public/js/main.js", "__decorateClass")
404 }
405
406 // Issue 13183.
407 func TestExternalsInAssets(t *testing.T) {
408 files := `
409 -- assets/js/util1.js --
410 export function hello1() {
411 return 'abcd';
412 }
413 -- assets/js/util2.js --
414 export function hello2() {
415 return 'efgh';
416 }
417 -- assets/js/main.js --
418 import { hello1 } from './util1.js';
419 import { hello2 } from './util2.js';
420
421 hello1();
422 hello2();
423 -- layouts/home.html --
424 Home.
425 {{ $js := resources.Get "js/main.js" | js.Build (dict "externals" (slice "./util1.js")) }}
426 {{ $js.Publish }}
427 `
428
429 b := hugolib.Test(t, files, hugolib.TestOptOsFs())
430
431 b.AssertFileContent("public/js/main.js", "efgh")
432 b.AssertFileContent("public/js/main.js", "! abcd")
433 }
434
435 func TestBuildErrorStack(t *testing.T) {
436 files := `
437 -- hugo.toml --
438 disableKinds=["page", "section", "taxonomy", "term", "sitemap", "robotsTXT"]
439 -- assets/js/main.js --
440 import { hello1, hello2 } from './util1';
441 hello1();
442 -- layouts/home.html --
443 {{ $js := resources.Get "js/main.js" | js.Build }}
444 JS Content:{{ $js.Content }}:End:
445 `
446
447 b, err := hugolib.TestE(t, files, hugolib.TestOptOsFs())
448 b.Assert(err, qt.IsNotNil)
449 b.Assert(err.Error(), qt.Contains, `execute of template failed: template: home.html:2:17`)
450 b.Assert(err.Error(), qt.Contains, `main.js:1:31": Could not resolve "./util1"`)
451 }
452
453 // ESBuild resolves imports not found in /assets on its own, following symlinks
454 // and with no notion of the project root.
455 func TestBuildImportOutsideProject(t *testing.T) {
456 c := qt.New(t)
457
458 base := t.TempDir()
459 secret := filepath.Join(base, "secret.txt")
460 c.Assert(os.WriteFile(secret, []byte("PWN-SECRET"), 0o644), qt.IsNil)
461
462 files := `
463 -- hugo.toml --
464 disableKinds = ["taxonomy", "term", "rss", "sitemap", "robotsTXT", "section", "page"]
465 theme = "mytheme"
466 SECURITY
467 -- themes/mytheme/hugo.toml --
468 -- themes/mytheme/assets/js/main.js --
469 import secret from "IMPORT";
470 import { helper } from "./helper.js";
471 console.log(secret, helper);
472 -- themes/mytheme/assets/js/helper.js --
473 export const helper = "LOCAL-HELPER-OK";
474 -- layouts/all.html --
475 {{ $js := resources.Get "js/main.js" | js.Build }}
476 RESULT:<pre>{{ $js.Content }}</pre>
477 `
478
479 build := func(c *qt.C, workingDir, imp, security string) (*hugolib.IntegrationTestBuilder, error) {
480 f := strings.ReplaceAll(files, "IMPORT", imp)
481 f = strings.ReplaceAll(f, "SECURITY", security)
482 return hugolib.NewIntegrationTestBuilder(
483 hugolib.IntegrationTestConfig{
484 T: c,
485 TxtarString: f,
486 NeedsOsFS: true,
487 WorkingDir: workingDir,
488 },
489 ).BuildE()
490 }
491
492 const outsideErr = `.*"[^"]*secret.txt" resolves to "[^"]*secret.txt" outside the project.*allowRead.*`
493
494 c.Run("Relative import", func(c *qt.C) {
495 _, err := build(c, filepath.Join(base, "relative"), "../secret.txt", "")
496 c.Assert(err, qt.ErrorMatches, outsideErr)
497 })
498
499 c.Run("Symlink in theme", func(c *qt.C) {
500 if runtime.GOOS == "windows" {
501 c.Skip("symlinks")
502 }
503 workingDir := filepath.Join(base, "symlink")
504 linkDir := filepath.Join(workingDir, "themes", "mytheme", "assets", "link")
505 c.Assert(os.MkdirAll(linkDir, 0o755), qt.IsNil)
506 c.Assert(os.Symlink(secret, filepath.Join(linkDir, "cred.txt")), qt.IsNil)
507 _, err := build(c, workingDir, "./themes/mytheme/assets/link/cred.txt", "")
508 c.Assert(err, qt.ErrorMatches, outsideErr)
509 })
510
511 c.Run("Relative import, target in allowRead", func(c *qt.C) {
512 b, err := build(c, filepath.Join(base, "allowed"), "../secret.txt", `
513 [security.node.permissions]
514 allowRead = [".", ".."]
515 `)
516 c.Assert(err, qt.IsNil)
517 b.AssertFileContent("public/index.html", "PWN-SECRET", "LOCAL-HELPER-OK")
518 })
519 }