index.cjs 24 KB

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