@jsenv/core 20.2.0 → 21.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/jsenv_compile_proxy.js +4 -6
  2. package/dist/jsenv_compile_proxy.js.map +3 -4
  3. package/dist/jsenv_exploring_redirector.js +4 -6
  4. package/dist/jsenv_exploring_redirector.js.map +3 -4
  5. package/dist/jsenv_toolbar.js +7 -16
  6. package/dist/jsenv_toolbar.js.map +4 -6
  7. package/main.js +2 -1
  8. package/package.json +3 -5
  9. package/readme.md +19 -19
  10. package/src/{convertCommonJsWithRollup.js → commonJsToJavaScriptModule.js} +27 -6
  11. package/src/execute.js +2 -2
  12. package/src/executeTestPlan.js +2 -2
  13. package/src/internal/building/createJsenvRollupPlugin.js +46 -58
  14. package/src/internal/building/html/parseHtmlRessource.js +5 -0
  15. package/src/internal/building/ressource_builder.js +70 -46
  16. package/src/internal/building/transformImportMetaUrlReferences.js +1 -1
  17. package/src/internal/compiling/compile-directory/fs-optimized-for-cache.js +1 -1
  18. package/src/internal/compiling/compile-directory/getOrGenerateCompiledFile.js +18 -14
  19. package/src/internal/compiling/compile-directory/updateMeta.js +31 -19
  20. package/src/internal/compiling/createCompiledFileService.js +125 -60
  21. package/src/internal/compiling/js-compilation-service/jsenvTransform.js +28 -13
  22. package/src/internal/compiling/js-compilation-service/transformJs.js +14 -92
  23. package/src/internal/compiling/jsenvCompilerForHtml.js +147 -187
  24. package/src/internal/compiling/jsenvCompilerForImportmap.js +79 -13
  25. package/src/internal/compiling/jsenvCompilerForJavaScript.js +33 -69
  26. package/src/internal/compiling/startCompileServer.js +1 -7
  27. package/src/internal/compiling/transformResultToCompilationResult.js +71 -28
  28. package/src/internal/executing/executePlan.js +2 -2
  29. package/src/internal/runtime/createBrowserRuntime/scanBrowserRuntimeFeatures.js +4 -7
  30. package/src/internal/toolbar/compilation/toolbar.compilation.js +3 -11
  31. package/src/startExploring.js +0 -2
  32. package/src/textToJavaScriptModule.js +10 -0
  33. package/src/internal/compiling/transformImportmap.js +0 -94
package/readme.md CHANGED
@@ -348,6 +348,20 @@ To get a better idea see [jsenv.config.js](./jsenv.config.js). The file can be i
348
348
 
349
349
  That being said it's only a recommendation. There is nothing enforcing or checking the presence of _jsenv.config.mjs_.
350
350
 
351
+ ## CommonJS
352
+
353
+ CommonJS module format rely on `module.exports` and `require`. It was invented by Node.js and is not standard JavaScript. If your code or one of your dependency uses it, it requires some configuration. The jsenv config below makes jsenv compatible with a package named _"whatever"_ that would be written in CommonJS.
354
+
355
+ _jsenv.config.mjs to use code written in CommonJS_:
356
+
357
+ ```js
358
+ import { jsenvBabelPluginMap, commonJsToJavaScriptModule } from "@jsenv/core"
359
+
360
+ export const customCompilers = {
361
+ "./node_modules/whatever/index.js": commonJsToJavaScriptModule,
362
+ }
363
+ ```
364
+
351
365
  ## React
352
366
 
353
367
  React is written in CommonJS and comes with jsx. If you use react and or jsx it requires some configuration.
@@ -356,7 +370,7 @@ _jsenv.config.mjs for react and jsx:_
356
370
 
357
371
  ```js
358
372
  import { createRequire } from "module"
359
- import { jsenvBabelPluginMap, convertCommonJsWithRollup } from "@jsenv/core"
373
+ import { jsenvBabelPluginMap, commonJsToJavaScriptModule } from "@jsenv/core"
360
374
 
361
375
  const require = createRequire(import.meta.url)
362
376
  const transformReactJSX = require("@babel/plugin-transform-react-jsx")
@@ -369,10 +383,10 @@ export const babelPluginMap = {
369
383
  ],
370
384
  }
371
385
 
372
- export const convertMap = {
373
- "./node_modules/react/index.js": convertCommonJsWithRollup,
386
+ export const customCompilers = {
387
+ "./node_modules/react/index.js": commonJsToJavaScriptModule,
374
388
  "./node_modules/react-dom/index.js": (options) => {
375
- return convertCommonJsWithRollup({ ...options, external: ["react"] })
389
+ return commonJsToJavaScriptModule({ ...options, external: ["react"] })
376
390
  },
377
391
  }
378
392
  ```
@@ -394,7 +408,7 @@ See also
394
408
 
395
409
  - [@jsenv/importmap-node-module](https://github.com/jsenv/importmap-node-module#import-map-node-module)
396
410
  - [babelPluginMap](./docs/shared-parameters.md#babelPluginMap)
397
- - [convertMap](./docs/shared-parameters.md#convertMap)
411
+ - [customCompilers](./docs/shared-parameters.md#customCompilers)
398
412
  - [transform-react-jsx on babel](https://babeljs.io/docs/en/next/babel-plugin-transform-react-jsx.html)
399
413
  - [importmap spec](https://github.com/WICG/import-maps#import-maps)
400
414
 
@@ -425,20 +439,6 @@ See also
425
439
  - [importDefaultExtension](./docs/shared-parameters.md#importDefaultExtension)
426
440
  - [transform-typescript on babel](https://babeljs.io/docs/en/next/babel-plugin-transform-typescript.html)
427
441
 
428
- ## CommonJS
429
-
430
- CommonJS module format rely on `module.exports` and `require`. It was invented by Node.js and is not standard JavaScript. If your code or one of your dependency uses it, it requires some configuration. The jsenv config below makes jsenv compatible with a package named _"whatever"_ that would be written in CommonJS.
431
-
432
- _jsenv.config.mjs to use code written in CommonJS_:
433
-
434
- ```js
435
- import { jsenvBabelPluginMap, convertCommonJsWithRollup } from "@jsenv/core"
436
-
437
- export const convertMap = {
438
- "./node_modules/whatever/index.js": convertCommonJsWithRollup,
439
- }
440
- ```
441
-
442
442
  # See also
443
443
 
444
444
  | Link | Description |
@@ -1,9 +1,15 @@
1
1
  import { urlToFileSystemPath, resolveUrl } from "@jsenv/filesystem"
2
+
2
3
  import { require } from "./internal/require.js"
4
+ import { transformResultToCompilationResult } from "./internal/compiling/transformResultToCompilationResult.js"
3
5
 
4
- export const convertCommonJsWithRollup = async ({
6
+ export const commonJsToJavaScriptModule = async ({
5
7
  url,
6
- urlAfterTransform,
8
+ compiledUrl,
9
+ projectDirectoryUrl,
10
+
11
+ sourcemapExcludeSources,
12
+
7
13
  replaceGlobalObject = true,
8
14
  replaceGlobalFilename = true,
9
15
  replaceGlobalDirname = true,
@@ -90,14 +96,29 @@ export const convertCommonJsWithRollup = async ({
90
96
  // https://rollupjs.org/guide/en#output-sourcemap
91
97
  sourcemap: true,
92
98
  sourcemapExcludeSources: true,
93
- ...(urlAfterTransform
94
- ? { dir: urlToFileSystemPath(resolveUrl("./", urlAfterTransform)) }
99
+ ...(compiledUrl
100
+ ? { dir: urlToFileSystemPath(resolveUrl("./", compiledUrl)) }
95
101
  : {}),
96
102
  }
97
103
 
98
- const result = await rollupBuild.generate(generateOptions)
104
+ const { output } = await rollupBuild.generate(generateOptions)
105
+ const { code, map } = output[0]
99
106
 
100
- return result.output[0]
107
+ return transformResultToCompilationResult(
108
+ {
109
+ contentType: "application/javascript",
110
+ code,
111
+ map,
112
+ },
113
+ {
114
+ projectDirectoryUrl,
115
+ originalFileContent: code,
116
+ originalFileUrl: url,
117
+ compiledFileUrl: compiledUrl,
118
+ sourcemapFileUrl: `${compiledUrl}.map`,
119
+ sourcemapExcludeSources,
120
+ },
121
+ )
101
122
  }
102
123
 
103
124
  const __filenameReplacement = `import.meta.url.slice('file:///'.length)`
package/src/execute.js CHANGED
@@ -50,7 +50,7 @@ export const execute = async ({
50
50
  compileServerIp,
51
51
  compileServerPort,
52
52
  babelPluginMap,
53
- convertMap,
53
+ customCompilers,
54
54
  compileServerCanReadFromFilesystem,
55
55
  compileServerCanWriteOnFilesystem,
56
56
  runtimeSupportDuringDev = jsenvRuntimeSupportDuringDev,
@@ -95,7 +95,7 @@ export const execute = async ({
95
95
  compileServerIp,
96
96
  compileServerPort,
97
97
  babelPluginMap,
98
- convertMap,
98
+ customCompilers,
99
99
  runtimeSupport: runtimeSupportDuringDev,
100
100
  compileServerCanReadFromFilesystem,
101
101
  compileServerCanWriteOnFilesystem,
@@ -77,7 +77,7 @@ export const executeTestPlan = async ({
77
77
  compileServerCanReadFromFilesystem,
78
78
  compileServerCanWriteOnFilesystem,
79
79
  babelPluginMap,
80
- convertMap,
80
+ customCompilers,
81
81
  // we could even affine depending on testPlan
82
82
  runtimeSupportDuringDev = jsenvRuntimeSupportDuringDev,
83
83
  jsenvDirectoryClean,
@@ -185,7 +185,7 @@ export const executeTestPlan = async ({
185
185
  compileServerCanReadFromFilesystem,
186
186
  compileServerCanWriteOnFilesystem,
187
187
  babelPluginMap,
188
- convertMap,
188
+ customCompilers,
189
189
  runtimeSupport: runtimeSupportDuringDev,
190
190
  })
191
191
 
@@ -33,10 +33,7 @@ import {
33
33
  import { importMapsFromHtml } from "./html/htmlScan.js"
34
34
  import { parseRessource } from "./parseRessource.js"
35
35
  import { fetchSourcemap } from "./fetchSourcemap.js"
36
- import {
37
- createRessourceBuilder,
38
- referenceToCodeForRollup,
39
- } from "./ressource_builder.js"
36
+ import { createRessourceBuilder } from "./ressource_builder.js"
40
37
  import { computeBuildRelativeUrl } from "./url-versioning.js"
41
38
  import { transformImportMetaUrlReferences } from "./transformImportMetaUrlReferences.js"
42
39
 
@@ -429,9 +426,7 @@ building ${entryFileRelativeUrls.length} entry files...`)
429
426
  // isRessourceHint,
430
427
  ressourceImporter,
431
428
  }) => {
432
- // Entry point is not a JS module and references a js module
433
- // -> html referencing js
434
- // we must wait for rollup build to be done to generate the html asset
429
+ // Entry point is not a JS module and references a js module (html referencing js)
435
430
  if (
436
431
  ressourceImporter.isEntryPoint &&
437
432
  !ressourceImporter.isJsModule &&
@@ -603,10 +598,6 @@ building ${entryFileRelativeUrls.length} entry files...`)
603
598
  return asRollupUrl(importUrl)
604
599
  },
605
600
 
606
- // TODO: when code is using new URL() pattern
607
- // the code after build is currently returning a string instead of an url object
608
- // can we always return an url object because resolveFileUrl is always called
609
- // by this pattern?
610
601
  resolveFileUrl: ({ referenceId, fileName }) => {
611
602
  const ressourceFound = ressourceBuilder.findRessource((ressource) => {
612
603
  return ressource.rollupReferenceId === referenceId
@@ -652,6 +643,7 @@ building ${entryFileRelativeUrls.length} entry files...`)
652
643
 
653
644
  const moduleInfo = this.getModuleInfo(id)
654
645
  const url = asServerUrl(id)
646
+ const importerUrl = urlImporterMap[url]
655
647
 
656
648
  // logger.debug(`loads ${url}`)
657
649
  const {
@@ -664,8 +656,6 @@ building ${entryFileRelativeUrls.length} entry files...`)
664
656
  moduleInfo,
665
657
  })
666
658
 
667
- const importerUrl = urlImporterMap[url]
668
-
669
659
  // Jsenv helpers are injected as import statements to provide code like babel helpers
670
660
  // For now we just compute the information that the target file is a jsenv helper
671
661
  // without doing anything special with "targetIsJsenvHelperFile" information
@@ -675,8 +665,9 @@ building ${entryFileRelativeUrls.length} entry files...`)
675
665
  jsenvHelpersDirectoryInfo.url,
676
666
  )
677
667
 
678
- // Store the fact that this file is referenced by js (static or dynamic import)
679
- ressourceBuilder.createReference({
668
+ // Store the fact that this ressource exists
669
+ // Happens when entry point references js, also for every static and dynamic imports
670
+ ressourceBuilder.createReferenceFoundByRollup({
680
671
  // we don't want to emit a js chunk for every js file found
681
672
  // (However we want if the file is preload/prefetch by something else)
682
673
  // so we tell asset builder not to emit a chunk for this js reference
@@ -685,7 +676,7 @@ building ${entryFileRelativeUrls.length} entry files...`)
685
676
  ressourceContentTypeExpected: responseContentType,
686
677
  referenceUrl: importerUrl,
687
678
  ressourceSpecifier: responseUrl,
688
- // rollup do not provide a way to know line and column for the static or dynamic import
679
+ // rollup do not expose a way to know line and column for the static or dynamic import
689
680
  // referencing that file
690
681
  referenceColumn: undefined,
691
682
  referenceLine: undefined,
@@ -706,6 +697,8 @@ building ${entryFileRelativeUrls.length} entry files...`)
706
697
  },
707
698
 
708
699
  async transform(codeInput, id) {
700
+ // we should try/catch here?
701
+ // because this.parse might fail
709
702
  const ast = this.parse(codeInput, {
710
703
  // used to know node line and column
711
704
  locations: true,
@@ -884,6 +877,8 @@ building ${entryFileRelativeUrls.length} entry files...`)
884
877
  const jsRessource = ressourceBuilder.findRessource(
885
878
  (ressource) => ressource.url === file.url,
886
879
  )
880
+ // avant buildEnd il se peut que certaines ressources ne soit pas encore inline
881
+ // donc dans inlinedCallback on voudras ptet delete ces ressources?
887
882
  if (jsRessource && jsRessource.isInline) {
888
883
  buildInlineFileContents[fileName] = file.code
889
884
  } else {
@@ -903,7 +898,7 @@ building ${entryFileRelativeUrls.length} entry files...`)
903
898
  // aux assets faisant référence a ces chunk js qu'ils sont terminés
904
899
  // et donc les assets peuvent connaitre le nom du chunk
905
900
  // et mettre a jour leur dépendance vers ce fichier js
906
- ressourceBuilder.buildEnd({ jsModuleBuild, buildManifest })
901
+ ressourceBuilder.rollupBuildEnd({ jsModuleBuild, buildManifest })
907
902
  // wait html files to be emitted
908
903
  await ressourceBuilder.getAllEntryPointsEmittedPromise()
909
904
 
@@ -960,6 +955,26 @@ building ${entryFileRelativeUrls.length} entry files...`)
960
955
  rollupBuild = injectSourcemapInRollupBuild(rollupBuild, {
961
956
  buildDirectoryUrl,
962
957
  })
958
+
959
+ // update rollupBuild, buildInlineFilesContents, buildManifest and buildMappings
960
+ // in case some ressources where inlined by ressourceBuilder.rollupBuildEnd
961
+ Object.keys(buildManifest).forEach((fileName) => {
962
+ const buildRelativeUrl = buildManifest[fileName]
963
+ const ressource = ressourceBuilder.findRessource(
964
+ (ressource) => ressource.buildRelativeUrl === buildRelativeUrl,
965
+ )
966
+ if (ressource && ressource.isInline) {
967
+ delete buildManifest[fileName]
968
+ const originalProjectUrl = asOriginalUrl(ressource.url)
969
+ delete buildMappings[
970
+ urlToRelativeUrl(originalProjectUrl, projectDirectoryUrl)
971
+ ]
972
+ buildInlineFileContents[buildRelativeUrl] =
973
+ rollupBuild[buildRelativeUrl].code
974
+ delete rollupBuild[buildRelativeUrl]
975
+ }
976
+ })
977
+
963
978
  rollupBuild = sortObjectByPathnames(rollupBuild)
964
979
  buildManifest = sortObjectByPathnames(buildManifest)
965
980
  buildMappings = sortObjectByPathnames(buildMappings)
@@ -1022,12 +1037,11 @@ building ${entryFileRelativeUrls.length} entry files...`)
1022
1037
  // },
1023
1038
  ) => {
1024
1039
  if (moduleUrl in inlineModuleScripts) {
1025
- const codeInput = inlineModuleScripts[moduleUrl]
1026
-
1027
1040
  const { code, map } = await transformJs({
1028
- projectDirectoryUrl,
1029
- code: codeInput,
1041
+ code: inlineModuleScripts[moduleUrl],
1030
1042
  url: asProjectUrl(moduleUrl), // transformJs expect a file:// url
1043
+ projectDirectoryUrl,
1044
+
1031
1045
  babelPluginMap,
1032
1046
  // moduleOutFormat: format // we are compiling for rollup output must be "esmodule"
1033
1047
  })
@@ -1087,44 +1101,18 @@ building ${entryFileRelativeUrls.length} entry files...`)
1087
1101
  }
1088
1102
  }
1089
1103
 
1090
- const moduleResponseBodyAsBuffer = Buffer.from(
1091
- await moduleResponse.arrayBuffer(),
1104
+ const urlRelativeToImporter = urlToRelativeUrl(moduleUrl, importerUrl)
1105
+ const jsenvPluginError = new Error(
1106
+ `"${responseContentType}" is not a valid type for JavaScript module
1107
+ --- js module url ---
1108
+ ${asOriginalUrl(moduleUrl)}
1109
+ --- importer url ---
1110
+ ${asOriginalUrl(importerUrl)}
1111
+ --- suggestion ---
1112
+ non-js ressources can be used with new URL("${urlRelativeToImporter}", import.meta.url)`,
1092
1113
  )
1093
- const contentType = moduleResponse.headers["content-type"]
1094
- const assetReferenceForImport =
1095
- await ressourceBuilder.createReferenceFoundInJs({
1096
- // Reference to this target is corresponds to a static or dynamic import.
1097
- // found in a given file (importerUrl).
1098
- // But we don't know the line and colum because rollup
1099
- // does not tell us that information
1100
- jsUrl: importerUrl,
1101
- jsLine: undefined,
1102
- jsColumn: undefined,
1103
- ressourceSpecifier: moduleResponse.url,
1104
-
1105
- contentType,
1106
- bufferBeforeBuild: moduleResponseBodyAsBuffer,
1107
- })
1108
- if (assetReferenceForImport) {
1109
- markBuildRelativeUrlAsUsedByJs(
1110
- assetReferenceForImport.ressource.buildRelativeUrl,
1111
- )
1112
- const content = `export default ${referenceToCodeForRollup(
1113
- assetReferenceForImport,
1114
- )}`
1115
-
1116
- return {
1117
- ...commonData,
1118
- contentRaw: String(moduleResponseBodyAsBuffer),
1119
- content,
1120
- }
1121
- }
1122
-
1123
- return {
1124
- ...commonData,
1125
- contentRaw: String(moduleResponseBodyAsBuffer),
1126
- content: String(moduleResponseBodyAsBuffer),
1127
- }
1114
+ storeLatestJsenvPluginError(jsenvPluginError)
1115
+ throw jsenvPluginError
1128
1116
  }
1129
1117
 
1130
1118
  const jsenvFetchUrl = async (url, importer) => {
@@ -36,6 +36,7 @@ import {
36
36
  parseSrcset,
37
37
  stringifySrcset,
38
38
  getHtmlNodeLocation,
39
+ removeHtmlNode,
39
40
  } from "@jsenv/core/src/internal/compiling/compileHtml.js"
40
41
  import {
41
42
  getJavaScriptSourceMappingUrl,
@@ -590,6 +591,10 @@ const linkHrefVisitor = (
590
591
  // we could remove the HTML node but better keep it untouched and let user decide what to do
591
592
  return
592
593
  }
594
+
595
+ ressource.inlinedCallbacks.push(() => {
596
+ removeHtmlNode(link)
597
+ })
593
598
  }
594
599
 
595
600
  if (ressource.isExternal) {
@@ -51,9 +51,8 @@ export const createRessourceBuilder = (
51
51
  entryBuffer,
52
52
  entryBuildRelativeUrl,
53
53
  }) => {
54
- // we don't really know where this reference to that asset file comes from
55
- // we could almost say it's from the script calling this function
56
- // so we could analyse stack trace here to put this function caller
54
+ // The entry point is conceptually referenced by code passing "entryPointMap"
55
+ // to buildProject. So we analyse stack trace to put this function caller
57
56
  // as the reference to this ressource file
58
57
  const callerLocation = getCallerLocation()
59
58
  const entryReference = createReference({
@@ -109,7 +108,14 @@ export const createRessourceBuilder = (
109
108
  )
110
109
  }
111
110
 
112
- const createReferenceFoundInJs = async ({
111
+ const createReferenceFoundByRollup = async (params) => {
112
+ return createReference({
113
+ fromRollup: true,
114
+ ...params,
115
+ })
116
+ }
117
+
118
+ const createReferenceFoundInJsModule = async ({
113
119
  jsUrl,
114
120
  jsLine,
115
121
  jsColumn,
@@ -147,12 +153,6 @@ export const createRessourceBuilder = (
147
153
 
148
154
  const ressourceMap = {}
149
155
  const ressourceRedirectionMap = {}
150
- // ok il faudrait faire un truc dans ce genre:
151
- // lorsqu'on a un preload, on fait une promesse
152
- // pour le moment ou la ressource est référencé par un autre truc
153
- // ensuite dans le callback lorsque le build rollup est fini
154
- // la on considere que ça n'a jamais été référencé, on resoud la promesse
155
- // malgré tout
156
156
  const createReference = ({
157
157
  referenceShouldNotEmitChunk,
158
158
  isRessourceHint,
@@ -169,13 +169,29 @@ export const createRessourceBuilder = (
169
169
  isInline,
170
170
  fileNamePattern,
171
171
  urlVersioningDisabled,
172
+
173
+ fromRollup,
172
174
  }) => {
173
- const importerUrl = referenceUrl
174
- const ressourceImporter = ressourceFromUrl(importerUrl) || {
175
- url: importerUrl,
176
- isEntryPoint: false, // maybe
177
- isJsModule: true,
178
- bufferAfterBuild: "",
175
+ const existingRessourceForReference = ressourceFromUrl(referenceUrl)
176
+ let ressourceImporter
177
+ if (existingRessourceForReference) {
178
+ ressourceImporter = existingRessourceForReference
179
+ } else {
180
+ const referenceOriginalUrl = asOriginalServerUrl(referenceUrl)
181
+ if (referenceOriginalUrl) {
182
+ ressourceImporter = ressourceFromUrl(referenceOriginalUrl)
183
+ }
184
+ if (!ressourceImporter) {
185
+ // happens only for entry points?
186
+ // in that case the importer is theoric
187
+ // see "getCallerLocation()" in createReferenceForEntryPoint
188
+ ressourceImporter = {
189
+ url: referenceUrl,
190
+ isEntryPoint: false,
191
+ isJsModule: true,
192
+ bufferAfterBuild: "",
193
+ }
194
+ }
179
195
  }
180
196
 
181
197
  const shouldBeIgnoredWarning = referenceShouldBeIgnoredWarning({
@@ -240,26 +256,6 @@ export const createRessourceBuilder = (
240
256
  }
241
257
  }
242
258
 
243
- const reference = {
244
- referenceShouldNotEmitChunk,
245
- isRessourceHint,
246
- ressourceContentTypeExpected,
247
- referenceUrl,
248
- referenceColumn,
249
- referenceLine,
250
-
251
- isInline,
252
- inlinedCallback: () => {
253
- reference.isInline = true
254
- const allReferenceAreInline = ressource.references.every(
255
- (reference) => reference.isInline,
256
- )
257
- if (allReferenceAreInline) {
258
- ressource.isInline = true
259
- }
260
- },
261
- }
262
-
263
259
  const existingRessource = ressourceFromUrl(ressourceUrl)
264
260
  let ressource
265
261
  if (existingRessource) {
@@ -267,7 +263,7 @@ export const createRessourceBuilder = (
267
263
  // allow to update the bufferBeforeBuild on existingRessource
268
264
  // this happens when rollup loads a js file and communicates to this code
269
265
  // what was loaded
270
- if (typeof bufferBeforeBuild !== "undefined") {
266
+ if (fromRollup) {
271
267
  ressource.bufferBeforeBuild = bufferBeforeBuild
272
268
  ressource.contentType = contentType
273
269
  }
@@ -286,8 +282,37 @@ export const createRessourceBuilder = (
286
282
  })
287
283
  ressourceMap[ressourceUrl] = ressource
288
284
  }
285
+
286
+ const reference = {
287
+ referenceShouldNotEmitChunk,
288
+ isRessourceHint,
289
+ ressourceContentTypeExpected,
290
+ referenceUrl,
291
+ referenceColumn,
292
+ referenceLine,
293
+
294
+ isInline,
295
+ inlinedCallback: () => {
296
+ reference.isInline = true
297
+ const allStrongReferenceAreInline = ressource.references.every(
298
+ (reference) => reference.isRessourceHint || reference.isInline,
299
+ )
300
+ if (allStrongReferenceAreInline) {
301
+ ressource.isInline = true
302
+ ressource.inlinedCallbacks.forEach((callback) => callback())
303
+ }
304
+ },
305
+ }
306
+
289
307
  reference.ressource = ressource
290
- ressource.addReference(reference, { isJsModule })
308
+ if (fromRollup && ressourceImporter.isEntryPoint) {
309
+ // do not add that reference, it's already know and would duplicate the html referencing a js file
310
+ // but do apply its effects
311
+ ressource.applyReferenceEffects(reference, { isJsModule })
312
+ } else {
313
+ ressource.references.push(reference)
314
+ ressource.applyReferenceEffects(reference, { isJsModule })
315
+ }
291
316
 
292
317
  return reference
293
318
  }
@@ -329,6 +354,7 @@ export const createRessourceBuilder = (
329
354
  ressource.usedPromise = new Promise((resolve) => {
330
355
  ressource.usedCallback = resolve
331
356
  })
357
+ ressource.inlinedCallbacks = []
332
358
  ressource.buildDonePromise = new Promise((resolve, reject) => {
333
359
  ressource.buildDoneCallback = ({ buildFileInfo, buildManifest }) => {
334
360
  if (!ressource.isJsModule) {
@@ -735,9 +761,7 @@ export const createRessourceBuilder = (
735
761
  return effects
736
762
  }
737
763
 
738
- const addReference = (reference, infoFromReference) => {
739
- ressource.references.push(reference)
740
-
764
+ const applyReferenceEffects = (reference, infoFromReference) => {
741
765
  const referenceEffects = onReference(reference, infoFromReference)
742
766
 
743
767
  logger.debug(
@@ -750,7 +774,7 @@ export const createRessourceBuilder = (
750
774
  }
751
775
 
752
776
  Object.assign(ressource, {
753
- addReference,
777
+ applyReferenceEffects,
754
778
  getBufferAvailablePromise,
755
779
  getDependenciesAvailablePromise,
756
780
  getReadyPromise,
@@ -761,7 +785,7 @@ export const createRessourceBuilder = (
761
785
  return ressource
762
786
  }
763
787
 
764
- const buildEnd = ({ jsModuleBuild, buildManifest }) => {
788
+ const rollupBuildEnd = ({ jsModuleBuild, buildManifest }) => {
765
789
  Object.keys(ressourceMap).forEach((ressourceUrl) => {
766
790
  const ressource = ressourceMap[ressourceUrl]
767
791
  const { buildDoneCallback } = ressource
@@ -843,10 +867,10 @@ ${showSourceLocation(referenceSourceAsString, {
843
867
 
844
868
  return {
845
869
  createReferenceForEntryPoint,
846
- createReferenceFoundInJs,
847
- createReference,
870
+ createReferenceFoundByRollup,
871
+ createReferenceFoundInJsModule,
848
872
 
849
- buildEnd,
873
+ rollupBuildEnd,
850
874
  getAllEntryPointsEmittedPromise,
851
875
  findRessource,
852
876
 
@@ -29,7 +29,7 @@ export const transformImportMetaUrlReferences = async ({
29
29
  const response = await fetch(ressourceUrl, url)
30
30
  const bufferBeforeBuild = Buffer.from(await response.arrayBuffer())
31
31
 
32
- const reference = await ressourceBuilder.createReferenceFoundInJs({
32
+ const reference = await ressourceBuilder.createReferenceFoundInJsModule({
33
33
  jsUrl: url,
34
34
  ...(node.loc
35
35
  ? {
@@ -52,6 +52,6 @@ export const writeFileContent = async (
52
52
  }
53
53
  }
54
54
 
55
- export const testFilePresence = async (url) => {
55
+ export const testFilePresence = (url) => {
56
56
  return existsSync(urlToFileSystemPath(url))
57
57
  }
@@ -88,6 +88,7 @@ export const getOrGenerateCompiledFile = async ({
88
88
  compileResult,
89
89
  compileResultStatus,
90
90
  compiledFileUrl,
91
+ // originalFileUrl,
91
92
  cacheHitTracking,
92
93
  }),
93
94
  )
@@ -214,21 +215,28 @@ const callCompile = async ({
214
215
  }) => {
215
216
  logger.debug(`compile ${originalFileUrl}`)
216
217
 
217
- const compileArgs =
218
+ const codeBeforeCompile =
218
219
  compile.length === 0
219
- ? []
220
- : await getArgumentsForCompile({ originalFileUrl, fileContentFallback })
220
+ ? ""
221
+ : await getCodeToCompile({ originalFileUrl, fileContentFallback })
221
222
 
223
+ const compileReturnValue = await compile({
224
+ code: codeBeforeCompile,
225
+ map: undefined,
226
+ })
227
+ if (typeof compileReturnValue !== "object" || compileReturnValue === null) {
228
+ throw new TypeError(
229
+ `compile must return an object, got ${compileReturnValue}`,
230
+ )
231
+ }
222
232
  const {
233
+ contentType,
234
+ compiledSource,
223
235
  sources = [],
224
236
  sourcesContent = [],
225
237
  assets = [],
226
238
  assetsContent = [],
227
- contentType,
228
- compiledSource,
229
- ...rest
230
- } = await compile(...compileArgs)
231
-
239
+ } = compileReturnValue
232
240
  if (typeof contentType !== "string") {
233
241
  throw new TypeError(
234
242
  `compile must return a contentType string, got ${contentType}`,
@@ -247,14 +255,10 @@ const callCompile = async ({
247
255
  sourcesContent,
248
256
  assets,
249
257
  assetsContent,
250
- ...rest,
251
258
  }
252
259
  }
253
260
 
254
- const getArgumentsForCompile = async ({
255
- originalFileUrl,
256
- fileContentFallback,
257
- }) => {
261
+ const getCodeToCompile = async ({ originalFileUrl, fileContentFallback }) => {
258
262
  let fileContent
259
263
  if (fileContentFallback) {
260
264
  try {
@@ -269,7 +273,7 @@ const getArgumentsForCompile = async ({
269
273
  } else {
270
274
  fileContent = await readFileContent(originalFileUrl)
271
275
  }
272
- return [fileContent]
276
+ return fileContent
273
277
  }
274
278
 
275
279
  const startAsap = async (fn, { logger, compiledFileUrl }) => {