@vitejs/plugin-legacy 7.2.0 → 8.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.js CHANGED
@@ -2,7 +2,6 @@ import { createRequire } from "node:module";
2
2
  import path from "node:path";
3
3
  import crypto from "node:crypto";
4
4
  import { fileURLToPath } from "node:url";
5
- import * as vite from "vite";
6
5
  import { build, normalizePath } from "vite";
7
6
  import MagicString from "magic-string";
8
7
  import browserslist from "browserslist";
@@ -14,16 +13,18 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
13
  var __getOwnPropNames = Object.getOwnPropertyNames;
15
14
  var __getProtoOf = Object.getPrototypeOf;
16
15
  var __hasOwnProp = Object.prototype.hasOwnProperty;
17
- var __commonJS = (cb, mod) => function() {
18
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
- };
16
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
17
  var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
22
- key = keys[i];
23
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
24
- get: ((k) => from[k]).bind(null, key),
25
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
26
- });
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) {
22
+ __defProp(to, key, {
23
+ get: ((k) => from[k]).bind(null, key),
24
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
25
+ });
26
+ }
27
+ }
27
28
  }
28
29
  return to;
29
30
  };
@@ -34,7 +35,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
35
 
35
36
  //#endregion
36
37
  //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
37
- var require_picocolors = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js": ((exports, module) => {
38
+ var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
38
39
  let p = process || {}, argv = p.argv || [], env = p.env || {};
39
40
  let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
40
41
  let formatter = (open, close, replace = open) => (input) => {
@@ -99,10 +100,11 @@ var require_picocolors = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/
99
100
  };
100
101
  module.exports = createColors();
101
102
  module.exports.createColors = createColors;
102
- }) });
103
+ }));
103
104
 
104
105
  //#endregion
105
106
  //#region src/snippets.ts
107
+ var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
106
108
  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()}}();`;
107
109
  const legacyPolyfillId = "vite-legacy-polyfill";
108
110
  const legacyEntryId = "vite-legacy-entry";
@@ -115,7 +117,6 @@ const modernChunkLegacyGuard = `export function __vite_legacy_guard(){${detectMo
115
117
 
116
118
  //#endregion
117
119
  //#region src/index.ts
118
- var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
119
120
  let babel;
120
121
  async function loadBabel() {
121
122
  return babel ??= import("@babel/core");
@@ -165,11 +166,8 @@ const modernTargetsEsbuild = [
165
166
  "safari12"
166
167
  ];
167
168
  const modernTargetsBabel = "edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12";
169
+ const outputOptionsForLegacyChunks = /* @__PURE__ */ new WeakSet();
168
170
  function viteLegacyPlugin(options = {}) {
169
- if ("rolldownVersion" in vite) {
170
- const { default: viteLegacyPluginForRolldownVite } = _require("#legacy-for-rolldown-vite");
171
- return viteLegacyPluginForRolldownVite(options);
172
- }
173
171
  let config;
174
172
  let targets;
175
173
  const modernTargets = options.modernTargets || modernTargetsBabel;
@@ -201,247 +199,255 @@ function viteLegacyPlugin(options = {}) {
201
199
  let overriddenBuildTarget = false;
202
200
  let overriddenBuildTargetOnlyModern = false;
203
201
  let overriddenDefaultModernTargets = false;
204
- const legacyConfigPlugin = {
205
- name: "vite:legacy-config",
206
- async config(config$1, env$1) {
207
- if (env$1.command === "build" && !config$1.build?.ssr) {
208
- if (!config$1.build) config$1.build = {};
209
- if (genLegacy && !config$1.build.cssTarget) config$1.build.cssTarget = "chrome61";
210
- if (genLegacy) {
211
- overriddenBuildTarget = config$1.build.target !== void 0;
212
- overriddenDefaultModernTargets = options.modernTargets !== void 0;
213
- } else overriddenBuildTargetOnlyModern = config$1.build.target !== void 0;
214
- if (options.modernTargets) {
215
- const { default: browserslistToEsbuild } = await import("browserslist-to-esbuild");
216
- config$1.build.target = browserslistToEsbuild(options.modernTargets);
217
- } else config$1.build.target = modernTargetsEsbuild;
202
+ return [
203
+ {
204
+ name: "vite:legacy-config",
205
+ async config(config$1, env$1) {
206
+ if (env$1.command === "build" && !config$1.build?.ssr) {
207
+ if (!config$1.build) config$1.build = {};
208
+ if (genLegacy && !config$1.build.cssTarget) config$1.build.cssTarget = "chrome61";
209
+ if (genLegacy) {
210
+ overriddenBuildTarget = config$1.build.target !== void 0;
211
+ overriddenDefaultModernTargets = options.modernTargets !== void 0;
212
+ } else overriddenBuildTargetOnlyModern = config$1.build.target !== void 0;
213
+ if (options.modernTargets) {
214
+ const { default: browserslistToEsbuild } = await import("browserslist-to-esbuild");
215
+ config$1.build.target = browserslistToEsbuild(options.modernTargets);
216
+ } else config$1.build.target = modernTargetsEsbuild;
217
+ }
218
+ return { define: { "import.meta.env.LEGACY": env$1.command === "serve" || config$1.build?.ssr ? false : legacyEnvVarMarker } };
219
+ },
220
+ configResolved(config$1) {
221
+ if (overriddenBuildTarget) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`));
222
+ if (overriddenBuildTargetOnlyModern) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy overrode 'build.target'. You should pass 'modernTargets' as an option to this plugin with the list of browsers to support instead.`));
223
+ if (overriddenDefaultModernTargets) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy 'modernTargets' option overrode the builtin targets of modern chunks. Some versions of browsers between legacy and modern may not be supported.`));
224
+ if (config$1.isWorker) config$1.logger.warn(import_picocolors.default.yellow(`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.`));
218
225
  }
219
- return { define: { "import.meta.env.LEGACY": env$1.command === "serve" || config$1.build?.ssr ? false : legacyEnvVarMarker } };
220
226
  },
221
- configResolved(config$1) {
222
- if (overriddenBuildTarget) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`));
223
- if (overriddenBuildTargetOnlyModern) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy overrode 'build.target'. You should pass 'modernTargets' as an option to this plugin with the list of browsers to support instead.`));
224
- if (overriddenDefaultModernTargets) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy 'modernTargets' option overrode the builtin targets of modern chunks. Some versions of browsers between legacy and modern may not be supported.`));
225
- if (config$1.isWorker) config$1.logger.warn(import_picocolors.default.yellow(`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.`));
226
- }
227
- };
228
- const legacyGenerateBundlePlugin = {
229
- name: "vite:legacy-generate-polyfill-chunk",
230
- apply: "build",
231
- async generateBundle(opts, bundle) {
232
- if (config.build.ssr) return;
233
- const chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
234
- if (chunkFileNameToPolyfills == null) throw new Error("Internal @vitejs/plugin-legacy error: discovered polyfills should exist");
235
- if (!isLegacyBundle(bundle, opts)) {
236
- for (const { modern } of chunkFileNameToPolyfills.values()) modern.forEach((p$1) => modernPolyfills.add(p$1));
237
- if (!modernPolyfills.size) return;
238
- if (isDebug) console.log(`[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills);
239
- await buildPolyfillChunk(config.mode, modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, "es", opts, true, genLegacy);
240
- return;
241
- }
242
- if (!genLegacy) return;
243
- for (const { legacy } of chunkFileNameToPolyfills.values()) legacy.forEach((p$1) => legacyPolyfills.add(p$1));
244
- if (options.polyfills !== false) await detectPolyfills(`Promise.resolve(); Promise.all();`, targets, assumptions, legacyPolyfills);
245
- if (legacyPolyfills.size || !options.externalSystemJS) {
246
- if (isDebug) console.log(`[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills);
247
- await buildPolyfillChunk(config.mode, legacyPolyfills, bundle, facadeToLegacyPolyfillMap, config.build, "iife", opts, options.externalSystemJS);
227
+ {
228
+ name: "vite:legacy-generate-polyfill-chunk",
229
+ apply: "build",
230
+ async generateBundle(opts, bundle) {
231
+ if (config.build.ssr) return;
232
+ const chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
233
+ if (chunkFileNameToPolyfills == null) throw new Error("Internal @vitejs/plugin-legacy error: discovered polyfills should exist");
234
+ if (!isLegacyBundle(bundle)) {
235
+ for (const { modern } of chunkFileNameToPolyfills.values()) modern.forEach((p$1) => modernPolyfills.add(p$1));
236
+ if (!modernPolyfills.size) return;
237
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills);
238
+ await buildPolyfillChunk(this, config.mode, modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, "es", opts, true, genLegacy);
239
+ return;
240
+ }
241
+ if (!genLegacy) return;
242
+ for (const { legacy } of chunkFileNameToPolyfills.values()) legacy.forEach((p$1) => legacyPolyfills.add(p$1));
243
+ if (options.polyfills !== false) await detectPolyfills(`Promise.resolve(); Promise.all();`, targets, assumptions, legacyPolyfills);
244
+ if (legacyPolyfills.size || !options.externalSystemJS) {
245
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills);
246
+ await buildPolyfillChunk(this, config.mode, legacyPolyfills, bundle, facadeToLegacyPolyfillMap, config.build, "iife", opts, options.externalSystemJS);
247
+ }
248
248
  }
249
- }
250
- };
251
- const legacyPostPlugin = {
252
- name: "vite:legacy-post-process",
253
- enforce: "post",
254
- apply: "build",
255
- renderStart(opts) {
256
- outputToChunkFileNameToPolyfills.set(opts, null);
257
249
  },
258
- configResolved(_config) {
259
- if (_config.build.lib) throw new Error("@vitejs/plugin-legacy does not support library mode.");
260
- config = _config;
261
- if (isDebug) console.log(`[@vitejs/plugin-legacy] modernTargets:`, modernTargets);
262
- if (!genLegacy || config.build.ssr) return;
263
- targets = options.targets || browserslistLoadConfig({ path: config.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR";
264
- if (isDebug) console.log(`[@vitejs/plugin-legacy] targets:`, targets);
265
- const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => {
266
- if (!fileNames) return path.posix.join(config.build.assetsDir, defaultFileName);
267
- return (chunkInfo) => {
268
- let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
269
- if (fileName.includes("[name]")) fileName = fileName.replace("[name]", "[name]-legacy");
270
- else if (nonLeadingHashInFileNameRE.test(fileName)) fileName = fileName.replace(prefixedHashInFileNameRE, "-legacy$&");
271
- else fileName = fileName.replace(/(.+?)\.(.+)/, "$1-legacy.$2");
272
- return fileName;
250
+ {
251
+ name: "vite:legacy-post-process",
252
+ enforce: "post",
253
+ apply: "build",
254
+ renderStart(opts) {
255
+ outputToChunkFileNameToPolyfills.set(opts, null);
256
+ },
257
+ configResolved(_config) {
258
+ if (_config.build.lib) throw new Error("@vitejs/plugin-legacy does not support library mode.");
259
+ config = _config;
260
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] modernTargets:`, modernTargets);
261
+ if (!genLegacy || config.build.ssr) return;
262
+ targets = options.targets || browserslistLoadConfig({ path: config.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR";
263
+ if (isDebug) console.log(`[@vitejs/plugin-legacy] targets:`, targets);
264
+ const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => {
265
+ if (!fileNames) return path.posix.join(config.build.assetsDir, defaultFileName);
266
+ return (chunkInfo) => {
267
+ let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
268
+ if (fileName.includes("[name]")) fileName = fileName.replace("[name]", "[name]-legacy");
269
+ else if (nonLeadingHashInFileNameRE.test(fileName)) fileName = fileName.replace(prefixedHashInFileNameRE, "-legacy$&");
270
+ else fileName = fileName.replace(/(.+?)\.(.+)/, "$1-legacy.$2");
271
+ return fileName;
272
+ };
273
273
  };
274
- };
275
- const createLegacyOutput = (options$1 = {}) => {
276
- return {
277
- ...options$1,
278
- format: "system",
279
- entryFileNames: getLegacyOutputFileName(options$1.entryFileNames),
280
- chunkFileNames: getLegacyOutputFileName(options$1.chunkFileNames)
274
+ const createLegacyOutput = (options$1 = {}) => {
275
+ return {
276
+ ...options$1,
277
+ format: "esm",
278
+ entryFileNames: getLegacyOutputFileName(options$1.entryFileNames),
279
+ chunkFileNames: getLegacyOutputFileName(options$1.chunkFileNames),
280
+ minify: false
281
+ };
281
282
  };
282
- };
283
- const { rollupOptions } = config.build;
284
- const { output } = rollupOptions;
285
- if (Array.isArray(output)) rollupOptions.output = [...output.map(createLegacyOutput), ...genModern ? output : []];
286
- else rollupOptions.output = [createLegacyOutput(output), ...genModern ? [output || {}] : []];
287
- },
288
- async renderChunk(raw, chunk, opts, { chunks }) {
289
- if (config.build.ssr) return null;
290
- let chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
291
- if (chunkFileNameToPolyfills == null) {
292
- chunkFileNameToPolyfills = /* @__PURE__ */ new Map();
293
- for (const fileName in chunks) chunkFileNameToPolyfills.set(fileName, {
294
- modern: /* @__PURE__ */ new Set(),
295
- legacy: /* @__PURE__ */ new Set()
283
+ const { rollupOptions } = config.build;
284
+ const { output } = rollupOptions;
285
+ if (Array.isArray(output)) rollupOptions.output = [...output.map(createLegacyOutput), ...genModern ? output : []];
286
+ else rollupOptions.output = [createLegacyOutput(output), ...genModern ? [output || {}] : []];
287
+ _config.isOutputOptionsForLegacyChunks = (opts) => outputOptionsForLegacyChunks.has(opts);
288
+ },
289
+ async renderChunk(raw, chunk, opts, { chunks }) {
290
+ if (config.build.ssr) return null;
291
+ let chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
292
+ if (chunkFileNameToPolyfills == null) {
293
+ chunkFileNameToPolyfills = /* @__PURE__ */ new Map();
294
+ for (const fileName in chunks) chunkFileNameToPolyfills.set(fileName, {
295
+ modern: /* @__PURE__ */ new Set(),
296
+ legacy: /* @__PURE__ */ new Set()
297
+ });
298
+ outputToChunkFileNameToPolyfills.set(opts, chunkFileNameToPolyfills);
299
+ }
300
+ const polyfillsDiscovered = chunkFileNameToPolyfills.get(chunk.fileName);
301
+ if (polyfillsDiscovered == null) throw new Error(`Internal @vitejs/plugin-legacy error: discovered polyfills for ${chunk.fileName} should exist`);
302
+ if (!isLegacyChunk(chunk)) {
303
+ if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) await detectPolyfills(raw, modernTargets, assumptions, polyfillsDiscovered.modern);
304
+ const ms = new MagicString(raw);
305
+ if (genLegacy && chunk.isEntry) ms.prepend(modernChunkLegacyGuard);
306
+ if (raw.includes(legacyEnvVarMarker)) {
307
+ const re = new RegExp(legacyEnvVarMarker, "g");
308
+ let match;
309
+ while (match = re.exec(raw)) ms.overwrite(match.index, match.index + legacyEnvVarMarker.length, `false`);
310
+ }
311
+ if (config.build.sourcemap) return {
312
+ code: ms.toString(),
313
+ map: ms.generateMap({ hires: "boundary" })
314
+ };
315
+ return { code: ms.toString() };
316
+ }
317
+ if (!genLegacy) return null;
318
+ outputOptionsForLegacyChunks.add(opts);
319
+ const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
320
+ const sourceMaps = !!config.build.sourcemap;
321
+ const babel$1 = await loadBabel();
322
+ const resultSystem = babel$1.transform(raw, {
323
+ babelrc: false,
324
+ configFile: false,
325
+ ast: true,
326
+ code: false,
327
+ sourceMaps,
328
+ plugins: [(await import("@babel/plugin-transform-dynamic-import")).default, (await import("@babel/plugin-transform-modules-systemjs")).default]
296
329
  });
297
- outputToChunkFileNameToPolyfills.set(opts, chunkFileNameToPolyfills);
298
- }
299
- const polyfillsDiscovered = chunkFileNameToPolyfills.get(chunk.fileName);
300
- if (polyfillsDiscovered == null) throw new Error(`Internal @vitejs/plugin-legacy error: discovered polyfills for ${chunk.fileName} should exist`);
301
- if (!isLegacyChunk(chunk, opts)) {
302
- if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) await detectPolyfills(raw, modernTargets, assumptions, polyfillsDiscovered.modern);
303
- const ms = new MagicString(raw);
304
- if (genLegacy && chunk.isEntry) ms.prepend(modernChunkLegacyGuard);
305
- if (raw.includes(legacyEnvVarMarker)) {
306
- const re = new RegExp(legacyEnvVarMarker, "g");
307
- let match;
308
- while (match = re.exec(raw)) ms.overwrite(match.index, match.index + legacyEnvVarMarker.length, `false`);
330
+ const babelTransformOptions = {
331
+ babelrc: false,
332
+ configFile: false,
333
+ cloneInputAst: false,
334
+ compact: !!config.build.minify,
335
+ sourceMaps,
336
+ inputSourceMap: void 0,
337
+ targets,
338
+ assumptions,
339
+ browserslistConfigFile: false,
340
+ presets: [[() => ({ plugins: [
341
+ recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy),
342
+ replaceLegacyEnvBabelPlugin(),
343
+ wrapIIFEBabelPlugin()
344
+ ] })], [(await import("@babel/preset-env")).default, {
345
+ bugfixes: true,
346
+ modules: false,
347
+ useBuiltIns: needPolyfills ? "usage" : false,
348
+ corejs: needPolyfills ? {
349
+ version: _require("core-js/package.json").version,
350
+ proposals: false
351
+ } : void 0,
352
+ shippedProposals: true
353
+ }]]
354
+ };
355
+ let result;
356
+ if (resultSystem) result = babel$1.transformFromAstSync(resultSystem.ast, void 0, babelTransformOptions);
357
+ else result = babel$1.transform(raw, babelTransformOptions);
358
+ if (result) return {
359
+ code: result.code,
360
+ map: result.map
361
+ };
362
+ return null;
363
+ },
364
+ transformIndexHtml(html, { chunk }) {
365
+ if (config.build.ssr) return;
366
+ if (!chunk) return;
367
+ if (chunk.fileName.includes("-legacy")) {
368
+ facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
369
+ if (genModern) return;
370
+ }
371
+ if (!genModern) html = html.replace(/<script type="module".*?<\/script>/g, "");
372
+ const tags = [];
373
+ const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
374
+ if (genModern) {
375
+ const modernPolyfillFilename = facadeToModernPolyfillMap.get(chunk.facadeModuleId);
376
+ if (modernPolyfillFilename) tags.push({
377
+ tag: "script",
378
+ attrs: {
379
+ type: "module",
380
+ crossorigin: true,
381
+ src: toAssetPathFromHtml(modernPolyfillFilename, chunk.facadeModuleId, config)
382
+ }
383
+ });
384
+ else if (modernPolyfills.size) throw new Error(`No corresponding modern polyfill chunk found for ${htmlFilename}`);
309
385
  }
310
- if (config.build.sourcemap) return {
311
- code: ms.toString(),
312
- map: ms.generateMap({ hires: "boundary" })
386
+ if (!genLegacy) return {
387
+ html,
388
+ tags
313
389
  };
314
- return { code: ms.toString() };
315
- }
316
- if (!genLegacy) return null;
317
- opts.__vite_skip_esbuild__ = true;
318
- opts.__vite_force_terser__ = true;
319
- opts.__vite_skip_asset_emit__ = true;
320
- const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
321
- const sourceMaps = !!config.build.sourcemap;
322
- const babel$1 = await loadBabel();
323
- const result = babel$1.transform(raw, {
324
- babelrc: false,
325
- configFile: false,
326
- compact: !!config.build.minify,
327
- sourceMaps,
328
- inputSourceMap: void 0,
329
- targets,
330
- assumptions,
331
- browserslistConfigFile: false,
332
- presets: [[() => ({ plugins: [
333
- recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy),
334
- replaceLegacyEnvBabelPlugin(),
335
- wrapIIFEBabelPlugin()
336
- ] })], [(await import("@babel/preset-env")).default, {
337
- bugfixes: true,
338
- modules: false,
339
- useBuiltIns: needPolyfills ? "usage" : false,
340
- corejs: needPolyfills ? {
341
- version: _require("core-js/package.json").version,
342
- proposals: false
343
- } : void 0,
344
- shippedProposals: true
345
- }]]
346
- });
347
- if (result) return {
348
- code: result.code,
349
- map: result.map
350
- };
351
- return null;
352
- },
353
- transformIndexHtml(html, { chunk }) {
354
- if (config.build.ssr) return;
355
- if (!chunk) return;
356
- if (chunk.fileName.includes("-legacy")) {
357
- facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
358
- if (genModern) return;
359
- }
360
- if (!genModern) html = html.replace(/<script type="module".*?<\/script>/g, "");
361
- const tags = [];
362
- const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
363
- if (genModern) {
364
- const modernPolyfillFilename = facadeToModernPolyfillMap.get(chunk.facadeModuleId);
365
- if (modernPolyfillFilename) tags.push({
390
+ if (genModern) tags.push({
366
391
  tag: "script",
367
- attrs: {
368
- type: "module",
369
- crossorigin: true,
370
- src: toAssetPathFromHtml(modernPolyfillFilename, chunk.facadeModuleId, config)
371
- }
392
+ attrs: { nomodule: genModern },
393
+ children: safari10NoModuleFix,
394
+ injectTo: "body"
372
395
  });
373
- else if (modernPolyfills.size) throw new Error(`No corresponding modern polyfill chunk found for ${htmlFilename}`);
374
- }
375
- if (!genLegacy) return {
376
- html,
377
- tags
378
- };
379
- if (genModern) tags.push({
380
- tag: "script",
381
- attrs: { nomodule: genModern },
382
- children: safari10NoModuleFix,
383
- injectTo: "body"
384
- });
385
- const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(chunk.facadeModuleId);
386
- if (legacyPolyfillFilename) tags.push({
387
- tag: "script",
388
- attrs: {
389
- nomodule: genModern,
390
- crossorigin: true,
391
- id: legacyPolyfillId,
392
- src: toAssetPathFromHtml(legacyPolyfillFilename, chunk.facadeModuleId, config)
393
- },
394
- injectTo: "body"
395
- });
396
- else if (legacyPolyfills.size) throw new Error(`No corresponding legacy polyfill chunk found for ${htmlFilename}`);
397
- const legacyEntryFilename = facadeToLegacyChunkMap.get(chunk.facadeModuleId);
398
- if (legacyEntryFilename) tags.push({
399
- tag: "script",
400
- attrs: {
401
- nomodule: genModern,
402
- crossorigin: true,
403
- id: legacyEntryId,
404
- "data-src": toAssetPathFromHtml(legacyEntryFilename, chunk.facadeModuleId, config)
405
- },
406
- children: systemJSInlineCode,
407
- injectTo: "body"
408
- });
409
- else throw new Error(`No corresponding legacy entry chunk found for ${htmlFilename}`);
410
- if (legacyPolyfillFilename && legacyEntryFilename && genModern) {
411
- tags.push({
396
+ const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(chunk.facadeModuleId);
397
+ if (legacyPolyfillFilename) tags.push({
412
398
  tag: "script",
413
- attrs: { type: "module" },
414
- children: detectModernBrowserCode,
415
- injectTo: "head"
399
+ attrs: {
400
+ nomodule: genModern,
401
+ crossorigin: true,
402
+ id: legacyPolyfillId,
403
+ src: toAssetPathFromHtml(legacyPolyfillFilename, chunk.facadeModuleId, config)
404
+ },
405
+ injectTo: "body"
416
406
  });
417
- tags.push({
407
+ else if (legacyPolyfills.size) throw new Error(`No corresponding legacy polyfill chunk found for ${htmlFilename}`);
408
+ const legacyEntryFilename = facadeToLegacyChunkMap.get(chunk.facadeModuleId);
409
+ if (legacyEntryFilename) tags.push({
418
410
  tag: "script",
419
- attrs: { type: "module" },
420
- children: dynamicFallbackInlineCode,
421
- injectTo: "head"
411
+ attrs: {
412
+ nomodule: genModern,
413
+ crossorigin: true,
414
+ id: legacyEntryId,
415
+ "data-src": toAssetPathFromHtml(legacyEntryFilename, chunk.facadeModuleId, config)
416
+ },
417
+ children: systemJSInlineCode,
418
+ injectTo: "body"
422
419
  });
423
- }
424
- return {
425
- html,
426
- tags
427
- };
428
- },
429
- generateBundle(opts, bundle) {
430
- if (config.build.ssr) return;
431
- if (isLegacyBundle(bundle, opts) && genModern) {
432
- for (const name in bundle) if (bundle[name].type === "asset" && !name.endsWith(".map")) delete bundle[name];
420
+ else throw new Error(`No corresponding legacy entry chunk found for ${htmlFilename}`);
421
+ if (legacyPolyfillFilename && legacyEntryFilename && genModern) {
422
+ tags.push({
423
+ tag: "script",
424
+ attrs: { type: "module" },
425
+ children: detectModernBrowserCode,
426
+ injectTo: "head"
427
+ });
428
+ tags.push({
429
+ tag: "script",
430
+ attrs: { type: "module" },
431
+ children: dynamicFallbackInlineCode,
432
+ injectTo: "head"
433
+ });
434
+ }
435
+ return {
436
+ html,
437
+ tags
438
+ };
439
+ },
440
+ generateBundle(_opts, bundle) {
441
+ if (config.build.ssr) return;
442
+ if (isLegacyBundle(bundle) && genModern) {
443
+ for (const name in bundle) if (bundle[name].type === "asset" && !name.endsWith(".map") && !name.includes("-legacy")) delete bundle[name];
444
+ }
433
445
  }
434
446
  }
435
- };
436
- return [
437
- legacyConfigPlugin,
438
- legacyGenerateBundlePlugin,
439
- legacyPostPlugin
440
447
  ];
441
448
  }
442
449
  async function detectPolyfills(code, targets, assumptions, list) {
443
- const babel$1 = await loadBabel();
444
- const result = babel$1.transform(code, {
450
+ const result = (await loadBabel()).transform(code, {
445
451
  ast: true,
446
452
  code: false,
447
453
  babelrc: false,
@@ -461,7 +467,7 @@ async function detectPolyfills(code, targets, assumptions, list) {
461
467
  if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) list.add(source);
462
468
  }
463
469
  }
464
- async function buildPolyfillChunk(mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS, prependModenChunkLegacyGuard) {
470
+ async function buildPolyfillChunk(ctx, mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS, prependModenChunkLegacyGuard) {
465
471
  let { minify, assetsDir, sourcemap } = buildOptions;
466
472
  minify = minify ? "terser" : false;
467
473
  const res = await build({
@@ -495,10 +501,18 @@ async function buildPolyfillChunk(mode, imports, bundle, facadeToChunkMap, build
495
501
  const chunk = bundle[key];
496
502
  if (chunk.type === "chunk" && chunk.facadeModuleId) facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
497
503
  }
498
- bundle[polyfillChunk.fileName] = polyfillChunk;
504
+ ctx.emitFile({
505
+ type: "asset",
506
+ fileName: polyfillChunk.fileName,
507
+ source: polyfillChunk.code
508
+ });
499
509
  if (polyfillChunk.sourcemapFileName) {
500
510
  const polyfillChunkMapAsset = _polyfillChunk.output.find((chunk) => chunk.type === "asset" && chunk.fileName === polyfillChunk.sourcemapFileName);
501
- if (polyfillChunkMapAsset) bundle[polyfillChunk.sourcemapFileName] = polyfillChunkMapAsset;
511
+ if (polyfillChunkMapAsset) ctx.emitFile({
512
+ type: "asset",
513
+ fileName: polyfillChunkMapAsset.fileName,
514
+ source: polyfillChunkMapAsset.source
515
+ });
502
516
  }
503
517
  }
504
518
  const polyfillId = "\0vite/legacy-polyfills";
@@ -531,15 +545,12 @@ function prependModenChunkLegacyGuardPlugin() {
531
545
  }
532
546
  };
533
547
  }
534
- function isLegacyChunk(chunk, options) {
535
- return options.format === "system" && chunk.fileName.includes("-legacy");
548
+ function isLegacyChunk(chunk) {
549
+ return chunk.fileName.includes("-legacy");
536
550
  }
537
- function isLegacyBundle(bundle, options) {
538
- if (options.format === "system") {
539
- const entryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry);
540
- return !!entryChunk && entryChunk.fileName.includes("-legacy");
541
- }
542
- return false;
551
+ function isLegacyBundle(bundle) {
552
+ const entryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry);
553
+ return !!entryChunk && entryChunk.fileName.includes("-legacy");
543
554
  }
544
555
  function recordAndRemovePolyfillBabelPlugin(polyfills) {
545
556
  return ({ types: t }) => ({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-legacy",
3
- "version": "7.2.0",
3
+ "version": "8.0.0-beta.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "Evan You",
@@ -27,23 +27,17 @@
27
27
  },
28
28
  "homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-legacy#readme",
29
29
  "funding": "https://github.com/vitejs/vite?sponsor=1",
30
- "imports": {
31
- "#legacy-for-rolldown-vite": {
32
- "types": "./types/legacy-for-rolldown-vite.d.ts",
33
- "default": "./dist/vendor/rolldown-vite/index.js"
34
- }
35
- },
36
30
  "dependencies": {
37
- "@babel/core": "^7.28.0",
31
+ "@babel/core": "^7.28.5",
38
32
  "@babel/plugin-transform-dynamic-import": "^7.27.1",
39
- "@babel/plugin-transform-modules-systemjs": "^7.27.1",
40
- "@babel/preset-env": "^7.28.0",
33
+ "@babel/plugin-transform-modules-systemjs": "^7.28.5",
34
+ "@babel/preset-env": "^7.28.5",
41
35
  "babel-plugin-polyfill-corejs3": "^0.13.0",
42
36
  "babel-plugin-polyfill-regenerator": "^0.6.5",
43
- "browserslist": "^4.25.1",
37
+ "browserslist": "^4.28.0",
44
38
  "browserslist-to-esbuild": "^2.1.1",
45
- "core-js": "^3.45.0",
46
- "magic-string": "^0.30.17",
39
+ "core-js": "^3.47.0",
40
+ "magic-string": "^0.30.21",
47
41
  "regenerator-runtime": "^0.14.1",
48
42
  "systemjs": "^6.15.1"
49
43
  },
@@ -52,12 +46,10 @@
52
46
  "vite": "^7.0.0"
53
47
  },
54
48
  "devDependencies": {
55
- "@vitejs/plugin-legacy-for-rolldown-vite": "https://pkg.pr.new/vitejs/rolldown-vite/@vitejs/plugin-legacy@b19b90a",
56
49
  "acorn": "^8.15.0",
57
- "fdir": "^6.4.6",
58
50
  "picocolors": "^1.1.1",
59
- "tsdown": "^0.13.3",
60
- "vite": "7.1.0"
51
+ "tsdown": "^0.16.8",
52
+ "vite": "8.0.0-beta.0"
61
53
  },
62
54
  "scripts": {
63
55
  "dev": "tsdown --watch",
@@ -1,607 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import path from "node:path";
3
- import crypto from "node:crypto";
4
- import { fileURLToPath } from "node:url";
5
- import { build, normalizePath } from "vite";
6
- import MagicString from "magic-string";
7
- import browserslist from "browserslist";
8
-
9
- //#region rolldown:runtime
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __commonJS = (cb, mod) => function() {
17
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
- };
19
- var __copyProps = (to, from, except, desc) => {
20
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
21
- key = keys[i];
22
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
23
- get: ((k) => from[k]).bind(null, key),
24
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
25
- });
26
- }
27
- return to;
28
- };
29
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
- value: mod,
31
- enumerable: true
32
- }) : target, mod));
33
-
34
- //#endregion
35
- //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
36
- var require_picocolors = __commonJS({ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
37
- let p = process || {}, argv = p.argv || [], env = p.env || {};
38
- let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
39
- let formatter = (open, close, replace = open) => (input) => {
40
- let string = "" + input, index = string.indexOf(close, open.length);
41
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
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
- let createColors = (enabled = isColorSupported) => {
53
- let f = enabled ? formatter : () => String;
54
- return {
55
- isColorSupported: enabled,
56
- reset: f("\x1B[0m", "\x1B[0m"),
57
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
58
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
59
- italic: f("\x1B[3m", "\x1B[23m"),
60
- underline: f("\x1B[4m", "\x1B[24m"),
61
- inverse: f("\x1B[7m", "\x1B[27m"),
62
- hidden: f("\x1B[8m", "\x1B[28m"),
63
- strikethrough: f("\x1B[9m", "\x1B[29m"),
64
- black: f("\x1B[30m", "\x1B[39m"),
65
- red: f("\x1B[31m", "\x1B[39m"),
66
- green: f("\x1B[32m", "\x1B[39m"),
67
- yellow: f("\x1B[33m", "\x1B[39m"),
68
- blue: f("\x1B[34m", "\x1B[39m"),
69
- magenta: f("\x1B[35m", "\x1B[39m"),
70
- cyan: f("\x1B[36m", "\x1B[39m"),
71
- white: f("\x1B[37m", "\x1B[39m"),
72
- gray: f("\x1B[90m", "\x1B[39m"),
73
- bgBlack: f("\x1B[40m", "\x1B[49m"),
74
- bgRed: f("\x1B[41m", "\x1B[49m"),
75
- bgGreen: f("\x1B[42m", "\x1B[49m"),
76
- bgYellow: f("\x1B[43m", "\x1B[49m"),
77
- bgBlue: f("\x1B[44m", "\x1B[49m"),
78
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
79
- bgCyan: f("\x1B[46m", "\x1B[49m"),
80
- bgWhite: f("\x1B[47m", "\x1B[49m"),
81
- blackBright: f("\x1B[90m", "\x1B[39m"),
82
- redBright: f("\x1B[91m", "\x1B[39m"),
83
- greenBright: f("\x1B[92m", "\x1B[39m"),
84
- yellowBright: f("\x1B[93m", "\x1B[39m"),
85
- blueBright: f("\x1B[94m", "\x1B[39m"),
86
- magentaBright: f("\x1B[95m", "\x1B[39m"),
87
- cyanBright: f("\x1B[96m", "\x1B[39m"),
88
- whiteBright: f("\x1B[97m", "\x1B[39m"),
89
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
90
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
91
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
92
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
93
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
94
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
95
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
96
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
97
- };
98
- };
99
- module.exports = createColors();
100
- module.exports.createColors = createColors;
101
- } });
102
-
103
- //#endregion
104
- //#region src/snippets.ts
105
- 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()}}();`;
106
- const legacyPolyfillId = "vite-legacy-polyfill";
107
- const legacyEntryId = "vite-legacy-entry";
108
- const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`;
109
- const detectModernBrowserVarName = "__vite_is_modern_browser";
110
- const detectModernBrowserDetector = `import.meta.url;import("_").catch(()=>1);(async function*(){})().next()`;
111
- const detectModernBrowserCode = `${detectModernBrowserDetector};window.${detectModernBrowserVarName}=true`;
112
- 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)}();`;
113
- const modernChunkLegacyGuard = `export function __vite_legacy_guard(){${detectModernBrowserDetector}};`;
114
-
115
- //#endregion
116
- //#region src/index.ts
117
- var import_picocolors = __toESM(require_picocolors(), 1);
118
- let babel;
119
- async function loadBabel() {
120
- return babel ??= import("@babel/core");
121
- }
122
- const { loadConfig: browserslistLoadConfig } = browserslist;
123
- function toOutputFilePathInHtml(filename, type, hostId, hostType, config, toRelative) {
124
- const { renderBuiltUrl } = config.experimental;
125
- let relative = config.base === "" || config.base === "./";
126
- if (renderBuiltUrl) {
127
- const result = renderBuiltUrl(filename, {
128
- hostId,
129
- hostType,
130
- type,
131
- ssr: !!config.build.ssr
132
- });
133
- if (typeof result === "object") {
134
- if (result.runtime) throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
135
- if (typeof result.relative === "boolean") relative = result.relative;
136
- } else if (result) return result;
137
- }
138
- if (relative && !config.build.ssr) return toRelative(filename, hostId);
139
- else return joinUrlSegments(config.decodedBase, filename);
140
- }
141
- function getBaseInHTML(urlRelativePath, config) {
142
- return config.base === "./" || config.base === "" ? path.posix.join(path.posix.relative(urlRelativePath, "").slice(0, -2), "./") : config.base;
143
- }
144
- function joinUrlSegments(a, b) {
145
- if (!a || !b) return a || b || "";
146
- if (a.endsWith("/")) a = a.substring(0, a.length - 1);
147
- if (b[0] !== "/") b = "/" + b;
148
- return a + b;
149
- }
150
- function toAssetPathFromHtml(filename, htmlPath, config) {
151
- const relativeUrlPath = normalizePath(path.relative(config.root, htmlPath));
152
- const toRelative = (filename$1, _hostId) => getBaseInHTML(relativeUrlPath, config) + filename$1;
153
- return toOutputFilePathInHtml(filename, "asset", htmlPath, "html", config, toRelative);
154
- }
155
- const legacyEnvVarMarker = `__VITE_IS_LEGACY__`;
156
- const _require = createRequire(import.meta.url);
157
- const nonLeadingHashInFileNameRE = /[^/]+\[hash(?::\d+)?\]/;
158
- const prefixedHashInFileNameRE = /\W?\[hash(?::\d+)?\]/;
159
- const outputOptionsForLegacyChunks = /* @__PURE__ */ new WeakSet();
160
- function viteLegacyPlugin(options = {}) {
161
- let config;
162
- let targets;
163
- let modernTargets;
164
- const modernTargetsEsbuild = [
165
- "es2020",
166
- "edge79",
167
- "firefox67",
168
- "chrome64",
169
- "safari12"
170
- ];
171
- const modernTargetsBabel = "edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12";
172
- const genLegacy = options.renderLegacyChunks !== false;
173
- const genModern = options.renderModernChunks !== false;
174
- if (!genLegacy && !genModern) throw new Error("`renderLegacyChunks` and `renderModernChunks` cannot be both false");
175
- const debugFlags = (process.env.DEBUG || "").split(",");
176
- const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy");
177
- const assumptions = options.assumptions || {};
178
- const facadeToLegacyChunkMap = /* @__PURE__ */ new Map();
179
- const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map();
180
- const facadeToModernPolyfillMap = /* @__PURE__ */ new Map();
181
- const modernPolyfills = /* @__PURE__ */ new Set();
182
- const legacyPolyfills = /* @__PURE__ */ new Set();
183
- const outputToChunkFileNameToPolyfills = /* @__PURE__ */ new WeakMap();
184
- if (Array.isArray(options.modernPolyfills) && genModern) options.modernPolyfills.forEach((i) => {
185
- modernPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
186
- });
187
- if (Array.isArray(options.additionalModernPolyfills)) options.additionalModernPolyfills.forEach((i) => {
188
- modernPolyfills.add(i);
189
- });
190
- if (Array.isArray(options.polyfills)) options.polyfills.forEach((i) => {
191
- if (i.startsWith(`regenerator`)) legacyPolyfills.add(`regenerator-runtime/runtime.js`);
192
- else legacyPolyfills.add(i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`);
193
- });
194
- if (Array.isArray(options.additionalLegacyPolyfills)) options.additionalLegacyPolyfills.forEach((i) => {
195
- legacyPolyfills.add(i);
196
- });
197
- let overriddenBuildTarget = false;
198
- let overriddenDefaultModernTargets = false;
199
- const legacyConfigPlugin = {
200
- name: "vite:legacy-config",
201
- async config(config$1, env$1) {
202
- if (env$1.command === "build" && !config$1.build?.ssr) {
203
- if (!config$1.build) config$1.build = {};
204
- if (genLegacy && !config$1.build.cssTarget) config$1.build.cssTarget = "chrome61";
205
- if (genLegacy) {
206
- overriddenBuildTarget = config$1.build.target !== void 0;
207
- overriddenDefaultModernTargets = options.modernTargets !== void 0;
208
- if (options.modernTargets) {
209
- const { default: browserslistToEsbuild } = await import("browserslist-to-esbuild");
210
- config$1.build.target = browserslistToEsbuild(options.modernTargets);
211
- } else config$1.build.target = modernTargetsEsbuild;
212
- }
213
- }
214
- return { define: { "import.meta.env.LEGACY": env$1.command === "serve" || config$1.build?.ssr ? false : legacyEnvVarMarker } };
215
- },
216
- configResolved(config$1) {
217
- if (overriddenBuildTarget) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`));
218
- if (overriddenDefaultModernTargets) config$1.logger.warn(import_picocolors.default.yellow(`plugin-legacy 'modernTargets' option overrode the builtin targets of modern chunks. Some versions of browsers between legacy and modern may not be supported.`));
219
- if (config$1.isWorker) config$1.logger.warn(import_picocolors.default.yellow(`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.`));
220
- }
221
- };
222
- const legacyGenerateBundlePlugin = {
223
- name: "vite:legacy-generate-polyfill-chunk",
224
- apply: "build",
225
- async generateBundle(opts, bundle) {
226
- if (config.build.ssr) return;
227
- const chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
228
- if (chunkFileNameToPolyfills == null) throw new Error("Internal @vitejs/plugin-legacy error: discovered polyfills should exist");
229
- if (!isLegacyBundle(bundle)) {
230
- for (const { modern } of chunkFileNameToPolyfills.values()) modern.forEach((p$1) => modernPolyfills.add(p$1));
231
- if (!modernPolyfills.size) return;
232
- if (isDebug) console.log(`[@vitejs/plugin-legacy] modern polyfills:`, modernPolyfills);
233
- await buildPolyfillChunk(this, config.mode, modernPolyfills, bundle, facadeToModernPolyfillMap, config.build, "es", opts, true, genLegacy);
234
- return;
235
- }
236
- if (!genLegacy) return;
237
- for (const { legacy } of chunkFileNameToPolyfills.values()) legacy.forEach((p$1) => legacyPolyfills.add(p$1));
238
- if (options.polyfills !== false) await detectPolyfills(`Promise.resolve(); Promise.all();`, targets, assumptions, legacyPolyfills);
239
- if (legacyPolyfills.size || !options.externalSystemJS) {
240
- if (isDebug) console.log(`[@vitejs/plugin-legacy] legacy polyfills:`, legacyPolyfills);
241
- await buildPolyfillChunk(this, config.mode, legacyPolyfills, bundle, facadeToLegacyPolyfillMap, config.build, "iife", opts, options.externalSystemJS);
242
- }
243
- }
244
- };
245
- const legacyPostPlugin = {
246
- name: "vite:legacy-post-process",
247
- enforce: "post",
248
- apply: "build",
249
- renderStart(opts) {
250
- outputToChunkFileNameToPolyfills.set(opts, null);
251
- },
252
- configResolved(_config) {
253
- if (_config.build.lib) throw new Error("@vitejs/plugin-legacy does not support library mode.");
254
- config = _config;
255
- modernTargets = options.modernTargets || modernTargetsBabel;
256
- if (isDebug) console.log(`[@vitejs/plugin-legacy] modernTargets:`, modernTargets);
257
- if (!genLegacy || config.build.ssr) return;
258
- targets = options.targets || browserslistLoadConfig({ path: config.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR";
259
- if (isDebug) console.log(`[@vitejs/plugin-legacy] targets:`, targets);
260
- const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => {
261
- if (!fileNames) return path.posix.join(config.build.assetsDir, defaultFileName);
262
- return (chunkInfo) => {
263
- let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
264
- if (fileName.includes("[name]")) fileName = fileName.replace("[name]", "[name]-legacy");
265
- else if (nonLeadingHashInFileNameRE.test(fileName)) fileName = fileName.replace(prefixedHashInFileNameRE, "-legacy$&");
266
- else fileName = fileName.replace(/(.+?)\.(.+)/, "$1-legacy.$2");
267
- return fileName;
268
- };
269
- };
270
- const createLegacyOutput = (options$1 = {}) => {
271
- return {
272
- ...options$1,
273
- format: "esm",
274
- entryFileNames: getLegacyOutputFileName(options$1.entryFileNames),
275
- chunkFileNames: getLegacyOutputFileName(options$1.chunkFileNames),
276
- minify: false
277
- };
278
- };
279
- const { rollupOptions } = config.build;
280
- const { output } = rollupOptions;
281
- if (Array.isArray(output)) rollupOptions.output = [...output.map(createLegacyOutput), ...genModern ? output : []];
282
- else rollupOptions.output = [createLegacyOutput(output), ...genModern ? [output || {}] : []];
283
- _config.isOutputOptionsForLegacyChunks = (opts) => outputOptionsForLegacyChunks.has(opts);
284
- },
285
- async renderChunk(raw, chunk, opts, { chunks }) {
286
- if (config.build.ssr) return null;
287
- let chunkFileNameToPolyfills = outputToChunkFileNameToPolyfills.get(opts);
288
- if (chunkFileNameToPolyfills == null) {
289
- chunkFileNameToPolyfills = /* @__PURE__ */ new Map();
290
- for (const fileName in chunks) chunkFileNameToPolyfills.set(fileName, {
291
- modern: /* @__PURE__ */ new Set(),
292
- legacy: /* @__PURE__ */ new Set()
293
- });
294
- outputToChunkFileNameToPolyfills.set(opts, chunkFileNameToPolyfills);
295
- }
296
- const polyfillsDiscovered = chunkFileNameToPolyfills.get(chunk.fileName);
297
- if (polyfillsDiscovered == null) throw new Error(`Internal @vitejs/plugin-legacy error: discovered polyfills for ${chunk.fileName} should exist`);
298
- if (!isLegacyChunk(chunk)) {
299
- if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) await detectPolyfills(raw, modernTargets, assumptions, polyfillsDiscovered.modern);
300
- const ms = new MagicString(raw);
301
- if (genLegacy && chunk.isEntry) ms.prepend(modernChunkLegacyGuard);
302
- if (raw.includes(legacyEnvVarMarker)) {
303
- const re = new RegExp(legacyEnvVarMarker, "g");
304
- let match;
305
- while (match = re.exec(raw)) ms.overwrite(match.index, match.index + legacyEnvVarMarker.length, `false`);
306
- }
307
- if (config.build.sourcemap) return {
308
- code: ms.toString(),
309
- map: ms.generateMap({ hires: "boundary" })
310
- };
311
- return { code: ms.toString() };
312
- }
313
- if (!genLegacy) return null;
314
- outputOptionsForLegacyChunks.add(opts);
315
- const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
316
- const sourceMaps = !!config.build.sourcemap;
317
- const babel$1 = await loadBabel();
318
- const resultSystem = babel$1.transform(raw, {
319
- babelrc: false,
320
- configFile: false,
321
- ast: true,
322
- code: false,
323
- sourceMaps,
324
- plugins: [(await import("@babel/plugin-transform-dynamic-import")).default, (await import("@babel/plugin-transform-modules-systemjs")).default]
325
- });
326
- const babelTransformOptions = {
327
- babelrc: false,
328
- configFile: false,
329
- cloneInputAst: false,
330
- compact: !!config.build.minify,
331
- sourceMaps,
332
- inputSourceMap: void 0,
333
- targets,
334
- assumptions,
335
- browserslistConfigFile: false,
336
- presets: [[() => ({ plugins: [
337
- recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy),
338
- replaceLegacyEnvBabelPlugin(),
339
- wrapIIFEBabelPlugin()
340
- ] })], [(await import("@babel/preset-env")).default, {
341
- bugfixes: true,
342
- modules: false,
343
- useBuiltIns: needPolyfills ? "usage" : false,
344
- corejs: needPolyfills ? {
345
- version: _require("core-js/package.json").version,
346
- proposals: false
347
- } : void 0,
348
- shippedProposals: true
349
- }]]
350
- };
351
- let result;
352
- if (resultSystem) result = babel$1.transformFromAstSync(resultSystem.ast, void 0, babelTransformOptions);
353
- else result = babel$1.transform(raw, babelTransformOptions);
354
- if (result) return {
355
- code: result.code,
356
- map: result.map
357
- };
358
- return null;
359
- },
360
- transformIndexHtml(html, { chunk }) {
361
- if (config.build.ssr) return;
362
- if (!chunk) return;
363
- if (chunk.fileName.includes("-legacy")) {
364
- facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
365
- if (genModern) return;
366
- }
367
- if (!genModern) html = html.replace(/<script type="module".*?<\/script>/g, "");
368
- const tags = [];
369
- const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
370
- if (genModern) {
371
- const modernPolyfillFilename = facadeToModernPolyfillMap.get(chunk.facadeModuleId);
372
- if (modernPolyfillFilename) tags.push({
373
- tag: "script",
374
- attrs: {
375
- type: "module",
376
- crossorigin: true,
377
- src: toAssetPathFromHtml(modernPolyfillFilename, chunk.facadeModuleId, config)
378
- }
379
- });
380
- else if (modernPolyfills.size) throw new Error(`No corresponding modern polyfill chunk found for ${htmlFilename}`);
381
- }
382
- if (!genLegacy) return {
383
- html,
384
- tags
385
- };
386
- if (genModern) tags.push({
387
- tag: "script",
388
- attrs: { nomodule: genModern },
389
- children: safari10NoModuleFix,
390
- injectTo: "body"
391
- });
392
- const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(chunk.facadeModuleId);
393
- if (legacyPolyfillFilename) tags.push({
394
- tag: "script",
395
- attrs: {
396
- nomodule: genModern,
397
- crossorigin: true,
398
- id: legacyPolyfillId,
399
- src: toAssetPathFromHtml(legacyPolyfillFilename, chunk.facadeModuleId, config)
400
- },
401
- injectTo: "body"
402
- });
403
- else if (legacyPolyfills.size) throw new Error(`No corresponding legacy polyfill chunk found for ${htmlFilename}`);
404
- const legacyEntryFilename = facadeToLegacyChunkMap.get(chunk.facadeModuleId);
405
- if (legacyEntryFilename) tags.push({
406
- tag: "script",
407
- attrs: {
408
- nomodule: genModern,
409
- crossorigin: true,
410
- id: legacyEntryId,
411
- "data-src": toAssetPathFromHtml(legacyEntryFilename, chunk.facadeModuleId, config)
412
- },
413
- children: systemJSInlineCode,
414
- injectTo: "body"
415
- });
416
- else throw new Error(`No corresponding legacy entry chunk found for ${htmlFilename}`);
417
- if (legacyPolyfillFilename && legacyEntryFilename && genModern) {
418
- tags.push({
419
- tag: "script",
420
- attrs: { type: "module" },
421
- children: detectModernBrowserCode,
422
- injectTo: "head"
423
- });
424
- tags.push({
425
- tag: "script",
426
- attrs: { type: "module" },
427
- children: dynamicFallbackInlineCode,
428
- injectTo: "head"
429
- });
430
- }
431
- return {
432
- html,
433
- tags
434
- };
435
- },
436
- generateBundle(_opts, bundle) {
437
- if (config.build.ssr) return;
438
- if (isLegacyBundle(bundle) && genModern) {
439
- for (const name in bundle) if (bundle[name].type === "asset" && !name.endsWith(".map") && !name.includes("-legacy")) delete bundle[name];
440
- }
441
- }
442
- };
443
- return [
444
- legacyConfigPlugin,
445
- legacyGenerateBundlePlugin,
446
- legacyPostPlugin
447
- ];
448
- }
449
- async function detectPolyfills(code, targets, assumptions, list) {
450
- const babel$1 = await loadBabel();
451
- const result = babel$1.transform(code, {
452
- ast: true,
453
- code: false,
454
- babelrc: false,
455
- configFile: false,
456
- compact: false,
457
- targets,
458
- assumptions,
459
- browserslistConfigFile: false,
460
- plugins: [[(await import("babel-plugin-polyfill-corejs3")).default, {
461
- method: "usage-global",
462
- version: _require("core-js/package.json").version,
463
- shippedProposals: true
464
- }], [(await import("babel-plugin-polyfill-regenerator")).default, { method: "usage-global" }]]
465
- });
466
- for (const node of result.ast.program.body) if (node.type === "ImportDeclaration") {
467
- const source = node.source.value;
468
- if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) list.add(source);
469
- }
470
- }
471
- async function buildPolyfillChunk(ctx, mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS, prependModenChunkLegacyGuard) {
472
- let { minify, assetsDir, sourcemap } = buildOptions;
473
- minify = minify ? "terser" : false;
474
- const res = await build({
475
- mode,
476
- root: path.dirname(fileURLToPath(import.meta.url)),
477
- configFile: false,
478
- logLevel: "error",
479
- plugins: [polyfillsPlugin(imports, excludeSystemJS), prependModenChunkLegacyGuard && prependModenChunkLegacyGuardPlugin()],
480
- build: {
481
- write: false,
482
- minify,
483
- assetsDir,
484
- sourcemap,
485
- rollupOptions: {
486
- input: { polyfills: polyfillId },
487
- output: {
488
- format,
489
- hashCharacters: rollupOutputOptions.hashCharacters,
490
- entryFileNames: rollupOutputOptions.entryFileNames
491
- }
492
- }
493
- },
494
- esbuild: false,
495
- optimizeDeps: { esbuildOptions: { target: "es5" } }
496
- });
497
- const _polyfillChunk = Array.isArray(res) ? res[0] : res;
498
- if (!("output" in _polyfillChunk)) return;
499
- const polyfillChunk = _polyfillChunk.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry);
500
- for (const key in bundle) {
501
- const chunk = bundle[key];
502
- if (chunk.type === "chunk" && chunk.facadeModuleId) facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
503
- }
504
- ctx.emitFile({
505
- type: "asset",
506
- fileName: polyfillChunk.fileName,
507
- source: polyfillChunk.code
508
- });
509
- if (polyfillChunk.sourcemapFileName) {
510
- const polyfillChunkMapAsset = _polyfillChunk.output.find((chunk) => chunk.type === "asset" && chunk.fileName === polyfillChunk.sourcemapFileName);
511
- if (polyfillChunkMapAsset) ctx.emitFile({
512
- type: "asset",
513
- fileName: polyfillChunkMapAsset.fileName,
514
- source: polyfillChunkMapAsset.source
515
- });
516
- }
517
- }
518
- const polyfillId = "\0vite/legacy-polyfills";
519
- function polyfillsPlugin(imports, excludeSystemJS) {
520
- return {
521
- name: "vite:legacy-polyfills",
522
- resolveId(id) {
523
- if (id === polyfillId) return id;
524
- },
525
- load(id) {
526
- if (id === polyfillId) return [...imports].map((i) => `import ${JSON.stringify(i)};`).join("") + (excludeSystemJS ? "" : `import "systemjs/dist/s.min.js";`);
527
- }
528
- };
529
- }
530
- function prependModenChunkLegacyGuardPlugin() {
531
- let sourceMapEnabled;
532
- return {
533
- name: "vite:legacy-prepend-moden-chunk-legacy-guard",
534
- configResolved(config) {
535
- sourceMapEnabled = !!config.build.sourcemap;
536
- },
537
- renderChunk(code) {
538
- if (!sourceMapEnabled) return modernChunkLegacyGuard + code;
539
- const ms = new MagicString(code);
540
- ms.prepend(modernChunkLegacyGuard);
541
- return {
542
- code: ms.toString(),
543
- map: ms.generateMap({ hires: "boundary" })
544
- };
545
- }
546
- };
547
- }
548
- function isLegacyChunk(chunk) {
549
- return chunk.fileName.includes("-legacy");
550
- }
551
- function isLegacyBundle(bundle) {
552
- const entryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry);
553
- return !!entryChunk && entryChunk.fileName.includes("-legacy");
554
- }
555
- function recordAndRemovePolyfillBabelPlugin(polyfills) {
556
- return ({ types: t }) => ({
557
- name: "vite-remove-polyfill-import",
558
- post({ path: path$1 }) {
559
- path$1.get("body").forEach((p$1) => {
560
- if (t.isImportDeclaration(p$1.node)) {
561
- polyfills.add(p$1.node.source.value);
562
- p$1.remove();
563
- }
564
- });
565
- }
566
- });
567
- }
568
- function replaceLegacyEnvBabelPlugin() {
569
- return ({ types: t }) => ({
570
- name: "vite-replace-env-legacy",
571
- visitor: { Identifier(path$1) {
572
- if (path$1.node.name === legacyEnvVarMarker) path$1.replaceWith(t.booleanLiteral(true));
573
- } }
574
- });
575
- }
576
- function wrapIIFEBabelPlugin() {
577
- return ({ types: t, template }) => {
578
- const buildIIFE = template(";(function(){%%body%%})();");
579
- return {
580
- name: "vite-wrap-iife",
581
- post({ path: path$1 }) {
582
- if (!this.isWrapped) {
583
- this.isWrapped = true;
584
- path$1.replaceWith(t.program(buildIIFE({ body: path$1.node.body })));
585
- }
586
- }
587
- };
588
- };
589
- }
590
- const cspHashes = [
591
- safari10NoModuleFix,
592
- systemJSInlineCode,
593
- detectModernBrowserCode,
594
- dynamicFallbackInlineCode
595
- ].map((i) => crypto.hash("sha256", i, "base64"));
596
- var src_default = viteLegacyPlugin;
597
- function viteLegacyPluginCjs(options) {
598
- return viteLegacyPlugin.call(this, options);
599
- }
600
- Object.assign(viteLegacyPluginCjs, {
601
- cspHashes,
602
- default: viteLegacyPluginCjs,
603
- detectPolyfills
604
- });
605
-
606
- //#endregion
607
- export { cspHashes, src_default as default, detectPolyfills, viteLegacyPluginCjs as "module.exports" };