index.mjs 61 KB

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