index.mjs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903
  1. import fs from 'node:fs';
  2. import { isCSSRequest, normalizePath as normalizePath$1, transformWithEsbuild, formatPostcssSourceMap, createFilter } from 'vite';
  3. import { shallowRef, computed } from 'vue';
  4. import { createRequire } from 'node:module';
  5. import path from 'node:path';
  6. import { createHash } from 'node:crypto';
  7. import require$$0 from 'tty';
  8. import require$$1 from 'util';
  9. const version = "4.6.2";
  10. function resolveCompiler(root) {
  11. const compiler = tryResolveCompiler(root) || tryResolveCompiler();
  12. if (!compiler) {
  13. throw new Error(
  14. `Failed to resolve vue/compiler-sfc.
  15. @vitejs/plugin-vue requires vue (>=3.2.25) to be present in the dependency tree.`
  16. );
  17. }
  18. return compiler;
  19. }
  20. function tryResolveCompiler(root) {
  21. const vueMeta = tryRequire("vue/package.json", root);
  22. if (vueMeta && vueMeta.version.split(".")[0] >= 3) {
  23. return tryRequire("vue/compiler-sfc", root);
  24. }
  25. }
  26. const _require = createRequire(import.meta.url);
  27. function tryRequire(id, from) {
  28. try {
  29. return from ? _require(_require.resolve(id, { paths: [from] })) : _require(id);
  30. } catch (e) {
  31. }
  32. }
  33. function parseVueRequest(id) {
  34. const [filename, rawQuery] = id.split(`?`, 2);
  35. const query = Object.fromEntries(new URLSearchParams(rawQuery));
  36. if (query.vue != null) {
  37. query.vue = true;
  38. }
  39. if (query.index != null) {
  40. query.index = Number(query.index);
  41. }
  42. if (query.raw != null) {
  43. query.raw = true;
  44. }
  45. if (query.url != null) {
  46. query.url = true;
  47. }
  48. if (query.scoped != null) {
  49. query.scoped = true;
  50. }
  51. return {
  52. filename,
  53. query
  54. };
  55. }
  56. function slash(path) {
  57. const isExtendedLengthPath = path.startsWith('\\\\?\\');
  58. if (isExtendedLengthPath) {
  59. return path;
  60. }
  61. return path.replace(/\\/g, '/');
  62. }
  63. const cache = /* @__PURE__ */ new Map();
  64. const hmrCache = /* @__PURE__ */ new Map();
  65. const prevCache = /* @__PURE__ */ new Map();
  66. function createDescriptor(filename, source, { root, isProduction, sourceMap, compiler, template }, hmr = false) {
  67. const { descriptor, errors } = compiler.parse(source, {
  68. filename,
  69. sourceMap,
  70. // @ts-ignore only available in Vue 3.4+
  71. templateParseOptions: template?.compilerOptions
  72. });
  73. const normalizedPath = slash(path.normalize(path.relative(root, filename)));
  74. descriptor.id = getHash(normalizedPath + (isProduction ? source : ""));
  75. (hmr ? hmrCache : cache).set(filename, descriptor);
  76. return { descriptor, errors };
  77. }
  78. function getPrevDescriptor(filename) {
  79. return prevCache.get(filename);
  80. }
  81. function invalidateDescriptor(filename, hmr = false) {
  82. const _cache = hmr ? hmrCache : cache;
  83. const prev = _cache.get(filename);
  84. _cache.delete(filename);
  85. if (prev) {
  86. prevCache.set(filename, prev);
  87. }
  88. }
  89. function getDescriptor(filename, options, createIfNotFound = true, hmr = false, code) {
  90. const _cache = hmr ? hmrCache : cache;
  91. if (_cache.has(filename)) {
  92. return _cache.get(filename);
  93. }
  94. if (createIfNotFound) {
  95. const { descriptor, errors } = createDescriptor(
  96. filename,
  97. code ?? fs.readFileSync(filename, "utf-8"),
  98. options,
  99. hmr
  100. );
  101. if (errors.length && !hmr) {
  102. throw errors[0];
  103. }
  104. return descriptor;
  105. }
  106. }
  107. function getSrcDescriptor(filename, query) {
  108. if (query.scoped) {
  109. return cache.get(`${filename}?src=${query.src}`);
  110. }
  111. return cache.get(filename);
  112. }
  113. function getTempSrcDescriptor(filename, query) {
  114. return {
  115. filename,
  116. id: query.id || "",
  117. styles: [
  118. {
  119. scoped: query.scoped,
  120. loc: {
  121. start: { line: 0, column: 0 }
  122. }
  123. }
  124. ]
  125. };
  126. }
  127. function setSrcDescriptor(filename, entry, scoped) {
  128. if (scoped) {
  129. cache.set(`${filename}?src=${entry.id}`, entry);
  130. return;
  131. }
  132. cache.set(filename, entry);
  133. }
  134. function getHash(text) {
  135. return createHash("sha256").update(text).digest("hex").substring(0, 8);
  136. }
  137. function createRollupError(id, error) {
  138. const { message, name, stack } = error;
  139. const rollupError = {
  140. id,
  141. plugin: "vue",
  142. message,
  143. name,
  144. stack
  145. };
  146. if ("code" in error && error.loc) {
  147. rollupError.loc = {
  148. file: id,
  149. line: error.loc.start.line,
  150. column: error.loc.start.column
  151. };
  152. }
  153. return rollupError;
  154. }
  155. async function transformTemplateAsModule(code, descriptor, options, pluginContext, ssr, customElement) {
  156. const result = compile(
  157. code,
  158. descriptor,
  159. options,
  160. pluginContext,
  161. ssr,
  162. customElement
  163. );
  164. let returnCode = result.code;
  165. if (options.devServer && options.devServer.config.server.hmr !== false && !ssr && !options.isProduction) {
  166. returnCode += `
  167. import.meta.hot.accept(({ render }) => {
  168. __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(descriptor.id)}, render)
  169. })`;
  170. }
  171. return {
  172. code: returnCode,
  173. map: result.map
  174. };
  175. }
  176. function transformTemplateInMain(code, descriptor, options, pluginContext, ssr, customElement) {
  177. const result = compile(
  178. code,
  179. descriptor,
  180. options,
  181. pluginContext,
  182. ssr,
  183. customElement
  184. );
  185. return {
  186. ...result,
  187. code: result.code.replace(
  188. /\nexport (function|const) (render|ssrRender)/,
  189. "\n$1 _sfc_$2"
  190. )
  191. };
  192. }
  193. function compile(code, descriptor, options, pluginContext, ssr, customElement) {
  194. const filename = descriptor.filename;
  195. resolveScript(descriptor, options, ssr, customElement);
  196. const result = options.compiler.compileTemplate({
  197. ...resolveTemplateCompilerOptions(descriptor, options, ssr),
  198. source: code
  199. });
  200. if (result.errors.length) {
  201. result.errors.forEach(
  202. (error) => pluginContext.error(
  203. typeof error === "string" ? { id: filename, message: error } : createRollupError(filename, error)
  204. )
  205. );
  206. }
  207. if (result.tips.length) {
  208. result.tips.forEach(
  209. (tip) => pluginContext.warn({
  210. id: filename,
  211. message: tip
  212. })
  213. );
  214. }
  215. return result;
  216. }
  217. function resolveTemplateCompilerOptions(descriptor, options, ssr) {
  218. const block = descriptor.template;
  219. if (!block) {
  220. return;
  221. }
  222. const resolvedScript = getResolvedScript(descriptor, ssr);
  223. const hasScoped = descriptor.styles.some((s) => s.scoped);
  224. const { id, filename, cssVars } = descriptor;
  225. let transformAssetUrls = options.template?.transformAssetUrls;
  226. let assetUrlOptions;
  227. if (options.devServer) {
  228. if (filename.startsWith(options.root)) {
  229. const devBase = options.devServer.config.base;
  230. assetUrlOptions = {
  231. base: (options.devServer.config.server?.origin ?? "") + devBase + slash(path.relative(options.root, path.dirname(filename))),
  232. includeAbsolute: !!devBase
  233. };
  234. }
  235. } else if (transformAssetUrls !== false) {
  236. assetUrlOptions = {
  237. includeAbsolute: true
  238. };
  239. }
  240. if (transformAssetUrls && typeof transformAssetUrls === "object") {
  241. if (Object.values(transformAssetUrls).some((val) => Array.isArray(val))) {
  242. transformAssetUrls = {
  243. ...assetUrlOptions,
  244. tags: transformAssetUrls
  245. };
  246. } else {
  247. transformAssetUrls = { ...assetUrlOptions, ...transformAssetUrls };
  248. }
  249. } else {
  250. transformAssetUrls = assetUrlOptions;
  251. }
  252. let preprocessOptions = block.lang && options.template?.preprocessOptions;
  253. if (block.lang === "pug") {
  254. preprocessOptions = {
  255. doctype: "html",
  256. ...preprocessOptions
  257. };
  258. }
  259. const expressionPlugins = options.template?.compilerOptions?.expressionPlugins || [];
  260. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  261. if (lang && /tsx?$/.test(lang) && !expressionPlugins.includes("typescript")) {
  262. expressionPlugins.push("typescript");
  263. }
  264. return {
  265. ...options.template,
  266. id,
  267. // @ts-ignore only available in vue 3.4+
  268. ast: canReuseAST(options.compiler.version) ? descriptor.template?.ast : void 0,
  269. filename,
  270. scoped: hasScoped,
  271. slotted: descriptor.slotted,
  272. isProd: options.isProduction,
  273. inMap: block.src ? void 0 : block.map,
  274. ssr,
  275. ssrCssVars: cssVars,
  276. transformAssetUrls,
  277. preprocessLang: block.lang === "html" ? void 0 : block.lang,
  278. preprocessOptions,
  279. compilerOptions: {
  280. ...options.template?.compilerOptions,
  281. scopeId: hasScoped ? `data-v-${id}` : void 0,
  282. bindingMetadata: resolvedScript ? resolvedScript.bindings : void 0,
  283. expressionPlugins,
  284. sourceMap: options.sourceMap
  285. }
  286. };
  287. }
  288. function canReuseAST(version) {
  289. if (version) {
  290. const [_, minor, patch] = version.split(".").map(Number);
  291. if (minor >= 4 && patch >= 3) {
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. const clientCache = /* @__PURE__ */ new WeakMap();
  298. const ssrCache = /* @__PURE__ */ new WeakMap();
  299. const typeDepToSFCMap = /* @__PURE__ */ new Map();
  300. function invalidateScript(filename) {
  301. const desc = cache.get(filename);
  302. if (desc) {
  303. clientCache.delete(desc);
  304. ssrCache.delete(desc);
  305. }
  306. }
  307. function getResolvedScript(descriptor, ssr) {
  308. return (ssr ? ssrCache : clientCache).get(descriptor);
  309. }
  310. function setResolvedScript(descriptor, script, ssr) {
  311. (ssr ? ssrCache : clientCache).set(descriptor, script);
  312. }
  313. function isUseInlineTemplate(descriptor, isProd) {
  314. return isProd && !!descriptor.scriptSetup && !descriptor.template?.src;
  315. }
  316. const scriptIdentifier = `_sfc_main`;
  317. function resolveScript(descriptor, options, ssr, customElement) {
  318. if (!descriptor.script && !descriptor.scriptSetup) {
  319. return null;
  320. }
  321. const cacheToUse = ssr ? ssrCache : clientCache;
  322. const cached = cacheToUse.get(descriptor);
  323. if (cached) {
  324. return cached;
  325. }
  326. let resolved = null;
  327. resolved = options.compiler.compileScript(descriptor, {
  328. ...options.script,
  329. id: descriptor.id,
  330. isProd: options.isProduction,
  331. inlineTemplate: isUseInlineTemplate(descriptor, !options.devServer),
  332. reactivityTransform: options.reactivityTransform !== false,
  333. templateOptions: resolveTemplateCompilerOptions(descriptor, options, ssr),
  334. sourceMap: options.sourceMap,
  335. genDefaultAs: canInlineMain(descriptor, options) ? scriptIdentifier : void 0,
  336. customElement
  337. });
  338. if (!options.isProduction && resolved?.deps) {
  339. for (const [key, sfcs] of typeDepToSFCMap) {
  340. if (sfcs.has(descriptor.filename) && !resolved.deps.includes(key)) {
  341. sfcs.delete(descriptor.filename);
  342. }
  343. }
  344. for (const dep of resolved.deps) {
  345. const existingSet = typeDepToSFCMap.get(dep);
  346. if (!existingSet) {
  347. typeDepToSFCMap.set(dep, /* @__PURE__ */ new Set([descriptor.filename]));
  348. } else {
  349. existingSet.add(descriptor.filename);
  350. }
  351. }
  352. }
  353. cacheToUse.set(descriptor, resolved);
  354. return resolved;
  355. }
  356. function canInlineMain(descriptor, options) {
  357. if (descriptor.script?.src || descriptor.scriptSetup?.src) {
  358. return false;
  359. }
  360. const lang = descriptor.script?.lang || descriptor.scriptSetup?.lang;
  361. if (!lang || lang === "js") {
  362. return true;
  363. }
  364. if (lang === "ts" && options.devServer) {
  365. return true;
  366. }
  367. return false;
  368. }
  369. const comma = ','.charCodeAt(0);
  370. const semicolon = ';'.charCodeAt(0);
  371. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  372. const intToChar = new Uint8Array(64); // 64 possible chars.
  373. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  374. for (let i = 0; i < chars.length; i++) {
  375. const c = chars.charCodeAt(i);
  376. intToChar[i] = c;
  377. charToInt[c] = i;
  378. }
  379. // Provide a fallback for older environments.
  380. const td = typeof TextDecoder !== 'undefined'
  381. ? /* #__PURE__ */ new TextDecoder()
  382. : typeof Buffer !== 'undefined'
  383. ? {
  384. decode(buf) {
  385. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  386. return out.toString();
  387. },
  388. }
  389. : {
  390. decode(buf) {
  391. let out = '';
  392. for (let i = 0; i < buf.length; i++) {
  393. out += String.fromCharCode(buf[i]);
  394. }
  395. return out;
  396. },
  397. };
  398. function decode(mappings) {
  399. const state = new Int32Array(5);
  400. const decoded = [];
  401. let index = 0;
  402. do {
  403. const semi = indexOf(mappings, index);
  404. const line = [];
  405. let sorted = true;
  406. let lastCol = 0;
  407. state[0] = 0;
  408. for (let i = index; i < semi; i++) {
  409. let seg;
  410. i = decodeInteger(mappings, i, state, 0); // genColumn
  411. const col = state[0];
  412. if (col < lastCol)
  413. sorted = false;
  414. lastCol = col;
  415. if (hasMoreVlq(mappings, i, semi)) {
  416. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  417. i = decodeInteger(mappings, i, state, 2); // sourceLine
  418. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  419. if (hasMoreVlq(mappings, i, semi)) {
  420. i = decodeInteger(mappings, i, state, 4); // namesIndex
  421. seg = [col, state[1], state[2], state[3], state[4]];
  422. }
  423. else {
  424. seg = [col, state[1], state[2], state[3]];
  425. }
  426. }
  427. else {
  428. seg = [col];
  429. }
  430. line.push(seg);
  431. }
  432. if (!sorted)
  433. sort(line);
  434. decoded.push(line);
  435. index = semi + 1;
  436. } while (index <= mappings.length);
  437. return decoded;
  438. }
  439. function indexOf(mappings, index) {
  440. const idx = mappings.indexOf(';', index);
  441. return idx === -1 ? mappings.length : idx;
  442. }
  443. function decodeInteger(mappings, pos, state, j) {
  444. let value = 0;
  445. let shift = 0;
  446. let integer = 0;
  447. do {
  448. const c = mappings.charCodeAt(pos++);
  449. integer = charToInt[c];
  450. value |= (integer & 31) << shift;
  451. shift += 5;
  452. } while (integer & 32);
  453. const shouldNegate = value & 1;
  454. value >>>= 1;
  455. if (shouldNegate) {
  456. value = -0x80000000 | -value;
  457. }
  458. state[j] += value;
  459. return pos;
  460. }
  461. function hasMoreVlq(mappings, i, length) {
  462. if (i >= length)
  463. return false;
  464. return mappings.charCodeAt(i) !== comma;
  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 state = new Int32Array(5);
  474. const bufLength = 1024 * 16;
  475. const subLength = bufLength - 36;
  476. const buf = new Uint8Array(bufLength);
  477. const sub = buf.subarray(0, subLength);
  478. let pos = 0;
  479. let out = '';
  480. for (let i = 0; i < decoded.length; i++) {
  481. const line = decoded[i];
  482. if (i > 0) {
  483. if (pos === bufLength) {
  484. out += td.decode(buf);
  485. pos = 0;
  486. }
  487. buf[pos++] = semicolon;
  488. }
  489. if (line.length === 0)
  490. continue;
  491. state[0] = 0;
  492. for (let j = 0; j < line.length; j++) {
  493. const segment = line[j];
  494. // We can push up to 5 ints, each int can take at most 7 chars, and we
  495. // may push a comma.
  496. if (pos > subLength) {
  497. out += td.decode(sub);
  498. buf.copyWithin(0, subLength, pos);
  499. pos -= subLength;
  500. }
  501. if (j > 0)
  502. buf[pos++] = comma;
  503. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  504. if (segment.length === 1)
  505. continue;
  506. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  507. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  508. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  509. if (segment.length === 4)
  510. continue;
  511. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  512. }
  513. }
  514. return out + td.decode(buf.subarray(0, pos));
  515. }
  516. function encodeInteger(buf, pos, state, segment, j) {
  517. const next = segment[j];
  518. let num = next - state[j];
  519. state[j] = next;
  520. num = num < 0 ? (-num << 1) | 1 : num << 1;
  521. do {
  522. let clamped = num & 0b011111;
  523. num >>>= 5;
  524. if (num > 0)
  525. clamped |= 0b100000;
  526. buf[pos++] = intToChar[clamped];
  527. } while (num > 0);
  528. return pos;
  529. }
  530. // Matches the scheme of a URL, eg "http://"
  531. const schemeRegex = /^[\w+.-]+:\/\//;
  532. /**
  533. * Matches the parts of a URL:
  534. * 1. Scheme, including ":", guaranteed.
  535. * 2. User/password, including "@", optional.
  536. * 3. Host, guaranteed.
  537. * 4. Port, including ":", optional.
  538. * 5. Path, including "/", optional.
  539. * 6. Query, including "?", optional.
  540. * 7. Hash, including "#", optional.
  541. */
  542. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  543. /**
  544. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  545. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  546. *
  547. * 1. Host, optional.
  548. * 2. Path, which may include "/", guaranteed.
  549. * 3. Query, including "?", optional.
  550. * 4. Hash, including "#", optional.
  551. */
  552. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  553. var UrlType;
  554. (function (UrlType) {
  555. UrlType[UrlType["Empty"] = 1] = "Empty";
  556. UrlType[UrlType["Hash"] = 2] = "Hash";
  557. UrlType[UrlType["Query"] = 3] = "Query";
  558. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  559. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  560. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  561. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  562. })(UrlType || (UrlType = {}));
  563. function isAbsoluteUrl(input) {
  564. return schemeRegex.test(input);
  565. }
  566. function isSchemeRelativeUrl(input) {
  567. return input.startsWith('//');
  568. }
  569. function isAbsolutePath(input) {
  570. return input.startsWith('/');
  571. }
  572. function isFileUrl(input) {
  573. return input.startsWith('file:');
  574. }
  575. function isRelative(input) {
  576. return /^[.?#]/.test(input);
  577. }
  578. function parseAbsoluteUrl(input) {
  579. const match = urlRegex.exec(input);
  580. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  581. }
  582. function parseFileUrl(input) {
  583. const match = fileRegex.exec(input);
  584. const path = match[2];
  585. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  586. }
  587. function makeUrl(scheme, user, host, port, path, query, hash) {
  588. return {
  589. scheme,
  590. user,
  591. host,
  592. port,
  593. path,
  594. query,
  595. hash,
  596. type: UrlType.Absolute,
  597. };
  598. }
  599. function parseUrl(input) {
  600. if (isSchemeRelativeUrl(input)) {
  601. const url = parseAbsoluteUrl('http:' + input);
  602. url.scheme = '';
  603. url.type = UrlType.SchemeRelative;
  604. return url;
  605. }
  606. if (isAbsolutePath(input)) {
  607. const url = parseAbsoluteUrl('http://foo.com' + input);
  608. url.scheme = '';
  609. url.host = '';
  610. url.type = UrlType.AbsolutePath;
  611. return url;
  612. }
  613. if (isFileUrl(input))
  614. return parseFileUrl(input);
  615. if (isAbsoluteUrl(input))
  616. return parseAbsoluteUrl(input);
  617. const url = parseAbsoluteUrl('http://foo.com/' + input);
  618. url.scheme = '';
  619. url.host = '';
  620. url.type = input
  621. ? input.startsWith('?')
  622. ? UrlType.Query
  623. : input.startsWith('#')
  624. ? UrlType.Hash
  625. : UrlType.RelativePath
  626. : UrlType.Empty;
  627. return url;
  628. }
  629. function stripPathFilename(path) {
  630. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  631. // paths. It's not a file, so we can't strip it.
  632. if (path.endsWith('/..'))
  633. return path;
  634. const index = path.lastIndexOf('/');
  635. return path.slice(0, index + 1);
  636. }
  637. function mergePaths(url, base) {
  638. normalizePath(base, base.type);
  639. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  640. // path).
  641. if (url.path === '/') {
  642. url.path = base.path;
  643. }
  644. else {
  645. // Resolution happens relative to the base path's directory, not the file.
  646. url.path = stripPathFilename(base.path) + url.path;
  647. }
  648. }
  649. /**
  650. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  651. * "foo/.". We need to normalize to a standard representation.
  652. */
  653. function normalizePath(url, type) {
  654. const rel = type <= UrlType.RelativePath;
  655. const pieces = url.path.split('/');
  656. // We need to preserve the first piece always, so that we output a leading slash. The item at
  657. // pieces[0] is an empty string.
  658. let pointer = 1;
  659. // Positive is the number of real directories we've output, used for popping a parent directory.
  660. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  661. let positive = 0;
  662. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  663. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  664. // real directory, we won't need to append, unless the other conditions happen again.
  665. let addTrailingSlash = false;
  666. for (let i = 1; i < pieces.length; i++) {
  667. const piece = pieces[i];
  668. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  669. if (!piece) {
  670. addTrailingSlash = true;
  671. continue;
  672. }
  673. // If we encounter a real directory, then we don't need to append anymore.
  674. addTrailingSlash = false;
  675. // A current directory, which we can always drop.
  676. if (piece === '.')
  677. continue;
  678. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  679. // have an excess of parents, and we'll need to keep the "..".
  680. if (piece === '..') {
  681. if (positive) {
  682. addTrailingSlash = true;
  683. positive--;
  684. pointer--;
  685. }
  686. else if (rel) {
  687. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  688. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  689. pieces[pointer++] = piece;
  690. }
  691. continue;
  692. }
  693. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  694. // any popped or dropped directories.
  695. pieces[pointer++] = piece;
  696. positive++;
  697. }
  698. let path = '';
  699. for (let i = 1; i < pointer; i++) {
  700. path += '/' + pieces[i];
  701. }
  702. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  703. path += '/';
  704. }
  705. url.path = path;
  706. }
  707. /**
  708. * Attempts to resolve `input` URL/path relative to `base`.
  709. */
  710. function resolve$1(input, base) {
  711. if (!input && !base)
  712. return '';
  713. const url = parseUrl(input);
  714. let inputType = url.type;
  715. if (base && inputType !== UrlType.Absolute) {
  716. const baseUrl = parseUrl(base);
  717. const baseType = baseUrl.type;
  718. switch (inputType) {
  719. case UrlType.Empty:
  720. url.hash = baseUrl.hash;
  721. // fall through
  722. case UrlType.Hash:
  723. url.query = baseUrl.query;
  724. // fall through
  725. case UrlType.Query:
  726. case UrlType.RelativePath:
  727. mergePaths(url, baseUrl);
  728. // fall through
  729. case UrlType.AbsolutePath:
  730. // The host, user, and port are joined, you can't copy one without the others.
  731. url.user = baseUrl.user;
  732. url.host = baseUrl.host;
  733. url.port = baseUrl.port;
  734. // fall through
  735. case UrlType.SchemeRelative:
  736. // The input doesn't have a schema at least, so we need to copy at least that over.
  737. url.scheme = baseUrl.scheme;
  738. }
  739. if (baseType > inputType)
  740. inputType = baseType;
  741. }
  742. normalizePath(url, inputType);
  743. const queryHash = url.query + url.hash;
  744. switch (inputType) {
  745. // This is impossible, because of the empty checks at the start of the function.
  746. // case UrlType.Empty:
  747. case UrlType.Hash:
  748. case UrlType.Query:
  749. return queryHash;
  750. case UrlType.RelativePath: {
  751. // The first char is always a "/", and we need it to be relative.
  752. const path = url.path.slice(1);
  753. if (!path)
  754. return queryHash || '.';
  755. if (isRelative(base || input) && !isRelative(path)) {
  756. // If base started with a leading ".", or there is no base and input started with a ".",
  757. // then we need to ensure that the relative path starts with a ".". We don't know if
  758. // relative starts with a "..", though, so check before prepending.
  759. return './' + path + queryHash;
  760. }
  761. return path + queryHash;
  762. }
  763. case UrlType.AbsolutePath:
  764. return url.path + queryHash;
  765. default:
  766. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  767. }
  768. }
  769. function resolve(input, base) {
  770. // The base is always treated as a directory, if it's not empty.
  771. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  772. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  773. if (base && !base.endsWith('/'))
  774. base += '/';
  775. return resolve$1(input, base);
  776. }
  777. /**
  778. * Removes everything after the last "/", but leaves the slash.
  779. */
  780. function stripFilename(path) {
  781. if (!path)
  782. return '';
  783. const index = path.lastIndexOf('/');
  784. return path.slice(0, index + 1);
  785. }
  786. const COLUMN$1 = 0;
  787. function maybeSort(mappings, owned) {
  788. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  789. if (unsortedIndex === mappings.length)
  790. return mappings;
  791. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  792. // not, we do not want to modify the consumer's input array.
  793. if (!owned)
  794. mappings = mappings.slice();
  795. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  796. mappings[i] = sortSegments(mappings[i], owned);
  797. }
  798. return mappings;
  799. }
  800. function nextUnsortedSegmentLine(mappings, start) {
  801. for (let i = start; i < mappings.length; i++) {
  802. if (!isSorted(mappings[i]))
  803. return i;
  804. }
  805. return mappings.length;
  806. }
  807. function isSorted(line) {
  808. for (let j = 1; j < line.length; j++) {
  809. if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
  810. return false;
  811. }
  812. }
  813. return true;
  814. }
  815. function sortSegments(line, owned) {
  816. if (!owned)
  817. line = line.slice();
  818. return line.sort(sortComparator);
  819. }
  820. function sortComparator(a, b) {
  821. return a[COLUMN$1] - b[COLUMN$1];
  822. }
  823. function memoizedState() {
  824. return {
  825. lastKey: -1,
  826. lastNeedle: -1,
  827. lastIndex: -1,
  828. };
  829. }
  830. /**
  831. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  832. */
  833. let decodedMappings;
  834. /**
  835. * Iterates each mapping in generated position order.
  836. */
  837. let eachMapping;
  838. class TraceMap {
  839. constructor(map, mapUrl) {
  840. const isString = typeof map === 'string';
  841. if (!isString && map._decodedMemo)
  842. return map;
  843. const parsed = (isString ? JSON.parse(map) : map);
  844. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  845. this.version = version;
  846. this.file = file;
  847. this.names = names || [];
  848. this.sourceRoot = sourceRoot;
  849. this.sources = sources;
  850. this.sourcesContent = sourcesContent;
  851. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  852. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  853. const { mappings } = parsed;
  854. if (typeof mappings === 'string') {
  855. this._encoded = mappings;
  856. this._decoded = undefined;
  857. }
  858. else {
  859. this._encoded = undefined;
  860. this._decoded = maybeSort(mappings, isString);
  861. }
  862. this._decodedMemo = memoizedState();
  863. this._bySources = undefined;
  864. this._bySourceMemos = undefined;
  865. }
  866. }
  867. (() => {
  868. decodedMappings = (map) => {
  869. return (map._decoded || (map._decoded = decode(map._encoded)));
  870. };
  871. eachMapping = (map, cb) => {
  872. const decoded = decodedMappings(map);
  873. const { names, resolvedSources } = map;
  874. for (let i = 0; i < decoded.length; i++) {
  875. const line = decoded[i];
  876. for (let j = 0; j < line.length; j++) {
  877. const seg = line[j];
  878. const generatedLine = i + 1;
  879. const generatedColumn = seg[0];
  880. let source = null;
  881. let originalLine = null;
  882. let originalColumn = null;
  883. let name = null;
  884. if (seg.length !== 1) {
  885. source = resolvedSources[seg[1]];
  886. originalLine = seg[2] + 1;
  887. originalColumn = seg[3];
  888. }
  889. if (seg.length === 5)
  890. name = names[seg[4]];
  891. cb({
  892. generatedLine,
  893. generatedColumn,
  894. source,
  895. originalLine,
  896. originalColumn,
  897. name,
  898. });
  899. }
  900. }
  901. };
  902. })();
  903. /**
  904. * Gets the index associated with `key` in the backing array, if it is already present.
  905. */
  906. let get;
  907. /**
  908. * Puts `key` into the backing array, if it is not already present. Returns
  909. * the index of the `key` in the backing array.
  910. */
  911. let put;
  912. /**
  913. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  914. * index of the `key` in the backing array.
  915. *
  916. * This is designed to allow synchronizing a second array with the contents of the backing array,
  917. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  918. * and there are never duplicates.
  919. */
  920. class SetArray {
  921. constructor() {
  922. this._indexes = { __proto__: null };
  923. this.array = [];
  924. }
  925. }
  926. (() => {
  927. get = (strarr, key) => strarr._indexes[key];
  928. put = (strarr, key) => {
  929. // The key may or may not be present. If it is present, it's a number.
  930. const index = get(strarr, key);
  931. if (index !== undefined)
  932. return index;
  933. const { array, _indexes: indexes } = strarr;
  934. return (indexes[key] = array.push(key) - 1);
  935. };
  936. })();
  937. const COLUMN = 0;
  938. const SOURCES_INDEX = 1;
  939. const SOURCE_LINE = 2;
  940. const SOURCE_COLUMN = 3;
  941. const NAMES_INDEX = 4;
  942. const NO_NAME = -1;
  943. /**
  944. * A high-level API to associate a generated position with an original source position. Line is
  945. * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.
  946. */
  947. let addMapping;
  948. /**
  949. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  950. * a sourcemap, or to JSON.stringify.
  951. */
  952. let toDecodedMap;
  953. /**
  954. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  955. * a sourcemap, or to JSON.stringify.
  956. */
  957. let toEncodedMap;
  958. /**
  959. * Constructs a new GenMapping, using the already present mappings of the input.
  960. */
  961. let fromMap;
  962. // This split declaration is only so that terser can elminiate the static initialization block.
  963. let addSegmentInternal;
  964. /**
  965. * Provides the state to generate a sourcemap.
  966. */
  967. class GenMapping {
  968. constructor({ file, sourceRoot } = {}) {
  969. this._names = new SetArray();
  970. this._sources = new SetArray();
  971. this._sourcesContent = [];
  972. this._mappings = [];
  973. this.file = file;
  974. this.sourceRoot = sourceRoot;
  975. }
  976. }
  977. (() => {
  978. addMapping = (map, mapping) => {
  979. return addMappingInternal(false, map, mapping);
  980. };
  981. toDecodedMap = (map) => {
  982. const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  983. removeEmptyFinalLines(mappings);
  984. return {
  985. version: 3,
  986. file: file || undefined,
  987. names: names.array,
  988. sourceRoot: sourceRoot || undefined,
  989. sources: sources.array,
  990. sourcesContent,
  991. mappings,
  992. };
  993. };
  994. toEncodedMap = (map) => {
  995. const decoded = toDecodedMap(map);
  996. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  997. };
  998. fromMap = (input) => {
  999. const map = new TraceMap(input);
  1000. const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
  1001. putAll(gen._names, map.names);
  1002. putAll(gen._sources, map.sources);
  1003. gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);
  1004. gen._mappings = decodedMappings(map);
  1005. return gen;
  1006. };
  1007. // Internal helpers
  1008. addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  1009. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  1010. const line = getLine(mappings, genLine);
  1011. const index = getColumnIndex(line, genColumn);
  1012. if (!source) {
  1013. if (skipable && skipSourceless(line, index))
  1014. return;
  1015. return insert(line, index, [genColumn]);
  1016. }
  1017. const sourcesIndex = put(sources, source);
  1018. const namesIndex = name ? put(names, name) : NO_NAME;
  1019. if (sourcesIndex === sourcesContent.length)
  1020. sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
  1021. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  1022. return;
  1023. }
  1024. return insert(line, index, name
  1025. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
  1026. : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  1027. };
  1028. })();
  1029. function getLine(mappings, index) {
  1030. for (let i = mappings.length; i <= index; i++) {
  1031. mappings[i] = [];
  1032. }
  1033. return mappings[index];
  1034. }
  1035. function getColumnIndex(line, genColumn) {
  1036. let index = line.length;
  1037. for (let i = index - 1; i >= 0; index = i--) {
  1038. const current = line[i];
  1039. if (genColumn >= current[COLUMN])
  1040. break;
  1041. }
  1042. return index;
  1043. }
  1044. function insert(array, index, value) {
  1045. for (let i = array.length; i > index; i--) {
  1046. array[i] = array[i - 1];
  1047. }
  1048. array[index] = value;
  1049. }
  1050. function removeEmptyFinalLines(mappings) {
  1051. const { length } = mappings;
  1052. let len = length;
  1053. for (let i = len - 1; i >= 0; len = i, i--) {
  1054. if (mappings[i].length > 0)
  1055. break;
  1056. }
  1057. if (len < length)
  1058. mappings.length = len;
  1059. }
  1060. function putAll(strarr, array) {
  1061. for (let i = 0; i < array.length; i++)
  1062. put(strarr, array[i]);
  1063. }
  1064. function skipSourceless(line, index) {
  1065. // The start of a line is already sourceless, so adding a sourceless segment to the beginning
  1066. // doesn't generate any useful information.
  1067. if (index === 0)
  1068. return true;
  1069. const prev = line[index - 1];
  1070. // If the previous segment is also sourceless, then adding another sourceless segment doesn't
  1071. // genrate any new information. Else, this segment will end the source/named segment and point to
  1072. // a sourceless position, which is useful.
  1073. return prev.length === 1;
  1074. }
  1075. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  1076. // A source/named segment at the start of a line gives position at that genColumn
  1077. if (index === 0)
  1078. return false;
  1079. const prev = line[index - 1];
  1080. // If the previous segment is sourceless, then we're transitioning to a source.
  1081. if (prev.length === 1)
  1082. return false;
  1083. // If the previous segment maps to the exact same source position, then this segment doesn't
  1084. // provide any new position information.
  1085. return (sourcesIndex === prev[SOURCES_INDEX] &&
  1086. sourceLine === prev[SOURCE_LINE] &&
  1087. sourceColumn === prev[SOURCE_COLUMN] &&
  1088. namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
  1089. }
  1090. function addMappingInternal(skipable, map, mapping) {
  1091. const { generated, source, original, name, content } = mapping;
  1092. if (!source) {
  1093. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null);
  1094. }
  1095. const s = source;
  1096. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content);
  1097. }
  1098. function getDefaultExportFromCjs (x) {
  1099. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  1100. }
  1101. var src = {exports: {}};
  1102. var browser = {exports: {}};
  1103. /**
  1104. * Helpers.
  1105. */
  1106. var ms;
  1107. var hasRequiredMs;
  1108. function requireMs () {
  1109. if (hasRequiredMs) return ms;
  1110. hasRequiredMs = 1;
  1111. var s = 1000;
  1112. var m = s * 60;
  1113. var h = m * 60;
  1114. var d = h * 24;
  1115. var w = d * 7;
  1116. var y = d * 365.25;
  1117. /**
  1118. * Parse or format the given `val`.
  1119. *
  1120. * Options:
  1121. *
  1122. * - `long` verbose formatting [false]
  1123. *
  1124. * @param {String|Number} val
  1125. * @param {Object} [options]
  1126. * @throws {Error} throw an error if val is not a non-empty string or a number
  1127. * @return {String|Number}
  1128. * @api public
  1129. */
  1130. ms = function(val, options) {
  1131. options = options || {};
  1132. var type = typeof val;
  1133. if (type === 'string' && val.length > 0) {
  1134. return parse(val);
  1135. } else if (type === 'number' && isFinite(val)) {
  1136. return options.long ? fmtLong(val) : fmtShort(val);
  1137. }
  1138. throw new Error(
  1139. 'val is not a non-empty string or a valid number. val=' +
  1140. JSON.stringify(val)
  1141. );
  1142. };
  1143. /**
  1144. * Parse the given `str` and return milliseconds.
  1145. *
  1146. * @param {String} str
  1147. * @return {Number}
  1148. * @api private
  1149. */
  1150. function parse(str) {
  1151. str = String(str);
  1152. if (str.length > 100) {
  1153. return;
  1154. }
  1155. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  1156. str
  1157. );
  1158. if (!match) {
  1159. return;
  1160. }
  1161. var n = parseFloat(match[1]);
  1162. var type = (match[2] || 'ms').toLowerCase();
  1163. switch (type) {
  1164. case 'years':
  1165. case 'year':
  1166. case 'yrs':
  1167. case 'yr':
  1168. case 'y':
  1169. return n * y;
  1170. case 'weeks':
  1171. case 'week':
  1172. case 'w':
  1173. return n * w;
  1174. case 'days':
  1175. case 'day':
  1176. case 'd':
  1177. return n * d;
  1178. case 'hours':
  1179. case 'hour':
  1180. case 'hrs':
  1181. case 'hr':
  1182. case 'h':
  1183. return n * h;
  1184. case 'minutes':
  1185. case 'minute':
  1186. case 'mins':
  1187. case 'min':
  1188. case 'm':
  1189. return n * m;
  1190. case 'seconds':
  1191. case 'second':
  1192. case 'secs':
  1193. case 'sec':
  1194. case 's':
  1195. return n * s;
  1196. case 'milliseconds':
  1197. case 'millisecond':
  1198. case 'msecs':
  1199. case 'msec':
  1200. case 'ms':
  1201. return n;
  1202. default:
  1203. return undefined;
  1204. }
  1205. }
  1206. /**
  1207. * Short format for `ms`.
  1208. *
  1209. * @param {Number} ms
  1210. * @return {String}
  1211. * @api private
  1212. */
  1213. function fmtShort(ms) {
  1214. var msAbs = Math.abs(ms);
  1215. if (msAbs >= d) {
  1216. return Math.round(ms / d) + 'd';
  1217. }
  1218. if (msAbs >= h) {
  1219. return Math.round(ms / h) + 'h';
  1220. }
  1221. if (msAbs >= m) {
  1222. return Math.round(ms / m) + 'm';
  1223. }
  1224. if (msAbs >= s) {
  1225. return Math.round(ms / s) + 's';
  1226. }
  1227. return ms + 'ms';
  1228. }
  1229. /**
  1230. * Long format for `ms`.
  1231. *
  1232. * @param {Number} ms
  1233. * @return {String}
  1234. * @api private
  1235. */
  1236. function fmtLong(ms) {
  1237. var msAbs = Math.abs(ms);
  1238. if (msAbs >= d) {
  1239. return plural(ms, msAbs, d, 'day');
  1240. }
  1241. if (msAbs >= h) {
  1242. return plural(ms, msAbs, h, 'hour');
  1243. }
  1244. if (msAbs >= m) {
  1245. return plural(ms, msAbs, m, 'minute');
  1246. }
  1247. if (msAbs >= s) {
  1248. return plural(ms, msAbs, s, 'second');
  1249. }
  1250. return ms + ' ms';
  1251. }
  1252. /**
  1253. * Pluralization helper.
  1254. */
  1255. function plural(ms, msAbs, n, name) {
  1256. var isPlural = msAbs >= n * 1.5;
  1257. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  1258. }
  1259. return ms;
  1260. }
  1261. var common;
  1262. var hasRequiredCommon;
  1263. function requireCommon () {
  1264. if (hasRequiredCommon) return common;
  1265. hasRequiredCommon = 1;
  1266. /**
  1267. * This is the common logic for both the Node.js and web browser
  1268. * implementations of `debug()`.
  1269. */
  1270. function setup(env) {
  1271. createDebug.debug = createDebug;
  1272. createDebug.default = createDebug;
  1273. createDebug.coerce = coerce;
  1274. createDebug.disable = disable;
  1275. createDebug.enable = enable;
  1276. createDebug.enabled = enabled;
  1277. createDebug.humanize = requireMs();
  1278. createDebug.destroy = destroy;
  1279. Object.keys(env).forEach(key => {
  1280. createDebug[key] = env[key];
  1281. });
  1282. /**
  1283. * The currently active debug mode names, and names to skip.
  1284. */
  1285. createDebug.names = [];
  1286. createDebug.skips = [];
  1287. /**
  1288. * Map of special "%n" handling functions, for the debug "format" argument.
  1289. *
  1290. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  1291. */
  1292. createDebug.formatters = {};
  1293. /**
  1294. * Selects a color for a debug namespace
  1295. * @param {String} namespace The namespace string for the debug instance to be colored
  1296. * @return {Number|String} An ANSI color code for the given namespace
  1297. * @api private
  1298. */
  1299. function selectColor(namespace) {
  1300. let hash = 0;
  1301. for (let i = 0; i < namespace.length; i++) {
  1302. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  1303. hash |= 0; // Convert to 32bit integer
  1304. }
  1305. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  1306. }
  1307. createDebug.selectColor = selectColor;
  1308. /**
  1309. * Create a debugger with the given `namespace`.
  1310. *
  1311. * @param {String} namespace
  1312. * @return {Function}
  1313. * @api public
  1314. */
  1315. function createDebug(namespace) {
  1316. let prevTime;
  1317. let enableOverride = null;
  1318. let namespacesCache;
  1319. let enabledCache;
  1320. function debug(...args) {
  1321. // Disabled?
  1322. if (!debug.enabled) {
  1323. return;
  1324. }
  1325. const self = debug;
  1326. // Set `diff` timestamp
  1327. const curr = Number(new Date());
  1328. const ms = curr - (prevTime || curr);
  1329. self.diff = ms;
  1330. self.prev = prevTime;
  1331. self.curr = curr;
  1332. prevTime = curr;
  1333. args[0] = createDebug.coerce(args[0]);
  1334. if (typeof args[0] !== 'string') {
  1335. // Anything else let's inspect with %O
  1336. args.unshift('%O');
  1337. }
  1338. // Apply any `formatters` transformations
  1339. let index = 0;
  1340. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  1341. // If we encounter an escaped % then don't increase the array index
  1342. if (match === '%%') {
  1343. return '%';
  1344. }
  1345. index++;
  1346. const formatter = createDebug.formatters[format];
  1347. if (typeof formatter === 'function') {
  1348. const val = args[index];
  1349. match = formatter.call(self, val);
  1350. // Now we need to remove `args[index]` since it's inlined in the `format`
  1351. args.splice(index, 1);
  1352. index--;
  1353. }
  1354. return match;
  1355. });
  1356. // Apply env-specific formatting (colors, etc.)
  1357. createDebug.formatArgs.call(self, args);
  1358. const logFn = self.log || createDebug.log;
  1359. logFn.apply(self, args);
  1360. }
  1361. debug.namespace = namespace;
  1362. debug.useColors = createDebug.useColors();
  1363. debug.color = createDebug.selectColor(namespace);
  1364. debug.extend = extend;
  1365. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  1366. Object.defineProperty(debug, 'enabled', {
  1367. enumerable: true,
  1368. configurable: false,
  1369. get: () => {
  1370. if (enableOverride !== null) {
  1371. return enableOverride;
  1372. }
  1373. if (namespacesCache !== createDebug.namespaces) {
  1374. namespacesCache = createDebug.namespaces;
  1375. enabledCache = createDebug.enabled(namespace);
  1376. }
  1377. return enabledCache;
  1378. },
  1379. set: v => {
  1380. enableOverride = v;
  1381. }
  1382. });
  1383. // Env-specific initialization logic for debug instances
  1384. if (typeof createDebug.init === 'function') {
  1385. createDebug.init(debug);
  1386. }
  1387. return debug;
  1388. }
  1389. function extend(namespace, delimiter) {
  1390. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  1391. newDebug.log = this.log;
  1392. return newDebug;
  1393. }
  1394. /**
  1395. * Enables a debug mode by namespaces. This can include modes
  1396. * separated by a colon and wildcards.
  1397. *
  1398. * @param {String} namespaces
  1399. * @api public
  1400. */
  1401. function enable(namespaces) {
  1402. createDebug.save(namespaces);
  1403. createDebug.namespaces = namespaces;
  1404. createDebug.names = [];
  1405. createDebug.skips = [];
  1406. let i;
  1407. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  1408. const len = split.length;
  1409. for (i = 0; i < len; i++) {
  1410. if (!split[i]) {
  1411. // ignore empty strings
  1412. continue;
  1413. }
  1414. namespaces = split[i].replace(/\*/g, '.*?');
  1415. if (namespaces[0] === '-') {
  1416. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  1417. } else {
  1418. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  1419. }
  1420. }
  1421. }
  1422. /**
  1423. * Disable debug output.
  1424. *
  1425. * @return {String} namespaces
  1426. * @api public
  1427. */
  1428. function disable() {
  1429. const namespaces = [
  1430. ...createDebug.names.map(toNamespace),
  1431. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  1432. ].join(',');
  1433. createDebug.enable('');
  1434. return namespaces;
  1435. }
  1436. /**
  1437. * Returns true if the given mode name is enabled, false otherwise.
  1438. *
  1439. * @param {String} name
  1440. * @return {Boolean}
  1441. * @api public
  1442. */
  1443. function enabled(name) {
  1444. if (name[name.length - 1] === '*') {
  1445. return true;
  1446. }
  1447. let i;
  1448. let len;
  1449. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  1450. if (createDebug.skips[i].test(name)) {
  1451. return false;
  1452. }
  1453. }
  1454. for (i = 0, len = createDebug.names.length; i < len; i++) {
  1455. if (createDebug.names[i].test(name)) {
  1456. return true;
  1457. }
  1458. }
  1459. return false;
  1460. }
  1461. /**
  1462. * Convert regexp to namespace
  1463. *
  1464. * @param {RegExp} regxep
  1465. * @return {String} namespace
  1466. * @api private
  1467. */
  1468. function toNamespace(regexp) {
  1469. return regexp.toString()
  1470. .substring(2, regexp.toString().length - 2)
  1471. .replace(/\.\*\?$/, '*');
  1472. }
  1473. /**
  1474. * Coerce `val`.
  1475. *
  1476. * @param {Mixed} val
  1477. * @return {Mixed}
  1478. * @api private
  1479. */
  1480. function coerce(val) {
  1481. if (val instanceof Error) {
  1482. return val.stack || val.message;
  1483. }
  1484. return val;
  1485. }
  1486. /**
  1487. * XXX DO NOT USE. This is a temporary stub function.
  1488. * XXX It WILL be removed in the next major release.
  1489. */
  1490. function destroy() {
  1491. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1492. }
  1493. createDebug.enable(createDebug.load());
  1494. return createDebug;
  1495. }
  1496. common = setup;
  1497. return common;
  1498. }
  1499. /* eslint-env browser */
  1500. var hasRequiredBrowser;
  1501. function requireBrowser () {
  1502. if (hasRequiredBrowser) return browser.exports;
  1503. hasRequiredBrowser = 1;
  1504. (function (module, exports) {
  1505. /**
  1506. * This is the web browser implementation of `debug()`.
  1507. */
  1508. exports.formatArgs = formatArgs;
  1509. exports.save = save;
  1510. exports.load = load;
  1511. exports.useColors = useColors;
  1512. exports.storage = localstorage();
  1513. exports.destroy = (() => {
  1514. let warned = false;
  1515. return () => {
  1516. if (!warned) {
  1517. warned = true;
  1518. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  1519. }
  1520. };
  1521. })();
  1522. /**
  1523. * Colors.
  1524. */
  1525. exports.colors = [
  1526. '#0000CC',
  1527. '#0000FF',
  1528. '#0033CC',
  1529. '#0033FF',
  1530. '#0066CC',
  1531. '#0066FF',
  1532. '#0099CC',
  1533. '#0099FF',
  1534. '#00CC00',
  1535. '#00CC33',
  1536. '#00CC66',
  1537. '#00CC99',
  1538. '#00CCCC',
  1539. '#00CCFF',
  1540. '#3300CC',
  1541. '#3300FF',
  1542. '#3333CC',
  1543. '#3333FF',
  1544. '#3366CC',
  1545. '#3366FF',
  1546. '#3399CC',
  1547. '#3399FF',
  1548. '#33CC00',
  1549. '#33CC33',
  1550. '#33CC66',
  1551. '#33CC99',
  1552. '#33CCCC',
  1553. '#33CCFF',
  1554. '#6600CC',
  1555. '#6600FF',
  1556. '#6633CC',
  1557. '#6633FF',
  1558. '#66CC00',
  1559. '#66CC33',
  1560. '#9900CC',
  1561. '#9900FF',
  1562. '#9933CC',
  1563. '#9933FF',
  1564. '#99CC00',
  1565. '#99CC33',
  1566. '#CC0000',
  1567. '#CC0033',
  1568. '#CC0066',
  1569. '#CC0099',
  1570. '#CC00CC',
  1571. '#CC00FF',
  1572. '#CC3300',
  1573. '#CC3333',
  1574. '#CC3366',
  1575. '#CC3399',
  1576. '#CC33CC',
  1577. '#CC33FF',
  1578. '#CC6600',
  1579. '#CC6633',
  1580. '#CC9900',
  1581. '#CC9933',
  1582. '#CCCC00',
  1583. '#CCCC33',
  1584. '#FF0000',
  1585. '#FF0033',
  1586. '#FF0066',
  1587. '#FF0099',
  1588. '#FF00CC',
  1589. '#FF00FF',
  1590. '#FF3300',
  1591. '#FF3333',
  1592. '#FF3366',
  1593. '#FF3399',
  1594. '#FF33CC',
  1595. '#FF33FF',
  1596. '#FF6600',
  1597. '#FF6633',
  1598. '#FF9900',
  1599. '#FF9933',
  1600. '#FFCC00',
  1601. '#FFCC33'
  1602. ];
  1603. /**
  1604. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1605. * and the Firebug extension (any Firefox version) are known
  1606. * to support "%c" CSS customizations.
  1607. *
  1608. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1609. */
  1610. // eslint-disable-next-line complexity
  1611. function useColors() {
  1612. // NB: In an Electron preload script, document will be defined but not fully
  1613. // initialized. Since we know we're in Chrome, we'll just detect this case
  1614. // explicitly
  1615. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  1616. return true;
  1617. }
  1618. // Internet Explorer and Edge do not support colors.
  1619. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  1620. return false;
  1621. }
  1622. // Is webkit? http://stackoverflow.com/a/16459606/376773
  1623. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  1624. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  1625. // Is firebug? http://stackoverflow.com/a/398120/376773
  1626. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  1627. // Is firefox >= v31?
  1628. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1629. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  1630. // Double check webkit in userAgent just in case we are in a worker
  1631. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  1632. }
  1633. /**
  1634. * Colorize log arguments if enabled.
  1635. *
  1636. * @api public
  1637. */
  1638. function formatArgs(args) {
  1639. args[0] = (this.useColors ? '%c' : '') +
  1640. this.namespace +
  1641. (this.useColors ? ' %c' : ' ') +
  1642. args[0] +
  1643. (this.useColors ? '%c ' : ' ') +
  1644. '+' + module.exports.humanize(this.diff);
  1645. if (!this.useColors) {
  1646. return;
  1647. }
  1648. const c = 'color: ' + this.color;
  1649. args.splice(1, 0, c, 'color: inherit');
  1650. // The final "%c" is somewhat tricky, because there could be other
  1651. // arguments passed either before or after the %c, so we need to
  1652. // figure out the correct index to insert the CSS into
  1653. let index = 0;
  1654. let lastC = 0;
  1655. args[0].replace(/%[a-zA-Z%]/g, match => {
  1656. if (match === '%%') {
  1657. return;
  1658. }
  1659. index++;
  1660. if (match === '%c') {
  1661. // We only are interested in the *last* %c
  1662. // (the user may have provided their own)
  1663. lastC = index;
  1664. }
  1665. });
  1666. args.splice(lastC, 0, c);
  1667. }
  1668. /**
  1669. * Invokes `console.debug()` when available.
  1670. * No-op when `console.debug` is not a "function".
  1671. * If `console.debug` is not available, falls back
  1672. * to `console.log`.
  1673. *
  1674. * @api public
  1675. */
  1676. exports.log = console.debug || console.log || (() => {});
  1677. /**
  1678. * Save `namespaces`.
  1679. *
  1680. * @param {String} namespaces
  1681. * @api private
  1682. */
  1683. function save(namespaces) {
  1684. try {
  1685. if (namespaces) {
  1686. exports.storage.setItem('debug', namespaces);
  1687. } else {
  1688. exports.storage.removeItem('debug');
  1689. }
  1690. } catch (error) {
  1691. // Swallow
  1692. // XXX (@Qix-) should we be logging these?
  1693. }
  1694. }
  1695. /**
  1696. * Load `namespaces`.
  1697. *
  1698. * @return {String} returns the previously persisted debug modes
  1699. * @api private
  1700. */
  1701. function load() {
  1702. let r;
  1703. try {
  1704. r = exports.storage.getItem('debug');
  1705. } catch (error) {
  1706. // Swallow
  1707. // XXX (@Qix-) should we be logging these?
  1708. }
  1709. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  1710. if (!r && typeof process !== 'undefined' && 'env' in process) {
  1711. r = process.env.DEBUG;
  1712. }
  1713. return r;
  1714. }
  1715. /**
  1716. * Localstorage attempts to return the localstorage.
  1717. *
  1718. * This is necessary because safari throws
  1719. * when a user disables cookies/localstorage
  1720. * and you attempt to access it.
  1721. *
  1722. * @return {LocalStorage}
  1723. * @api private
  1724. */
  1725. function localstorage() {
  1726. try {
  1727. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  1728. // The Browser also has localStorage in the global context.
  1729. return localStorage;
  1730. } catch (error) {
  1731. // Swallow
  1732. // XXX (@Qix-) should we be logging these?
  1733. }
  1734. }
  1735. module.exports = requireCommon()(exports);
  1736. const {formatters} = module.exports;
  1737. /**
  1738. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1739. */
  1740. formatters.j = function (v) {
  1741. try {
  1742. return JSON.stringify(v);
  1743. } catch (error) {
  1744. return '[UnexpectedJSONParseError]: ' + error.message;
  1745. }
  1746. };
  1747. } (browser, browser.exports));
  1748. return browser.exports;
  1749. }
  1750. var node = {exports: {}};
  1751. /**
  1752. * Module dependencies.
  1753. */
  1754. var hasRequiredNode;
  1755. function requireNode () {
  1756. if (hasRequiredNode) return node.exports;
  1757. hasRequiredNode = 1;
  1758. (function (module, exports) {
  1759. const tty = require$$0;
  1760. const util = require$$1;
  1761. /**
  1762. * This is the Node.js implementation of `debug()`.
  1763. */
  1764. exports.init = init;
  1765. exports.log = log;
  1766. exports.formatArgs = formatArgs;
  1767. exports.save = save;
  1768. exports.load = load;
  1769. exports.useColors = useColors;
  1770. exports.destroy = util.deprecate(
  1771. () => {},
  1772. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  1773. );
  1774. /**
  1775. * Colors.
  1776. */
  1777. exports.colors = [6, 2, 3, 4, 5, 1];
  1778. try {
  1779. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  1780. // eslint-disable-next-line import/no-extraneous-dependencies
  1781. const supportsColor = require('supports-color');
  1782. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  1783. exports.colors = [
  1784. 20,
  1785. 21,
  1786. 26,
  1787. 27,
  1788. 32,
  1789. 33,
  1790. 38,
  1791. 39,
  1792. 40,
  1793. 41,
  1794. 42,
  1795. 43,
  1796. 44,
  1797. 45,
  1798. 56,
  1799. 57,
  1800. 62,
  1801. 63,
  1802. 68,
  1803. 69,
  1804. 74,
  1805. 75,
  1806. 76,
  1807. 77,
  1808. 78,
  1809. 79,
  1810. 80,
  1811. 81,
  1812. 92,
  1813. 93,
  1814. 98,
  1815. 99,
  1816. 112,
  1817. 113,
  1818. 128,
  1819. 129,
  1820. 134,
  1821. 135,
  1822. 148,
  1823. 149,
  1824. 160,
  1825. 161,
  1826. 162,
  1827. 163,
  1828. 164,
  1829. 165,
  1830. 166,
  1831. 167,
  1832. 168,
  1833. 169,
  1834. 170,
  1835. 171,
  1836. 172,
  1837. 173,
  1838. 178,
  1839. 179,
  1840. 184,
  1841. 185,
  1842. 196,
  1843. 197,
  1844. 198,
  1845. 199,
  1846. 200,
  1847. 201,
  1848. 202,
  1849. 203,
  1850. 204,
  1851. 205,
  1852. 206,
  1853. 207,
  1854. 208,
  1855. 209,
  1856. 214,
  1857. 215,
  1858. 220,
  1859. 221
  1860. ];
  1861. }
  1862. } catch (error) {
  1863. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  1864. }
  1865. /**
  1866. * Build up the default `inspectOpts` object from the environment variables.
  1867. *
  1868. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  1869. */
  1870. exports.inspectOpts = Object.keys(process.env).filter(key => {
  1871. return /^debug_/i.test(key);
  1872. }).reduce((obj, key) => {
  1873. // Camel-case
  1874. const prop = key
  1875. .substring(6)
  1876. .toLowerCase()
  1877. .replace(/_([a-z])/g, (_, k) => {
  1878. return k.toUpperCase();
  1879. });
  1880. // Coerce string value into JS value
  1881. let val = process.env[key];
  1882. if (/^(yes|on|true|enabled)$/i.test(val)) {
  1883. val = true;
  1884. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  1885. val = false;
  1886. } else if (val === 'null') {
  1887. val = null;
  1888. } else {
  1889. val = Number(val);
  1890. }
  1891. obj[prop] = val;
  1892. return obj;
  1893. }, {});
  1894. /**
  1895. * Is stdout a TTY? Colored output is enabled when `true`.
  1896. */
  1897. function useColors() {
  1898. return 'colors' in exports.inspectOpts ?
  1899. Boolean(exports.inspectOpts.colors) :
  1900. tty.isatty(process.stderr.fd);
  1901. }
  1902. /**
  1903. * Adds ANSI color escape codes if enabled.
  1904. *
  1905. * @api public
  1906. */
  1907. function formatArgs(args) {
  1908. const {namespace: name, useColors} = this;
  1909. if (useColors) {
  1910. const c = this.color;
  1911. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  1912. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  1913. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  1914. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  1915. } else {
  1916. args[0] = getDate() + name + ' ' + args[0];
  1917. }
  1918. }
  1919. function getDate() {
  1920. if (exports.inspectOpts.hideDate) {
  1921. return '';
  1922. }
  1923. return new Date().toISOString() + ' ';
  1924. }
  1925. /**
  1926. * Invokes `util.format()` with the specified arguments and writes to stderr.
  1927. */
  1928. function log(...args) {
  1929. return process.stderr.write(util.format(...args) + '\n');
  1930. }
  1931. /**
  1932. * Save `namespaces`.
  1933. *
  1934. * @param {String} namespaces
  1935. * @api private
  1936. */
  1937. function save(namespaces) {
  1938. if (namespaces) {
  1939. process.env.DEBUG = namespaces;
  1940. } else {
  1941. // If you set a process.env field to null or undefined, it gets cast to the
  1942. // string 'null' or 'undefined'. Just delete instead.
  1943. delete process.env.DEBUG;
  1944. }
  1945. }
  1946. /**
  1947. * Load `namespaces`.
  1948. *
  1949. * @return {String} returns the previously persisted debug modes
  1950. * @api private
  1951. */
  1952. function load() {
  1953. return process.env.DEBUG;
  1954. }
  1955. /**
  1956. * Init logic for `debug` instances.
  1957. *
  1958. * Create a new `inspectOpts` object in case `useColors` is set
  1959. * differently for a particular `debug` instance.
  1960. */
  1961. function init(debug) {
  1962. debug.inspectOpts = {};
  1963. const keys = Object.keys(exports.inspectOpts);
  1964. for (let i = 0; i < keys.length; i++) {
  1965. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  1966. }
  1967. }
  1968. module.exports = requireCommon()(exports);
  1969. const {formatters} = module.exports;
  1970. /**
  1971. * Map %o to `util.inspect()`, all on a single line.
  1972. */
  1973. formatters.o = function (v) {
  1974. this.inspectOpts.colors = this.useColors;
  1975. return util.inspect(v, this.inspectOpts)
  1976. .split('\n')
  1977. .map(str => str.trim())
  1978. .join(' ');
  1979. };
  1980. /**
  1981. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  1982. */
  1983. formatters.O = function (v) {
  1984. this.inspectOpts.colors = this.useColors;
  1985. return util.inspect(v, this.inspectOpts);
  1986. };
  1987. } (node, node.exports));
  1988. return node.exports;
  1989. }
  1990. /**
  1991. * Detect Electron renderer / nwjs process, which is node, but we should
  1992. * treat as a browser.
  1993. */
  1994. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  1995. src.exports = requireBrowser();
  1996. } else {
  1997. src.exports = requireNode();
  1998. }
  1999. var srcExports = src.exports;
  2000. const _debug = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
  2001. const debug = _debug("vite:hmr");
  2002. const directRequestRE = /(?:\?|&)direct\b/;
  2003. async function handleHotUpdate({ file, modules, read }, options) {
  2004. const prevDescriptor = getDescriptor(file, options, false, true);
  2005. if (!prevDescriptor) {
  2006. return;
  2007. }
  2008. const content = await read();
  2009. const { descriptor } = createDescriptor(file, content, options, true);
  2010. let needRerender = false;
  2011. const affectedModules = /* @__PURE__ */ new Set();
  2012. const mainModule = getMainModule(modules);
  2013. const templateModule = modules.find((m) => /type=template/.test(m.url));
  2014. const scriptChanged = hasScriptChanged(prevDescriptor, descriptor);
  2015. if (scriptChanged) {
  2016. affectedModules.add(getScriptModule(modules) || mainModule);
  2017. }
  2018. if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
  2019. if (!scriptChanged) {
  2020. setResolvedScript(
  2021. descriptor,
  2022. getResolvedScript(prevDescriptor, false),
  2023. false
  2024. );
  2025. }
  2026. affectedModules.add(templateModule);
  2027. needRerender = true;
  2028. }
  2029. let didUpdateStyle = false;
  2030. const prevStyles = prevDescriptor.styles || [];
  2031. const nextStyles = descriptor.styles || [];
  2032. if (prevDescriptor.cssVars.join("") !== descriptor.cssVars.join("")) {
  2033. affectedModules.add(mainModule);
  2034. }
  2035. if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
  2036. affectedModules.add(templateModule);
  2037. affectedModules.add(mainModule);
  2038. }
  2039. for (let i = 0; i < nextStyles.length; i++) {
  2040. const prev = prevStyles[i];
  2041. const next = nextStyles[i];
  2042. if (!prev || !isEqualBlock(prev, next)) {
  2043. didUpdateStyle = true;
  2044. const mod = modules.find(
  2045. (m) => m.url.includes(`type=style&index=${i}`) && m.url.endsWith(`.${next.lang || "css"}`) && !directRequestRE.test(m.url)
  2046. );
  2047. if (mod) {
  2048. affectedModules.add(mod);
  2049. if (mod.url.includes("&inline")) {
  2050. affectedModules.add(mainModule);
  2051. }
  2052. } else {
  2053. affectedModules.add(mainModule);
  2054. }
  2055. }
  2056. }
  2057. if (prevStyles.length > nextStyles.length) {
  2058. affectedModules.add(mainModule);
  2059. }
  2060. const prevCustoms = prevDescriptor.customBlocks || [];
  2061. const nextCustoms = descriptor.customBlocks || [];
  2062. if (prevCustoms.length !== nextCustoms.length) {
  2063. affectedModules.add(mainModule);
  2064. } else {
  2065. for (let i = 0; i < nextCustoms.length; i++) {
  2066. const prev = prevCustoms[i];
  2067. const next = nextCustoms[i];
  2068. if (!prev || !isEqualBlock(prev, next)) {
  2069. const mod = modules.find(
  2070. (m) => m.url.includes(`type=${prev.type}&index=${i}`)
  2071. );
  2072. if (mod) {
  2073. affectedModules.add(mod);
  2074. } else {
  2075. affectedModules.add(mainModule);
  2076. }
  2077. }
  2078. }
  2079. }
  2080. const updateType = [];
  2081. if (needRerender) {
  2082. updateType.push(`template`);
  2083. if (!templateModule) {
  2084. affectedModules.add(mainModule);
  2085. } else if (mainModule && !affectedModules.has(mainModule)) {
  2086. const styleImporters = [...mainModule.importers].filter(
  2087. (m) => isCSSRequest(m.url)
  2088. );
  2089. styleImporters.forEach((m) => affectedModules.add(m));
  2090. }
  2091. }
  2092. if (didUpdateStyle) {
  2093. updateType.push(`style`);
  2094. }
  2095. if (updateType.length) {
  2096. if (file.endsWith(".vue")) {
  2097. invalidateDescriptor(file);
  2098. } else {
  2099. cache.set(file, descriptor);
  2100. }
  2101. debug(`[vue:update(${updateType.join("&")})] ${file}`);
  2102. }
  2103. return [...affectedModules].filter(Boolean);
  2104. }
  2105. function isEqualBlock(a, b) {
  2106. if (!a && !b)
  2107. return true;
  2108. if (!a || !b)
  2109. return false;
  2110. if (a.src && b.src && a.src === b.src)
  2111. return true;
  2112. if (a.content !== b.content)
  2113. return false;
  2114. const keysA = Object.keys(a.attrs);
  2115. const keysB = Object.keys(b.attrs);
  2116. if (keysA.length !== keysB.length) {
  2117. return false;
  2118. }
  2119. return keysA.every((key) => a.attrs[key] === b.attrs[key]);
  2120. }
  2121. function isOnlyTemplateChanged(prev, next) {
  2122. 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]));
  2123. }
  2124. function hasScriptChanged(prev, next) {
  2125. if (!isEqualBlock(prev.script, next.script)) {
  2126. return true;
  2127. }
  2128. if (!isEqualBlock(prev.scriptSetup, next.scriptSetup)) {
  2129. return true;
  2130. }
  2131. const prevResolvedScript = getResolvedScript(prev, false);
  2132. const prevImports = prevResolvedScript?.imports;
  2133. if (prevImports) {
  2134. return !next.template || next.shouldForceReload(prevImports);
  2135. }
  2136. return false;
  2137. }
  2138. function getMainModule(modules) {
  2139. return modules.filter((m) => !/type=/.test(m.url) || /type=script/.test(m.url)).sort((m1, m2) => {
  2140. return m1.url.length - m2.url.length;
  2141. })[0];
  2142. }
  2143. function getScriptModule(modules) {
  2144. return modules.find((m) => /type=script.*&lang\.\w+$/.test(m.url));
  2145. }
  2146. function handleTypeDepChange(affectedComponents, { modules, server: { moduleGraph } }) {
  2147. const affected = /* @__PURE__ */ new Set();
  2148. for (const file of affectedComponents) {
  2149. invalidateScript(file);
  2150. const mods = moduleGraph.getModulesByFile(file);
  2151. if (mods) {
  2152. const arr = [...mods];
  2153. affected.add(getScriptModule(arr) || getMainModule(arr));
  2154. }
  2155. }
  2156. return [...modules, ...affected];
  2157. }
  2158. const EXPORT_HELPER_ID = "\0plugin-vue:export-helper";
  2159. const helperCode = `
  2160. export default (sfc, props) => {
  2161. const target = sfc.__vccOpts || sfc;
  2162. for (const [key, val] of props) {
  2163. target[key] = val;
  2164. }
  2165. return target;
  2166. }
  2167. `;
  2168. async function transformMain(code, filename, options, pluginContext, ssr, customElement) {
  2169. const { devServer, isProduction, devToolsEnabled } = options;
  2170. const prevDescriptor = getPrevDescriptor(filename);
  2171. const { descriptor, errors } = createDescriptor(filename, code, options);
  2172. if (fs.existsSync(filename)) {
  2173. getDescriptor(
  2174. filename,
  2175. options,
  2176. true,
  2177. true,
  2178. // for vue files, create descriptor from fs read to be consistent with
  2179. // logic in handleHotUpdate()
  2180. // for non vue files, e.g. md files in vitepress, we assume
  2181. // `hmrContext.read` is overwriten so handleHotUpdate() is dealing with
  2182. // post-transform code, so we populate the descriptor with post-transform
  2183. // code here as well.
  2184. filename.endsWith(".vue") ? void 0 : code
  2185. );
  2186. }
  2187. if (errors.length) {
  2188. errors.forEach(
  2189. (error) => pluginContext.error(createRollupError(filename, error))
  2190. );
  2191. return null;
  2192. }
  2193. const attachedProps = [];
  2194. const hasScoped = descriptor.styles.some((s) => s.scoped);
  2195. const { code: scriptCode, map: scriptMap } = await genScriptCode(
  2196. descriptor,
  2197. options,
  2198. pluginContext,
  2199. ssr,
  2200. customElement
  2201. );
  2202. const hasTemplateImport = descriptor.template && !isUseInlineTemplate(descriptor, !devServer);
  2203. let templateCode = "";
  2204. let templateMap = void 0;
  2205. if (hasTemplateImport) {
  2206. ({ code: templateCode, map: templateMap } = await genTemplateCode(
  2207. descriptor,
  2208. options,
  2209. pluginContext,
  2210. ssr,
  2211. customElement
  2212. ));
  2213. }
  2214. if (hasTemplateImport) {
  2215. attachedProps.push(
  2216. ssr ? ["ssrRender", "_sfc_ssrRender"] : ["render", "_sfc_render"]
  2217. );
  2218. } else {
  2219. if (prevDescriptor && !isEqualBlock(descriptor.template, prevDescriptor.template)) {
  2220. attachedProps.push([ssr ? "ssrRender" : "render", "() => {}"]);
  2221. }
  2222. }
  2223. const stylesCode = await genStyleCode(
  2224. descriptor,
  2225. pluginContext,
  2226. customElement,
  2227. attachedProps
  2228. );
  2229. const customBlocksCode = await genCustomBlockCode(descriptor, pluginContext);
  2230. const output = [
  2231. scriptCode,
  2232. templateCode,
  2233. stylesCode,
  2234. customBlocksCode
  2235. ];
  2236. if (hasScoped) {
  2237. attachedProps.push([`__scopeId`, JSON.stringify(`data-v-${descriptor.id}`)]);
  2238. }
  2239. if (devToolsEnabled || devServer && !isProduction) {
  2240. attachedProps.push([
  2241. `__file`,
  2242. JSON.stringify(isProduction ? path.basename(filename) : filename)
  2243. ]);
  2244. }
  2245. if (devServer && devServer.config.server.hmr !== false && !ssr && !isProduction) {
  2246. output.push(`_sfc_main.__hmrId = ${JSON.stringify(descriptor.id)}`);
  2247. output.push(
  2248. `typeof __VUE_HMR_RUNTIME__ !== 'undefined' && __VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)`
  2249. );
  2250. if (prevDescriptor && isOnlyTemplateChanged(prevDescriptor, descriptor)) {
  2251. output.push(`export const _rerender_only = true`);
  2252. }
  2253. output.push(
  2254. `import.meta.hot.accept(mod => {`,
  2255. ` if (!mod) return`,
  2256. ` const { default: updated, _rerender_only } = mod`,
  2257. ` if (_rerender_only) {`,
  2258. ` __VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)`,
  2259. ` } else {`,
  2260. ` __VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)`,
  2261. ` }`,
  2262. `})`
  2263. );
  2264. }
  2265. if (ssr) {
  2266. const normalizedFilename = normalizePath$1(
  2267. path.relative(options.root, filename)
  2268. );
  2269. output.push(
  2270. `import { useSSRContext as __vite_useSSRContext } from 'vue'`,
  2271. `const _sfc_setup = _sfc_main.setup`,
  2272. `_sfc_main.setup = (props, ctx) => {`,
  2273. ` const ssrContext = __vite_useSSRContext()`,
  2274. ` ;(ssrContext.modules || (ssrContext.modules = new Set())).add(${JSON.stringify(
  2275. normalizedFilename
  2276. )})`,
  2277. ` return _sfc_setup ? _sfc_setup(props, ctx) : undefined`,
  2278. `}`
  2279. );
  2280. }
  2281. let resolvedMap = void 0;
  2282. if (options.sourceMap) {
  2283. if (scriptMap && templateMap) {
  2284. const gen = fromMap(
  2285. // version property of result.map is declared as string
  2286. // but actually it is `3`
  2287. scriptMap
  2288. );
  2289. const tracer = new TraceMap(
  2290. // same above
  2291. templateMap
  2292. );
  2293. const offset = (scriptCode.match(/\r?\n/g)?.length ?? 0) + 1;
  2294. eachMapping(tracer, (m) => {
  2295. if (m.source == null)
  2296. return;
  2297. addMapping(gen, {
  2298. source: m.source,
  2299. original: { line: m.originalLine, column: m.originalColumn },
  2300. generated: {
  2301. line: m.generatedLine + offset,
  2302. column: m.generatedColumn
  2303. }
  2304. });
  2305. });
  2306. resolvedMap = toEncodedMap(gen);
  2307. resolvedMap.sourcesContent = templateMap.sourcesContent;
  2308. } else {
  2309. resolvedMap = scriptMap ?? templateMap;
  2310. }
  2311. }
  2312. if (!attachedProps.length) {
  2313. output.push(`export default _sfc_main`);
  2314. } else {
  2315. output.push(
  2316. `import _export_sfc from '${EXPORT_HELPER_ID}'`,
  2317. `export default /*#__PURE__*/_export_sfc(_sfc_main, [${attachedProps.map(([key, val]) => `['${key}',${val}]`).join(",")}])`
  2318. );
  2319. }
  2320. let resolvedCode = output.join("\n");
  2321. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  2322. if (lang && /tsx?$/.test(lang) && !descriptor.script?.src) {
  2323. const { code: code2, map } = await transformWithEsbuild(
  2324. resolvedCode,
  2325. filename,
  2326. {
  2327. loader: "ts",
  2328. target: "esnext",
  2329. sourcemap: options.sourceMap
  2330. },
  2331. resolvedMap
  2332. );
  2333. resolvedCode = code2;
  2334. resolvedMap = resolvedMap ? map : resolvedMap;
  2335. }
  2336. return {
  2337. code: resolvedCode,
  2338. map: resolvedMap || {
  2339. mappings: ""
  2340. },
  2341. meta: {
  2342. vite: {
  2343. lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js"
  2344. }
  2345. }
  2346. };
  2347. }
  2348. async function genTemplateCode(descriptor, options, pluginContext, ssr, customElement) {
  2349. const template = descriptor.template;
  2350. const hasScoped = descriptor.styles.some((style) => style.scoped);
  2351. if ((!template.lang || template.lang === "html") && !template.src) {
  2352. return transformTemplateInMain(
  2353. template.content,
  2354. descriptor,
  2355. options,
  2356. pluginContext,
  2357. ssr,
  2358. customElement
  2359. );
  2360. } else {
  2361. if (template.src) {
  2362. await linkSrcToDescriptor(
  2363. template.src,
  2364. descriptor,
  2365. pluginContext,
  2366. hasScoped
  2367. );
  2368. }
  2369. const src = template.src || descriptor.filename;
  2370. const srcQuery = template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : "";
  2371. const scopedQuery = hasScoped ? `&scoped=${descriptor.id}` : ``;
  2372. const attrsQuery = attrsToQuery(template.attrs, "js", true);
  2373. const query = `?vue&type=template${srcQuery}${scopedQuery}${attrsQuery}`;
  2374. const request = JSON.stringify(src + query);
  2375. const renderFnName = ssr ? "ssrRender" : "render";
  2376. return {
  2377. code: `import { ${renderFnName} as _sfc_${renderFnName} } from ${request}`,
  2378. map: void 0
  2379. };
  2380. }
  2381. }
  2382. async function genScriptCode(descriptor, options, pluginContext, ssr, customElement) {
  2383. let scriptCode = `const ${scriptIdentifier} = {}`;
  2384. let map;
  2385. const script = resolveScript(descriptor, options, ssr, customElement);
  2386. if (script) {
  2387. if (canInlineMain(descriptor, options)) {
  2388. if (!options.compiler.version) {
  2389. const userPlugins = options.script?.babelParserPlugins || [];
  2390. const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
  2391. scriptCode = options.compiler.rewriteDefault(
  2392. script.content,
  2393. scriptIdentifier,
  2394. [...defaultPlugins, ...userPlugins]
  2395. );
  2396. } else {
  2397. scriptCode = script.content;
  2398. }
  2399. map = script.map;
  2400. } else {
  2401. if (script.src) {
  2402. await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
  2403. }
  2404. const src = script.src || descriptor.filename;
  2405. const langFallback = script.src && path.extname(src).slice(1) || "js";
  2406. const attrsQuery = attrsToQuery(script.attrs, langFallback);
  2407. const srcQuery = script.src ? `&src=true` : ``;
  2408. const query = `?vue&type=script${srcQuery}${attrsQuery}`;
  2409. const request = JSON.stringify(src + query);
  2410. scriptCode = `import _sfc_main from ${request}
  2411. export * from ${request}`;
  2412. }
  2413. }
  2414. return {
  2415. code: scriptCode,
  2416. map
  2417. };
  2418. }
  2419. async function genStyleCode(descriptor, pluginContext, customElement, attachedProps) {
  2420. let stylesCode = ``;
  2421. let cssModulesMap;
  2422. if (descriptor.styles.length) {
  2423. for (let i = 0; i < descriptor.styles.length; i++) {
  2424. const style = descriptor.styles[i];
  2425. if (style.src) {
  2426. await linkSrcToDescriptor(
  2427. style.src,
  2428. descriptor,
  2429. pluginContext,
  2430. style.scoped
  2431. );
  2432. }
  2433. const src = style.src || descriptor.filename;
  2434. const attrsQuery = attrsToQuery(style.attrs, "css");
  2435. const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
  2436. const directQuery = customElement ? `&inline` : ``;
  2437. const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
  2438. const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}`;
  2439. const styleRequest = src + query + attrsQuery;
  2440. if (style.module) {
  2441. if (customElement) {
  2442. throw new Error(
  2443. `<style module> is not supported in custom elements mode.`
  2444. );
  2445. }
  2446. const [importCode, nameMap] = genCSSModulesCode(
  2447. i,
  2448. styleRequest,
  2449. style.module
  2450. );
  2451. stylesCode += importCode;
  2452. Object.assign(cssModulesMap || (cssModulesMap = {}), nameMap);
  2453. } else {
  2454. if (customElement) {
  2455. stylesCode += `
  2456. import _style_${i} from ${JSON.stringify(
  2457. styleRequest
  2458. )}`;
  2459. } else {
  2460. stylesCode += `
  2461. import ${JSON.stringify(styleRequest)}`;
  2462. }
  2463. }
  2464. }
  2465. if (customElement) {
  2466. attachedProps.push([
  2467. `styles`,
  2468. `[${descriptor.styles.map((_, i) => `_style_${i}`).join(",")}]`
  2469. ]);
  2470. }
  2471. }
  2472. if (cssModulesMap) {
  2473. const mappingCode = Object.entries(cssModulesMap).reduce(
  2474. (code, [key, value]) => code + `"${key}":${value},
  2475. `,
  2476. "{\n"
  2477. ) + "}";
  2478. stylesCode += `
  2479. const cssModules = ${mappingCode}`;
  2480. attachedProps.push([`__cssModules`, `cssModules`]);
  2481. }
  2482. return stylesCode;
  2483. }
  2484. function genCSSModulesCode(index, request, moduleName) {
  2485. const styleVar = `style${index}`;
  2486. const exposedName = typeof moduleName === "string" ? moduleName : "$style";
  2487. const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
  2488. return [
  2489. `
  2490. import ${styleVar} from ${JSON.stringify(moduleRequest)}`,
  2491. { [exposedName]: styleVar }
  2492. ];
  2493. }
  2494. async function genCustomBlockCode(descriptor, pluginContext) {
  2495. let code = "";
  2496. for (let index = 0; index < descriptor.customBlocks.length; index++) {
  2497. const block = descriptor.customBlocks[index];
  2498. if (block.src) {
  2499. await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
  2500. }
  2501. const src = block.src || descriptor.filename;
  2502. const attrsQuery = attrsToQuery(block.attrs, block.type);
  2503. const srcQuery = block.src ? `&src=true` : ``;
  2504. const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
  2505. const request = JSON.stringify(src + query);
  2506. code += `import block${index} from ${request}
  2507. `;
  2508. code += `if (typeof block${index} === 'function') block${index}(_sfc_main)
  2509. `;
  2510. }
  2511. return code;
  2512. }
  2513. async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
  2514. const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src;
  2515. setSrcDescriptor(srcFile.replace(/\?.*$/, ""), descriptor, scoped);
  2516. }
  2517. const ignoreList = [
  2518. "id",
  2519. "index",
  2520. "src",
  2521. "type",
  2522. "lang",
  2523. "module",
  2524. "scoped",
  2525. "generic"
  2526. ];
  2527. function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
  2528. let query = ``;
  2529. for (const name in attrs) {
  2530. const value = attrs[name];
  2531. if (!ignoreList.includes(name)) {
  2532. query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
  2533. }
  2534. }
  2535. if (langFallback || attrs.lang) {
  2536. query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
  2537. }
  2538. return query;
  2539. }
  2540. async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
  2541. const block = descriptor.styles[index];
  2542. const result = await options.compiler.compileStyleAsync({
  2543. ...options.style,
  2544. filename: descriptor.filename,
  2545. id: `data-v-${descriptor.id}`,
  2546. isProd: options.isProduction,
  2547. source: code,
  2548. scoped: block.scoped,
  2549. ...options.cssDevSourcemap ? {
  2550. postcssOptions: {
  2551. map: {
  2552. from: filename,
  2553. inline: false,
  2554. annotation: false
  2555. }
  2556. }
  2557. } : {}
  2558. });
  2559. if (result.errors.length) {
  2560. result.errors.forEach((error) => {
  2561. if (error.line && error.column) {
  2562. error.loc = {
  2563. file: descriptor.filename,
  2564. line: error.line + block.loc.start.line,
  2565. column: error.column
  2566. };
  2567. }
  2568. pluginContext.error(error);
  2569. });
  2570. return null;
  2571. }
  2572. const map = result.map ? await formatPostcssSourceMap(
  2573. // version property of result.map is declared as string
  2574. // but actually it is a number
  2575. result.map,
  2576. filename
  2577. ) : { mappings: "" };
  2578. return {
  2579. code: result.code,
  2580. map
  2581. };
  2582. }
  2583. function vuePlugin(rawOptions = {}) {
  2584. const options = shallowRef({
  2585. isProduction: process.env.NODE_ENV === "production",
  2586. compiler: null,
  2587. // to be set in buildStart
  2588. include: /\.vue$/,
  2589. customElement: /\.ce\.vue$/,
  2590. reactivityTransform: false,
  2591. ...rawOptions,
  2592. root: process.cwd(),
  2593. sourceMap: true,
  2594. cssDevSourcemap: false,
  2595. devToolsEnabled: process.env.NODE_ENV !== "production"
  2596. });
  2597. const filter = computed(
  2598. () => createFilter(options.value.include, options.value.exclude)
  2599. );
  2600. const customElementFilter = computed(
  2601. () => typeof options.value.customElement === "boolean" ? () => options.value.customElement : createFilter(options.value.customElement)
  2602. );
  2603. const refTransformFilter = computed(
  2604. () => options.value.reactivityTransform === false ? () => false : options.value.reactivityTransform === true ? createFilter(/\.(j|t)sx?$/, /node_modules/) : createFilter(options.value.reactivityTransform)
  2605. );
  2606. return {
  2607. name: "vite:vue",
  2608. api: {
  2609. get options() {
  2610. return options.value;
  2611. },
  2612. set options(value) {
  2613. options.value = value;
  2614. },
  2615. version
  2616. },
  2617. handleHotUpdate(ctx) {
  2618. if (options.value.compiler.invalidateTypeCache) {
  2619. options.value.compiler.invalidateTypeCache(ctx.file);
  2620. }
  2621. if (typeDepToSFCMap.has(ctx.file)) {
  2622. return handleTypeDepChange(typeDepToSFCMap.get(ctx.file), ctx);
  2623. }
  2624. if (filter.value(ctx.file)) {
  2625. return handleHotUpdate(ctx, options.value);
  2626. }
  2627. },
  2628. config(config) {
  2629. return {
  2630. resolve: {
  2631. dedupe: config.build?.ssr ? [] : ["vue"]
  2632. },
  2633. define: {
  2634. __VUE_OPTIONS_API__: config.define?.__VUE_OPTIONS_API__ ?? true,
  2635. __VUE_PROD_DEVTOOLS__: config.define?.__VUE_PROD_DEVTOOLS__ ?? false,
  2636. __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: config.define?.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ ?? false
  2637. },
  2638. ssr: {
  2639. // @ts-ignore -- config.legacy.buildSsrCjsExternalHeuristics will be removed in Vite 5
  2640. external: config.legacy?.buildSsrCjsExternalHeuristics ? ["vue", "@vue/server-renderer"] : []
  2641. }
  2642. };
  2643. },
  2644. configResolved(config) {
  2645. options.value = {
  2646. ...options.value,
  2647. root: config.root,
  2648. sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
  2649. cssDevSourcemap: config.css?.devSourcemap ?? false,
  2650. isProduction: config.isProduction,
  2651. devToolsEnabled: !!config.define.__VUE_PROD_DEVTOOLS__ || !config.isProduction
  2652. };
  2653. },
  2654. configureServer(server) {
  2655. options.value.devServer = server;
  2656. },
  2657. buildStart() {
  2658. const compiler = options.value.compiler = options.value.compiler || resolveCompiler(options.value.root);
  2659. if (compiler.invalidateTypeCache) {
  2660. options.value.devServer?.watcher.on("unlink", (file) => {
  2661. compiler.invalidateTypeCache(file);
  2662. });
  2663. }
  2664. },
  2665. async resolveId(id) {
  2666. if (id === EXPORT_HELPER_ID) {
  2667. return id;
  2668. }
  2669. if (parseVueRequest(id).query.vue) {
  2670. return id;
  2671. }
  2672. },
  2673. load(id, opt) {
  2674. const ssr = opt?.ssr === true;
  2675. if (id === EXPORT_HELPER_ID) {
  2676. return helperCode;
  2677. }
  2678. const { filename, query } = parseVueRequest(id);
  2679. if (query.vue) {
  2680. if (query.src) {
  2681. return fs.readFileSync(filename, "utf-8");
  2682. }
  2683. const descriptor = getDescriptor(filename, options.value);
  2684. let block;
  2685. if (query.type === "script") {
  2686. block = getResolvedScript(descriptor, ssr);
  2687. } else if (query.type === "template") {
  2688. block = descriptor.template;
  2689. } else if (query.type === "style") {
  2690. block = descriptor.styles[query.index];
  2691. } else if (query.index != null) {
  2692. block = descriptor.customBlocks[query.index];
  2693. }
  2694. if (block) {
  2695. return {
  2696. code: block.content,
  2697. map: block.map
  2698. };
  2699. }
  2700. }
  2701. },
  2702. transform(code, id, opt) {
  2703. const ssr = opt?.ssr === true;
  2704. const { filename, query } = parseVueRequest(id);
  2705. if (query.raw || query.url) {
  2706. return;
  2707. }
  2708. if (!filter.value(filename) && !query.vue) {
  2709. if (!query.vue && refTransformFilter.value(filename) && options.value.compiler.shouldTransformRef(code)) {
  2710. const result = options.value.compiler.transformRef(code, {
  2711. filename,
  2712. sourceMap: true
  2713. });
  2714. return result;
  2715. }
  2716. return;
  2717. }
  2718. if (!query.vue) {
  2719. return transformMain(
  2720. code,
  2721. filename,
  2722. options.value,
  2723. this,
  2724. ssr,
  2725. customElementFilter.value(filename)
  2726. );
  2727. } else {
  2728. const descriptor = query.src ? getSrcDescriptor(filename, query) || getTempSrcDescriptor(filename, query) : getDescriptor(filename, options.value);
  2729. if (query.type === "template") {
  2730. return transformTemplateAsModule(
  2731. code,
  2732. descriptor,
  2733. options.value,
  2734. this,
  2735. ssr,
  2736. customElementFilter.value(filename)
  2737. );
  2738. } else if (query.type === "style") {
  2739. return transformStyle(
  2740. code,
  2741. descriptor,
  2742. Number(query.index || 0),
  2743. options.value,
  2744. this,
  2745. filename
  2746. );
  2747. }
  2748. }
  2749. }
  2750. };
  2751. }
  2752. export { vuePlugin as default, parseVueRequest };