index.cjs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. "use strict";
  2. const path = require("node:path");
  3. const os = require("node:os");
  4. const node_module = require("node:module");
  5. const fastGlob = require("fast-glob");
  6. const path$1 = require("path");
  7. const fs = require("fs");
  8. const _interopDefaultLegacy = (e) => e && typeof e === "object" && "default" in e ? e : { default: e };
  9. const path__default = /* @__PURE__ */ _interopDefaultLegacy(path);
  10. const os__default = /* @__PURE__ */ _interopDefaultLegacy(os);
  11. const fastGlob__default = /* @__PURE__ */ _interopDefaultLegacy(fastGlob);
  12. const path$1__default = /* @__PURE__ */ _interopDefaultLegacy(path$1);
  13. const fs__default = /* @__PURE__ */ _interopDefaultLegacy(fs);
  14. const DEFAULT_EXTENSIONS = [
  15. ".mjs",
  16. ".js",
  17. ".mts",
  18. ".ts",
  19. ".jsx",
  20. ".tsx",
  21. ".json"
  22. ];
  23. const KNOWN_SFC_EXTENSIONS = [
  24. ".vue",
  25. ".svelte"
  26. ];
  27. const KNOWN_ASSET_TYPES = [
  28. "png",
  29. "jpe?g",
  30. "jfif",
  31. "pjpeg",
  32. "pjp",
  33. "gif",
  34. "svg",
  35. "ico",
  36. "webp",
  37. "avif",
  38. "mp4",
  39. "webm",
  40. "ogg",
  41. "mp3",
  42. "wav",
  43. "flac",
  44. "aac",
  45. "woff2?",
  46. "eot",
  47. "ttf",
  48. "otf",
  49. "webmanifest",
  50. "pdf",
  51. "txt"
  52. ];
  53. const KNOWN_CSS_TYPES = [
  54. "css",
  55. "less",
  56. "sass",
  57. "scss",
  58. "styl",
  59. "stylus",
  60. "pcss",
  61. "postcss"
  62. ];
  63. const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm;
  64. const singlelineCommentsRE = /\/\/.*/g;
  65. class MagicString {
  66. constructor(str) {
  67. this.str = str;
  68. this.starts = "";
  69. this.ends = "";
  70. }
  71. append(content) {
  72. this.ends += content;
  73. return this;
  74. }
  75. prepend(content) {
  76. this.starts = content + this.starts;
  77. return this;
  78. }
  79. overwrite(start, end, content) {
  80. if (end < start) {
  81. throw new Error(`"end" con't be less than "start".`);
  82. }
  83. if (!this.overwrites) {
  84. this.overwrites = [];
  85. }
  86. this.overwrites.push({ loc: [start, end], content });
  87. return this;
  88. }
  89. toString() {
  90. let str = this.str;
  91. if (this.overwrites) {
  92. const arr = [...this.overwrites].sort((a, b) => b.loc[0] - a.loc[0]);
  93. for (const { loc: [start, end], content } of arr) {
  94. str = str.slice(0, start) + content + str.slice(end);
  95. }
  96. }
  97. return this.starts + str + this.ends;
  98. }
  99. }
  100. function relativeify$1(relative) {
  101. if (relative === "") {
  102. return ".";
  103. }
  104. if (!relative.startsWith(".")) {
  105. return "./" + relative;
  106. }
  107. return relative;
  108. }
  109. async function walk(ast, visitors, ancestors = []) {
  110. var _a;
  111. if (!ast)
  112. return;
  113. if (Array.isArray(ast)) {
  114. for (const element of ast) {
  115. await walk(element, visitors, ancestors);
  116. }
  117. } else {
  118. ancestors = ancestors.concat(ast);
  119. for (const key of Object.keys(ast)) {
  120. await (typeof ast[key] === "object" && walk(ast[key], visitors, ancestors));
  121. }
  122. }
  123. await ((_a = visitors[ast.type]) === null || _a === void 0 ? void 0 : _a.call(visitors, ast, ancestors));
  124. }
  125. walk.sync = function walkSync(ast, visitors, ancestors = []) {
  126. var _a;
  127. if (!ast)
  128. return;
  129. if (Array.isArray(ast)) {
  130. for (const element of ast) {
  131. walkSync(element, visitors, ancestors);
  132. }
  133. } else {
  134. ancestors = ancestors.concat(ast);
  135. for (const key of Object.keys(ast)) {
  136. typeof ast[key] === "object" && walkSync(ast[key], visitors, ancestors);
  137. }
  138. }
  139. (_a = visitors[ast.type]) === null || _a === void 0 ? void 0 : _a.call(visitors, ast, ancestors);
  140. };
  141. const isWindows$1 = os__default.default.platform() === "win32";
  142. function slash$1(p) {
  143. return p.replace(/\\/g, "/");
  144. }
  145. function normalizePath$1(id) {
  146. return path__default.default.posix.normalize(isWindows$1 ? slash$1(id) : id);
  147. }
  148. var TopScopeType = /* @__PURE__ */ ((TopScopeType2) => {
  149. TopScopeType2["ExpressionStatement"] = "ExpressionStatement";
  150. TopScopeType2["VariableDeclaration"] = "VariableDeclaration";
  151. return TopScopeType2;
  152. })(TopScopeType || {});
  153. function analyzer(ast, code, id) {
  154. const analyzed = {
  155. ast,
  156. code,
  157. id,
  158. require: [],
  159. exports: []
  160. };
  161. walk.sync(ast, {
  162. CallExpression(node, ancestors) {
  163. if (node.callee.name !== "require")
  164. return;
  165. const dynamic = checkDynamicId(node);
  166. analyzed.require.push({
  167. node,
  168. ancestors,
  169. topScopeNode: dynamic === "dynamic" ? void 0 : findTopLevelScope(ancestors),
  170. dynamic: checkDynamicId(node)
  171. });
  172. },
  173. AssignmentExpression(node) {
  174. if (node.left.type !== "MemberExpression")
  175. return;
  176. if (!(node.left.object.type === "Identifier" && ["module", "exports"].includes(node.left.object.name)))
  177. return;
  178. analyzed.exports.push({
  179. node,
  180. token: {
  181. left: node.left.object.name,
  182. right: node.left.property.name
  183. }
  184. });
  185. }
  186. });
  187. return analyzed;
  188. }
  189. function checkDynamicId(node) {
  190. var _a, _b, _c;
  191. if (((_a = node.arguments[0]) == null ? void 0 : _a.type) === "TemplateLiteral" && ((_b = node.arguments[0]) == null ? void 0 : _b.quasis.length) === 1) {
  192. return "Literal";
  193. }
  194. return ((_c = node.arguments[0]) == null ? void 0 : _c.type) !== "Literal" ? "dynamic" : void 0;
  195. }
  196. function findTopLevelScope(ancestors) {
  197. const ances = ancestors.map((an) => an.type).join();
  198. const arr = [...ancestors].reverse();
  199. if (/Program,ExpressionStatement,(MemberExpression,)?CallExpression$/.test(ances)) {
  200. return arr.find((e) => e.type === "ExpressionStatement");
  201. }
  202. if (/Program,VariableDeclaration,VariableDeclarator,(MemberExpression,)?CallExpression$/.test(ances)) {
  203. return arr.find((e) => e.type === "VariableDeclaration");
  204. }
  205. }
  206. function generateImport(analyzed) {
  207. var _a;
  208. const imports = [];
  209. let count = 0;
  210. for (const req of analyzed.require) {
  211. const {
  212. node,
  213. ancestors,
  214. topScopeNode,
  215. dynamic
  216. } = req;
  217. if (dynamic === "dynamic")
  218. continue;
  219. const impt = { node, topScopeNode };
  220. const importName = `__CJS__import__${count++}__`;
  221. const requireIdNode = node.arguments[0];
  222. let requireId;
  223. if (!requireIdNode)
  224. continue;
  225. if (requireIdNode.type === "Literal") {
  226. requireId = requireIdNode.value;
  227. } else if (dynamic === "Literal") {
  228. requireId = requireIdNode.quasis[0].value.raw;
  229. }
  230. if (!requireId) {
  231. const codeSnippets = analyzed.code.slice(node.start, node.end);
  232. throw new Error(`The following require statement cannot be converted.
  233. -> ${codeSnippets}
  234. ${"^".repeat(codeSnippets.length)}`);
  235. }
  236. if (topScopeNode) {
  237. switch (topScopeNode.type) {
  238. case TopScopeType.ExpressionStatement:
  239. impt.importee = `import '${requireId}'`;
  240. break;
  241. case TopScopeType.VariableDeclaration:
  242. const VariableDeclarator = topScopeNode.declarations[0];
  243. const { id, init } = VariableDeclarator;
  244. let LV;
  245. if (id.type === "Identifier") {
  246. LV = id.name;
  247. } else if (id.type === "ObjectPattern") {
  248. LV = [];
  249. for (const { key, value } of id.properties) {
  250. LV.push({ key: key.name, value: value.name });
  251. }
  252. } else {
  253. throw new Error(`Unknown VariableDeclarator.id.type(L-V): ${id.type}`);
  254. }
  255. const LV_str = (spe) => typeof LV === "object" ? LV.map((e) => e.key === e.value ? e.key : `${e.key} ${spe} ${e.value}`).join(", ") : "";
  256. if (init.type === "CallExpression") {
  257. if (typeof LV === "string") {
  258. impt.importee = `import * as ${LV} from '${requireId}'`;
  259. } else {
  260. impt.importee = `import { ${LV_str("as")} } from '${requireId}'`;
  261. }
  262. } else if (init.type === "MemberExpression") {
  263. const onlyOneMember = (_a = ancestors.find((an) => an.type === "MemberExpression")) == null ? void 0 : _a.property.name;
  264. const importDefault = onlyOneMember === "default";
  265. if (typeof LV === "string") {
  266. if (importDefault) {
  267. impt.importee = `import ${LV} from '${requireId}'`;
  268. } else {
  269. impt.importee = onlyOneMember === LV ? `import { ${LV} } from '${requireId}'` : `import { ${onlyOneMember} as ${LV} } from '${requireId}'`;
  270. }
  271. } else {
  272. if (importDefault) {
  273. impt.importee = `import ${importName} from '${requireId}'`;
  274. } else {
  275. impt.importee = `import { ${onlyOneMember} as ${importName} } from '${requireId}'`;
  276. }
  277. impt.declaration = `const { ${LV_str(":")} } = ${importName}`;
  278. }
  279. } else {
  280. throw new Error(`Unknown VariableDeclarator.init.type(R-V): ${id.init}`);
  281. }
  282. break;
  283. default:
  284. throw new Error(`Unknown TopScopeType: ${topScopeNode}`);
  285. }
  286. } else {
  287. impt.importee = `import * as ${importName} from '${requireId}'`;
  288. impt.importName = importName;
  289. }
  290. imports.push(impt);
  291. }
  292. return imports;
  293. }
  294. function generateExport(analyzed) {
  295. if (!analyzed.exports.length) {
  296. return null;
  297. }
  298. const memberDefault = analyzed.exports.find((exp) => exp.token.left === "module" || exp.token.right === "default");
  299. let members = analyzed.exports.filter((exp) => exp.token.left !== "module" && exp.token.right !== "default").map((exp) => exp.token.right);
  300. members = [...new Set(members)];
  301. const membersDeclaration = members.map(
  302. (m) => `const __CJS__export_${m}__ = (module.exports == null ? {} : module.exports).${m}`
  303. );
  304. const membersExport = members.map((m) => `__CJS__export_${m}__ as ${m}`);
  305. if (memberDefault) {
  306. membersDeclaration.unshift(`const __CJS__export_default__ = (module.exports == null ? {} : module.exports).default || module.exports`);
  307. membersExport.unshift("__CJS__export_default__ as default");
  308. }
  309. return {
  310. polyfill: "const module = { exports: {} }; const exports = module.exports;",
  311. exportDeclaration: `
  312. ${membersDeclaration.join(";\n")};
  313. export {
  314. ${membersExport.join(",\n ")},
  315. }
  316. `.trim()
  317. };
  318. }
  319. const normallyImporteeRE = /^\.{1,2}\/[.-/\w]+(\.\w+)$/;
  320. [
  321. ...node_module.builtinModules.map((m) => !m.startsWith("_")),
  322. ...node_module.builtinModules.map((m) => !m.startsWith("_")).map((m) => `node:${m}`)
  323. ];
  324. function isCommonjs(code) {
  325. code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
  326. return /\b(?:require|module|exports)\b/.test(code);
  327. }
  328. function relativeify(relative) {
  329. if (relative === "") {
  330. return ".";
  331. }
  332. if (!relative.startsWith(".")) {
  333. return "./" + relative;
  334. }
  335. return relative;
  336. }
  337. const isWindows = os__default.default.platform() === "win32";
  338. function slash(p) {
  339. return p.replace(/\\/g, "/");
  340. }
  341. function normalizePath(id) {
  342. return path__default.default.posix.normalize(isWindows ? slash(id) : id);
  343. }
  344. function toLooseGlob(glob) {
  345. if (glob.includes("**"))
  346. return glob;
  347. const lastIndex = glob.lastIndexOf("*");
  348. let tail = "";
  349. if (lastIndex > -1) {
  350. tail = glob.slice(lastIndex + 1);
  351. glob = glob.slice(0, lastIndex + 1);
  352. }
  353. if (glob.endsWith("/*")) {
  354. return glob + "*/*" + tail;
  355. }
  356. if (glob.endsWith("*")) {
  357. return [glob + tail, glob + "/**" + (tail.startsWith("/") ? tail : "/*" + tail)];
  358. }
  359. return glob + tail;
  360. }
  361. function mappingPath(paths, alias) {
  362. const maps = {};
  363. for (const p of paths) {
  364. let importee = p;
  365. if (alias) {
  366. const [find, replacement] = Object.entries(alias)[0];
  367. importee = p.replace(find, replacement);
  368. }
  369. const ext = path$1__default.default.extname(importee);
  370. maps[p] = [
  371. importee.endsWith(`/index${ext}`) && importee.replace(`/index${ext}`, ""),
  372. importee.replace(ext, ""),
  373. importee
  374. ].filter(Boolean);
  375. }
  376. return maps;
  377. }
  378. class Resolve {
  379. constructor(config, resolve = config.createResolver()) {
  380. this.config = config;
  381. this.resolve = resolve;
  382. }
  383. async tryResolve(importee, importer) {
  384. return await this.tryResolveAlias(importee, importer) || this.tryResolveBare(importee, importer);
  385. }
  386. async tryResolveAlias(importee, importer) {
  387. const { importee: ipte, importeeRaw = ipte } = this.parseImportee(importee);
  388. const resolvedId = await this.resolve(ipte, importer, true);
  389. if (!resolvedId)
  390. return;
  391. const alias = this.config.resolve.alias.find(
  392. (a) => a.find instanceof RegExp ? a.find.test(ipte) : ipte.startsWith(a.find + "/")
  393. );
  394. if (!alias)
  395. return;
  396. const findString = alias.find instanceof RegExp ? alias.find.exec(importee)[0] : alias.find;
  397. const relativePath = alias.replacement.startsWith(".") ? alias.replacement : relativeify(path$1__default.default.posix.relative(path$1__default.default.dirname(importer), alias.replacement));
  398. const resolvedAlias = {
  399. ...alias,
  400. findString,
  401. relative: findString.endsWith("/") ? relativePath.endsWith("/") ? relativePath : relativePath + "/" : relativePath
  402. };
  403. return {
  404. type: "alias",
  405. ...this.resolveAlias(importeeRaw, importer, resolvedAlias)
  406. };
  407. }
  408. tryResolveBare(importee, importer) {
  409. const { importee: ipte, importeeRaw = ipte } = this.parseImportee(importee);
  410. if (/^[\.\/]/.test(ipte)) {
  411. return;
  412. }
  413. const paths = ipte.split("/");
  414. const node_modules = path$1__default.default.join(this.config.root, "node_modules");
  415. let level = "";
  416. let find, replacement;
  417. let p;
  418. while (p = paths.shift()) {
  419. level = path$1__default.default.posix.join(level, p);
  420. const fullPath = path$1__default.default.join(node_modules, level);
  421. if (fs__default.default.existsSync(fullPath)) {
  422. find = level;
  423. const relativePath = relativeify(path$1__default.default.posix.relative(path$1__default.default.dirname(importer), node_modules));
  424. replacement = `${relativePath}/${level}`;
  425. }
  426. }
  427. if (!find)
  428. return;
  429. const alias = {
  430. find,
  431. replacement,
  432. findString: find,
  433. relative: replacement.startsWith(".") ? replacement : relativeify(path$1__default.default.posix.relative(path$1__default.default.dirname(importer), replacement))
  434. };
  435. return {
  436. type: "bare",
  437. ...this.resolveAlias(importeeRaw, importer, alias)
  438. };
  439. }
  440. resolveAlias(importee, importer, alias) {
  441. const { find, replacement } = alias;
  442. let {
  443. importee: ipte,
  444. importeeRaw = ipte,
  445. startQuotation = ""
  446. } = this.parseImportee(importee);
  447. if (replacement.startsWith(".")) {
  448. ipte = ipte.replace(find, replacement);
  449. } else {
  450. const relativePath = relativeify(path$1__default.default.posix.relative(
  451. path$1__default.default.dirname(importer),
  452. normalizePath(replacement)
  453. ));
  454. ipte = ipte.replace(find instanceof RegExp ? find : find + "/", "");
  455. ipte = `${relativePath}/${ipte}`;
  456. }
  457. return {
  458. alias,
  459. import: {
  460. importee: importeeRaw,
  461. importer,
  462. resolved: startQuotation + ipte
  463. }
  464. };
  465. }
  466. parseImportee(importee) {
  467. const result = { importee };
  468. if (/^[`'"]/.test(importee)) {
  469. result.importee = importee.slice(1);
  470. result.importeeRaw = importee;
  471. result.startQuotation = importee.slice(0, 1);
  472. }
  473. return result;
  474. }
  475. }
  476. const example = "For example: import(`./foo/${bar}.js`).";
  477. function sanitizeString(str) {
  478. if (str.includes("*")) {
  479. throw new Error("A dynamic import cannot contain * characters.");
  480. }
  481. return str;
  482. }
  483. function templateLiteralToGlob(node) {
  484. let glob = "";
  485. for (let i = 0; i < node.quasis.length; i += 1) {
  486. glob += sanitizeString(node.quasis[i].value.raw);
  487. if (node.expressions[i]) {
  488. glob += expressionToGlob(node.expressions[i]);
  489. }
  490. }
  491. return glob;
  492. }
  493. function callExpressionToGlob(node) {
  494. const { callee } = node;
  495. if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "concat") {
  496. return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join("")}`;
  497. }
  498. return "*";
  499. }
  500. function binaryExpressionToGlob(node) {
  501. if (node.operator !== "+") {
  502. throw new Error(`${node.operator} operator is not supported.`);
  503. }
  504. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  505. }
  506. function expressionToGlob(node) {
  507. switch (node.type) {
  508. case "TemplateLiteral":
  509. return templateLiteralToGlob(node);
  510. case "CallExpression":
  511. return callExpressionToGlob(node);
  512. case "BinaryExpression":
  513. return binaryExpressionToGlob(node);
  514. case "Literal":
  515. return sanitizeString(node.value);
  516. default:
  517. return "*";
  518. }
  519. }
  520. async function dynamicImportToGlob(node, sourceString, resolver) {
  521. var _a;
  522. let glob = expressionToGlob(node);
  523. glob = (_a = await (resolver == null ? void 0 : resolver(glob))) != null ? _a : glob;
  524. if (!glob.includes("*") || glob.startsWith("data:")) {
  525. return null;
  526. }
  527. glob = glob.replace(/\*\*/g, "*");
  528. if (glob.startsWith("*")) {
  529. throw new Error(
  530. `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
  531. );
  532. }
  533. if (glob.startsWith("/")) {
  534. throw new Error(
  535. `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  536. );
  537. }
  538. if (!glob.startsWith("./") && !glob.startsWith("../")) {
  539. throw new Error(
  540. `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  541. );
  542. }
  543. const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/;
  544. if (ownDirectoryStarExtension.test(glob)) {
  545. throw new Error(
  546. `invalid import "${sourceString}". Variable imports cannot import their own directory, place imports in a separate directory or make the import filename more specific. ${example}`
  547. );
  548. }
  549. if (path$1__default.default.extname(glob) === "") {
  550. throw new Error(
  551. `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
  552. );
  553. }
  554. return glob;
  555. }
  556. class DynaimcRequire {
  557. constructor(config, options, resolve = new Resolve(config)) {
  558. this.config = config;
  559. this.options = options;
  560. this.resolve = resolve;
  561. }
  562. async generateRuntime(analyzed) {
  563. var _a, _b, _c;
  564. const options = this.options;
  565. const id = analyzed.id;
  566. let counter = 0;
  567. const importCache = /* @__PURE__ */ new Map();
  568. const records = [];
  569. for (const req of analyzed.require) {
  570. const { node, dynamic } = req;
  571. if (dynamic !== "dynamic")
  572. continue;
  573. const globResult = await globFiles(
  574. node,
  575. analyzed.code,
  576. analyzed.id,
  577. this.resolve,
  578. this.options.extensions,
  579. ((_a = options.dynamic) == null ? void 0 : _a.loose) !== false
  580. );
  581. if (!globResult)
  582. continue;
  583. const record = { node };
  584. let { files, resolved, normally } = globResult;
  585. files = files.filter((f) => normalizePath$1(path__default.default.join(path__default.default.dirname(id), f)) !== id);
  586. ((_b = options.dynamic) == null ? void 0 : _b.onFiles) && (files = ((_c = options.dynamic) == null ? void 0 : _c.onFiles(files, id)) || files);
  587. if (normally) {
  588. record.normally = normally;
  589. continue;
  590. }
  591. if (!(files == null ? void 0 : files.length))
  592. continue;
  593. const maps = mappingPath(
  594. files,
  595. resolved ? { [resolved.alias.relative]: resolved.alias.findString } : void 0
  596. );
  597. let counter2 = 0;
  598. record.dynaimc = {
  599. importee: [],
  600. runtimeName: `__matchRequireRuntime${counter}__`,
  601. runtimeFn: ""
  602. };
  603. const cases = [];
  604. for (const [localFile, importeeList] of Object.entries(maps)) {
  605. let dynamic_require2import = importCache.get(localFile);
  606. if (!dynamic_require2import) {
  607. importCache.set(
  608. localFile,
  609. dynamic_require2import = `__dynamic_require2import__${counter}__${counter2++}`
  610. );
  611. }
  612. record.dynaimc.importee.push(`import * as ${dynamic_require2import} from '${localFile}'`);
  613. cases.push(importeeList.map((importee) => ` case '${importee}':`).concat(` return ${dynamic_require2import};`).join("\n"));
  614. }
  615. record.dynaimc.runtimeFn = `function ${record.dynaimc.runtimeName}(path) {
  616. switch(path) {
  617. ${cases.join("\n")}
  618. default: throw new Error("Cann't found module: " + path);
  619. }
  620. }`;
  621. records.push(record);
  622. }
  623. return records.length ? records : null;
  624. }
  625. }
  626. async function globFiles(node, code, importer, resolve, extensions, loose = true) {
  627. let files;
  628. let resolved;
  629. let normally;
  630. const PAHT_FILL = "####/";
  631. const EXT_FILL = ".extension";
  632. let glob;
  633. let globRaw;
  634. glob = await dynamicImportToGlob(
  635. node.arguments[0],
  636. code.slice(node.start, node.end),
  637. async (raw) => {
  638. globRaw = raw;
  639. resolved = await resolve.tryResolve(raw, importer);
  640. if (resolved) {
  641. raw = resolved.import.resolved;
  642. }
  643. if (!path__default.default.extname(raw)) {
  644. raw = raw + EXT_FILL;
  645. }
  646. if (/^\.\/\*\.\w+$/.test(raw)) {
  647. raw = raw.replace("./*", `./${PAHT_FILL}*`);
  648. }
  649. return raw;
  650. }
  651. );
  652. if (!glob) {
  653. if (normallyImporteeRE.test(globRaw)) {
  654. normally = globRaw;
  655. return { normally };
  656. }
  657. return;
  658. }
  659. const globs = [].concat(loose ? toLooseGlob(glob) : glob).map((g) => {
  660. g.includes(PAHT_FILL) && (g = g.replace(PAHT_FILL, ""));
  661. g.endsWith(EXT_FILL) && (g = g.replace(EXT_FILL, ""));
  662. return g;
  663. });
  664. const fileGlobs = globs.map(
  665. (g) => path__default.default.extname(g) ? g : g + `.{${extensions.map((e) => e.replace(/^\./, "")).join(",")}}`
  666. );
  667. files = fastGlob__default.default.sync(fileGlobs, { cwd: path__default.default.dirname(importer) }).map((file) => relativeify$1(file));
  668. return { files, resolved };
  669. }
  670. function commonjs(options = {}) {
  671. let config;
  672. let extensions = DEFAULT_EXTENSIONS;
  673. let dynaimcRequire;
  674. return {
  675. apply: "serve",
  676. name: "vite-plugin-commonjs",
  677. configResolved(_config) {
  678. var _a;
  679. config = _config;
  680. if ((_a = config.resolve) == null ? void 0 : _a.extensions)
  681. extensions = config.resolve.extensions;
  682. dynaimcRequire = new DynaimcRequire(_config, {
  683. ...options,
  684. extensions: [
  685. ...extensions,
  686. ...KNOWN_SFC_EXTENSIONS,
  687. ...KNOWN_ASSET_TYPES.map((type) => "." + type),
  688. ...KNOWN_CSS_TYPES.map((type) => "." + type)
  689. ]
  690. });
  691. },
  692. async transform(code, id) {
  693. var _a;
  694. if (/node_modules\/(?!\.vite\/)/.test(id))
  695. return;
  696. if (!extensions.includes(path__default.default.extname(id)))
  697. return;
  698. if (!isCommonjs(code))
  699. return;
  700. if (((_a = options.filter) == null ? void 0 : _a.call(options, id)) === false)
  701. return;
  702. const ast = this.parse(code);
  703. const analyzed = analyzer(ast, code, id);
  704. const imports = generateImport(analyzed);
  705. const exportRuntime = id.includes("node_modules/.vite") ? null : generateExport(analyzed);
  706. const dynamics = await dynaimcRequire.generateRuntime(analyzed);
  707. const hoistImports = [];
  708. const ms = new MagicString(code);
  709. for (const impt of imports) {
  710. const {
  711. node,
  712. importee: imptee,
  713. declaration,
  714. importName,
  715. topScopeNode
  716. } = impt;
  717. const importee = imptee + ";";
  718. let importStatement;
  719. if (topScopeNode) {
  720. if (topScopeNode.type === TopScopeType.ExpressionStatement) {
  721. importStatement = importee;
  722. } else if (topScopeNode.type === TopScopeType.VariableDeclaration) {
  723. importStatement = declaration ? `${importee} ${declaration};` : importee;
  724. }
  725. } else {
  726. hoistImports.push(importee);
  727. importStatement = importName;
  728. }
  729. if (importStatement) {
  730. const start = topScopeNode ? topScopeNode.start : node.start;
  731. const end = topScopeNode ? topScopeNode.end : node.end;
  732. ms.overwrite(start, end, importStatement);
  733. }
  734. }
  735. if (hoistImports.length) {
  736. ms.prepend(["/* import-hoist-S */", ...hoistImports, "/* import-hoist-E */"].join(" "));
  737. }
  738. if (exportRuntime) {
  739. const polyfill = [
  740. "/* export-runtime-S */",
  741. exportRuntime.polyfill,
  742. "/* export-runtime-E */"
  743. ].join(" ");
  744. const _exports = [
  745. "/* export-statement-S */",
  746. exportRuntime.exportDeclaration,
  747. "/* export-statement-E */"
  748. ].filter(Boolean).join("\n");
  749. ms.prepend(polyfill).append(_exports);
  750. }
  751. if (dynamics) {
  752. const requires = [];
  753. const runtimes = [];
  754. let count = 0;
  755. for (const dynamic of dynamics) {
  756. const { node, normally, dynaimc: dymc } = dynamic;
  757. if (normally) {
  758. const name = `__require2import__${count++}__`;
  759. requires.push(`import * as ${name} from "${normally}";`);
  760. ms.overwrite(node.callee.start, node.callee.end, name);
  761. } else if (dymc) {
  762. requires.push(...dymc.importee.map((impt) => impt + ";"));
  763. runtimes.push(dymc.runtimeFn);
  764. ms.overwrite(node.callee.start, node.callee.end, dymc.runtimeFn);
  765. }
  766. }
  767. if (requires.length) {
  768. ms.prepend(["/* import-require2import-S */", ...requires, "/* import-require2import-E */"].join(" "));
  769. }
  770. if (runtimes.length) {
  771. ms.append(runtimes.join("\n"));
  772. }
  773. }
  774. const _code = ms.toString();
  775. return _code === code ? null : _code;
  776. }
  777. };
  778. }
  779. module.exports = commonjs;