index.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. import path from 'node:path';
  2. import { createHash } from 'node:crypto';
  3. import { createRequire } from 'node:module';
  4. import { fileURLToPath } from 'node:url';
  5. import { build, normalizePath } from 'vite';
  6. import MagicString from 'magic-string';
  7. import require$$0 from 'tty';
  8. import browserslist from 'browserslist';
  9. function getDefaultExportFromCjs (x) {
  10. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  11. }
  12. var picocolors = {exports: {}};
  13. let tty = require$$0;
  14. let isColorSupported =
  15. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  16. ("FORCE_COLOR" in process.env ||
  17. process.argv.includes("--color") ||
  18. process.platform === "win32" ||
  19. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  20. "CI" in process.env);
  21. let formatter =
  22. (open, close, replace = open) =>
  23. input => {
  24. let string = "" + input;
  25. let index = string.indexOf(close, open.length);
  26. return ~index
  27. ? open + replaceClose(string, close, replace, index) + close
  28. : open + string + close
  29. };
  30. let replaceClose = (string, close, replace, index) => {
  31. let start = string.substring(0, index) + replace;
  32. let end = string.substring(index + close.length);
  33. let nextIndex = end.indexOf(close);
  34. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  35. };
  36. let createColors = (enabled = isColorSupported) => ({
  37. isColorSupported: enabled,
  38. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  39. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  40. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  41. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  42. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  43. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  44. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  45. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  46. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  47. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  48. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  49. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  50. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  51. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  52. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  53. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  54. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  55. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  56. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  57. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  58. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  59. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  60. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  61. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  62. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  63. });
  64. picocolors.exports = createColors();
  65. picocolors.exports.createColors = createColors;
  66. var picocolorsExports = picocolors.exports;
  67. const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  68. 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()}}();`;
  69. const legacyPolyfillId = "vite-legacy-polyfill";
  70. const legacyEntryId = "vite-legacy-entry";
  71. const systemJSInlineCode = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`;
  72. const detectModernBrowserVarName = "__vite_is_modern_browser";
  73. const detectModernBrowserDetector = 'import.meta.url;import("_").catch(()=>1);async function* g(){};';
  74. const detectModernBrowserCode = `${detectModernBrowserDetector}if(location.protocol!="file:"){window.${detectModernBrowserVarName}=true}`;
  75. 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)}();`;
  76. const modernChunkLegacyGuard = `export function __vite_legacy_guard(){${detectModernBrowserDetector}};`;
  77. let babel;
  78. async function loadBabel() {
  79. if (!babel) {
  80. babel = await import('@babel/core');
  81. }
  82. return babel;
  83. }
  84. const { loadConfig: browserslistLoadConfig } = browserslist;
  85. function toOutputFilePathInHtml(filename, type, hostId, hostType, config, toRelative) {
  86. const { renderBuiltUrl } = config.experimental;
  87. let relative = config.base === "" || config.base === "./";
  88. if (renderBuiltUrl) {
  89. const result = renderBuiltUrl(filename, {
  90. hostId,
  91. hostType,
  92. type,
  93. ssr: !!config.build.ssr
  94. });
  95. if (typeof result === "object") {
  96. if (result.runtime) {
  97. throw new Error(
  98. `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`
  99. );
  100. }
  101. if (typeof result.relative === "boolean") {
  102. relative = result.relative;
  103. }
  104. } else if (result) {
  105. return result;
  106. }
  107. }
  108. if (relative && !config.build.ssr) {
  109. return toRelative(filename, hostId);
  110. } else {
  111. return config.base + filename;
  112. }
  113. }
  114. function getBaseInHTML(urlRelativePath, config) {
  115. return config.base === "./" || config.base === "" ? path.posix.join(
  116. path.posix.relative(urlRelativePath, "").slice(0, -2),
  117. "./"
  118. ) : config.base;
  119. }
  120. function toAssetPathFromHtml(filename, htmlPath, config) {
  121. const relativeUrlPath = normalizePath(path.relative(config.root, htmlPath));
  122. const toRelative = (filename2, hostId) => getBaseInHTML(relativeUrlPath, config) + filename2;
  123. return toOutputFilePathInHtml(
  124. filename,
  125. "asset",
  126. htmlPath,
  127. "html",
  128. config,
  129. toRelative
  130. );
  131. }
  132. const legacyEnvVarMarker = `__VITE_IS_LEGACY__`;
  133. const _require = createRequire(import.meta.url);
  134. function viteLegacyPlugin(options = {}) {
  135. let config;
  136. let targets;
  137. const genLegacy = options.renderLegacyChunks !== false;
  138. const genModern = options.renderModernChunks !== false;
  139. if (!genLegacy && !genModern) {
  140. throw new Error(
  141. "`renderLegacyChunks` and `renderModernChunks` cannot be both false"
  142. );
  143. }
  144. const debugFlags = (process.env.DEBUG || "").split(",");
  145. const isDebug = debugFlags.includes("vite:*") || debugFlags.includes("vite:legacy");
  146. const facadeToLegacyChunkMap = /* @__PURE__ */ new Map();
  147. const facadeToLegacyPolyfillMap = /* @__PURE__ */ new Map();
  148. const facadeToModernPolyfillMap = /* @__PURE__ */ new Map();
  149. const modernPolyfills = /* @__PURE__ */ new Set();
  150. const legacyPolyfills = /* @__PURE__ */ new Set();
  151. if (Array.isArray(options.modernPolyfills) && genModern) {
  152. options.modernPolyfills.forEach((i) => {
  153. modernPolyfills.add(
  154. i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`
  155. );
  156. });
  157. }
  158. if (Array.isArray(options.polyfills)) {
  159. options.polyfills.forEach((i) => {
  160. if (i.startsWith(`regenerator`)) {
  161. legacyPolyfills.add(`regenerator-runtime/runtime.js`);
  162. } else {
  163. legacyPolyfills.add(
  164. i.includes("/") ? `core-js/${i}` : `core-js/modules/${i}.js`
  165. );
  166. }
  167. });
  168. }
  169. if (Array.isArray(options.additionalLegacyPolyfills)) {
  170. options.additionalLegacyPolyfills.forEach((i) => {
  171. legacyPolyfills.add(i);
  172. });
  173. }
  174. let overriddenBuildTarget = false;
  175. const legacyConfigPlugin = {
  176. name: "vite:legacy-config",
  177. config(config2, env) {
  178. if (env.command === "build" && !config2.build?.ssr) {
  179. if (!config2.build) {
  180. config2.build = {};
  181. }
  182. if (!config2.build.cssTarget) {
  183. config2.build.cssTarget = "chrome61";
  184. }
  185. if (genLegacy) {
  186. overriddenBuildTarget = config2.build.target !== void 0;
  187. config2.build.target = [
  188. "es2020",
  189. "edge79",
  190. "firefox67",
  191. "chrome64",
  192. "safari12"
  193. ];
  194. }
  195. }
  196. return {
  197. define: {
  198. "import.meta.env.LEGACY": env.command === "serve" || config2.build?.ssr ? false : legacyEnvVarMarker
  199. }
  200. };
  201. },
  202. configResolved(config2) {
  203. if (overriddenBuildTarget) {
  204. config2.logger.warn(
  205. colors.yellow(
  206. `plugin-legacy overrode 'build.target'. You should pass 'targets' as an option to this plugin with the list of legacy browsers to support instead.`
  207. )
  208. );
  209. }
  210. }
  211. };
  212. const legacyGenerateBundlePlugin = {
  213. name: "vite:legacy-generate-polyfill-chunk",
  214. apply: "build",
  215. async generateBundle(opts, bundle) {
  216. if (config.build.ssr) {
  217. return;
  218. }
  219. if (!isLegacyBundle(bundle, opts)) {
  220. if (!modernPolyfills.size) {
  221. return;
  222. }
  223. isDebug && console.log(
  224. `[@vitejs/plugin-legacy] modern polyfills:`,
  225. modernPolyfills
  226. );
  227. await buildPolyfillChunk(
  228. config.mode,
  229. modernPolyfills,
  230. bundle,
  231. facadeToModernPolyfillMap,
  232. config.build,
  233. "es",
  234. opts,
  235. true
  236. );
  237. return;
  238. }
  239. if (!genLegacy) {
  240. return;
  241. }
  242. if (legacyPolyfills.size) {
  243. await detectPolyfills(
  244. `Promise.resolve(); Promise.all();`,
  245. targets,
  246. legacyPolyfills
  247. );
  248. isDebug && console.log(
  249. `[@vitejs/plugin-legacy] legacy polyfills:`,
  250. legacyPolyfills
  251. );
  252. await buildPolyfillChunk(
  253. config.mode,
  254. legacyPolyfills,
  255. bundle,
  256. facadeToLegacyPolyfillMap,
  257. // force using terser for legacy polyfill minification, since esbuild
  258. // isn't legacy-safe
  259. config.build,
  260. "iife",
  261. opts,
  262. options.externalSystemJS
  263. );
  264. }
  265. }
  266. };
  267. const legacyPostPlugin = {
  268. name: "vite:legacy-post-process",
  269. enforce: "post",
  270. apply: "build",
  271. configResolved(_config) {
  272. if (_config.build.lib) {
  273. throw new Error("@vitejs/plugin-legacy does not support library mode.");
  274. }
  275. config = _config;
  276. if (!genLegacy || config.build.ssr) {
  277. return;
  278. }
  279. targets = options.targets || browserslistLoadConfig({ path: config.root }) || "last 2 versions and not dead, > 0.3%, Firefox ESR";
  280. isDebug && console.log(`[@vitejs/plugin-legacy] targets:`, targets);
  281. const getLegacyOutputFileName = (fileNames, defaultFileName = "[name]-legacy-[hash].js") => {
  282. if (!fileNames) {
  283. return path.posix.join(config.build.assetsDir, defaultFileName);
  284. }
  285. return (chunkInfo) => {
  286. let fileName = typeof fileNames === "function" ? fileNames(chunkInfo) : fileNames;
  287. if (fileName.includes("[name]")) {
  288. fileName = fileName.replace("[name]", "[name]-legacy");
  289. } else {
  290. fileName = fileName.replace(/(.+)\.(.+)/, "$1-legacy.$2");
  291. }
  292. return fileName;
  293. };
  294. };
  295. const createLegacyOutput = (options2 = {}) => {
  296. return {
  297. ...options2,
  298. format: "system",
  299. entryFileNames: getLegacyOutputFileName(options2.entryFileNames),
  300. chunkFileNames: getLegacyOutputFileName(options2.chunkFileNames)
  301. };
  302. };
  303. const { rollupOptions } = config.build;
  304. const { output } = rollupOptions;
  305. if (Array.isArray(output)) {
  306. rollupOptions.output = [
  307. ...output.map(createLegacyOutput),
  308. ...genModern ? output : []
  309. ];
  310. } else {
  311. rollupOptions.output = [
  312. createLegacyOutput(output),
  313. ...genModern ? [output || {}] : []
  314. ];
  315. }
  316. },
  317. async renderChunk(raw, chunk, opts) {
  318. if (config.build.ssr) {
  319. return null;
  320. }
  321. if (!isLegacyChunk(chunk, opts)) {
  322. if (options.modernPolyfills && !Array.isArray(options.modernPolyfills) && genModern) {
  323. await detectPolyfills(raw, { esmodules: true }, modernPolyfills);
  324. }
  325. const ms = new MagicString(raw);
  326. if (genLegacy && chunk.isEntry) {
  327. ms.prepend(modernChunkLegacyGuard);
  328. }
  329. if (raw.includes(legacyEnvVarMarker)) {
  330. const re = new RegExp(legacyEnvVarMarker, "g");
  331. let match;
  332. while (match = re.exec(raw)) {
  333. ms.overwrite(
  334. match.index,
  335. match.index + legacyEnvVarMarker.length,
  336. `false`
  337. );
  338. }
  339. }
  340. if (config.build.sourcemap) {
  341. return {
  342. code: ms.toString(),
  343. map: ms.generateMap({ hires: true })
  344. };
  345. }
  346. return {
  347. code: ms.toString()
  348. };
  349. }
  350. if (!genLegacy) {
  351. return null;
  352. }
  353. opts.__vite_skip_esbuild__ = true;
  354. opts.__vite_force_terser__ = true;
  355. opts.__vite_skip_asset_emit__ = true;
  356. const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills);
  357. const sourceMaps = !!config.build.sourcemap;
  358. const babel2 = await loadBabel();
  359. const result = babel2.transform(raw, {
  360. babelrc: false,
  361. configFile: false,
  362. compact: !!config.build.minify,
  363. sourceMaps,
  364. inputSourceMap: void 0,
  365. // sourceMaps ? chunk.map : undefined, `.map` TODO: moved to OutputChunk?
  366. presets: [
  367. // forcing our plugin to run before preset-env by wrapping it in a
  368. // preset so we can catch the injected import statements...
  369. [
  370. () => ({
  371. plugins: [
  372. recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
  373. replaceLegacyEnvBabelPlugin(),
  374. wrapIIFEBabelPlugin()
  375. ]
  376. })
  377. ],
  378. [
  379. (await import('@babel/preset-env')).default,
  380. createBabelPresetEnvOptions(targets, {
  381. needPolyfills,
  382. ignoreBrowserslistConfig: options.ignoreBrowserslistConfig
  383. })
  384. ]
  385. ]
  386. });
  387. if (result)
  388. return { code: result.code, map: result.map };
  389. return null;
  390. },
  391. transformIndexHtml(html, { chunk }) {
  392. if (config.build.ssr)
  393. return;
  394. if (!chunk)
  395. return;
  396. if (chunk.fileName.includes("-legacy")) {
  397. facadeToLegacyChunkMap.set(chunk.facadeModuleId, chunk.fileName);
  398. if (genModern) {
  399. return;
  400. }
  401. }
  402. if (!genModern) {
  403. html = html.replace(/<script type="module".*?<\/script>/g, "");
  404. }
  405. const tags = [];
  406. const htmlFilename = chunk.facadeModuleId?.replace(/\?.*$/, "");
  407. if (genModern) {
  408. const modernPolyfillFilename = facadeToModernPolyfillMap.get(
  409. chunk.facadeModuleId
  410. );
  411. if (modernPolyfillFilename) {
  412. tags.push({
  413. tag: "script",
  414. attrs: {
  415. type: "module",
  416. crossorigin: true,
  417. src: toAssetPathFromHtml(
  418. modernPolyfillFilename,
  419. chunk.facadeModuleId,
  420. config
  421. )
  422. }
  423. });
  424. } else if (modernPolyfills.size) {
  425. throw new Error(
  426. `No corresponding modern polyfill chunk found for ${htmlFilename}`
  427. );
  428. }
  429. }
  430. if (!genLegacy) {
  431. return { html, tags };
  432. }
  433. if (genModern) {
  434. tags.push({
  435. tag: "script",
  436. attrs: { nomodule: genModern },
  437. children: safari10NoModuleFix,
  438. injectTo: "body"
  439. });
  440. }
  441. const legacyPolyfillFilename = facadeToLegacyPolyfillMap.get(
  442. chunk.facadeModuleId
  443. );
  444. if (legacyPolyfillFilename) {
  445. tags.push({
  446. tag: "script",
  447. attrs: {
  448. nomodule: genModern,
  449. crossorigin: true,
  450. id: legacyPolyfillId,
  451. src: toAssetPathFromHtml(
  452. legacyPolyfillFilename,
  453. chunk.facadeModuleId,
  454. config
  455. )
  456. },
  457. injectTo: "body"
  458. });
  459. } else if (legacyPolyfills.size) {
  460. throw new Error(
  461. `No corresponding legacy polyfill chunk found for ${htmlFilename}`
  462. );
  463. }
  464. const legacyEntryFilename = facadeToLegacyChunkMap.get(
  465. chunk.facadeModuleId
  466. );
  467. if (legacyEntryFilename) {
  468. tags.push({
  469. tag: "script",
  470. attrs: {
  471. nomodule: genModern,
  472. crossorigin: true,
  473. // we set the entry path on the element as an attribute so that the
  474. // script content will stay consistent - which allows using a constant
  475. // hash value for CSP.
  476. id: legacyEntryId,
  477. "data-src": toAssetPathFromHtml(
  478. legacyEntryFilename,
  479. chunk.facadeModuleId,
  480. config
  481. )
  482. },
  483. children: systemJSInlineCode,
  484. injectTo: "body"
  485. });
  486. } else {
  487. throw new Error(
  488. `No corresponding legacy entry chunk found for ${htmlFilename}`
  489. );
  490. }
  491. if (legacyPolyfillFilename && legacyEntryFilename && genModern) {
  492. tags.push({
  493. tag: "script",
  494. attrs: { type: "module" },
  495. children: detectModernBrowserCode,
  496. injectTo: "head"
  497. });
  498. tags.push({
  499. tag: "script",
  500. attrs: { type: "module" },
  501. children: dynamicFallbackInlineCode,
  502. injectTo: "head"
  503. });
  504. }
  505. return {
  506. html,
  507. tags
  508. };
  509. },
  510. generateBundle(opts, bundle) {
  511. if (config.build.ssr) {
  512. return;
  513. }
  514. if (isLegacyBundle(bundle, opts) && genModern) {
  515. for (const name in bundle) {
  516. if (bundle[name].type === "asset" && !/.+\.map$/.test(name)) {
  517. delete bundle[name];
  518. }
  519. }
  520. }
  521. }
  522. };
  523. return [legacyConfigPlugin, legacyGenerateBundlePlugin, legacyPostPlugin];
  524. }
  525. async function detectPolyfills(code, targets, list) {
  526. const babel2 = await loadBabel();
  527. const result = babel2.transform(code, {
  528. ast: true,
  529. babelrc: false,
  530. configFile: false,
  531. presets: [
  532. [
  533. (await import('@babel/preset-env')).default,
  534. createBabelPresetEnvOptions(targets, {
  535. ignoreBrowserslistConfig: true
  536. })
  537. ]
  538. ]
  539. });
  540. for (const node of result.ast.program.body) {
  541. if (node.type === "ImportDeclaration") {
  542. const source = node.source.value;
  543. if (source.startsWith("core-js/") || source.startsWith("regenerator-runtime/")) {
  544. list.add(source);
  545. }
  546. }
  547. }
  548. }
  549. function createBabelPresetEnvOptions(targets, {
  550. needPolyfills = true,
  551. ignoreBrowserslistConfig
  552. }) {
  553. return {
  554. targets,
  555. bugfixes: true,
  556. loose: false,
  557. modules: false,
  558. useBuiltIns: needPolyfills ? "usage" : false,
  559. corejs: needPolyfills ? {
  560. version: _require("core-js/package.json").version,
  561. proposals: false
  562. } : void 0,
  563. shippedProposals: true,
  564. ignoreBrowserslistConfig
  565. };
  566. }
  567. async function buildPolyfillChunk(mode, imports, bundle, facadeToChunkMap, buildOptions, format, rollupOutputOptions, excludeSystemJS) {
  568. let { minify, assetsDir } = buildOptions;
  569. minify = minify ? "terser" : false;
  570. const res = await build({
  571. mode,
  572. // so that everything is resolved from here
  573. root: path.dirname(fileURLToPath(import.meta.url)),
  574. configFile: false,
  575. logLevel: "error",
  576. plugins: [polyfillsPlugin(imports, excludeSystemJS)],
  577. build: {
  578. write: false,
  579. minify,
  580. assetsDir,
  581. rollupOptions: {
  582. input: {
  583. polyfills: polyfillId
  584. },
  585. output: {
  586. format,
  587. entryFileNames: rollupOutputOptions.entryFileNames
  588. }
  589. }
  590. },
  591. // Don't run esbuild for transpilation or minification
  592. // because we don't want to transpile code.
  593. esbuild: false,
  594. optimizeDeps: {
  595. esbuildOptions: {
  596. // If a value above 'es5' is set, esbuild injects helper functions which uses es2015 features.
  597. // This limits the input code not to include es2015+ codes.
  598. // But core-js is the only dependency which includes commonjs code
  599. // and core-js doesn't include es2015+ codes.
  600. target: "es5"
  601. }
  602. }
  603. });
  604. const _polyfillChunk = Array.isArray(res) ? res[0] : res;
  605. if (!("output" in _polyfillChunk))
  606. return;
  607. const polyfillChunk = _polyfillChunk.output[0];
  608. for (const key in bundle) {
  609. const chunk = bundle[key];
  610. if (chunk.type === "chunk" && chunk.facadeModuleId) {
  611. facadeToChunkMap.set(chunk.facadeModuleId, polyfillChunk.fileName);
  612. }
  613. }
  614. bundle[polyfillChunk.fileName] = polyfillChunk;
  615. }
  616. const polyfillId = "\0vite/legacy-polyfills";
  617. function polyfillsPlugin(imports, excludeSystemJS) {
  618. return {
  619. name: "vite:legacy-polyfills",
  620. resolveId(id) {
  621. if (id === polyfillId) {
  622. return id;
  623. }
  624. },
  625. load(id) {
  626. if (id === polyfillId) {
  627. return [...imports].map((i) => `import ${JSON.stringify(i)};`).join("") + (excludeSystemJS ? "" : `import "systemjs/dist/s.min.js";`);
  628. }
  629. }
  630. };
  631. }
  632. function isLegacyChunk(chunk, options) {
  633. return options.format === "system" && chunk.fileName.includes("-legacy");
  634. }
  635. function isLegacyBundle(bundle, options) {
  636. if (options.format === "system") {
  637. const entryChunk = Object.values(bundle).find(
  638. (output) => output.type === "chunk" && output.isEntry
  639. );
  640. return !!entryChunk && entryChunk.fileName.includes("-legacy");
  641. }
  642. return false;
  643. }
  644. function recordAndRemovePolyfillBabelPlugin(polyfills) {
  645. return ({ types: t }) => ({
  646. name: "vite-remove-polyfill-import",
  647. post({ path: path2 }) {
  648. path2.get("body").forEach((p) => {
  649. if (t.isImportDeclaration(p.node)) {
  650. polyfills.add(p.node.source.value);
  651. p.remove();
  652. }
  653. });
  654. }
  655. });
  656. }
  657. function replaceLegacyEnvBabelPlugin() {
  658. return ({ types: t }) => ({
  659. name: "vite-replace-env-legacy",
  660. visitor: {
  661. Identifier(path2) {
  662. if (path2.node.name === legacyEnvVarMarker) {
  663. path2.replaceWith(t.booleanLiteral(true));
  664. }
  665. }
  666. }
  667. });
  668. }
  669. function wrapIIFEBabelPlugin() {
  670. return ({ types: t, template }) => {
  671. const buildIIFE = template(";(function(){%%body%%})();");
  672. return {
  673. name: "vite-wrap-iife",
  674. post({ path: path2 }) {
  675. if (!this.isWrapped) {
  676. this.isWrapped = true;
  677. path2.replaceWith(t.program(buildIIFE({ body: path2.node.body })));
  678. }
  679. }
  680. };
  681. };
  682. }
  683. const cspHashes = [
  684. safari10NoModuleFix,
  685. systemJSInlineCode,
  686. detectModernBrowserCode,
  687. dynamicFallbackInlineCode
  688. ].map((i) => createHash("sha256").update(i).digest("base64"));
  689. export { cspHashes, viteLegacyPlugin as default, detectPolyfills };