index.mjs 58 KB

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