index.mjs 86 KB

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