index.js 24 KB

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