@jsenv/plugin-transpilation 1.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 (127) hide show
  1. package/README.md +3 -0
  2. package/package.json +60 -0
  3. package/src/as_js_module/convert_js_classic_to_js_module.js +42 -0
  4. package/src/as_js_module/jsenv_plugin_as_js_module.js +89 -0
  5. package/src/babel/apply_js_transpilation.js +74 -0
  6. package/src/babel/babel_helper_directory/README.md +8 -0
  7. package/src/babel/babel_helper_directory/babel_helper_directory.js +35 -0
  8. package/src/babel/babel_helper_directory/babel_helpers/AsyncGenerator/AsyncGenerator.js +112 -0
  9. package/src/babel/babel_helper_directory/babel_helpers/AwaitValue/AwaitValue.js +3 -0
  10. package/src/babel/babel_helper_directory/babel_helpers/applyDecoratedDescriptor/applyDecoratedDescriptor.js +23 -0
  11. package/src/babel/babel_helper_directory/babel_helpers/applyDecs/applyDecs.js +802 -0
  12. package/src/babel/babel_helper_directory/babel_helpers/applyDecs2203/applyDecs2203.js +635 -0
  13. package/src/babel/babel_helper_directory/babel_helpers/applyDecs2203R/applyDecs2203R.js +642 -0
  14. package/src/babel/babel_helper_directory/babel_helpers/applyDecs2301/applyDecs2301.js +691 -0
  15. package/src/babel/babel_helper_directory/babel_helpers/arrayLikeToArray/arrayLikeToArray.js +7 -0
  16. package/src/babel/babel_helper_directory/babel_helpers/arrayWithHoles/arrayWithHoles.js +4 -0
  17. package/src/babel/babel_helper_directory/babel_helpers/arrayWithoutHoles/arrayWithoutHoles.js +6 -0
  18. package/src/babel/babel_helper_directory/babel_helpers/assertThisInitialized/assertThisInitialized.js +7 -0
  19. package/src/babel/babel_helper_directory/babel_helpers/asyncGeneratorDelegate/asyncGeneratorDelegate.js +55 -0
  20. package/src/babel/babel_helper_directory/babel_helpers/asyncIterator/asyncIterator.js +65 -0
  21. package/src/babel/babel_helper_directory/babel_helpers/asyncToGenerator/asyncToGenerator.js +34 -0
  22. package/src/babel/babel_helper_directory/babel_helpers/awaitAsyncGenerator/awaitAsyncGenerator.js +5 -0
  23. package/src/babel/babel_helper_directory/babel_helpers/checkInRHS/checkInRHS.js +9 -0
  24. package/src/babel/babel_helper_directory/babel_helpers/classApplyDescriptorDestructureSet/classApplyDescriptorDestructureSet.js +20 -0
  25. package/src/babel/babel_helper_directory/babel_helpers/classApplyDescriptorGet/classApplyDescriptorGet.js +6 -0
  26. package/src/babel/babel_helper_directory/babel_helpers/classApplyDescriptorSet/classApplyDescriptorSet.js +13 -0
  27. package/src/babel/babel_helper_directory/babel_helpers/classCallCheck/classCallCheck.js +5 -0
  28. package/src/babel/babel_helper_directory/babel_helpers/classCheckPrivateStaticAccess/classCheckPrivateStaticAccess.js +5 -0
  29. package/src/babel/babel_helper_directory/babel_helpers/classCheckPrivateStaticFieldDescriptor/classCheckPrivateStaticFieldDescriptor.js +6 -0
  30. package/src/babel/babel_helper_directory/babel_helpers/classExtractFieldDescriptor/classExtractFieldDescriptor.js +7 -0
  31. package/src/babel/babel_helper_directory/babel_helpers/classNameTDZError/classNameTDZError.js +4 -0
  32. package/src/babel/babel_helper_directory/babel_helpers/classPrivateFieldDestructureSet/classPrivateFieldDestructureSet.js +7 -0
  33. package/src/babel/babel_helper_directory/babel_helpers/classPrivateFieldGet/classPrivateFieldGet.js +7 -0
  34. package/src/babel/babel_helper_directory/babel_helpers/classPrivateFieldLooseBase/classPrivateFieldLooseBase.js +6 -0
  35. package/src/babel/babel_helper_directory/babel_helpers/classPrivateFieldLooseKey/classPrivateFieldLooseKey.js +5 -0
  36. package/src/babel/babel_helper_directory/babel_helpers/classPrivateFieldSet/classPrivateFieldSet.js +8 -0
  37. package/src/babel/babel_helper_directory/babel_helpers/classPrivateMethodGet/classPrivateMethodGet.js +6 -0
  38. package/src/babel/babel_helper_directory/babel_helpers/classPrivateMethodSet/classPrivateMethodSet.js +3 -0
  39. package/src/babel/babel_helper_directory/babel_helpers/classStaticPrivateFieldSpecGet/classStaticPrivateFieldSpecGet.js +9 -0
  40. package/src/babel/babel_helper_directory/babel_helpers/classStaticPrivateFieldSpecSet/classStaticPrivateFieldSpecSet.js +15 -0
  41. package/src/babel/babel_helper_directory/babel_helpers/classStaticPrivateMethodGet/classStaticPrivateMethodGet.js +6 -0
  42. package/src/babel/babel_helper_directory/babel_helpers/classStaticPrivateMethodSet/classStaticPrivateMethodSet.js +3 -0
  43. package/src/babel/babel_helper_directory/babel_helpers/construct/construct.js +16 -0
  44. package/src/babel/babel_helper_directory/babel_helpers/createClass/createClass.js +17 -0
  45. package/src/babel/babel_helper_directory/babel_helpers/createForOfIteratorHelper/createForOfIteratorHelper.js +60 -0
  46. package/src/babel/babel_helper_directory/babel_helpers/createForOfIteratorHelperLoose/createForOfIteratorHelperLoose.js +23 -0
  47. package/src/babel/babel_helper_directory/babel_helpers/createRawReactElement/createRawReactElement.js +50 -0
  48. package/src/babel/babel_helper_directory/babel_helpers/createSuper/createSuper.js +22 -0
  49. package/src/babel/babel_helper_directory/babel_helpers/decorate/decorate.js +403 -0
  50. package/src/babel/babel_helper_directory/babel_helpers/defaults/defaults.js +11 -0
  51. package/src/babel/babel_helper_directory/babel_helpers/defineAccessor/defineAccessor.js +6 -0
  52. package/src/babel/babel_helper_directory/babel_helpers/defineEnumerableProperties/defineEnumerableProperties.js +23 -0
  53. package/src/babel/babel_helper_directory/babel_helpers/defineProperty/defineProperty.js +21 -0
  54. package/src/babel/babel_helper_directory/babel_helpers/extends/extends.js +14 -0
  55. package/src/babel/babel_helper_directory/babel_helpers/get/get.js +19 -0
  56. package/src/babel/babel_helper_directory/babel_helpers/getPrototypeOf/getPrototypeOf.js +4 -0
  57. package/src/babel/babel_helper_directory/babel_helpers/identity/identity.js +3 -0
  58. package/src/babel/babel_helper_directory/babel_helpers/inherits/inherits.js +19 -0
  59. package/src/babel/babel_helper_directory/babel_helpers/inheritsLoose/inheritsLoose.js +7 -0
  60. package/src/babel/babel_helper_directory/babel_helpers/initializerDefineProperty/initializerDefineProperty.js +10 -0
  61. package/src/babel/babel_helper_directory/babel_helpers/initializerWarningHelper/initializerWarningHelper.js +6 -0
  62. package/src/babel/babel_helper_directory/babel_helpers/instanceof/instanceof.js +6 -0
  63. package/src/babel/babel_helper_directory/babel_helpers/interopRequireDefault/interopRequireDefault.js +3 -0
  64. package/src/babel/babel_helper_directory/babel_helpers/interopRequireWildcard/interopRequireWildcard.js +37 -0
  65. package/src/babel/babel_helper_directory/babel_helpers/isNativeFunction/isNativeFunction.js +4 -0
  66. package/src/babel/babel_helper_directory/babel_helpers/isNativeReflectConstruct/isNativeReflectConstruct.js +21 -0
  67. package/src/babel/babel_helper_directory/babel_helpers/iterableToArray/iterableToArray.js +7 -0
  68. package/src/babel/babel_helper_directory/babel_helpers/iterableToArrayLimit/iterableToArrayLimit.js +54 -0
  69. package/src/babel/babel_helper_directory/babel_helpers/iterableToArrayLimitLoose/iterableToArrayLimitLoose.js +16 -0
  70. package/src/babel/babel_helper_directory/babel_helpers/jsx/jsx.js +50 -0
  71. package/src/babel/babel_helper_directory/babel_helpers/maybeArrayLike/maybeArrayLike.js +10 -0
  72. package/src/babel/babel_helper_directory/babel_helpers/newArrowCheck/newArrowCheck.js +5 -0
  73. package/src/babel/babel_helper_directory/babel_helpers/nonIterableRest/nonIterableRest.js +5 -0
  74. package/src/babel/babel_helper_directory/babel_helpers/nonIterableSpread/nonIterableSpread.js +5 -0
  75. package/src/babel/babel_helper_directory/babel_helpers/objectDestructuringEmpty/objectDestructuringEmpty.js +3 -0
  76. package/src/babel/babel_helper_directory/babel_helpers/objectSpread/objectSpread.js +23 -0
  77. package/src/babel/babel_helper_directory/babel_helpers/objectSpread2/objectSpread2.js +41 -0
  78. package/src/babel/babel_helper_directory/babel_helpers/objectWithoutProperties/objectWithoutProperties.js +19 -0
  79. package/src/babel/babel_helper_directory/babel_helpers/objectWithoutPropertiesLoose/objectWithoutPropertiesLoose.js +13 -0
  80. package/src/babel/babel_helper_directory/babel_helpers/overloadYield/overloadYield.js +11 -0
  81. package/src/babel/babel_helper_directory/babel_helpers/possibleConstructorReturn/possibleConstructorReturn.js +10 -0
  82. package/src/babel/babel_helper_directory/babel_helpers/readOnlyError/readOnlyError.js +4 -0
  83. package/src/babel/babel_helper_directory/babel_helpers/regeneratorRuntime/regeneratorRuntime.js +702 -0
  84. package/src/babel/babel_helper_directory/babel_helpers/set/set.js +44 -0
  85. package/src/babel/babel_helper_directory/babel_helpers/setPrototypeOf/setPrototypeOf.js +6 -0
  86. package/src/babel/babel_helper_directory/babel_helpers/skipFirstGeneratorNext/skipFirstGeneratorNext.js +8 -0
  87. package/src/babel/babel_helper_directory/babel_helpers/slicedToArray/slicedToArray.js +10 -0
  88. package/src/babel/babel_helper_directory/babel_helpers/slicedToArrayLoose/slicedToArrayLoose.js +13 -0
  89. package/src/babel/babel_helper_directory/babel_helpers/superPropBase/superPropBase.js +10 -0
  90. package/src/babel/babel_helper_directory/babel_helpers/taggedTemplateLiteral/taggedTemplateLiteral.js +10 -0
  91. package/src/babel/babel_helper_directory/babel_helpers/taggedTemplateLiteralLoose/taggedTemplateLiteralLoose.js +7 -0
  92. package/src/babel/babel_helper_directory/babel_helpers/tdz/tdz.js +4 -0
  93. package/src/babel/babel_helper_directory/babel_helpers/temporalRef/temporalRef.js +6 -0
  94. package/src/babel/babel_helper_directory/babel_helpers/temporalUndefined/temporalUndefined.js +3 -0
  95. package/src/babel/babel_helper_directory/babel_helpers/toArray/toArray.js +10 -0
  96. package/src/babel/babel_helper_directory/babel_helpers/toConsumableArray/toConsumableArray.js +10 -0
  97. package/src/babel/babel_helper_directory/babel_helpers/toPrimitive/toPrimitive.js +10 -0
  98. package/src/babel/babel_helper_directory/babel_helpers/toPropertyKey/toPropertyKey.js +6 -0
  99. package/src/babel/babel_helper_directory/babel_helpers/typeof/typeof.js +14 -0
  100. package/src/babel/babel_helper_directory/babel_helpers/unsupportedIterableToArray/unsupportedIterableToArray.js +12 -0
  101. package/src/babel/babel_helper_directory/babel_helpers/wrapAsyncGenerator/wrapAsyncGenerator.js +8 -0
  102. package/src/babel/babel_helper_directory/babel_helpers/wrapNativeSuper/wrapNativeSuper.js +30 -0
  103. package/src/babel/babel_helper_directory/babel_helpers/wrapRegExp/wrapRegExp.js +77 -0
  104. package/src/babel/babel_helper_directory/babel_helpers/writeOnlyError/writeOnlyError.js +4 -0
  105. package/src/babel/babel_plugin_babel_helpers_as_jsenv_imports.js +53 -0
  106. package/src/babel/babel_plugin_structure.js +176 -0
  107. package/src/babel/babel_plugins_compatibility.js +432 -0
  108. package/src/babel/global_this/babel_plugin_global_this_injector.js +56 -0
  109. package/src/babel/global_this/client/global_this_js_classic.js +25 -0
  110. package/src/babel/global_this/client/global_this_js_module.js +21 -0
  111. package/src/babel/jsenv_plugin_babel.js +35 -0
  112. package/src/babel/new_stylesheet/babel_plugin_new_stylesheet_injector.js +149 -0
  113. package/src/babel/new_stylesheet/client/new_stylesheet.js +381 -0
  114. package/src/babel/polyfill_injection_in_babel_ast.js +41 -0
  115. package/src/babel/regenerator_runtime/babel_plugin_regenerator_runtime_injector.js +49 -0
  116. package/src/babel/regenerator_runtime/client/regenerator_runtime.js +748 -0
  117. package/src/css/apply_css_transpilation.js +41 -0
  118. package/src/css/jsenv_plugin_css_transpilation.js +17 -0
  119. package/src/import_assertions/jsenv_plugin_import_assertions.js +244 -0
  120. package/src/import_meta_resolve/jsenv_plugin_import_meta_resolve.js +48 -0
  121. package/src/js_module_fallback/jsenv_plugin_js_module_conversion.js +136 -0
  122. package/src/js_module_fallback/jsenv_plugin_js_module_fallback.js +46 -0
  123. package/src/js_module_fallback/jsenv_plugin_js_module_fallback_inside_html.js +240 -0
  124. package/src/js_module_fallback/jsenv_plugin_js_module_fallback_on_workers.js +62 -0
  125. package/src/jsenv_plugin_transpilation.js +54 -0
  126. package/src/main.js +2 -0
  127. package/src/top_level_await/jsenv_plugin_top_level_await.js +94 -0
@@ -0,0 +1,41 @@
1
+ import { fileURLToPath } from "node:url";
2
+
3
+ export const applyCssTranspilation = async ({
4
+ input,
5
+ inputUrl,
6
+ runtimeCompat,
7
+ }) => {
8
+ // https://lightningcss.dev/docs.html
9
+ const { transform } = await import("lightningcss");
10
+ const targets = runtimeCompatToTargets(runtimeCompat);
11
+ const { code, map } = transform({
12
+ filename: fileURLToPath(inputUrl),
13
+ code: Buffer.from(input),
14
+ targets,
15
+ minify: false,
16
+ drafts: {
17
+ nesting: true,
18
+ customMedia: true,
19
+ },
20
+ });
21
+ return { content: String(code), sourcemap: map };
22
+ };
23
+
24
+ const runtimeCompatToTargets = (runtimeCompat) => {
25
+ const targets = {};
26
+ ["chrome", "firefox", "ie", "opera", "safari"].forEach((runtimeName) => {
27
+ const version = runtimeCompat[runtimeName];
28
+ if (version) {
29
+ targets[runtimeName] = versionToBits(version);
30
+ }
31
+ });
32
+ return targets;
33
+ };
34
+
35
+ const versionToBits = (version) => {
36
+ const [major, minor = 0, patch = 0] = version
37
+ .split("-")[0]
38
+ .split(".")
39
+ .map((v) => parseInt(v, 10));
40
+ return (major << 16) | (minor << 8) | patch;
41
+ };
@@ -0,0 +1,17 @@
1
+ import { applyCssTranspilation } from "./apply_css_transpilation.js";
2
+
3
+ export const jsenvPluginCssTranspilation = () => {
4
+ return {
5
+ name: "jsenv:css_transpilation",
6
+ appliesDuring: "*",
7
+ transformUrlContent: {
8
+ css: async (urlInfo, context) => {
9
+ return applyCssTranspilation({
10
+ input: urlInfo.content,
11
+ inputUrl: urlInfo.originalUrl,
12
+ runtimeCompat: context.runtimeCompat,
13
+ });
14
+ },
15
+ },
16
+ };
17
+ };
@@ -0,0 +1,244 @@
1
+ /*
2
+ * Jsenv wont touch code where "specifier" or "type" is dynamic (see code below)
3
+ * ```js
4
+ * const file = "./style.css"
5
+ * const type = "css"
6
+ * import(file, { assert: { type }})
7
+ * ```
8
+ * Jsenv could throw an error when it knows some browsers in runtimeCompat
9
+ * do not support import assertions
10
+ * But for now (as it is simpler) we let the browser throw the error
11
+ */
12
+
13
+ import { urlToFilename, injectQueryParams } from "@jsenv/urls";
14
+ import { JS_QUOTES } from "@jsenv/utils/src/string/js_quotes.js";
15
+
16
+ export const jsenvPluginImportAssertions = ({
17
+ json = "auto",
18
+ css = "auto",
19
+ text = "auto",
20
+ }) => {
21
+ const transpilations = { json, css, text };
22
+ const shouldTranspileImportAssertion = (context, type) => {
23
+ const transpilation = transpilations[type];
24
+ if (transpilation === true) {
25
+ return true;
26
+ }
27
+ if (transpilation === "auto") {
28
+ return !context.isSupportedOnCurrentClients(`import_type_${type}`);
29
+ }
30
+ return false;
31
+ };
32
+ const markAsJsModuleProxy = (reference) => {
33
+ reference.expectedType = "js_module";
34
+ reference.filename = `${urlToFilename(reference.url)}.js`;
35
+ };
36
+ const turnIntoJsModuleProxy = (reference, type) => {
37
+ reference.mutation = (magicSource) => {
38
+ const { assertNode } = reference;
39
+ if (reference.subtype === "import_dynamic") {
40
+ const assertPropertyNode = assertNode.properties.find(
41
+ (prop) => prop.key.name === "assert",
42
+ );
43
+ const assertPropertyValue = assertPropertyNode.value;
44
+ const typePropertyNode = assertPropertyValue.properties.find(
45
+ (prop) => prop.key.name === "type",
46
+ );
47
+ magicSource.remove({
48
+ start: typePropertyNode.start,
49
+ end: typePropertyNode.end,
50
+ });
51
+ } else {
52
+ magicSource.remove({
53
+ start: assertNode.start,
54
+ end: assertNode.end,
55
+ });
56
+ }
57
+ };
58
+ const newUrl = injectQueryParams(reference.url, {
59
+ [`as_${type}_module`]: "",
60
+ });
61
+ markAsJsModuleProxy(reference);
62
+ return newUrl;
63
+ };
64
+
65
+ const importAssertions = {
66
+ name: "jsenv:import_assertions",
67
+ appliesDuring: "*",
68
+ init: (context) => {
69
+ // transpilation is forced during build so that
70
+ // - avoid rollup to see import assertions
71
+ // We would have to tell rollup to ignore import with assertion
72
+ // - means rollup can bundle more js file together
73
+ // - means url versioning can work for css inlined in js
74
+ if (context.build) {
75
+ transpilations.json = true;
76
+ transpilations.css = true;
77
+ transpilations.text = true;
78
+ }
79
+ },
80
+ redirectReference: (reference, context) => {
81
+ if (!reference.assert) {
82
+ return null;
83
+ }
84
+ const { searchParams } = reference;
85
+ if (
86
+ searchParams.has("as_json_module") ||
87
+ searchParams.has("as_css_module") ||
88
+ searchParams.has("as_text_module")
89
+ ) {
90
+ markAsJsModuleProxy(reference);
91
+ return null;
92
+ }
93
+ const type = reference.assert.type;
94
+ if (shouldTranspileImportAssertion(context, type)) {
95
+ return turnIntoJsModuleProxy(reference, type);
96
+ }
97
+ return null;
98
+ },
99
+ };
100
+ return [importAssertions, ...jsenvPluginAsModules()];
101
+ };
102
+
103
+ const jsenvPluginAsModules = () => {
104
+ const asJsonModule = {
105
+ name: `jsenv:as_json_module`,
106
+ appliesDuring: "*",
107
+ fetchUrlContent: async (urlInfo, context) => {
108
+ const [jsonReference, jsonUrlInfo] = context.getWithoutSearchParam({
109
+ urlInfo,
110
+ context,
111
+ searchParam: "as_json_module",
112
+ expectedType: "json",
113
+ });
114
+ if (!jsonReference) {
115
+ return null;
116
+ }
117
+ await context.fetchUrlContent(jsonUrlInfo, {
118
+ reference: jsonReference,
119
+ });
120
+ if (context.dev) {
121
+ context.referenceUtils.found({
122
+ type: "js_import",
123
+ subtype: jsonReference.subtype,
124
+ specifier: jsonReference.url,
125
+ expectedType: "js_module",
126
+ });
127
+ } else if (context.build && jsonUrlInfo.dependents.size === 0) {
128
+ context.urlGraph.deleteUrlInfo(jsonUrlInfo.url);
129
+ }
130
+ const jsonText = JSON.stringify(jsonUrlInfo.content.trim());
131
+ return {
132
+ // here we could `export default ${jsonText}`:
133
+ // but js engine are optimized to recognize JSON.parse
134
+ // and use a faster parsing strategy
135
+ content: `export default JSON.parse(${jsonText})`,
136
+ contentType: "text/javascript",
137
+ type: "js_module",
138
+ originalUrl: jsonUrlInfo.originalUrl,
139
+ originalContent: jsonUrlInfo.originalContent,
140
+ data: jsonUrlInfo.data,
141
+ };
142
+ },
143
+ };
144
+
145
+ const asCssModule = {
146
+ name: `jsenv:as_css_module`,
147
+ appliesDuring: "*",
148
+ fetchUrlContent: async (urlInfo, context) => {
149
+ const [cssReference, cssUrlInfo] = context.getWithoutSearchParam({
150
+ urlInfo,
151
+ context,
152
+ searchParam: "as_css_module",
153
+ expectedType: "css",
154
+ });
155
+ if (!cssReference) {
156
+ return null;
157
+ }
158
+ await context.fetchUrlContent(cssUrlInfo, {
159
+ reference: cssReference,
160
+ });
161
+ if (context.dev) {
162
+ context.referenceUtils.found({
163
+ type: "js_import",
164
+ subtype: cssReference.subtype,
165
+ specifier: cssReference.url,
166
+ expectedType: "js_module",
167
+ });
168
+ } else if (context.build && cssUrlInfo.dependents.size === 0) {
169
+ context.urlGraph.deleteUrlInfo(cssUrlInfo.url);
170
+ }
171
+ const cssText = JS_QUOTES.escapeSpecialChars(cssUrlInfo.content, {
172
+ // If template string is choosen and runtime do not support template literals
173
+ // it's ok because "jsenv:new_inline_content" plugin executes after this one
174
+ // and convert template strings into raw strings
175
+ canUseTemplateString: true,
176
+ });
177
+ return {
178
+ content: `import ${JSON.stringify(
179
+ context.referenceUtils.inlineContentClientFileUrl,
180
+ )};
181
+
182
+ const inlineContent = new __InlineContent__(${cssText}, { type: "text/css" });
183
+ const stylesheet = new CSSStyleSheet();
184
+ stylesheet.replaceSync(inlineContent.text);
185
+ export default stylesheet;`,
186
+ contentType: "text/javascript",
187
+ type: "js_module",
188
+ originalUrl: cssUrlInfo.originalUrl,
189
+ originalContent: cssUrlInfo.originalContent,
190
+ data: cssUrlInfo.data,
191
+ };
192
+ },
193
+ };
194
+
195
+ const asTextModule = {
196
+ name: `jsenv:as_text_module`,
197
+ appliesDuring: "*",
198
+ fetchUrlContent: async (urlInfo, context) => {
199
+ const [textReference, textUrlInfo] = context.getWithoutSearchParam({
200
+ urlInfo,
201
+ context,
202
+ searchParam: "as_text_module",
203
+ expectedType: "text",
204
+ });
205
+ if (!textReference) {
206
+ return null;
207
+ }
208
+ await context.fetchUrlContent(textUrlInfo, {
209
+ reference: textReference,
210
+ });
211
+ if (context.dev) {
212
+ context.referenceUtils.found({
213
+ type: "js_import",
214
+ subtype: textReference.subtype,
215
+ specifier: textReference.url,
216
+ expectedType: "js_module",
217
+ });
218
+ } else if (context.build && textUrlInfo.dependents.size === 0) {
219
+ context.urlGraph.deleteUrlInfo(textUrlInfo.url);
220
+ }
221
+ const textPlain = JS_QUOTES.escapeSpecialChars(urlInfo.content, {
222
+ // If template string is choosen and runtime do not support template literals
223
+ // it's ok because "jsenv:new_inline_content" plugin executes after this one
224
+ // and convert template strings into raw strings
225
+ canUseTemplateString: true,
226
+ });
227
+ return {
228
+ content: `import ${JSON.stringify(
229
+ context.referenceUtils.inlineContentClientFileUrl,
230
+ )};
231
+
232
+ const inlineContent = new InlineContent(${textPlain}, { type: "text/plain" });
233
+ export default inlineContent.text;`,
234
+ contentType: "text/javascript",
235
+ type: "js_module",
236
+ originalUrl: textUrlInfo.originalUrl,
237
+ originalContent: textUrlInfo.originalContent,
238
+ data: textUrlInfo.data,
239
+ };
240
+ },
241
+ };
242
+
243
+ return [asJsonModule, asCssModule, asTextModule];
244
+ };
@@ -0,0 +1,48 @@
1
+ import { createMagicSource } from "@jsenv/sourcemap";
2
+
3
+ export const jsenvPluginImportMetaResolve = () => {
4
+ return {
5
+ name: "jsenv:import_meta_resolve",
6
+ appliesDuring: "*",
7
+ init: (context) => {
8
+ if (context.isSupportedOnCurrentClients("import_meta_resolve")) {
9
+ return false;
10
+ }
11
+ // keep it untouched, systemjs will handle it
12
+ if (context.systemJsTranspilation) {
13
+ return false;
14
+ }
15
+ return true;
16
+ },
17
+ transformUrlContent: {
18
+ js_module: async (urlInfo, context) => {
19
+ const magicSource = createMagicSource(urlInfo.content);
20
+ context.referenceUtils._references.forEach((ref) => {
21
+ if (ref.subtype === "import_meta_resolve") {
22
+ const originalSpecifierLength = Buffer.byteLength(ref.specifier);
23
+ const specifierLength = Buffer.byteLength(
24
+ ref.generatedSpecifier.slice(1, -1), // remove `"` around
25
+ );
26
+ const specifierLengthDiff =
27
+ specifierLength - originalSpecifierLength;
28
+ const end = ref.node.end + specifierLengthDiff;
29
+ magicSource.replace({
30
+ start: ref.node.start,
31
+ end,
32
+ replacement: `new URL(${ref.generatedSpecifier}, import.meta.url).href`,
33
+ });
34
+ const currentLengthBeforeSpecifier = "import.meta.resolve(".length;
35
+ const newLengthBeforeSpecifier = "new URL(".length;
36
+ const lengthDiff =
37
+ currentLengthBeforeSpecifier - newLengthBeforeSpecifier;
38
+ ref.specifierColumn -= lengthDiff;
39
+ ref.specifierStart -= lengthDiff;
40
+ ref.specifierEnd =
41
+ ref.specifierStart + Buffer.byteLength(ref.generatedSpecifier);
42
+ }
43
+ });
44
+ return magicSource.toContentAndSourcemap();
45
+ },
46
+ },
47
+ };
48
+ };
@@ -0,0 +1,136 @@
1
+ /*
2
+ * - propagate "?js_module_fallback" query string param on urls
3
+ * - perform conversion from js module to js classic when url uses "?js_module_fallback"
4
+ */
5
+
6
+ import { injectQueryParams } from "@jsenv/urls";
7
+ import { convertJsModuleToJsClassic } from "@jsenv/js-module-fallback";
8
+
9
+ export const jsenvPluginJsModuleConversion = ({
10
+ systemJsInjection,
11
+ systemJsClientFileUrl,
12
+ generateJsClassicFilename,
13
+ }) => {
14
+ const isReferencingJsModule = (reference) => {
15
+ if (
16
+ reference.type === "js_import" ||
17
+ reference.subtype === "system_register_arg" ||
18
+ reference.subtype === "system_import_arg"
19
+ ) {
20
+ return true;
21
+ }
22
+ if (reference.type === "js_url" && reference.expectedType === "js_module") {
23
+ return true;
24
+ }
25
+ return false;
26
+ };
27
+
28
+ const shouldPropagateJsModuleConversion = (reference, context) => {
29
+ if (isReferencingJsModule(reference, context)) {
30
+ const parentUrlInfo = context.urlGraph.getUrlInfo(reference.parentUrl);
31
+ if (!parentUrlInfo) {
32
+ return false;
33
+ }
34
+ const parentGotAsJsClassic = new URL(parentUrlInfo.url).searchParams.has(
35
+ "js_module_fallback",
36
+ );
37
+ return parentGotAsJsClassic;
38
+ }
39
+ return false;
40
+ };
41
+
42
+ const markAsJsClassicProxy = (reference) => {
43
+ reference.expectedType = "js_classic";
44
+ reference.filename = generateJsClassicFilename(reference.url);
45
+ };
46
+
47
+ const turnIntoJsClassicProxy = (reference) => {
48
+ const urlTransformed = injectQueryParams(reference.url, {
49
+ js_module_fallback: "",
50
+ });
51
+ markAsJsClassicProxy(reference);
52
+ return urlTransformed;
53
+ };
54
+
55
+ return {
56
+ name: "jsenv:js_module_conversion",
57
+ appliesDuring: "*",
58
+ redirectReference: (reference, context) => {
59
+ if (reference.searchParams.has("js_module_fallback")) {
60
+ markAsJsClassicProxy(reference);
61
+ return null;
62
+ }
63
+ // We want to propagate transformation of js module to js classic to:
64
+ // - import specifier (static/dynamic import + re-export)
65
+ // - url specifier when inside System.register/_context.import()
66
+ // (because it's the transpiled equivalent of static and dynamic imports)
67
+ // And not other references otherwise we could try to transform inline resources
68
+ // or specifiers inside new URL()...
69
+ if (shouldPropagateJsModuleConversion(reference, context)) {
70
+ return turnIntoJsClassicProxy(reference, context);
71
+ }
72
+ return null;
73
+ },
74
+ fetchUrlContent: async (urlInfo, context) => {
75
+ const [jsModuleReference, jsModuleUrlInfo] =
76
+ context.getWithoutSearchParam({
77
+ urlInfo,
78
+ context,
79
+ searchParam: "js_module_fallback",
80
+ // override the expectedType to "js_module"
81
+ // because when there is ?js_module_fallback it means the underlying resource
82
+ // is a js_module
83
+ expectedType: "js_module",
84
+ });
85
+ if (!jsModuleReference) {
86
+ return null;
87
+ }
88
+ await context.fetchUrlContent(jsModuleUrlInfo, {
89
+ reference: jsModuleReference,
90
+ });
91
+ if (context.dev) {
92
+ context.referenceUtils.found({
93
+ type: "js_import",
94
+ subtype: jsModuleReference.subtype,
95
+ specifier: jsModuleReference.url,
96
+ expectedType: "js_module",
97
+ });
98
+ } else if (context.build && jsModuleUrlInfo.dependents.size === 0) {
99
+ context.urlGraph.deleteUrlInfo(jsModuleUrlInfo.url);
100
+ }
101
+
102
+ let outputFormat;
103
+ if (urlInfo.isEntryPoint && !jsModuleUrlInfo.data.usesImport) {
104
+ // if it's an entry point without dependency (it does not use import)
105
+ // then we can use UMD
106
+ outputFormat = "umd";
107
+ } else {
108
+ // otherwise we have to use system in case it's imported
109
+ // by an other file (for entry points)
110
+ // or to be able to import when it uses import
111
+ outputFormat = "system";
112
+ }
113
+ urlInfo.data.jsClassicFormat = outputFormat;
114
+ const { content, sourcemap } = await convertJsModuleToJsClassic({
115
+ rootDirectoryUrl: context.rootDirectoryUrl,
116
+ systemJsInjection,
117
+ systemJsClientFileUrl,
118
+ input: jsModuleUrlInfo.content,
119
+ inputIsEntryPoint: urlInfo.isEntryPoint,
120
+ inputSourcemap: jsModuleUrlInfo.sourcemap,
121
+ inputUrl: jsModuleUrlInfo.url,
122
+ outputUrl: jsModuleUrlInfo.generatedUrl,
123
+ outputFormat,
124
+ });
125
+ return {
126
+ content,
127
+ contentType: "text/javascript",
128
+ type: "js_classic",
129
+ originalUrl: jsModuleUrlInfo.originalUrl,
130
+ originalContent: jsModuleUrlInfo.originalContent,
131
+ sourcemap,
132
+ data: jsModuleUrlInfo.data,
133
+ };
134
+ },
135
+ };
136
+ };
@@ -0,0 +1,46 @@
1
+ import { urlToFilename } from "@jsenv/urls";
2
+ import { systemJsClientFileUrlDefault } from "@jsenv/js-module-fallback";
3
+
4
+ import { jsenvPluginJsModuleConversion } from "./jsenv_plugin_js_module_conversion.js";
5
+ import { jsenvPluginJsModuleFallbackInsideHtml } from "./jsenv_plugin_js_module_fallback_inside_html.js";
6
+ import { jsenvPluginJsModuleFallbackOnWorkers } from "./jsenv_plugin_js_module_fallback_on_workers.js";
7
+
8
+ export const jsenvPluginJsModuleFallback = ({
9
+ systemJsInjection = true,
10
+ systemJsClientFileUrl = systemJsClientFileUrlDefault,
11
+ }) => {
12
+ return [
13
+ jsenvPluginJsModuleFallbackInsideHtml({
14
+ systemJsInjection,
15
+ systemJsClientFileUrl,
16
+ }),
17
+ jsenvPluginJsModuleFallbackOnWorkers(),
18
+ jsenvPluginJsModuleConversion({
19
+ systemJsInjection,
20
+ systemJsClientFileUrl,
21
+ generateJsClassicFilename,
22
+ }),
23
+ ];
24
+ };
25
+
26
+ const generateJsClassicFilename = (url) => {
27
+ const filename = urlToFilename(url);
28
+ let [basename, extension] = splitFileExtension(filename);
29
+ const { searchParams } = new URL(url);
30
+ if (
31
+ searchParams.has("as_json_module") ||
32
+ searchParams.has("as_css_module") ||
33
+ searchParams.has("as_text_module")
34
+ ) {
35
+ extension = ".js";
36
+ }
37
+ return `${basename}.nomodule${extension}`;
38
+ };
39
+
40
+ const splitFileExtension = (filename) => {
41
+ const dotLastIndex = filename.lastIndexOf(".");
42
+ if (dotLastIndex === -1) {
43
+ return [filename, ""];
44
+ }
45
+ return [filename.slice(0, dotLastIndex), filename.slice(dotLastIndex)];
46
+ };