@vitejs/plugin-legacy 6.1.0 → 7.0.0-beta.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.
package/dist/index.cjs DELETED
@@ -1,864 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const path = require('node:path');
6
- const crypto = require('node:crypto');
7
- const node_module = require('node:module');
8
- const node_url = require('node:url');
9
- const vite = require('vite');
10
- const MagicString = require('magic-string');
11
- const browserslist = require('browserslist');
12
-
13
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
14
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
15
-
16
- const path__default = /*#__PURE__*/_interopDefaultCompat(path);
17
- const crypto__default = /*#__PURE__*/_interopDefaultCompat(crypto);
18
- const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
19
- const browserslist__default = /*#__PURE__*/_interopDefaultCompat(browserslist);
20
-
21
- function getDefaultExportFromCjs (x) {
22
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
23
- }
24
-
25
- var picocolors = {exports: {}};
26
-
27
- var hasRequiredPicocolors;
28
-
29
- function requirePicocolors () {
30
- if (hasRequiredPicocolors) return picocolors.exports;
31
- hasRequiredPicocolors = 1;
32
- let p = process || {}, argv = p.argv || [], env = p.env || {};
33
- let isColorSupported =
34
- !(!!env.NO_COLOR || argv.includes("--no-color")) &&
35
- (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
36
-
37
- let formatter = (open, close, replace = open) =>
38
- input => {
39
- let string = "" + input, index = string.indexOf(close, open.length);
40
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
41
- };
42
-
43
- let replaceClose = (string, close, replace, index) => {
44
- let result = "", cursor = 0;
45
- do {
46
- result += string.substring(cursor, index) + replace;
47
- cursor = index + close.length;
48
- index = string.indexOf(close, cursor);
49
- } while (~index)
50
- return result + string.substring(cursor)
51
- };
52
-
53
- let createColors = (enabled = isColorSupported) => {
54
- let f = enabled ? formatter : () => String;
55
- return {
56
- isColorSupported: enabled,
57
- reset: f("\x1b[0m", "\x1b[0m"),
58
- bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
59
- dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
60
- italic: f("\x1b[3m", "\x1b[23m"),
61
- underline: f("\x1b[4m", "\x1b[24m"),
62
- inverse: f("\x1b[7m", "\x1b[27m"),
63
- hidden: f("\x1b[8m", "\x1b[28m"),
64
- strikethrough: f("\x1b[9m", "\x1b[29m"),
65
-
66
- black: f("\x1b[30m", "\x1b[39m"),
67
- red: f("\x1b[31m", "\x1b[39m"),
68
- green: f("\x1b[32m", "\x1b[39m"),
69
- yellow: f("\x1b[33m", "\x1b[39m"),
70
- blue: f("\x1b[34m", "\x1b[39m"),
71
- magenta: f("\x1b[35m", "\x1b[39m"),
72
- cyan: f("\x1b[36m", "\x1b[39m"),
73
- white: f("\x1b[37m", "\x1b[39m"),
74
- gray: f("\x1b[90m", "\x1b[39m"),
75
-
76
- bgBlack: f("\x1b[40m", "\x1b[49m"),
77
- bgRed: f("\x1b[41m", "\x1b[49m"),
78
- bgGreen: f("\x1b[42m", "\x1b[49m"),
79
- bgYellow: f("\x1b[43m", "\x1b[49m"),
80
- bgBlue: f("\x1b[44m", "\x1b[49m"),
81
- bgMagenta: f("\x1b[45m", "\x1b[49m"),
82
- bgCyan: f("\x1b[46m", "\x1b[49m"),
83
- bgWhite: f("\x1b[47m", "\x1b[49m"),
84
-
85
- blackBright: f("\x1b[90m", "\x1b[39m"),
86
- redBright: f("\x1b[91m", "\x1b[39m"),
87
- greenBright: f("\x1b[92m", "\x1b[39m"),
88
- yellowBright: f("\x1b[93m", "\x1b[39m"),
89
- blueBright: f("\x1b[94m", "\x1b[39m"),
90
- magentaBright: f("\x1b[95m", "\x1b[39m"),
91
- cyanBright: f("\x1b[96m", "\x1b[39m"),
92
- whiteBright: f("\x1b[97m", "\x1b[39m"),
93
-
94
- bgBlackBright: f("\x1b[100m", "\x1b[49m"),
95
- bgRedBright: f("\x1b[101m", "\x1b[49m"),
96
- bgGreenBright: f("\x1b[102m", "\x1b[49m"),
97
- bgYellowBright: f("\x1b[103m", "\x1b[49m"),
98
- bgBlueBright: f("\x1b[104m", "\x1b[49m"),
99
- bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
100
- bgCyanBright: f("\x1b[106m", "\x1b[49m"),
101
- bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
102
- }
103
- };
104
-
105
- picocolors.exports = createColors();
106
- picocolors.exports.createColors = createColors;
107
- return picocolors.exports;
108
- }
109
-
110
- var picocolorsExports = /*@__PURE__*/ requirePicocolors();
111
- const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
112
-
113
- const safari10NoModuleFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`;
114
- const legacyPolyfillId = "vite-legacy-polyfill";
115
- const legacyEntryId = "vite-legacy-entry";
116
- const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`;
117
- const detectModernBrowserVarName = "__vite_is_modern_browser";
118
- const detectModernBrowserDetector = `import.meta.url;import("_").catch(()=>1);(async function*(){})().next()`;
119
- const detectModernBrowserCode = `${detectModernBrowserDetector};if(location.protocol!="file:"){window.${detectModernBrowserVarName}=true}`;
120
- const dynamicFallbackInlineCode = `!function(){if(window.${detectModernBrowserVarName})return;console.warn("vite: loading legacy chunks, syntax error above and the same error below should be ignored");var e=document.getElementById("${legacyPolyfillId}"),n=document.createElement("script");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`;
121
- const modernChunkLegacyGuard = `export function __vite_legacy_guard(){${detectModernBrowserDetector}};`;
122
-
123
- let babel;
124
- async function loadBabel() {
125
- return babel ??= import('@babel/core');
126
- }
127
- const { loadConfig: browserslistLoadConfig } = browserslist__default;
128
- function toOutputFilePathInHtml(filename, type, hostId, hostType, config, toRelative) {
129
- const { renderBuiltUrl } = config.experimental;
130
- let relative = config.base === "" || config.base === "./";
131
- if (renderBuiltUrl) {
132
- const result = renderBuiltUrl(filename, {
133
- hostId,
134
- hostType,
135
- type,
136
- ssr: !!config.build.ssr
137
- });
138
- if (typeof result === "object") {
139
- if (result.runtime) {
140
- throw new Error(
141
- `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`
142
- );
143
- }
144
- if (typeof result.relative === "boolean") {
145
- relative = result.relative;
146
- }
147
- } else if (result) {
148
- return result;
149
- }
150
- }
151
- if (relative && !config.build.ssr) {
152
- return toRelative(filename, hostId);
153
- } else {
154
- return joinUrlSegments(config.decodedBase, filename);
155
- }
156
- }
157
- function getBaseInHTML(urlRelativePath, config) {
158
- return config.base === "./" || config.base === "" ? path__default.posix.join(
159
- path__default.posix.relative(urlRelativePath, "").slice(0, -2),
160
- "./"
161
- ) : config.base;
162
- }
163
- function joinUrlSegments(a, b) {
164
- if (!a || !b) {
165
- return a || b || "";
166
- }
167
- if (a.endsWith("/")) {
168
- a = a.substring(0, a.length - 1);
169
- }
170
- if (b[0] !== "/") {
171
- b = "/" + b;
172
- }
173
- return a + b;
174
- }
175
- function toAssetPathFromHtml(filename, htmlPath, config) {
176
- const relativeUrlPath = vite.normalizePath(path__default.relative(config.root, htmlPath));
177
- const toRelative = (filename2, _hostId) => getBaseInHTML(relativeUrlPath, config) + filename2;
178
- return toOutputFilePathInHtml(
179
- filename,
180
- "asset",
181
- htmlPath,
182
- "html",
183
- config,
184
- toRelative
185
- );
186
- }
187
- const legacyEnvVarMarker = `__VITE_IS_LEGACY__`;
188
- const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
189
- const nonLeadingHashInFileNameRE = /[^/]+\[hash(?::\d+)?\]/;
190
- const prefixedHashInFileNameRE = /\W?\[hash(?::\d+)?\]/;
191
- function viteLegacyPlugin(options = {}) {
192
- let config;
193
- let targets;
194
- let modernTargets;
195
- const modernTargetsEsbuild = [
196
- "es2020",
197
- "edge79",
198
- "firefox67",
199
- "chrome64",
200
- "safari12"
201
- ];
202
- const modernTargetsBabel = "edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12";
203
- const genLegacy = options.renderLegacyChunks !== false;
204
- const genModern = options.renderModernChunks !== false;
205
- if (!genLegacy && !genModern) {
206
- throw new Error(
207
- "`renderLegacyChunks` and `renderModernChunks` cannot be both false"
208
- );
209
- }
210
- const debugFlags = (process.env.DEBUG || "").split(",");
211
- const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy");
212
- const assumptions = options.assumptions || {};
213
- const facadeToLegacyChunkMap = /* @__PURE__ */ new Map();
214
- const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map();
215
- const facadeToModernPolyfillMap = /* @__PURE__ */ new Map();
216
- const modernPolyfills = /* @__PURE__ */ new Set();
217
- const legacyPolyfills = /* @__PURE__ */ new Set();
218
- const outputToChunkFileNameToPolyfills = /* @__PURE__ */ new WeakMap();
219
- if (Array.isArray(options.modernPolyfills) && genModern) {
220
- options.modernPolyfills.forEach((i) => {
221
- modernPolyfills.add(
222
- i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`
223
- );
224
- });
225
- }
226
- if (Array.isArray(options.additionalModernPolyfills)) {
227
- options.additionalModernPolyfills.forEach((i) => {
228
- modernPolyfills.add(i);
229
- });
230
- }
231
- if (Array.isArray(options.polyfills)) {
232
- options.polyfills.forEach((i) => {
233
- if (i.startsWith(`regenerator`)) {
234
- legacyPolyfills.add(`regenerator-runtime/runtime.js`);
235
- } else {
236
- legacyPolyfills.add(
237
- i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`
238
- );
239
- }
240
- });
241
- }
242
- if (Array.isArray(options.additionalLegacyPolyfills)) {
243
- options.additionalLegacyPolyfills.forEach((i) => {
244
- legacyPolyfills.add(i);
245
- });
246
- }
247
- let overriddenBuildTarget = false;
248
- let overriddenDefaultModernTargets = false;
249
- const legacyConfigPlugin = {
250
- name: "vite:legacy-config",
251
- async config(config2, env) {
252
- if (env.command === "build" && !config2.build?.ssr) {
253
- if (!config2.build) {
254
- config2.build = {};
255
- }
256
- if (!config2.build.cssTarget) {
257
- config2.build.cssTarget = "chrome61";
258
- }
259
- if (genLegacy) {
260
- overriddenBuildTarget = config2.build.target !== void 0;
261
- overriddenDefaultModernTargets = options.modernTargets !== void 0;
262
- if (options.modernTargets) {
263
- const { default: browserslistToEsbuild } = await import('browserslist-to-esbuild');
264
- config2.build.target = browserslistToEsbuild(options.modernTargets);
265
- } else {
266
- config2.build.target = modernTargetsEsbuild;
267
- }
268
- }
269
- }
270
- return {
271
- define: {
272
- "import.meta.env.LEGACY": env.command === "serve" || config2.build?.ssr ? false : legacyEnvVarMarker
273
- }
274
- };
275
- },
276
- configResolved(config2) {
277
- if (overriddenBuildTarget) {
278
- config2.logger.warn(
279
- colors.yellow(
280
- `plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`
281
- )
282
- );
283
- }
284
- if (overriddenDefaultModernTargets) {
285
- config2.logger.warn(
286
- colors.yellow(
287
- `plugin-legacy 'modernTargets' option overrode the builtin targets of modern chunks. Some versions of browsers between legacy and modern may not be supported.`
288
- )
289
- );
290
- }
291
- if (config2.isWorker) {
292
- config2.logger.warn(
293
- colors.yellow(
294
- `plugin-legacy should not be passed to 'worker.plugins'. Pass to 'plugins' instead. Note that generating legacy chunks for workers are not supported by plugin-legacy.`
295
- )
296
- );
297
- }
298
- }
299
- };
300
- const legacyGenerateBundlePlugin = {
301
- name: "vite:legacy-generate-polyfill-chunk",
302
- apply: "build",
303
- async generateBundle(opts, bundle) {
304
- if (config.build.ssr) {
305
- return;
306
- }
307
- const chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
308
- if (chunkFileNameToPolyfills == null) {
309
- throw new Error(
310
- "Internal @vitejs/plugin-legacy error: discovered polyfills should exist"
311
- );
312
- }
313
- if (!isLegacyBundle(bundle, opts)) {
314
- for (const { modern } of chunkFileNameToPolyfills.values()) {
315
- modern.forEach((p) => modernPolyfills.add(p));
316
- }
317
- if (!modernPolyfills.size) {
318
- return;
319
- }
320
- if (isDebug) {
321
- console.log(
322
- `[@vitejs/plugin-legacy] modern polyfills:`,
323
- modernPolyfills
324
- );
325
- }
326
- await buildPolyfillChunk(
327
- config.mode,
328
- modernPolyfills,
329
- bundle,
330
- facadeToModernPolyfillMap,
331
- config.build,
332
- "es",
333
- opts,
334
- true,
335
- genLegacy
336
- );
337
- return;
338
- }
339
- if (!genLegacy) {
340
- return;
341
- }
342
- for (const { legacy } of chunkFileNameToPolyfills.values()) {
343
- legacy.forEach((p) => legacyPolyfills.add(p));
344
- }
345
- if (options.polyfills !== false) {
346
- await detectPolyfills(
347
- `Promise.resolve(); Promise.all();`,
348
- targets,
349
- assumptions,
350
- legacyPolyfills
351
- );
352
- }
353
- if (legacyPolyfills.size || !options.externalSystemJS) {
354
- if (isDebug) {
355
- console.log(
356
- `[@vitejs/plugin-legacy] legacy polyfills:`,
357
- legacyPolyfills
358
- );
359
- }
360
- await buildPolyfillChunk(
361
- config.mode,
362
- legacyPolyfills,
363
- bundle,
364
- facadeToLegacyPolyfillMap,
365
- // force using terser for legacy polyfill minification, since esbuild
366
- // isn't legacy-safe
367
- config.build,
368
- "iife",
369
- opts,
370
- options.externalSystemJS
371
- );
372
- }
373
- }
374
- };
375
- const legacyPostPlugin = {
376
- name: "vite:legacy-post-process",
377
- enforce: "post",
378
- apply: "build",
379
- renderStart(opts) {
380
- outputToChunkFileNameToPolyfills.set(opts, null);
381
- },
382
- configResolved(_config) {
383
- if (_config.build.lib) {
384
- throw new Error("@vitejs/plugin-legacy does not support library mode.");
385
- }
386
- config = _config;
387
- modernTargets = options.modernTargets || modernTargetsBabel;
388
- if (isDebug) {
389
- console.log(`[@vitejs/plugin-legacy] modernTargets:`, modernTargets);
390
- }
391
- if (!genLegacy || config.build.ssr) {
392
- return;
393
- }
394
- targets = options.targets || browserslistLoadConfig({ path: config.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR";
395
- if (isDebug) {
396
- console.log(`[@vitejs/plugin-legacy] targets:`, targets);
397
- }
398
- const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => {
399
- if (!fileNames) {
400
- return path__default.posix.join(config.build.assetsDir, defaultFileName);
401
- }
402
- return (chunkInfo) => {
403
- let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
404
- if (fileName.includes("[name]")) {
405
- fileName = fileName.replace("[name]", "[name]-legacy");
406
- } else if (nonLeadingHashInFileNameRE.test(fileName)) {
407
- fileName = fileName.replace(prefixedHashInFileNameRE, "-legacy$&");
408
- } else {
409
- fileName = fileName.replace(/(.+?)\.(.+)/, "$1-legacy.$2");
410
- }
411
- return fileName;
412
- };
413
- };
414
- const createLegacyOutput = (options2 = {}) => {
415
- return {
416
- ...options2,
417
- format: "system",
418
- entryFileNames: getLegacyOutputFileName(options2.entryFileNames),
419
- chunkFileNames: getLegacyOutputFileName(options2.chunkFileNames)
420
- };
421
- };
422
- const { rollupOptions } = config.build;
423
- const { output } = rollupOptions;
424
- if (Array.isArray(output)) {
425
- rollupOptions.output = [
426
- ...output.map(createLegacyOutput),
427
- ...genModern ? output : []
428
- ];
429
- } else {
430
- rollupOptions.output = [
431
- createLegacyOutput(output),
432
- ...genModern ? [output || {}] : []
433
- ];
434
- }
435
- },
436
- async renderChunk(raw, chunk, opts, { chunks }) {
437
- if (config.build.ssr) {
438
- return null;
439
- }
440
- let chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
441
- if (chunkFileNameToPolyfills == null) {
442
- chunkFileNameToPolyfills = /* @__PURE__ */ new Map();
443
- for (const fileName in chunks) {
444
- chunkFileNameToPolyfills.set(fileName, {
445
- modern: /* @__PURE__ */ new Set(),
446
- legacy: /* @__PURE__ */ new Set()
447
- });
448
- }
449
- outputToChunkFileNameToPolyfills.set(opts, chunkFileNameToPolyfills);
450
- }
451
- const polyfillsDiscovered = chunkFileNameToPolyfills.get(chunk.fileName);
452
- if (polyfillsDiscovered == null) {
453
- throw new Error(
454
- `Internal @vitejs/plugin-legacy error: discovered polyfills for ${chunk.fileName} should exist`
455
- );
456
- }
457
- if (!isLegacyChunk(chunk, opts)) {
458
- if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) {
459
- await detectPolyfills(
460
- raw,
461
- modernTargets,
462
- assumptions,
463
- polyfillsDiscovered.modern
464
- );
465
- }
466
- const ms = new MagicString__default(raw);
467
- if (genLegacy && chunk.isEntry) {
468
- ms.prepend(modernChunkLegacyGuard);
469
- }
470
- if (raw.includes(legacyEnvVarMarker)) {
471
- const re = new RegExp(legacyEnvVarMarker, "g");
472
- let match;
473
- while (match = re.exec(raw)) {
474
- ms.overwrite(
475
- match.index,
476
- match.index + legacyEnvVarMarker.length,
477
- `false`
478
- );
479
- }
480
- }
481
- if (config.build.sourcemap) {
482
- return {
483
- code: ms.toString(),
484
- map: ms.generateMap({ hires: "boundary" })
485
- };
486
- }
487
- return {
488
- code: ms.toString()
489
- };
490
- }
491
- if (!genLegacy) {
492
- return null;
493
- }
494
- opts.__vite_skip_esbuild__ = true;
495
- opts.__vite_force_terser__ = true;
496
- opts.__vite_skip_asset_emit__ = true;
497
- const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
498
- const sourceMaps = !!config.build.sourcemap;
499
- const babel2 = await loadBabel();
500
- const result = babel2.transform(raw, {
501
- babelrc: false,
502
- configFile: false,
503
- compact: !!config.build.minify,
504
- sourceMaps,
505
- inputSourceMap: void 0,
506
- assumptions,
507
- presets: [
508
- // forcing our plugin to run before preset-env by wrapping it in a
509
- // preset so we can catch the injected import statements...
510
- [
511
- () => ({
512
- plugins: [
513
- recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy),
514
- replaceLegacyEnvBabelPlugin(),
515
- wrapIIFEBabelPlugin()
516
- ]
517
- })
518
- ],
519
- [
520
- (await import('@babel/preset-env')).default,
521
- createBabelPresetEnvOptions(targets, { needPolyfills })
522
- ]
523
- ]
524
- });
525
- if (result) return { code: result.code, map: result.map };
526
- return null;
527
- },
528
- transformIndexHtml(html, { chunk }) {
529
- if (config.build.ssr) return;
530
- if (!chunk) return;
531
- if (chunk.fileName.includes("-legacy")) {
532
- facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
533
- if (genModern) {
534
- return;
535
- }
536
- }
537
- if (!genModern) {
538
- html = html.replace(/<script type="module".*?<\/script>/g, "");
539
- }
540
- const tags = [];
541
- const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
542
- if (genModern) {
543
- const modernPolyfillFilename = facadeToModernPolyfillMap.get(
544
- chunk.facadeModuleId
545
- );
546
- if (modernPolyfillFilename) {
547
- tags.push({
548
- tag: "script",
549
- attrs: {
550
- type: "module",
551
- crossorigin: true,
552
- src: toAssetPathFromHtml(
553
- modernPolyfillFilename,
554
- chunk.facadeModuleId,
555
- config
556
- )
557
- }
558
- });
559
- } else if (modernPolyfills.size) {
560
- throw new Error(
561
- `No corresponding modern polyfill chunk found for ${htmlFilename}`
562
- );
563
- }
564
- }
565
- if (!genLegacy) {
566
- return { html, tags };
567
- }
568
- if (genModern) {
569
- tags.push({
570
- tag: "script",
571
- attrs: { nomodule: genModern },
572
- children: safari10NoModuleFix,
573
- injectTo: "body"
574
- });
575
- }
576
- const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(
577
- chunk.facadeModuleId
578
- );
579
- if (legacyPolyfillFilename) {
580
- tags.push({
581
- tag: "script",
582
- attrs: {
583
- nomodule: genModern,
584
- crossorigin: true,
585
- id: legacyPolyfillId,
586
- src: toAssetPathFromHtml(
587
- legacyPolyfillFilename,
588
- chunk.facadeModuleId,
589
- config
590
- )
591
- },
592
- injectTo: "body"
593
- });
594
- } else if (legacyPolyfills.size) {
595
- throw new Error(
596
- `No corresponding legacy polyfill chunk found for ${htmlFilename}`
597
- );
598
- }
599
- const legacyEntryFilename = facadeToLegacyChunkMap.get(
600
- chunk.facadeModuleId
601
- );
602
- if (legacyEntryFilename) {
603
- tags.push({
604
- tag: "script",
605
- attrs: {
606
- nomodule: genModern,
607
- crossorigin: true,
608
- // we set the entry path on the element as an attribute so that the
609
- // script content will stay consistent - which allows using a constant
610
- // hash value for CSP.
611
- id: legacyEntryId,
612
- "data-src": toAssetPathFromHtml(
613
- legacyEntryFilename,
614
- chunk.facadeModuleId,
615
- config
616
- )
617
- },
618
- children: systemJSInlineCode,
619
- injectTo: "body"
620
- });
621
- } else {
622
- throw new Error(
623
- `No corresponding legacy entry chunk found for ${htmlFilename}`
624
- );
625
- }
626
- if (legacyPolyfillFilename && legacyEntryFilename && genModern) {
627
- tags.push({
628
- tag: "script",
629
- attrs: { type: "module" },
630
- children: detectModernBrowserCode,
631
- injectTo: "head"
632
- });
633
- tags.push({
634
- tag: "script",
635
- attrs: { type: "module" },
636
- children: dynamicFallbackInlineCode,
637
- injectTo: "head"
638
- });
639
- }
640
- return {
641
- html,
642
- tags
643
- };
644
- },
645
- generateBundle(opts, bundle) {
646
- if (config.build.ssr) {
647
- return;
648
- }
649
- if (isLegacyBundle(bundle, opts) && genModern) {
650
- for (const name in bundle) {
651
- if (bundle[name].type === "asset" && !/.+\.map$/.test(name)) {
652
- delete bundle[name];
653
- }
654
- }
655
- }
656
- }
657
- };
658
- return [legacyConfigPlugin, legacyGenerateBundlePlugin, legacyPostPlugin];
659
- }
660
- async function detectPolyfills(code, targets, assumptions, list) {
661
- const babel2 = await loadBabel();
662
- const result = babel2.transform(code, {
663
- ast: true,
664
- babelrc: false,
665
- configFile: false,
666
- compact: false,
667
- assumptions,
668
- presets: [
669
- [
670
- (await import('@babel/preset-env')).default,
671
- createBabelPresetEnvOptions(targets, {})
672
- ]
673
- ]
674
- });
675
- for (const node of result.ast.program.body) {
676
- if (node.type === "ImportDeclaration") {
677
- const source = node.source.value;
678
- if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) {
679
- list.add(source);
680
- }
681
- }
682
- }
683
- }
684
- function createBabelPresetEnvOptions(targets, { needPolyfills = true }) {
685
- return {
686
- targets,
687
- bugfixes: true,
688
- loose: false,
689
- modules: false,
690
- useBuiltIns: needPolyfills ? "usage" : false,
691
- corejs: needPolyfills ? {
692
- version: _require("core-js/package.json").version,
693
- proposals: false
694
- } : void 0,
695
- shippedProposals: true,
696
- ignoreBrowserslistConfig: true
697
- };
698
- }
699
- async function buildPolyfillChunk(mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS, prependModenChunkLegacyGuard) {
700
- let { minify, assetsDir, sourcemap } = buildOptions;
701
- minify = minify ? "terser" : false;
702
- const res = await vite.build({
703
- mode,
704
- // so that everything is resolved from here
705
- root: path__default.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))),
706
- configFile: false,
707
- logLevel: "error",
708
- plugins: [
709
- polyfillsPlugin(imports, excludeSystemJS),
710
- prependModenChunkLegacyGuard && prependModenChunkLegacyGuardPlugin()
711
- ],
712
- build: {
713
- write: false,
714
- minify,
715
- assetsDir,
716
- sourcemap,
717
- rollupOptions: {
718
- input: {
719
- polyfills: polyfillId
720
- },
721
- output: {
722
- format,
723
- hashCharacters: rollupOutputOptions.hashCharacters,
724
- entryFileNames: rollupOutputOptions.entryFileNames,
725
- sourcemapBaseUrl: rollupOutputOptions.sourcemapBaseUrl
726
- }
727
- }
728
- },
729
- // Don't run esbuild for transpilation or minification
730
- // because we don't want to transpile code.
731
- esbuild: false,
732
- optimizeDeps: {
733
- esbuildOptions: {
734
- // If a value above 'es5' is set, esbuild injects helper functions which uses es2015 features.
735
- // This limits the input code not to include es2015+ codes.
736
- // But core-js is the only dependency which includes commonjs code
737
- // and core-js doesn't include es2015+ codes.
738
- target: "es5"
739
- }
740
- }
741
- });
742
- const _polyfillChunk = Array.isArray(res) ? res[0] : res;
743
- if (!("output" in _polyfillChunk)) return;
744
- const polyfillChunk = _polyfillChunk.output.find(
745
- (chunk) => chunk.type === "chunk" && chunk.isEntry
746
- );
747
- for (const key in bundle) {
748
- const chunk = bundle[key];
749
- if (chunk.type === "chunk" && chunk.facadeModuleId) {
750
- facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
751
- }
752
- }
753
- bundle[polyfillChunk.fileName] = polyfillChunk;
754
- if (polyfillChunk.sourcemapFileName) {
755
- const polyfillChunkMapAsset = _polyfillChunk.output.find(
756
- (chunk) => chunk.type === "asset" && chunk.fileName === polyfillChunk.sourcemapFileName
757
- );
758
- if (polyfillChunkMapAsset) {
759
- bundle[polyfillChunk.sourcemapFileName] = polyfillChunkMapAsset;
760
- }
761
- }
762
- }
763
- const polyfillId = "\0vite/legacy-polyfills";
764
- function polyfillsPlugin(imports, excludeSystemJS) {
765
- return {
766
- name: "vite:legacy-polyfills",
767
- resolveId(id) {
768
- if (id === polyfillId) {
769
- return id;
770
- }
771
- },
772
- load(id) {
773
- if (id === polyfillId) {
774
- return [...imports].map((i) => `import ${JSON.stringify(i)};`).join("") + (excludeSystemJS ? "" : `import "systemjs/dist/s.min.js";`);
775
- }
776
- }
777
- };
778
- }
779
- function prependModenChunkLegacyGuardPlugin() {
780
- let sourceMapEnabled;
781
- return {
782
- name: "vite:legacy-prepend-moden-chunk-legacy-guard",
783
- configResolved(config) {
784
- sourceMapEnabled = !!config.build.sourcemap;
785
- },
786
- renderChunk(code) {
787
- if (!sourceMapEnabled) {
788
- return modernChunkLegacyGuard + code;
789
- }
790
- const ms = new MagicString__default(code);
791
- ms.prepend(modernChunkLegacyGuard);
792
- return {
793
- code: ms.toString(),
794
- map: ms.generateMap({ hires: "boundary" })
795
- };
796
- }
797
- };
798
- }
799
- function isLegacyChunk(chunk, options) {
800
- return options.format === "system" && chunk.fileName.includes("-legacy");
801
- }
802
- function isLegacyBundle(bundle, options) {
803
- if (options.format === "system") {
804
- const entryChunk = Object.values(bundle).find(
805
- (output) => output.type === "chunk" && output.isEntry
806
- );
807
- return !!entryChunk && entryChunk.fileName.includes("-legacy");
808
- }
809
- return false;
810
- }
811
- function recordAndRemovePolyfillBabelPlugin(polyfills) {
812
- return ({ types: t }) => ({
813
- name: "vite-remove-polyfill-import",
814
- post({ path: path2 }) {
815
- path2.get("body").forEach((p) => {
816
- if (t.isImportDeclaration(p.node)) {
817
- polyfills.add(p.node.source.value);
818
- p.remove();
819
- }
820
- });
821
- }
822
- });
823
- }
824
- function replaceLegacyEnvBabelPlugin() {
825
- return ({ types: t }) => ({
826
- name: "vite-replace-env-legacy",
827
- visitor: {
828
- Identifier(path2) {
829
- if (path2.node.name === legacyEnvVarMarker) {
830
- path2.replaceWith(t.booleanLiteral(true));
831
- }
832
- }
833
- }
834
- });
835
- }
836
- function wrapIIFEBabelPlugin() {
837
- return ({ types: t, template }) => {
838
- const buildIIFE = template(";(function(){%%body%%})();");
839
- return {
840
- name: "vite-wrap-iife",
841
- post({ path: path2 }) {
842
- if (!this.isWrapped) {
843
- this.isWrapped = true;
844
- path2.replaceWith(t.program(buildIIFE({ body: path2.node.body })));
845
- }
846
- }
847
- };
848
- };
849
- }
850
- const hash = (
851
- // eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
852
- crypto__default.hash ?? ((algorithm, data, outputEncoding) => crypto__default.createHash(algorithm).update(data).digest(outputEncoding))
853
- );
854
- const cspHashes = [
855
- safari10NoModuleFix,
856
- systemJSInlineCode,
857
- detectModernBrowserCode,
858
- dynamicFallbackInlineCode
859
- ].map((i) => hash("sha256", i, "base64"));
860
-
861
- module.exports = viteLegacyPlugin;
862
- module.exports.cspHashes = cspHashes;
863
- module.exports.default = viteLegacyPlugin;
864
- module.exports.detectPolyfills = detectPolyfills;