index.mjs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. import { createRequire } from "node:module";
  2. import fs from "node:fs";
  3. import { createFilter, formatPostcssSourceMap, isCSSRequest, normalizePath, transformWithEsbuild } from "vite";
  4. import { computed, shallowRef } from "vue";
  5. import { exactRegex, makeIdFiltersToMatchWithQuery } from "@rolldown/pluginutils";
  6. import path from "node:path";
  7. import crypto from "node:crypto";
  8. import { isatty } from "node:tty";
  9. import { formatWithOptions, inspect } from "node:util";
  10. //#region package.json
  11. var version = "6.0.7";
  12. //#endregion
  13. //#region src/compiler.ts
  14. function resolveCompiler(root) {
  15. const compiler = tryResolveCompiler(root) || tryResolveCompiler();
  16. if (!compiler) throw new Error("Failed to resolve vue/compiler-sfc.\n@vitejs/plugin-vue requires vue (>=3.2.25) to be present in the dependency tree.");
  17. return compiler;
  18. }
  19. function tryResolveCompiler(root) {
  20. const vueMeta = tryRequire("vue/package.json", root);
  21. if (vueMeta && vueMeta.version.split(".")[0] >= 3) return tryRequire("vue/compiler-sfc", root);
  22. }
  23. const _require = createRequire(import.meta.url);
  24. function tryRequire(id, from) {
  25. try {
  26. return from ? _require(_require.resolve(id, { paths: [from] })) : _require(id);
  27. } catch (e) {}
  28. }
  29. //#endregion
  30. //#region src/utils/query.ts
  31. function parseVueRequest(id) {
  32. const [filename, rawQuery] = id.split(`?`, 2);
  33. const query = Object.fromEntries(new URLSearchParams(rawQuery));
  34. if (query.vue != null) query.vue = true;
  35. if (query.index != null) query.index = Number(query.index);
  36. if (query.raw != null) query.raw = true;
  37. if (query.url != null) query.url = true;
  38. if (query.scoped != null) query.scoped = true;
  39. return {
  40. filename,
  41. query
  42. };
  43. }
  44. //#endregion
  45. //#region src/utils/descriptorCache.ts
  46. const cache = /* @__PURE__ */ new Map();
  47. const hmrCache = /* @__PURE__ */ new Map();
  48. const prevCache = /* @__PURE__ */ new Map();
  49. function createDescriptor(filename, source, { root, isProduction, sourceMap, compiler, template, features }, hmr = false) {
  50. const { descriptor, errors } = compiler.parse(source, {
  51. filename,
  52. sourceMap,
  53. templateParseOptions: template?.compilerOptions
  54. });
  55. const normalizedPath = normalizePath(path.relative(root, filename));
  56. const componentIdGenerator = features?.componentIdGenerator;
  57. if (componentIdGenerator === "filepath") descriptor.id = getHash(normalizedPath);
  58. else if (componentIdGenerator === "filepath-source") descriptor.id = getHash(normalizedPath + source);
  59. else if (typeof componentIdGenerator === "function") descriptor.id = componentIdGenerator(normalizedPath, source, isProduction, getHash);
  60. else descriptor.id = getHash(normalizedPath + (isProduction ? source : ""));
  61. (hmr ? hmrCache : cache).set(filename, descriptor);
  62. return {
  63. descriptor,
  64. errors
  65. };
  66. }
  67. function getPrevDescriptor(filename) {
  68. return prevCache.get(filename);
  69. }
  70. function invalidateDescriptor(filename, hmr = false) {
  71. const _cache = hmr ? hmrCache : cache;
  72. const prev = _cache.get(filename);
  73. _cache.delete(filename);
  74. if (prev) prevCache.set(filename, prev);
  75. }
  76. function getDescriptor(filename, options, createIfNotFound = true, hmr = false, code) {
  77. const _cache = hmr ? hmrCache : cache;
  78. if (_cache.has(filename)) return _cache.get(filename);
  79. if (createIfNotFound) {
  80. const { descriptor, errors } = createDescriptor(filename, code ?? fs.readFileSync(filename, "utf-8"), options, hmr);
  81. if (errors.length && !hmr) throw errors[0];
  82. return descriptor;
  83. }
  84. }
  85. function getSrcDescriptor(filename, query) {
  86. if (query.scoped) return cache.get(`${filename}?src=${query.src}`);
  87. return cache.get(filename);
  88. }
  89. function getTempSrcDescriptor(filename, query) {
  90. return {
  91. filename,
  92. id: query.id || "",
  93. styles: [{
  94. scoped: query.scoped,
  95. loc: { start: {
  96. line: 0,
  97. column: 0
  98. } }
  99. }],
  100. isTemp: true
  101. };
  102. }
  103. function setSrcDescriptor(filename, entry, scoped) {
  104. if (scoped) {
  105. cache.set(`${filename}?src=${entry.id}`, entry);
  106. return;
  107. }
  108. cache.set(filename, entry);
  109. }
  110. function getHash(text) {
  111. return crypto.hash("sha256", text, "hex").substring(0, 8);
  112. }
  113. //#endregion
  114. //#region ../../node_modules/.pnpm/slash@5.1.0/node_modules/slash/index.js
  115. function slash(path) {
  116. if (path.startsWith("\\\\?\\")) return path;
  117. return path.replace(/\\/g, "/");
  118. }
  119. //#endregion
  120. //#region src/utils/error.ts
  121. function createRollupError(id, error) {
  122. const { message, name, stack } = error;
  123. const rollupError = {
  124. id,
  125. plugin: "vue",
  126. message,
  127. name,
  128. stack
  129. };
  130. if ("code" in error && error.loc) rollupError.loc = {
  131. file: id,
  132. line: error.loc.start.line,
  133. column: error.loc.start.column
  134. };
  135. return rollupError;
  136. }
  137. //#endregion
  138. //#region src/template.ts
  139. async function transformTemplateAsModule(code, filename, descriptor, options, pluginContext, ssr, customElement) {
  140. const result = compile(code, filename, descriptor, options, pluginContext, ssr, customElement);
  141. let returnCode = result.code;
  142. returnCode += `\nexport const multiRoot = ${JSON.stringify(result.multiRoot)}`;
  143. if (options.devServer && options.devServer.config.server.hmr !== false && !ssr && !options.isProduction) returnCode += `\nimport.meta.hot.accept(({ render }) => {
  144. __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(descriptor.id)}, render)
  145. })`;
  146. return {
  147. code: returnCode,
  148. map: result.map
  149. };
  150. }
  151. /**
  152. * transform the template directly in the main SFC module
  153. */
  154. function transformTemplateInMain(code, descriptor, options, pluginContext, ssr, customElement) {
  155. const result = compile(code, descriptor.filename, descriptor, options, pluginContext, ssr, customElement);
  156. return {
  157. ...result,
  158. code: result.code.replace(/\nexport (function|const) (render|ssrRender)/, "\n$1 _sfc_$2")
  159. };
  160. }
  161. function compile(code, filename, descriptor, options, pluginContext, ssr, customElement) {
  162. resolveScript(descriptor, options, ssr, customElement);
  163. const result = options.compiler.compileTemplate({
  164. ...resolveTemplateCompilerOptions(descriptor, options, filename, ssr),
  165. source: code
  166. });
  167. if (result.errors.length) result.errors.forEach((error) => pluginContext.error(typeof error === "string" ? {
  168. id: filename,
  169. message: error
  170. } : createRollupError(filename, error)));
  171. if (result.tips.length) result.tips.forEach((tip) => pluginContext.warn({
  172. id: filename,
  173. message: tip
  174. }));
  175. return result;
  176. }
  177. function resolveTemplateCompilerOptions(descriptor, options, filename, ssr) {
  178. const block = descriptor.template;
  179. if (!block) return;
  180. const resolvedScript = getResolvedScript(descriptor, ssr);
  181. const hasScoped = descriptor.styles.some((s) => s.scoped);
  182. const { id, cssVars } = descriptor;
  183. let transformAssetUrls = options.template?.transformAssetUrls;
  184. let assetUrlOptions;
  185. if (transformAssetUrls === false) {} else if (options.devServer) {
  186. if (filename.startsWith(options.root)) {
  187. const devBase = options.devServer.config.base;
  188. assetUrlOptions = {
  189. base: (options.devServer.config.server?.origin ?? "") + devBase + slash(path.relative(options.root, path.dirname(filename))),
  190. includeAbsolute: !!devBase
  191. };
  192. }
  193. } else assetUrlOptions = { includeAbsolute: true };
  194. if (transformAssetUrls && typeof transformAssetUrls === "object") if (Object.values(transformAssetUrls).some((val) => Array.isArray(val))) transformAssetUrls = {
  195. ...assetUrlOptions,
  196. tags: transformAssetUrls
  197. };
  198. else transformAssetUrls = {
  199. ...assetUrlOptions,
  200. ...transformAssetUrls
  201. };
  202. else transformAssetUrls = assetUrlOptions;
  203. let preprocessOptions = block.lang && options.template?.preprocessOptions;
  204. if (block.lang === "pug") preprocessOptions = {
  205. doctype: "html",
  206. ...preprocessOptions
  207. };
  208. const expressionPlugins = options.template?.compilerOptions?.expressionPlugins || [];
  209. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  210. if (lang && /tsx?$/.test(lang) && !expressionPlugins.includes("typescript")) expressionPlugins.push("typescript");
  211. return {
  212. ...options.template,
  213. vapor: descriptor.vapor,
  214. id,
  215. ast: canReuseAST(options.compiler.version) ? descriptor.template?.ast : void 0,
  216. filename,
  217. scoped: hasScoped,
  218. slotted: descriptor.slotted,
  219. isProd: options.isProduction,
  220. inMap: block.src ? void 0 : block.map,
  221. ssr,
  222. ssrCssVars: cssVars,
  223. transformAssetUrls,
  224. preprocessLang: block.lang === "html" ? void 0 : block.lang,
  225. preprocessOptions,
  226. compilerOptions: {
  227. ...options.template?.compilerOptions,
  228. scopeId: hasScoped ? `data-v-${id}` : void 0,
  229. bindingMetadata: resolvedScript ? resolvedScript.bindings : void 0,
  230. expressionPlugins,
  231. sourceMap: options.sourceMap
  232. }
  233. };
  234. }
  235. /**
  236. * Versions before 3.4.3 have issues when the user has passed additional
  237. * template parse options e.g. `isCustomElement`.
  238. */
  239. function canReuseAST(version) {
  240. if (version) {
  241. const [_, minor, patch] = version.split(".").map(Number);
  242. if (minor >= 4 && patch >= 3) return true;
  243. }
  244. return false;
  245. }
  246. //#endregion
  247. //#region src/script.ts
  248. let clientCache = /* @__PURE__ */ new WeakMap();
  249. let ssrCache = /* @__PURE__ */ new WeakMap();
  250. const typeDepToSFCMap = /* @__PURE__ */ new Map();
  251. function invalidateScript(filename) {
  252. const desc = cache.get(filename);
  253. if (desc) {
  254. clientCache.delete(desc);
  255. ssrCache.delete(desc);
  256. }
  257. }
  258. function getResolvedScript(descriptor, ssr) {
  259. return (ssr ? ssrCache : clientCache).get(descriptor);
  260. }
  261. function setResolvedScript(descriptor, script, ssr) {
  262. (ssr ? ssrCache : clientCache).set(descriptor, script);
  263. }
  264. function clearScriptCache() {
  265. clientCache = /* @__PURE__ */ new WeakMap();
  266. ssrCache = /* @__PURE__ */ new WeakMap();
  267. }
  268. function isUseInlineTemplate(descriptor, options) {
  269. return !options.devServer && !options.devToolsEnabled && !!descriptor.scriptSetup && !descriptor.template?.src;
  270. }
  271. const scriptIdentifier = `_sfc_main`;
  272. function resolveScript(descriptor, options, ssr, customElement) {
  273. if (!descriptor.script && !descriptor.scriptSetup) return null;
  274. const cached = getResolvedScript(descriptor, ssr);
  275. if (cached) return cached;
  276. const resolved = options.compiler.compileScript(descriptor, {
  277. ...options.script,
  278. id: descriptor.id,
  279. isProd: options.isProduction,
  280. inlineTemplate: isUseInlineTemplate(descriptor, options),
  281. templateOptions: resolveTemplateCompilerOptions(descriptor, options, descriptor.filename, ssr),
  282. sourceMap: options.sourceMap,
  283. genDefaultAs: canInlineMain(descriptor, options) ? scriptIdentifier : void 0,
  284. customElement,
  285. propsDestructure: options.features?.propsDestructure ?? options.script?.propsDestructure
  286. });
  287. if (!options.isProduction && resolved?.deps) {
  288. for (const [key, sfcs] of typeDepToSFCMap) if (sfcs.has(descriptor.filename) && !resolved.deps.includes(key)) sfcs.delete(descriptor.filename);
  289. for (const dep of resolved.deps) {
  290. const existingSet = typeDepToSFCMap.get(dep);
  291. if (!existingSet) typeDepToSFCMap.set(dep, new Set([descriptor.filename]));
  292. else existingSet.add(descriptor.filename);
  293. }
  294. }
  295. setResolvedScript(descriptor, resolved, ssr);
  296. return resolved;
  297. }
  298. function canInlineMain(descriptor, options) {
  299. if (descriptor.script?.src || descriptor.scriptSetup?.src) return false;
  300. const lang = descriptor.script?.lang || descriptor.scriptSetup?.lang;
  301. if (!lang || lang === "js") return true;
  302. if (lang === "ts" && options.devServer) return true;
  303. return false;
  304. }
  305. //#endregion
  306. //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  307. var comma = ",".charCodeAt(0);
  308. var semicolon = ";".charCodeAt(0);
  309. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  310. var intToChar = new Uint8Array(64);
  311. var charToInt = new Uint8Array(128);
  312. for (let i = 0; i < chars.length; i++) {
  313. const c = chars.charCodeAt(i);
  314. intToChar[i] = c;
  315. charToInt[c] = i;
  316. }
  317. function decodeInteger(reader, relative) {
  318. let value = 0;
  319. let shift = 0;
  320. let integer = 0;
  321. do {
  322. integer = charToInt[reader.next()];
  323. value |= (integer & 31) << shift;
  324. shift += 5;
  325. } while (integer & 32);
  326. const shouldNegate = value & 1;
  327. value >>>= 1;
  328. if (shouldNegate) value = -2147483648 | -value;
  329. return relative + value;
  330. }
  331. function encodeInteger(builder, num, relative) {
  332. let delta = num - relative;
  333. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  334. do {
  335. let clamped = delta & 31;
  336. delta >>>= 5;
  337. if (delta > 0) clamped |= 32;
  338. builder.write(intToChar[clamped]);
  339. } while (delta > 0);
  340. return num;
  341. }
  342. function hasMoreVlq(reader, max) {
  343. if (reader.pos >= max) return false;
  344. return reader.peek() !== comma;
  345. }
  346. var bufLength = 1024 * 16;
  347. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
  348. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
  349. } } : { decode(buf) {
  350. let out = "";
  351. for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
  352. return out;
  353. } };
  354. var StringWriter = class {
  355. constructor() {
  356. this.pos = 0;
  357. this.out = "";
  358. this.buffer = new Uint8Array(bufLength);
  359. }
  360. write(v) {
  361. const { buffer } = this;
  362. buffer[this.pos++] = v;
  363. if (this.pos === bufLength) {
  364. this.out += td.decode(buffer);
  365. this.pos = 0;
  366. }
  367. }
  368. flush() {
  369. const { buffer, out, pos } = this;
  370. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  371. }
  372. };
  373. var StringReader = class {
  374. constructor(buffer) {
  375. this.pos = 0;
  376. this.buffer = buffer;
  377. }
  378. next() {
  379. return this.buffer.charCodeAt(this.pos++);
  380. }
  381. peek() {
  382. return this.buffer.charCodeAt(this.pos);
  383. }
  384. indexOf(char) {
  385. const { buffer, pos } = this;
  386. const idx = buffer.indexOf(char, pos);
  387. return idx === -1 ? buffer.length : idx;
  388. }
  389. };
  390. function decode(mappings) {
  391. const { length } = mappings;
  392. const reader = new StringReader(mappings);
  393. const decoded = [];
  394. let genColumn = 0;
  395. let sourcesIndex = 0;
  396. let sourceLine = 0;
  397. let sourceColumn = 0;
  398. let namesIndex = 0;
  399. do {
  400. const semi = reader.indexOf(";");
  401. const line = [];
  402. let sorted = true;
  403. let lastCol = 0;
  404. genColumn = 0;
  405. while (reader.pos < semi) {
  406. let seg;
  407. genColumn = decodeInteger(reader, genColumn);
  408. if (genColumn < lastCol) sorted = false;
  409. lastCol = genColumn;
  410. if (hasMoreVlq(reader, semi)) {
  411. sourcesIndex = decodeInteger(reader, sourcesIndex);
  412. sourceLine = decodeInteger(reader, sourceLine);
  413. sourceColumn = decodeInteger(reader, sourceColumn);
  414. if (hasMoreVlq(reader, semi)) {
  415. namesIndex = decodeInteger(reader, namesIndex);
  416. seg = [
  417. genColumn,
  418. sourcesIndex,
  419. sourceLine,
  420. sourceColumn,
  421. namesIndex
  422. ];
  423. } else seg = [
  424. genColumn,
  425. sourcesIndex,
  426. sourceLine,
  427. sourceColumn
  428. ];
  429. } else seg = [genColumn];
  430. line.push(seg);
  431. reader.pos++;
  432. }
  433. if (!sorted) sort(line);
  434. decoded.push(line);
  435. reader.pos = semi + 1;
  436. } while (reader.pos <= length);
  437. return decoded;
  438. }
  439. function sort(line) {
  440. line.sort(sortComparator$1);
  441. }
  442. function sortComparator$1(a, b) {
  443. return a[0] - b[0];
  444. }
  445. function encode(decoded) {
  446. const writer = new StringWriter();
  447. let sourcesIndex = 0;
  448. let sourceLine = 0;
  449. let sourceColumn = 0;
  450. let namesIndex = 0;
  451. for (let i = 0; i < decoded.length; i++) {
  452. const line = decoded[i];
  453. if (i > 0) writer.write(semicolon);
  454. if (line.length === 0) continue;
  455. let genColumn = 0;
  456. for (let j = 0; j < line.length; j++) {
  457. const segment = line[j];
  458. if (j > 0) writer.write(comma);
  459. genColumn = encodeInteger(writer, segment[0], genColumn);
  460. if (segment.length === 1) continue;
  461. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  462. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  463. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  464. if (segment.length === 4) continue;
  465. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  466. }
  467. }
  468. return writer.flush();
  469. }
  470. //#endregion
  471. //#region ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
  472. const schemeRegex = /^[\w+.-]+:\/\//;
  473. /**
  474. * Matches the parts of a URL:
  475. * 1. Scheme, including ":", guaranteed.
  476. * 2. User/password, including "@", optional.
  477. * 3. Host, guaranteed.
  478. * 4. Port, including ":", optional.
  479. * 5. Path, including "/", optional.
  480. * 6. Query, including "?", optional.
  481. * 7. Hash, including "#", optional.
  482. */
  483. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  484. /**
  485. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  486. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  487. *
  488. * 1. Host, optional.
  489. * 2. Path, which may include "/", guaranteed.
  490. * 3. Query, including "?", optional.
  491. * 4. Hash, including "#", optional.
  492. */
  493. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  494. function isAbsoluteUrl(input) {
  495. return schemeRegex.test(input);
  496. }
  497. function isSchemeRelativeUrl(input) {
  498. return input.startsWith("//");
  499. }
  500. function isAbsolutePath(input) {
  501. return input.startsWith("/");
  502. }
  503. function isFileUrl(input) {
  504. return input.startsWith("file:");
  505. }
  506. function isRelative(input) {
  507. return /^[.?#]/.test(input);
  508. }
  509. function parseAbsoluteUrl(input) {
  510. const match = urlRegex.exec(input);
  511. return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
  512. }
  513. function parseFileUrl(input) {
  514. const match = fileRegex.exec(input);
  515. const path = match[2];
  516. return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
  517. }
  518. function makeUrl(scheme, user, host, port, path, query, hash) {
  519. return {
  520. scheme,
  521. user,
  522. host,
  523. port,
  524. path,
  525. query,
  526. hash,
  527. type: 7
  528. };
  529. }
  530. function parseUrl(input) {
  531. if (isSchemeRelativeUrl(input)) {
  532. const url = parseAbsoluteUrl("http:" + input);
  533. url.scheme = "";
  534. url.type = 6;
  535. return url;
  536. }
  537. if (isAbsolutePath(input)) {
  538. const url = parseAbsoluteUrl("http://foo.com" + input);
  539. url.scheme = "";
  540. url.host = "";
  541. url.type = 5;
  542. return url;
  543. }
  544. if (isFileUrl(input)) return parseFileUrl(input);
  545. if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
  546. const url = parseAbsoluteUrl("http://foo.com/" + input);
  547. url.scheme = "";
  548. url.host = "";
  549. url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
  550. return url;
  551. }
  552. function stripPathFilename(path) {
  553. if (path.endsWith("/..")) return path;
  554. const index = path.lastIndexOf("/");
  555. return path.slice(0, index + 1);
  556. }
  557. function mergePaths(url, base) {
  558. normalizePath$1(base, base.type);
  559. if (url.path === "/") url.path = base.path;
  560. else url.path = stripPathFilename(base.path) + url.path;
  561. }
  562. /**
  563. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  564. * "foo/.". We need to normalize to a standard representation.
  565. */
  566. function normalizePath$1(url, type) {
  567. const rel = type <= 4;
  568. const pieces = url.path.split("/");
  569. let pointer = 1;
  570. let positive = 0;
  571. let addTrailingSlash = false;
  572. for (let i = 1; i < pieces.length; i++) {
  573. const piece = pieces[i];
  574. if (!piece) {
  575. addTrailingSlash = true;
  576. continue;
  577. }
  578. addTrailingSlash = false;
  579. if (piece === ".") continue;
  580. if (piece === "..") {
  581. if (positive) {
  582. addTrailingSlash = true;
  583. positive--;
  584. pointer--;
  585. } else if (rel) pieces[pointer++] = piece;
  586. continue;
  587. }
  588. pieces[pointer++] = piece;
  589. positive++;
  590. }
  591. let path = "";
  592. for (let i = 1; i < pointer; i++) path += "/" + pieces[i];
  593. if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/";
  594. url.path = path;
  595. }
  596. /**
  597. * Attempts to resolve `input` URL/path relative to `base`.
  598. */
  599. function resolve(input, base) {
  600. if (!input && !base) return "";
  601. const url = parseUrl(input);
  602. let inputType = url.type;
  603. if (base && inputType !== 7) {
  604. const baseUrl = parseUrl(base);
  605. const baseType = baseUrl.type;
  606. switch (inputType) {
  607. case 1: url.hash = baseUrl.hash;
  608. case 2: url.query = baseUrl.query;
  609. case 3:
  610. case 4: mergePaths(url, baseUrl);
  611. case 5:
  612. url.user = baseUrl.user;
  613. url.host = baseUrl.host;
  614. url.port = baseUrl.port;
  615. case 6: url.scheme = baseUrl.scheme;
  616. }
  617. if (baseType > inputType) inputType = baseType;
  618. }
  619. normalizePath$1(url, inputType);
  620. const queryHash = url.query + url.hash;
  621. switch (inputType) {
  622. case 2:
  623. case 3: return queryHash;
  624. case 4: {
  625. const path = url.path.slice(1);
  626. if (!path) return queryHash || ".";
  627. if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash;
  628. return path + queryHash;
  629. }
  630. case 5: return url.path + queryHash;
  631. default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
  632. }
  633. }
  634. //#endregion
  635. //#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  636. function stripFilename(path) {
  637. if (!path) return "";
  638. const index = path.lastIndexOf("/");
  639. return path.slice(0, index + 1);
  640. }
  641. function resolver(mapUrl, sourceRoot) {
  642. const from = stripFilename(mapUrl);
  643. const prefix = sourceRoot ? sourceRoot + "/" : "";
  644. return (source) => resolve(prefix + (source || ""), from);
  645. }
  646. var COLUMN$1 = 0;
  647. function maybeSort(mappings, owned) {
  648. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  649. if (unsortedIndex === mappings.length) return mappings;
  650. if (!owned) mappings = mappings.slice();
  651. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) mappings[i] = sortSegments(mappings[i], owned);
  652. return mappings;
  653. }
  654. function nextUnsortedSegmentLine(mappings, start) {
  655. for (let i = start; i < mappings.length; i++) if (!isSorted(mappings[i])) return i;
  656. return mappings.length;
  657. }
  658. function isSorted(line) {
  659. for (let j = 1; j < line.length; j++) if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) return false;
  660. return true;
  661. }
  662. function sortSegments(line, owned) {
  663. if (!owned) line = line.slice();
  664. return line.sort(sortComparator);
  665. }
  666. function sortComparator(a, b) {
  667. return a[COLUMN$1] - b[COLUMN$1];
  668. }
  669. function memoizedState() {
  670. return {
  671. lastKey: -1,
  672. lastNeedle: -1,
  673. lastIndex: -1
  674. };
  675. }
  676. function parse(map) {
  677. return typeof map === "string" ? JSON.parse(map) : map;
  678. }
  679. var TraceMap = class {
  680. constructor(map, mapUrl) {
  681. const isString = typeof map === "string";
  682. if (!isString && map._decodedMemo) return map;
  683. const parsed = parse(map);
  684. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  685. this.version = version;
  686. this.file = file;
  687. this.names = names || [];
  688. this.sourceRoot = sourceRoot;
  689. this.sources = sources;
  690. this.sourcesContent = sourcesContent;
  691. this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
  692. const resolve = resolver(mapUrl, sourceRoot);
  693. this.resolvedSources = sources.map(resolve);
  694. const { mappings } = parsed;
  695. if (typeof mappings === "string") {
  696. this._encoded = mappings;
  697. this._decoded = void 0;
  698. } else if (Array.isArray(mappings)) {
  699. this._encoded = void 0;
  700. this._decoded = maybeSort(mappings, isString);
  701. } else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
  702. else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
  703. this._decodedMemo = memoizedState();
  704. this._bySources = void 0;
  705. this._bySourceMemos = void 0;
  706. }
  707. };
  708. function cast$1(map) {
  709. return map;
  710. }
  711. function decodedMappings(map) {
  712. var _a;
  713. return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded));
  714. }
  715. function eachMapping(map, cb) {
  716. const decoded = decodedMappings(map);
  717. const { names, resolvedSources } = map;
  718. for (let i = 0; i < decoded.length; i++) {
  719. const line = decoded[i];
  720. for (let j = 0; j < line.length; j++) {
  721. const seg = line[j];
  722. const generatedLine = i + 1;
  723. const generatedColumn = seg[0];
  724. let source = null;
  725. let originalLine = null;
  726. let originalColumn = null;
  727. let name = null;
  728. if (seg.length !== 1) {
  729. source = resolvedSources[seg[1]];
  730. originalLine = seg[2] + 1;
  731. originalColumn = seg[3];
  732. }
  733. if (seg.length === 5) name = names[seg[4]];
  734. cb({
  735. generatedLine,
  736. generatedColumn,
  737. source,
  738. originalLine,
  739. originalColumn,
  740. name
  741. });
  742. }
  743. }
  744. }
  745. //#endregion
  746. //#region ../../node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
  747. var SetArray = class {
  748. constructor() {
  749. this._indexes = { __proto__: null };
  750. this.array = [];
  751. }
  752. };
  753. function cast(set) {
  754. return set;
  755. }
  756. function get(setarr, key) {
  757. return cast(setarr)._indexes[key];
  758. }
  759. function put(setarr, key) {
  760. const index = get(setarr, key);
  761. if (index !== void 0) return index;
  762. const { array, _indexes: indexes } = cast(setarr);
  763. return indexes[key] = array.push(key) - 1;
  764. }
  765. var COLUMN = 0;
  766. var SOURCES_INDEX = 1;
  767. var SOURCE_LINE = 2;
  768. var SOURCE_COLUMN = 3;
  769. var NAMES_INDEX = 4;
  770. var NO_NAME = -1;
  771. var GenMapping = class {
  772. constructor({ file, sourceRoot } = {}) {
  773. this._names = new SetArray();
  774. this._sources = new SetArray();
  775. this._sourcesContent = [];
  776. this._mappings = [];
  777. this.file = file;
  778. this.sourceRoot = sourceRoot;
  779. this._ignoreList = new SetArray();
  780. }
  781. };
  782. function cast2(map) {
  783. return map;
  784. }
  785. function addMapping(map, mapping) {
  786. return addMappingInternal(false, map, mapping);
  787. }
  788. function toDecodedMap(map) {
  789. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map);
  790. removeEmptyFinalLines(mappings);
  791. return {
  792. version: 3,
  793. file: map.file || void 0,
  794. names: names.array,
  795. sourceRoot: map.sourceRoot || void 0,
  796. sources: sources.array,
  797. sourcesContent,
  798. mappings,
  799. ignoreList: ignoreList.array
  800. };
  801. }
  802. function toEncodedMap(map) {
  803. const decoded = toDecodedMap(map);
  804. return Object.assign({}, decoded, { mappings: encode(decoded.mappings) });
  805. }
  806. function fromMap(input) {
  807. const map = new TraceMap(input);
  808. const gen = new GenMapping({
  809. file: map.file,
  810. sourceRoot: map.sourceRoot
  811. });
  812. putAll(cast2(gen)._names, map.names);
  813. putAll(cast2(gen)._sources, map.sources);
  814. cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);
  815. cast2(gen)._mappings = decodedMappings(map);
  816. if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList);
  817. return gen;
  818. }
  819. function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
  820. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map);
  821. const line = getIndex(mappings, genLine);
  822. const index = getColumnIndex(line, genColumn);
  823. if (!source) {
  824. if (skipable && skipSourceless(line, index)) return;
  825. return insert(line, index, [genColumn]);
  826. }
  827. const sourcesIndex = put(sources, source);
  828. const namesIndex = name ? put(names, name) : NO_NAME;
  829. if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
  830. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
  831. return insert(line, index, name ? [
  832. genColumn,
  833. sourcesIndex,
  834. sourceLine,
  835. sourceColumn,
  836. namesIndex
  837. ] : [
  838. genColumn,
  839. sourcesIndex,
  840. sourceLine,
  841. sourceColumn
  842. ]);
  843. }
  844. function getIndex(arr, index) {
  845. for (let i = arr.length; i <= index; i++) arr[i] = [];
  846. return arr[index];
  847. }
  848. function getColumnIndex(line, genColumn) {
  849. let index = line.length;
  850. for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN]) break;
  851. return index;
  852. }
  853. function insert(array, index, value) {
  854. for (let i = array.length; i > index; i--) array[i] = array[i - 1];
  855. array[index] = value;
  856. }
  857. function removeEmptyFinalLines(mappings) {
  858. const { length } = mappings;
  859. let len = length;
  860. for (let i = len - 1; i >= 0; len = i, i--) if (mappings[i].length > 0) break;
  861. if (len < length) mappings.length = len;
  862. }
  863. function putAll(setarr, array) {
  864. for (let i = 0; i < array.length; i++) put(setarr, array[i]);
  865. }
  866. function skipSourceless(line, index) {
  867. if (index === 0) return true;
  868. return line[index - 1].length === 1;
  869. }
  870. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  871. if (index === 0) return false;
  872. const prev = line[index - 1];
  873. if (prev.length === 1) return false;
  874. return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
  875. }
  876. function addMappingInternal(skipable, map, mapping) {
  877. const { generated, source, original, name, content } = mapping;
  878. if (!source) return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null);
  879. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, source, original.line - 1, original.column, name, content);
  880. }
  881. //#endregion
  882. //#region ../../node_modules/.pnpm/obug@2.1.1/node_modules/obug/dist/core.js
  883. function coerce(value) {
  884. if (value instanceof Error) return value.stack || value.message;
  885. return value;
  886. }
  887. function selectColor(colors, namespace) {
  888. let hash = 0;
  889. for (let i = 0; i < namespace.length; i++) {
  890. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  891. hash |= 0;
  892. }
  893. return colors[Math.abs(hash) % colors.length];
  894. }
  895. function matchesTemplate(search, template) {
  896. let searchIndex = 0;
  897. let templateIndex = 0;
  898. let starIndex = -1;
  899. let matchIndex = 0;
  900. while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
  901. starIndex = templateIndex;
  902. matchIndex = searchIndex;
  903. templateIndex++;
  904. } else {
  905. searchIndex++;
  906. templateIndex++;
  907. }
  908. else if (starIndex !== -1) {
  909. templateIndex = starIndex + 1;
  910. matchIndex++;
  911. searchIndex = matchIndex;
  912. } else return false;
  913. while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
  914. return templateIndex === template.length;
  915. }
  916. function humanize(value) {
  917. if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`;
  918. return `${value}ms`;
  919. }
  920. let globalNamespaces = "";
  921. function createDebug$1(namespace, options) {
  922. let prevTime;
  923. let enableOverride;
  924. let namespacesCache;
  925. let enabledCache;
  926. const debug = (...args) => {
  927. if (!debug.enabled) return;
  928. const curr = Date.now();
  929. const diff = curr - (prevTime || curr);
  930. prevTime = curr;
  931. args[0] = coerce(args[0]);
  932. if (typeof args[0] !== "string") args.unshift("%O");
  933. let index = 0;
  934. args[0] = args[0].replace(/%([a-z%])/gi, (match, format) => {
  935. if (match === "%%") return "%";
  936. index++;
  937. const formatter = options.formatters[format];
  938. if (typeof formatter === "function") {
  939. const value = args[index];
  940. match = formatter.call(debug, value);
  941. args.splice(index, 1);
  942. index--;
  943. }
  944. return match;
  945. });
  946. options.formatArgs.call(debug, diff, args);
  947. debug.log(...args);
  948. };
  949. debug.extend = function(namespace$1, delimiter = ":") {
  950. return createDebug$1(this.namespace + delimiter + namespace$1, {
  951. useColors: this.useColors,
  952. color: this.color,
  953. formatArgs: this.formatArgs,
  954. formatters: this.formatters,
  955. inspectOpts: this.inspectOpts,
  956. log: this.log,
  957. humanize: this.humanize
  958. });
  959. };
  960. Object.assign(debug, options);
  961. debug.namespace = namespace;
  962. Object.defineProperty(debug, "enabled", {
  963. enumerable: true,
  964. configurable: false,
  965. get: () => {
  966. if (enableOverride != null) return enableOverride;
  967. if (namespacesCache !== globalNamespaces) {
  968. namespacesCache = globalNamespaces;
  969. enabledCache = enabled(namespace);
  970. }
  971. return enabledCache;
  972. },
  973. set: (v) => {
  974. enableOverride = v;
  975. }
  976. });
  977. return debug;
  978. }
  979. let names = [];
  980. let skips = [];
  981. function enable(namespaces$1) {
  982. globalNamespaces = namespaces$1;
  983. names = [];
  984. skips = [];
  985. const split = globalNamespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
  986. for (const ns of split) if (ns[0] === "-") skips.push(ns.slice(1));
  987. else names.push(ns);
  988. }
  989. function enabled(name) {
  990. for (const skip of skips) if (matchesTemplate(name, skip)) return false;
  991. for (const ns of names) if (matchesTemplate(name, ns)) return true;
  992. return false;
  993. }
  994. //#endregion
  995. //#region ../../node_modules/.pnpm/obug@2.1.1/node_modules/obug/dist/node.js
  996. const colors = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
  997. 20,
  998. 21,
  999. 26,
  1000. 27,
  1001. 32,
  1002. 33,
  1003. 38,
  1004. 39,
  1005. 40,
  1006. 41,
  1007. 42,
  1008. 43,
  1009. 44,
  1010. 45,
  1011. 56,
  1012. 57,
  1013. 62,
  1014. 63,
  1015. 68,
  1016. 69,
  1017. 74,
  1018. 75,
  1019. 76,
  1020. 77,
  1021. 78,
  1022. 79,
  1023. 80,
  1024. 81,
  1025. 92,
  1026. 93,
  1027. 98,
  1028. 99,
  1029. 112,
  1030. 113,
  1031. 128,
  1032. 129,
  1033. 134,
  1034. 135,
  1035. 148,
  1036. 149,
  1037. 160,
  1038. 161,
  1039. 162,
  1040. 163,
  1041. 164,
  1042. 165,
  1043. 166,
  1044. 167,
  1045. 168,
  1046. 169,
  1047. 170,
  1048. 171,
  1049. 172,
  1050. 173,
  1051. 178,
  1052. 179,
  1053. 184,
  1054. 185,
  1055. 196,
  1056. 197,
  1057. 198,
  1058. 199,
  1059. 200,
  1060. 201,
  1061. 202,
  1062. 203,
  1063. 204,
  1064. 205,
  1065. 206,
  1066. 207,
  1067. 208,
  1068. 209,
  1069. 214,
  1070. 215,
  1071. 220,
  1072. 221
  1073. ] : [
  1074. 6,
  1075. 2,
  1076. 3,
  1077. 4,
  1078. 5,
  1079. 1
  1080. ];
  1081. const inspectOpts = Object.keys(process.env).filter((key) => /^debug_/i.test(key)).reduce((obj, key) => {
  1082. const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
  1083. let value = process.env[key];
  1084. const lowerCase = typeof value === "string" && value.toLowerCase();
  1085. if (value === "null") value = null;
  1086. else if (lowerCase === "yes" || lowerCase === "on" || lowerCase === "true" || lowerCase === "enabled") value = true;
  1087. else if (lowerCase === "no" || lowerCase === "off" || lowerCase === "false" || lowerCase === "disabled") value = false;
  1088. else value = Number(value);
  1089. obj[prop] = value;
  1090. return obj;
  1091. }, {});
  1092. function useColors() {
  1093. return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
  1094. }
  1095. function getDate() {
  1096. if (inspectOpts.hideDate) return "";
  1097. return `${(/* @__PURE__ */ new Date()).toISOString()} `;
  1098. }
  1099. function formatArgs(diff, args) {
  1100. const { namespace: name, useColors: useColors$1 } = this;
  1101. if (useColors$1) {
  1102. const c = this.color;
  1103. const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
  1104. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  1105. args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
  1106. args.push(`${colorCode}m+${this.humanize(diff)}\u001B[0m`);
  1107. } else args[0] = `${getDate()}${name} ${args[0]}`;
  1108. }
  1109. function log(...args) {
  1110. process.stderr.write(`${formatWithOptions(this.inspectOpts, ...args)}\n`);
  1111. }
  1112. const defaultOptions = {
  1113. useColors: useColors(),
  1114. formatArgs,
  1115. formatters: {
  1116. o(v) {
  1117. this.inspectOpts.colors = this.useColors;
  1118. return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
  1119. },
  1120. O(v) {
  1121. this.inspectOpts.colors = this.useColors;
  1122. return inspect(v, this.inspectOpts);
  1123. }
  1124. },
  1125. inspectOpts,
  1126. log,
  1127. humanize
  1128. };
  1129. function createDebug(namespace, options) {
  1130. var _ref;
  1131. const color = (_ref = options && options.color) !== null && _ref !== void 0 ? _ref : selectColor(colors, namespace);
  1132. return createDebug$1(namespace, Object.assign(defaultOptions, { color }, options));
  1133. }
  1134. enable(process.env.DEBUG || "");
  1135. //#endregion
  1136. //#region src/handleHotUpdate.ts
  1137. const debug = createDebug("vite:hmr");
  1138. /**
  1139. * Vite-specific HMR handling
  1140. */
  1141. async function handleHotUpdate({ file, modules, read }, options, customElement, typeDepModules) {
  1142. const prevDescriptor = getDescriptor(file, options, false, true);
  1143. if (!prevDescriptor) return;
  1144. const { descriptor } = createDescriptor(file, await read(), options, true);
  1145. let needRerender = false;
  1146. const nonJsModules = modules.filter((m) => m.type !== "js");
  1147. const jsModules = modules.filter((m) => m.type === "js");
  1148. const affectedModules = new Set(nonJsModules);
  1149. const mainModule = getMainModule(jsModules);
  1150. const templateModule = jsModules.find((m) => /type=template/.test(m.url));
  1151. resolveScript(descriptor, options, false, customElement);
  1152. const scriptChanged = hasScriptChanged(prevDescriptor, descriptor);
  1153. if (scriptChanged) affectedModules.add(getScriptModule(jsModules) || mainModule);
  1154. if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
  1155. if (!scriptChanged) setResolvedScript(descriptor, getResolvedScript(prevDescriptor, false), false);
  1156. affectedModules.add(templateModule);
  1157. needRerender = true;
  1158. }
  1159. let didUpdateStyle = false;
  1160. const prevStyles = prevDescriptor.styles || [];
  1161. const nextStyles = descriptor.styles || [];
  1162. if (prevDescriptor.cssVars.join("") !== descriptor.cssVars.join("")) affectedModules.add(mainModule);
  1163. if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
  1164. affectedModules.add(templateModule);
  1165. affectedModules.add(mainModule);
  1166. }
  1167. for (let i = 0; i < nextStyles.length; i++) {
  1168. const prev = prevStyles[i];
  1169. const next = nextStyles[i];
  1170. if (!prev || !isEqualBlock(prev, next)) {
  1171. didUpdateStyle = true;
  1172. const mod = jsModules.find((m) => m.url.includes(`type=style&index=${i}`) && m.url.endsWith(`.${next.lang || "css"}`));
  1173. if (mod) {
  1174. affectedModules.add(mod);
  1175. if (mod.url.includes("&inline")) affectedModules.add(mainModule);
  1176. } else affectedModules.add(mainModule);
  1177. }
  1178. }
  1179. if (prevStyles.length > nextStyles.length) affectedModules.add(mainModule);
  1180. const prevCustoms = prevDescriptor.customBlocks || [];
  1181. const nextCustoms = descriptor.customBlocks || [];
  1182. if (prevCustoms.length !== nextCustoms.length) affectedModules.add(mainModule);
  1183. else for (let i = 0; i < nextCustoms.length; i++) {
  1184. const prev = prevCustoms[i];
  1185. const next = nextCustoms[i];
  1186. if (!prev || !isEqualBlock(prev, next)) {
  1187. const mod = jsModules.find((m) => m.url.includes(`type=${prev.type}&index=${i}`));
  1188. if (mod) affectedModules.add(mod);
  1189. else affectedModules.add(mainModule);
  1190. }
  1191. }
  1192. const updateType = [];
  1193. if (needRerender) {
  1194. updateType.push(`template`);
  1195. if (!templateModule) affectedModules.add(mainModule);
  1196. else if (mainModule && !affectedModules.has(mainModule)) [...mainModule.importers].filter((m) => isCSSRequest(m.url)).forEach((m) => affectedModules.add(m));
  1197. }
  1198. if (didUpdateStyle) updateType.push(`style`);
  1199. if (updateType.length) {
  1200. if (file.endsWith(".vue")) invalidateDescriptor(file);
  1201. else cache.set(file, descriptor);
  1202. debug(`[vue:update(${updateType.join("&")})] ${file}`);
  1203. }
  1204. return [...affectedModules, ...typeDepModules || []].filter(Boolean);
  1205. }
  1206. function isEqualBlock(a, b) {
  1207. if (!a && !b) return true;
  1208. if (!a || !b) return false;
  1209. if (a.src && b.src && a.src === b.src) return true;
  1210. if (a.content !== b.content) return false;
  1211. const keysA = Object.keys(a.attrs);
  1212. const keysB = Object.keys(b.attrs);
  1213. if (keysA.length !== keysB.length) return false;
  1214. return keysA.every((key) => a.attrs[key] === b.attrs[key]);
  1215. }
  1216. function isOnlyTemplateChanged(prev, next) {
  1217. return !hasScriptChanged(prev, next) && prev.styles.length === next.styles.length && prev.styles.every((s, i) => isEqualBlock(s, next.styles[i])) && prev.customBlocks.length === next.customBlocks.length && prev.customBlocks.every((s, i) => isEqualBlock(s, next.customBlocks[i]));
  1218. }
  1219. function deepEqual(obj1, obj2, excludeProps = [], deepParentsOfObj1 = []) {
  1220. if (typeof obj1 !== typeof obj2) return false;
  1221. if (obj1 == null || obj2 == null || typeof obj1 !== "object" || deepParentsOfObj1.includes(obj1)) return obj1 === obj2;
  1222. const keys1 = Object.keys(obj1);
  1223. const keys2 = Object.keys(obj2);
  1224. if (keys1.length !== keys2.length) return false;
  1225. for (const key of keys1) {
  1226. if (excludeProps.includes(key)) continue;
  1227. if (!deepEqual(obj1[key], obj2[key], excludeProps, [...deepParentsOfObj1, obj1])) return false;
  1228. }
  1229. return true;
  1230. }
  1231. function isEqualAst(prev, next) {
  1232. if (typeof prev === "undefined" || typeof next === "undefined") return prev === next;
  1233. if (prev.length !== next.length) return false;
  1234. for (let i = 0; i < prev.length; i++) {
  1235. const prevNode = prev[i];
  1236. const nextNode = next[i];
  1237. if (!deepEqual(prevNode, nextNode, [
  1238. "start",
  1239. "end",
  1240. "loc",
  1241. "range",
  1242. "leadingComments",
  1243. "trailingComments",
  1244. "innerComments",
  1245. "_ownerScope",
  1246. "_resolvedReference",
  1247. "_resolvedElements"
  1248. ])) return false;
  1249. }
  1250. return true;
  1251. }
  1252. function hasScriptChanged(prev, next) {
  1253. if (prev.vapor !== next.vapor) return true;
  1254. const prevScript = getResolvedScript(prev, false);
  1255. const nextScript = getResolvedScript(next, false);
  1256. if (!isEqualBlock(prev.script, next.script) && !isEqualAst(prevScript?.scriptAst, nextScript?.scriptAst)) return true;
  1257. if (!isEqualBlock(prev.scriptSetup, next.scriptSetup) && !isEqualAst(prevScript?.scriptSetupAst, nextScript?.scriptSetupAst)) return true;
  1258. const prevImports = getResolvedScript(prev, false)?.imports;
  1259. if (prevImports) return !next.template || next.shouldForceReload(prevImports);
  1260. return false;
  1261. }
  1262. function getMainModule(jsModules) {
  1263. return jsModules.filter((m) => !/type=/.test(m.url) || /type=script/.test(m.url)).sort((m1, m2) => {
  1264. return m1.url.length - m2.url.length;
  1265. })[0];
  1266. }
  1267. function getScriptModule(jsModules) {
  1268. return jsModules.find((m) => /type=script.*&lang\.\w+$/.test(m.url));
  1269. }
  1270. function handleTypeDepChange(affectedComponents, { modules, server: { moduleGraph } }) {
  1271. const affected = /* @__PURE__ */ new Set();
  1272. for (const file of affectedComponents) {
  1273. invalidateScript(file);
  1274. const mods = moduleGraph.getModulesByFile(file);
  1275. if (mods) {
  1276. const arr = [...mods];
  1277. affected.add(getScriptModule(arr) || getMainModule(arr));
  1278. }
  1279. }
  1280. return [...modules, ...affected];
  1281. }
  1282. //#endregion
  1283. //#region src/helper.ts
  1284. const EXPORT_HELPER_ID = "\0plugin-vue:export-helper";
  1285. const helperCode = `
  1286. export default (sfc, props) => {
  1287. const target = sfc.__vccOpts || sfc;
  1288. for (const [key, val] of props) {
  1289. target[key] = val;
  1290. }
  1291. return target;
  1292. }
  1293. `;
  1294. //#endregion
  1295. //#region src/main.ts
  1296. async function transformMain(code, filename, options, pluginContext, ssr, customElement) {
  1297. const { devServer, isProduction, devToolsEnabled } = options;
  1298. const prevDescriptor = getPrevDescriptor(filename);
  1299. const { descriptor, errors } = createDescriptor(filename, code, options);
  1300. if (fs.existsSync(filename)) getDescriptor(filename, options, true, true, filename.endsWith(".vue") ? void 0 : code);
  1301. if (errors.length) {
  1302. errors.forEach((error) => pluginContext.error(createRollupError(filename, error)));
  1303. return null;
  1304. }
  1305. const attachedProps = [];
  1306. const hasScoped = descriptor.styles.some((s) => s.scoped);
  1307. const isTemplateOnlyVapor = !descriptor.script && !descriptor.scriptSetup && descriptor.vapor;
  1308. const { code: scriptCode, map: scriptMap } = await genScriptCode(descriptor, options, pluginContext, ssr, customElement);
  1309. const hasTemplateImport = descriptor.template && !isUseInlineTemplate(descriptor, options);
  1310. const isTemplateInlined = !!descriptor.template && (!descriptor.template.lang || descriptor.template.lang === "html") && !descriptor.template.src;
  1311. let templateCode = "";
  1312. let templateMap = void 0;
  1313. let templateMultiRoot;
  1314. if (hasTemplateImport) ({code: templateCode, map: templateMap, multiRoot: templateMultiRoot} = await genTemplateCode(descriptor, options, pluginContext, ssr, customElement));
  1315. if (hasTemplateImport) attachedProps.push(ssr ? ["ssrRender", "_sfc_ssrRender"] : ["render", "_sfc_render"]);
  1316. else if (prevDescriptor && !isEqualBlock(descriptor.template, prevDescriptor.template)) attachedProps.push([ssr ? "ssrRender" : "render", "() => {}"]);
  1317. const stylesCode = await genStyleCode(descriptor, pluginContext, customElement, attachedProps);
  1318. const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext);
  1319. const output = [
  1320. scriptCode,
  1321. templateCode,
  1322. isTemplateOnlyVapor ? `${scriptIdentifier}.__multiRoot = ${isTemplateInlined ? templateMultiRoot : "_sfc_multiRoot"}` : "",
  1323. stylesCode,
  1324. customBlocksCode
  1325. ];
  1326. if (hasScoped) attachedProps.push([`__scopeId`, JSON.stringify(`data-v-${descriptor.id}`)]);
  1327. if (devToolsEnabled || devServer && !isProduction) attachedProps.push([`__file`, JSON.stringify(isProduction ? path.basename(filename) : filename)]);
  1328. if (devServer && devServer.config.server.hmr !== false && !ssr && !isProduction) {
  1329. output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`);
  1330. output.push("typeof __VUE_HMR_RUNTIME__ !== 'undefined' && __VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)");
  1331. output.push(`import.meta.hot.on('file-changed', ({ file }) => {`, ` __VUE_HMR_RUNTIME__.CHANGED_FILE = file`, `})`);
  1332. if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) output.push(`export const _rerender_only = __VUE_HMR_RUNTIME__.CHANGED_FILE === ${JSON.stringify(normalizePath(filename))}`);
  1333. output.push(`import.meta.hot.accept(mod => {`, ` if (!mod) return`, ` const { default: updated, _rerender_only } = mod`, ` if (_rerender_only) {`, ` __VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)`, ` } else {`, ` __VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)`, ` }`, `})`);
  1334. }
  1335. if (ssr) {
  1336. const normalizedFilename = normalizePath(path.relative(options.root, filename));
  1337. output.push(`import { useSSRContext as __vite_useSSRContext } from 'vue'`, `const _sfc_setup = _sfc_main.setup`, `_sfc_main.setup = (props, ctx) => {`, ` const ssrContext = __vite_useSSRContext()`, ` ;(ssrContext.modules || (ssrContext.modules = new Set())).add(${JSON.stringify(normalizedFilename)})`, ` return _sfc_setup ? _sfc_setup(props, ctx) : undefined`, `}`);
  1338. }
  1339. let resolvedMap = void 0;
  1340. if (options.sourceMap) if (templateMap) {
  1341. const gen = fromMap(scriptMap ?? {
  1342. file: filename,
  1343. sourceRoot: "",
  1344. version: 3,
  1345. sources: [],
  1346. sourcesContent: [],
  1347. names: [],
  1348. mappings: ""
  1349. });
  1350. const tracer = new TraceMap(templateMap);
  1351. const offset = (scriptCode.match(/\r?\n/g)?.length ?? 0) + 1;
  1352. eachMapping(tracer, (m) => {
  1353. if (m.source == null) return;
  1354. addMapping(gen, {
  1355. source: m.source,
  1356. original: {
  1357. line: m.originalLine,
  1358. column: m.originalColumn
  1359. },
  1360. generated: {
  1361. line: m.generatedLine + offset,
  1362. column: m.generatedColumn
  1363. }
  1364. });
  1365. });
  1366. resolvedMap = toEncodedMap(gen);
  1367. resolvedMap.sourcesContent = templateMap.sourcesContent;
  1368. } else resolvedMap = scriptMap;
  1369. if (!attachedProps.length) output.push(`export default _sfc_main`);
  1370. else output.push(`import _export_sfc from '${EXPORT_HELPER_ID}'`, `export default /*#__PURE__*/_export_sfc(_sfc_main, [${attachedProps.map(([key, val]) => `['${key}',${val}]`).join(",")}])`);
  1371. let resolvedCode = output.join("\n");
  1372. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  1373. if (lang && /tsx?$/.test(lang) && !descriptor.script?.src) {
  1374. const { transformWithOxc } = await import("vite");
  1375. if (transformWithOxc) {
  1376. const { code, map } = await transformWithOxc(resolvedCode, filename, {
  1377. ...options.devServer?.config.oxc,
  1378. lang: "ts",
  1379. sourcemap: options.sourceMap
  1380. }, resolvedMap);
  1381. resolvedCode = code;
  1382. resolvedMap = resolvedMap ? map : resolvedMap;
  1383. } else {
  1384. const { code, map } = await transformWithEsbuild(resolvedCode, filename, {
  1385. target: "esnext",
  1386. charset: "utf8",
  1387. ...options.devServer?.config.esbuild,
  1388. loader: "ts",
  1389. sourcemap: options.sourceMap
  1390. }, resolvedMap);
  1391. resolvedCode = code;
  1392. resolvedMap = resolvedMap ? map : resolvedMap;
  1393. }
  1394. }
  1395. return {
  1396. code: resolvedCode,
  1397. map: resolvedMap || { mappings: "" },
  1398. meta: { vite: { lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js" } }
  1399. };
  1400. }
  1401. async function genTemplateCode(descriptor, options, pluginContext, ssr, customElement) {
  1402. const template = descriptor.template;
  1403. const hasScoped = descriptor.styles.some((style) => style.scoped);
  1404. const needsMultiRoot = !descriptor.script && !descriptor.scriptSetup && descriptor.vapor;
  1405. if ((!template.lang || template.lang === "html") && !template.src) {
  1406. const result = transformTemplateInMain(template.content, descriptor, options, pluginContext, ssr, customElement);
  1407. return {
  1408. ...result,
  1409. multiRoot: needsMultiRoot ? result.multiRoot : void 0
  1410. };
  1411. } else {
  1412. if (template.src) await linkSrcToDescriptor(template.src, descriptor, pluginContext, hasScoped);
  1413. const src = template.src || descriptor.filename;
  1414. const query = `?vue&type=template${template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : ""}${hasScoped ? `&scoped=${descriptor.id}` : ``}${attrsToQuery(template.attrs, "js", true)}`;
  1415. const request = JSON.stringify(src + query);
  1416. const renderFnName = ssr ? "ssrRender" : "render";
  1417. return {
  1418. code: `import { ${renderFnName} as _sfc_${renderFnName}${needsMultiRoot ? ", multiRoot as _sfc_multiRoot" : ""} } from ${request}`,
  1419. map: void 0
  1420. };
  1421. }
  1422. }
  1423. async function genScriptCode(descriptor, options, pluginContext, ssr, customElement) {
  1424. let scriptCode = `const ${scriptIdentifier} = { ${descriptor.vapor ? "__vapor: true" : ""} }`;
  1425. let map;
  1426. const script = resolveScript(descriptor, options, ssr, customElement);
  1427. if (script) if (canInlineMain(descriptor, options)) {
  1428. if (!options.compiler.version) {
  1429. const userPlugins = options.script?.babelParserPlugins || [];
  1430. const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
  1431. scriptCode = options.compiler.rewriteDefault(script.content, scriptIdentifier, [...defaultPlugins, ...userPlugins]);
  1432. } else scriptCode = script.content;
  1433. map = script.map;
  1434. } else {
  1435. if (script.src) await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
  1436. const src = script.src || descriptor.filename;
  1437. const langFallback = script.src && path.extname(src).slice(1) || "js";
  1438. const attrsQuery = attrsToQuery(script.attrs, langFallback);
  1439. const query = `?vue&type=script${script.src ? `&src=true` : ``}${attrsQuery}`;
  1440. const request = JSON.stringify(src + query);
  1441. scriptCode = `import _sfc_main from ${request}\nexport * from ${request}`;
  1442. }
  1443. return {
  1444. code: scriptCode,
  1445. map
  1446. };
  1447. }
  1448. async function genStyleCode(descriptor, pluginContext, customElement, attachedProps) {
  1449. let stylesCode = ``;
  1450. let cssModulesMap;
  1451. if (descriptor.styles.length) {
  1452. for (let i = 0; i < descriptor.styles.length; i++) {
  1453. const style = descriptor.styles[i];
  1454. if (style.src) await linkSrcToDescriptor(style.src, descriptor, pluginContext, style.scoped);
  1455. const src = style.src || descriptor.filename;
  1456. const attrsQuery = attrsToQuery(style.attrs, "css");
  1457. const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
  1458. const directQuery = customElement ? `&inline` : ``;
  1459. const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
  1460. const styleRequest = src + `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}` + attrsQuery;
  1461. if (style.module) {
  1462. if (customElement) throw new Error(`<style module> is not supported in custom elements mode.`);
  1463. const [importCode, nameMap] = genCSSModulesCode(i, styleRequest, style.module);
  1464. stylesCode += importCode;
  1465. Object.assign(cssModulesMap ||= {}, nameMap);
  1466. } else if (customElement) stylesCode += `\nimport _style_${i} from ${JSON.stringify(styleRequest)}`;
  1467. else stylesCode += `\nimport ${JSON.stringify(styleRequest)}`;
  1468. }
  1469. if (customElement) attachedProps.push([`styles`, `[${descriptor.styles.map((_, i) => `_style_${i}`).join(",")}]`]);
  1470. }
  1471. if (cssModulesMap) {
  1472. const mappingCode = Object.entries(cssModulesMap).reduce((code, [key, value]) => code + `"${key}":${value},\n`, "{\n") + "}";
  1473. stylesCode += `\nconst cssModules = ${mappingCode}`;
  1474. attachedProps.push([`__cssModules`, `cssModules`]);
  1475. }
  1476. return stylesCode;
  1477. }
  1478. function genCSSModulesCode(index, request, moduleName) {
  1479. const styleVar = `style${index}`;
  1480. const exposedName = typeof moduleName === "string" ? moduleName : "$style";
  1481. const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
  1482. return [`\nimport ${styleVar} from ${JSON.stringify(moduleRequest)}`, { [exposedName]: styleVar }];
  1483. }
  1484. async function genCustomBlockCode(descriptor, pluginContext) {
  1485. let code = "";
  1486. for (let index = 0; index < descriptor.customBlocks.length; index++) {
  1487. const block = descriptor.customBlocks[index];
  1488. if (block.src) await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
  1489. const src = block.src || descriptor.filename;
  1490. const attrsQuery = attrsToQuery(block.attrs, block.type);
  1491. const srcQuery = block.src ? `&src=true` : ``;
  1492. const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
  1493. const request = JSON.stringify(src + query);
  1494. code += `import block${index} from ${request}\n`;
  1495. code += `if (typeof block${index} === 'function') block${index}(_sfc_main)\n`;
  1496. }
  1497. return code;
  1498. }
  1499. /**
  1500. * For blocks with src imports, it is important to link the imported file
  1501. * with its owner SFC descriptor so that we can get the information about
  1502. * the owner SFC when compiling that file in the transform phase.
  1503. */
  1504. async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
  1505. setSrcDescriptor(((await pluginContext.resolve(src, descriptor.filename))?.id || src).replace(/\?.*$/, ""), descriptor, scoped);
  1506. }
  1507. const ignoreList = [
  1508. "id",
  1509. "index",
  1510. "src",
  1511. "type",
  1512. "lang",
  1513. "module",
  1514. "scoped",
  1515. "generic"
  1516. ];
  1517. function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
  1518. let query = ``;
  1519. for (const name in attrs) {
  1520. const value = attrs[name];
  1521. if (!ignoreList.includes(name)) query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
  1522. }
  1523. if (langFallback || attrs.lang) query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
  1524. return query;
  1525. }
  1526. //#endregion
  1527. //#region src/style.ts
  1528. async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
  1529. const block = descriptor.styles[index];
  1530. const result = await options.compiler.compileStyleAsync({
  1531. ...options.style,
  1532. filename: descriptor.filename,
  1533. id: `data-v-${descriptor.id}`,
  1534. isProd: options.isProduction,
  1535. source: code,
  1536. scoped: block.scoped,
  1537. ...options.cssDevSourcemap ? { postcssOptions: { map: {
  1538. from: filename,
  1539. inline: false,
  1540. annotation: false
  1541. } } } : {}
  1542. });
  1543. if (result.errors.length) {
  1544. result.errors.forEach((error) => {
  1545. if (error.line && error.column) error.loc = {
  1546. file: descriptor.filename,
  1547. line: error.line + block.loc.start.line,
  1548. column: error.column
  1549. };
  1550. pluginContext.error(error);
  1551. });
  1552. return null;
  1553. }
  1554. const map = result.map ? await formatPostcssSourceMap(result.map, filename) : { mappings: "" };
  1555. return {
  1556. code: result.code,
  1557. map,
  1558. meta: block.scoped && !descriptor.isTemp ? { vite: { cssScopeTo: [descriptor.filename, "default"] } } : void 0
  1559. };
  1560. }
  1561. //#endregion
  1562. //#region src/index.ts
  1563. function vuePlugin(rawOptions = {}) {
  1564. clearScriptCache();
  1565. const options = shallowRef({
  1566. isProduction: process.env.NODE_ENV === "production",
  1567. compiler: null,
  1568. customElement: /\.ce\.vue$/,
  1569. ...rawOptions,
  1570. root: process.cwd(),
  1571. sourceMap: true,
  1572. cssDevSourcemap: false
  1573. });
  1574. const include = shallowRef(rawOptions.include ?? /\.vue$/);
  1575. const exclude = shallowRef(rawOptions.exclude);
  1576. let optionsHookIsCalled = false;
  1577. const filter = computed(() => createFilter(include.value, exclude.value));
  1578. const customElementFilter = computed(() => {
  1579. const customElement = options.value.features?.customElement || options.value.customElement;
  1580. return typeof customElement === "boolean" ? () => customElement : createFilter(customElement);
  1581. });
  1582. let transformCachedModule = false;
  1583. const plugin = {
  1584. name: "vite:vue",
  1585. api: {
  1586. get options() {
  1587. return options.value;
  1588. },
  1589. set options(value) {
  1590. options.value = value;
  1591. },
  1592. get include() {
  1593. return include.value;
  1594. },
  1595. set include(value) {
  1596. if (optionsHookIsCalled) throw new Error("include cannot be updated after `options` hook is called");
  1597. include.value = value;
  1598. },
  1599. get exclude() {
  1600. return exclude.value;
  1601. },
  1602. set exclude(value) {
  1603. if (optionsHookIsCalled) throw new Error("exclude cannot be updated after `options` hook is called");
  1604. exclude.value = value;
  1605. },
  1606. version
  1607. },
  1608. handleHotUpdate(ctx) {
  1609. ctx.server.ws.send({
  1610. type: "custom",
  1611. event: "file-changed",
  1612. data: { file: normalizePath(ctx.file) }
  1613. });
  1614. if (options.value.compiler.invalidateTypeCache) options.value.compiler.invalidateTypeCache(ctx.file);
  1615. let typeDepModules;
  1616. const matchesFilter = filter.value(ctx.file);
  1617. if (typeDepToSFCMap.has(ctx.file)) {
  1618. typeDepModules = handleTypeDepChange(typeDepToSFCMap.get(ctx.file), ctx);
  1619. if (!matchesFilter) return typeDepModules;
  1620. }
  1621. if (matchesFilter) return handleHotUpdate(ctx, options.value, customElementFilter.value(ctx.file), typeDepModules);
  1622. },
  1623. config(config) {
  1624. const parseDefine = (v) => {
  1625. try {
  1626. return typeof v === "string" ? JSON.parse(v) : v;
  1627. } catch (err) {
  1628. return v;
  1629. }
  1630. };
  1631. return {
  1632. resolve: { dedupe: config.build?.ssr ? [] : ["vue"] },
  1633. define: {
  1634. __VUE_OPTIONS_API__: options.value.features?.optionsAPI ?? parseDefine(config.define?.__VUE_OPTIONS_API__) ?? true,
  1635. __VUE_PROD_DEVTOOLS__: (options.value.features?.prodDevtools || parseDefine(config.define?.__VUE_PROD_DEVTOOLS__)) ?? false,
  1636. __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: (options.value.features?.prodHydrationMismatchDetails || parseDefine(config.define?.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__)) ?? false
  1637. },
  1638. ssr: { external: config.legacy?.buildSsrCjsExternalHeuristics ? ["vue", "@vue/server-renderer"] : [] }
  1639. };
  1640. },
  1641. configResolved(config) {
  1642. options.value = {
  1643. ...options.value,
  1644. root: config.root,
  1645. sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
  1646. cssDevSourcemap: config.css?.devSourcemap ?? false,
  1647. isProduction: config.isProduction,
  1648. devToolsEnabled: !!(options.value.features?.prodDevtools || config.define.__VUE_PROD_DEVTOOLS__ || !config.isProduction)
  1649. };
  1650. const _warn = config.logger.warn;
  1651. config.logger.warn = (...args) => {
  1652. if (args[0].match(/\[lightningcss\] '(deep|slotted|global)' is not recognized as a valid pseudo-/)) return;
  1653. _warn(...args);
  1654. };
  1655. transformCachedModule = config.command === "build" && options.value.sourceMap && config.build.watch != null;
  1656. },
  1657. options() {
  1658. optionsHookIsCalled = true;
  1659. plugin.transform.filter = { id: {
  1660. include: [...makeIdFiltersToMatchWithQuery(ensureArray(include.value)), /[?&]vue\b/],
  1661. exclude: exclude.value
  1662. } };
  1663. },
  1664. shouldTransformCachedModule({ id }) {
  1665. if (transformCachedModule && parseVueRequest(id).query.vue) return true;
  1666. return false;
  1667. },
  1668. configureServer(server) {
  1669. options.value.devServer = server;
  1670. },
  1671. buildStart() {
  1672. const compiler = options.value.compiler = options.value.compiler || resolveCompiler(options.value.root);
  1673. if (compiler.invalidateTypeCache) options.value.devServer?.watcher.on("unlink", (file) => {
  1674. compiler.invalidateTypeCache(file);
  1675. });
  1676. },
  1677. resolveId: {
  1678. filter: { id: [exactRegex(EXPORT_HELPER_ID), /[?&]vue\b/] },
  1679. handler(id) {
  1680. if (id === "\0plugin-vue:export-helper") return id;
  1681. if (parseVueRequest(id).query.vue) return id;
  1682. }
  1683. },
  1684. load: {
  1685. filter: { id: [exactRegex(EXPORT_HELPER_ID), /[?&]vue\b/] },
  1686. handler(id, opt) {
  1687. if (id === "\0plugin-vue:export-helper") return helperCode;
  1688. const ssr = opt?.ssr === true;
  1689. const { filename, query } = parseVueRequest(id);
  1690. if (query.vue) {
  1691. if (query.src) return fs.readFileSync(filename, "utf-8");
  1692. const descriptor = getDescriptor(filename, options.value);
  1693. let block;
  1694. if (query.type === "script") block = resolveScript(descriptor, options.value, ssr, customElementFilter.value(filename));
  1695. else if (query.type === "template") block = descriptor.template;
  1696. else if (query.type === "style") block = descriptor.styles[query.index];
  1697. else if (query.index != null) block = descriptor.customBlocks[query.index];
  1698. if (block) return {
  1699. code: block.content,
  1700. map: block.map
  1701. };
  1702. }
  1703. }
  1704. },
  1705. transform: { handler(code, id, opt) {
  1706. const ssr = opt?.ssr === true;
  1707. const { filename, query } = parseVueRequest(id);
  1708. if (query.raw || query.url) return;
  1709. if (!filter.value(filename) && !query.vue) return;
  1710. if (!query.vue) return transformMain(code, filename, options.value, this, ssr, customElementFilter.value(filename));
  1711. else {
  1712. const descriptor = query.src ? getSrcDescriptor(filename, query) || getTempSrcDescriptor(filename, query) : getDescriptor(filename, options.value);
  1713. if (query.src) this.addWatchFile(filename);
  1714. if (query.type === "template") return transformTemplateAsModule(code, filename, descriptor, options.value, this, ssr, customElementFilter.value(filename));
  1715. else if (query.type === "style") return transformStyle(code, descriptor, Number(query.index || 0), options.value, this, filename);
  1716. }
  1717. } }
  1718. };
  1719. return plugin;
  1720. }
  1721. function ensureArray(value) {
  1722. return Array.isArray(value) ? value : [value];
  1723. }
  1724. function vuePluginCjs(options) {
  1725. return vuePlugin.call(this, options);
  1726. }
  1727. Object.assign(vuePluginCjs, {
  1728. default: vuePluginCjs,
  1729. parseVueRequest
  1730. });
  1731. //#endregion
  1732. export { vuePlugin as default, vuePluginCjs as "module.exports", parseVueRequest };