index.mjs 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061
  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.3";
  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 (scriptMap && templateMap) {
  2390. const gen = fromMap(
  2391. // version property of result.map is declared as string
  2392. // but actually it is `3`
  2393. scriptMap
  2394. );
  2395. const tracer = new TraceMap(
  2396. // same above
  2397. templateMap
  2398. );
  2399. const offset = (scriptCode.match(/\r?\n/g)?.length ?? 0) + 1;
  2400. eachMapping(tracer, (m) => {
  2401. if (m.source == null) return;
  2402. addMapping(gen, {
  2403. source: m.source,
  2404. original: { line: m.originalLine, column: m.originalColumn },
  2405. generated: {
  2406. line: m.generatedLine + offset,
  2407. column: m.generatedColumn
  2408. }
  2409. });
  2410. });
  2411. resolvedMap = toEncodedMap(gen);
  2412. resolvedMap.sourcesContent = templateMap.sourcesContent;
  2413. } else {
  2414. resolvedMap = scriptMap ?? templateMap;
  2415. }
  2416. }
  2417. if (!attachedProps.length) {
  2418. output.push(`export default _sfc_main`);
  2419. } else {
  2420. output.push(
  2421. `import _export_sfc from '${EXPORT_HELPER_ID}'`,
  2422. `export default /*#__PURE__*/_export_sfc(_sfc_main, [${attachedProps.map(([key, val]) => `['${key}',${val}]`).join(",")}])`
  2423. );
  2424. }
  2425. let resolvedCode = output.join("\n");
  2426. const lang = descriptor.scriptSetup?.lang || descriptor.script?.lang;
  2427. if (lang && /tsx?$/.test(lang) && !descriptor.script?.src) {
  2428. const { code: code2, map } = await transformWithEsbuild(
  2429. resolvedCode,
  2430. filename,
  2431. {
  2432. target: "esnext",
  2433. // #430 support decorators in .vue file
  2434. // target can be overridden by esbuild config target
  2435. ...options.devServer?.config.esbuild,
  2436. loader: "ts",
  2437. sourcemap: options.sourceMap
  2438. },
  2439. resolvedMap
  2440. );
  2441. resolvedCode = code2;
  2442. resolvedMap = resolvedMap ? map : resolvedMap;
  2443. }
  2444. return {
  2445. code: resolvedCode,
  2446. map: resolvedMap || {
  2447. mappings: ""
  2448. },
  2449. meta: {
  2450. vite: {
  2451. lang: descriptor.script?.lang || descriptor.scriptSetup?.lang || "js"
  2452. }
  2453. }
  2454. };
  2455. }
  2456. async function genTemplateCode(descriptor, options, pluginContext, ssr, customElement) {
  2457. const template = descriptor.template;
  2458. const hasScoped = descriptor.styles.some((style) => style.scoped);
  2459. if ((!template.lang || template.lang === "html") && !template.src) {
  2460. return transformTemplateInMain(
  2461. template.content,
  2462. descriptor,
  2463. options,
  2464. pluginContext,
  2465. ssr,
  2466. customElement
  2467. );
  2468. } else {
  2469. if (template.src) {
  2470. await linkSrcToDescriptor(
  2471. template.src,
  2472. descriptor,
  2473. pluginContext,
  2474. hasScoped
  2475. );
  2476. }
  2477. const src = template.src || descriptor.filename;
  2478. const srcQuery = template.src ? hasScoped ? `&src=${descriptor.id}` : "&src=true" : "";
  2479. const scopedQuery = hasScoped ? `&scoped=${descriptor.id}` : ``;
  2480. const attrsQuery = attrsToQuery(template.attrs, "js", true);
  2481. const query = `?vue&type=template${srcQuery}${scopedQuery}${attrsQuery}`;
  2482. const request = JSON.stringify(src + query);
  2483. const renderFnName = ssr ? "ssrRender" : "render";
  2484. return {
  2485. code: `import { ${renderFnName} as _sfc_${renderFnName} } from ${request}`,
  2486. map: void 0
  2487. };
  2488. }
  2489. }
  2490. async function genScriptCode(descriptor, options, pluginContext, ssr, customElement) {
  2491. const vaporFlag = descriptor.vapor ? "__vapor: true" : "";
  2492. let scriptCode = `const ${scriptIdentifier} = { ${vaporFlag} }`;
  2493. let map;
  2494. const script = resolveScript(descriptor, options, ssr, customElement);
  2495. if (script) {
  2496. if (canInlineMain(descriptor, options)) {
  2497. if (!options.compiler.version) {
  2498. const userPlugins = options.script?.babelParserPlugins || [];
  2499. const defaultPlugins = script.lang === "ts" ? userPlugins.includes("decorators") ? ["typescript"] : ["typescript", "decorators-legacy"] : [];
  2500. scriptCode = options.compiler.rewriteDefault(
  2501. script.content,
  2502. scriptIdentifier,
  2503. [...defaultPlugins, ...userPlugins]
  2504. );
  2505. } else {
  2506. scriptCode = script.content;
  2507. }
  2508. map = script.map;
  2509. } else {
  2510. if (script.src) {
  2511. await linkSrcToDescriptor(script.src, descriptor, pluginContext, false);
  2512. }
  2513. const src = script.src || descriptor.filename;
  2514. const langFallback = script.src && path.extname(src).slice(1) || "js";
  2515. const attrsQuery = attrsToQuery(script.attrs, langFallback);
  2516. const srcQuery = script.src ? `&src=true` : ``;
  2517. const query = `?vue&type=script${srcQuery}${attrsQuery}`;
  2518. const request = JSON.stringify(src + query);
  2519. scriptCode = `import _sfc_main from ${request}
  2520. export * from ${request}`;
  2521. }
  2522. }
  2523. return {
  2524. code: scriptCode,
  2525. map
  2526. };
  2527. }
  2528. async function genStyleCode(descriptor, pluginContext, customElement, attachedProps) {
  2529. let stylesCode = ``;
  2530. let cssModulesMap;
  2531. if (descriptor.styles.length) {
  2532. for (let i = 0; i < descriptor.styles.length; i++) {
  2533. const style = descriptor.styles[i];
  2534. if (style.src) {
  2535. await linkSrcToDescriptor(
  2536. style.src,
  2537. descriptor,
  2538. pluginContext,
  2539. style.scoped
  2540. );
  2541. }
  2542. const src = style.src || descriptor.filename;
  2543. const attrsQuery = attrsToQuery(style.attrs, "css");
  2544. const srcQuery = style.src ? style.scoped ? `&src=${descriptor.id}` : "&src=true" : "";
  2545. const directQuery = customElement ? `&inline` : ``;
  2546. const scopedQuery = style.scoped ? `&scoped=${descriptor.id}` : ``;
  2547. const query = `?vue&type=style&index=${i}${srcQuery}${directQuery}${scopedQuery}`;
  2548. const styleRequest = src + query + attrsQuery;
  2549. if (style.module) {
  2550. if (customElement) {
  2551. throw new Error(
  2552. `<style module> is not supported in custom elements mode.`
  2553. );
  2554. }
  2555. const [importCode, nameMap] = genCSSModulesCode(
  2556. i,
  2557. styleRequest,
  2558. style.module
  2559. );
  2560. stylesCode += importCode;
  2561. Object.assign(cssModulesMap ||= {}, nameMap);
  2562. } else {
  2563. if (customElement) {
  2564. stylesCode += `
  2565. import _style_${i} from ${JSON.stringify(
  2566. styleRequest
  2567. )}`;
  2568. } else {
  2569. stylesCode += `
  2570. import ${JSON.stringify(styleRequest)}`;
  2571. }
  2572. }
  2573. }
  2574. if (customElement) {
  2575. attachedProps.push([
  2576. `styles`,
  2577. `[${descriptor.styles.map((_, i) => `_style_${i}`).join(",")}]`
  2578. ]);
  2579. }
  2580. }
  2581. if (cssModulesMap) {
  2582. const mappingCode = Object.entries(cssModulesMap).reduce(
  2583. (code, [key, value]) => code + `"${key}":${value},
  2584. `,
  2585. "{\n"
  2586. ) + "}";
  2587. stylesCode += `
  2588. const cssModules = ${mappingCode}`;
  2589. attachedProps.push([`__cssModules`, `cssModules`]);
  2590. }
  2591. return stylesCode;
  2592. }
  2593. function genCSSModulesCode(index, request, moduleName) {
  2594. const styleVar = `style${index}`;
  2595. const exposedName = typeof moduleName === "string" ? moduleName : "$style";
  2596. const moduleRequest = request.replace(/\.(\w+)$/, ".module.$1");
  2597. return [
  2598. `
  2599. import ${styleVar} from ${JSON.stringify(moduleRequest)}`,
  2600. { [exposedName]: styleVar }
  2601. ];
  2602. }
  2603. async function genCustomBlockCode(descriptor, pluginContext) {
  2604. let code = "";
  2605. for (let index = 0; index < descriptor.customBlocks.length; index++) {
  2606. const block = descriptor.customBlocks[index];
  2607. if (block.src) {
  2608. await linkSrcToDescriptor(block.src, descriptor, pluginContext, false);
  2609. }
  2610. const src = block.src || descriptor.filename;
  2611. const attrsQuery = attrsToQuery(block.attrs, block.type);
  2612. const srcQuery = block.src ? `&src=true` : ``;
  2613. const query = `?vue&type=${block.type}&index=${index}${srcQuery}${attrsQuery}`;
  2614. const request = JSON.stringify(src + query);
  2615. code += `import block${index} from ${request}
  2616. `;
  2617. code += `if (typeof block${index} === 'function') block${index}(_sfc_main)
  2618. `;
  2619. }
  2620. return code;
  2621. }
  2622. async function linkSrcToDescriptor(src, descriptor, pluginContext, scoped) {
  2623. const srcFile = (await pluginContext.resolve(src, descriptor.filename))?.id || src;
  2624. setSrcDescriptor(srcFile.replace(/\?.*$/, ""), descriptor, scoped);
  2625. }
  2626. const ignoreList = [
  2627. "id",
  2628. "index",
  2629. "src",
  2630. "type",
  2631. "lang",
  2632. "module",
  2633. "scoped",
  2634. "generic"
  2635. ];
  2636. function attrsToQuery(attrs, langFallback, forceLangFallback = false) {
  2637. let query = ``;
  2638. for (const name in attrs) {
  2639. const value = attrs[name];
  2640. if (!ignoreList.includes(name)) {
  2641. query += `&${encodeURIComponent(name)}${value ? `=${encodeURIComponent(value)}` : ``}`;
  2642. }
  2643. }
  2644. if (langFallback || attrs.lang) {
  2645. query += `lang` in attrs ? forceLangFallback ? `&lang.${langFallback}` : `&lang.${attrs.lang}` : `&lang.${langFallback}`;
  2646. }
  2647. return query;
  2648. }
  2649. async function transformStyle(code, descriptor, index, options, pluginContext, filename) {
  2650. const block = descriptor.styles[index];
  2651. const result = await options.compiler.compileStyleAsync({
  2652. ...options.style,
  2653. filename: descriptor.filename,
  2654. id: `data-v-${descriptor.id}`,
  2655. isProd: options.isProduction,
  2656. source: code,
  2657. scoped: block.scoped,
  2658. ...options.cssDevSourcemap ? {
  2659. postcssOptions: {
  2660. map: {
  2661. from: filename,
  2662. inline: false,
  2663. annotation: false
  2664. }
  2665. }
  2666. } : {}
  2667. });
  2668. if (result.errors.length) {
  2669. result.errors.forEach((error) => {
  2670. if (error.line && error.column) {
  2671. error.loc = {
  2672. file: descriptor.filename,
  2673. line: error.line + block.loc.start.line,
  2674. column: error.column
  2675. };
  2676. }
  2677. pluginContext.error(error);
  2678. });
  2679. return null;
  2680. }
  2681. const map = result.map ? await formatPostcssSourceMap(
  2682. // version property of result.map is declared as string
  2683. // but actually it is a number
  2684. result.map,
  2685. filename
  2686. ) : { mappings: "" };
  2687. return {
  2688. code: result.code,
  2689. map,
  2690. meta: block.scoped && !descriptor.isTemp ? {
  2691. vite: {
  2692. cssScopeTo: [descriptor.filename, "default"]
  2693. }
  2694. } : void 0
  2695. };
  2696. }
  2697. function vuePlugin(rawOptions = {}) {
  2698. clearScriptCache();
  2699. const options = shallowRef({
  2700. isProduction: process.env.NODE_ENV === "production",
  2701. compiler: null,
  2702. // to be set in buildStart
  2703. include: /\.vue$/,
  2704. customElement: /\.ce\.vue$/,
  2705. ...rawOptions,
  2706. root: process.cwd(),
  2707. sourceMap: true,
  2708. cssDevSourcemap: false
  2709. });
  2710. const filter = computed(
  2711. () => createFilter(options.value.include, options.value.exclude)
  2712. );
  2713. const customElementFilter = computed(() => {
  2714. const customElement = options.value.features?.customElement || options.value.customElement;
  2715. return typeof customElement === "boolean" ? () => customElement : createFilter(customElement);
  2716. });
  2717. let transformCachedModule = false;
  2718. return {
  2719. name: "vite:vue",
  2720. api: {
  2721. get options() {
  2722. return options.value;
  2723. },
  2724. set options(value) {
  2725. options.value = value;
  2726. },
  2727. version
  2728. },
  2729. handleHotUpdate(ctx) {
  2730. ctx.server.ws.send({
  2731. type: "custom",
  2732. event: "file-changed",
  2733. data: { file: normalizePath$1(ctx.file) }
  2734. });
  2735. if (options.value.compiler.invalidateTypeCache) {
  2736. options.value.compiler.invalidateTypeCache(ctx.file);
  2737. }
  2738. let typeDepModules;
  2739. const matchesFilter = filter.value(ctx.file);
  2740. if (typeDepToSFCMap.has(ctx.file)) {
  2741. typeDepModules = handleTypeDepChange(
  2742. typeDepToSFCMap.get(ctx.file),
  2743. ctx
  2744. );
  2745. if (!matchesFilter) return typeDepModules;
  2746. }
  2747. if (matchesFilter) {
  2748. return handleHotUpdate(
  2749. ctx,
  2750. options.value,
  2751. customElementFilter.value(ctx.file),
  2752. typeDepModules
  2753. );
  2754. }
  2755. },
  2756. config(config) {
  2757. const parseDefine = (v) => {
  2758. try {
  2759. return typeof v === "string" ? JSON.parse(v) : v;
  2760. } catch (err) {
  2761. return v;
  2762. }
  2763. };
  2764. return {
  2765. resolve: {
  2766. dedupe: config.build?.ssr ? [] : ["vue"]
  2767. },
  2768. define: {
  2769. __VUE_OPTIONS_API__: options.value.features?.optionsAPI ?? parseDefine(config.define?.__VUE_OPTIONS_API__) ?? true,
  2770. __VUE_PROD_DEVTOOLS__: (options.value.features?.prodDevtools || parseDefine(config.define?.__VUE_PROD_DEVTOOLS__)) ?? false,
  2771. __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: (options.value.features?.prodHydrationMismatchDetails || parseDefine(
  2772. config.define?.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__
  2773. )) ?? false
  2774. },
  2775. ssr: {
  2776. // @ts-ignore -- config.legacy.buildSsrCjsExternalHeuristics will be removed in Vite 5
  2777. external: config.legacy?.buildSsrCjsExternalHeuristics ? ["vue", "@vue/server-renderer"] : []
  2778. }
  2779. };
  2780. },
  2781. configResolved(config) {
  2782. options.value = {
  2783. ...options.value,
  2784. root: config.root,
  2785. sourceMap: config.command === "build" ? !!config.build.sourcemap : true,
  2786. cssDevSourcemap: config.css?.devSourcemap ?? false,
  2787. isProduction: config.isProduction,
  2788. devToolsEnabled: !!(options.value.features?.prodDevtools || config.define.__VUE_PROD_DEVTOOLS__ || !config.isProduction)
  2789. };
  2790. const _warn = config.logger.warn;
  2791. config.logger.warn = (...args) => {
  2792. const msg = args[0];
  2793. if (msg.match(
  2794. /\[lightningcss\] '(deep|slotted|global)' is not recognized as a valid pseudo-/
  2795. )) {
  2796. return;
  2797. }
  2798. _warn(...args);
  2799. };
  2800. transformCachedModule = config.command === "build" && options.value.sourceMap && config.build.watch != null;
  2801. },
  2802. shouldTransformCachedModule({ id }) {
  2803. if (transformCachedModule && parseVueRequest(id).query.vue) {
  2804. return true;
  2805. }
  2806. return false;
  2807. },
  2808. configureServer(server) {
  2809. options.value.devServer = server;
  2810. },
  2811. buildStart() {
  2812. const compiler = options.value.compiler = options.value.compiler || resolveCompiler(options.value.root);
  2813. if (compiler.invalidateTypeCache) {
  2814. options.value.devServer?.watcher.on("unlink", (file) => {
  2815. compiler.invalidateTypeCache(file);
  2816. });
  2817. }
  2818. },
  2819. async resolveId(id) {
  2820. if (id === EXPORT_HELPER_ID) {
  2821. return id;
  2822. }
  2823. if (parseVueRequest(id).query.vue) {
  2824. return id;
  2825. }
  2826. },
  2827. load(id, opt) {
  2828. if (id === EXPORT_HELPER_ID) {
  2829. return helperCode;
  2830. }
  2831. const ssr = opt?.ssr === true;
  2832. const { filename, query } = parseVueRequest(id);
  2833. if (query.vue) {
  2834. if (query.src) {
  2835. return fs.readFileSync(filename, "utf-8");
  2836. }
  2837. const descriptor = getDescriptor(filename, options.value);
  2838. let block;
  2839. if (query.type === "script") {
  2840. block = resolveScript(
  2841. descriptor,
  2842. options.value,
  2843. ssr,
  2844. customElementFilter.value(filename)
  2845. );
  2846. } else if (query.type === "template") {
  2847. block = descriptor.template;
  2848. } else if (query.type === "style") {
  2849. block = descriptor.styles[query.index];
  2850. } else if (query.index != null) {
  2851. block = descriptor.customBlocks[query.index];
  2852. }
  2853. if (block) {
  2854. return {
  2855. code: block.content,
  2856. map: block.map
  2857. };
  2858. }
  2859. }
  2860. },
  2861. transform(code, id, opt) {
  2862. const ssr = opt?.ssr === true;
  2863. const { filename, query } = parseVueRequest(id);
  2864. if (query.raw || query.url) {
  2865. return;
  2866. }
  2867. if (!filter.value(filename) && !query.vue) {
  2868. return;
  2869. }
  2870. if (!query.vue) {
  2871. return transformMain(
  2872. code,
  2873. filename,
  2874. options.value,
  2875. this,
  2876. ssr,
  2877. customElementFilter.value(filename)
  2878. );
  2879. } else {
  2880. const descriptor = query.src ? getSrcDescriptor(filename, query) || getTempSrcDescriptor(filename, query) : getDescriptor(filename, options.value);
  2881. if (query.src) {
  2882. this.addWatchFile(filename);
  2883. }
  2884. if (query.type === "template") {
  2885. return transformTemplateAsModule(
  2886. code,
  2887. descriptor,
  2888. options.value,
  2889. this,
  2890. ssr,
  2891. customElementFilter.value(filename)
  2892. );
  2893. } else if (query.type === "style") {
  2894. return transformStyle(
  2895. code,
  2896. descriptor,
  2897. Number(query.index || 0),
  2898. options.value,
  2899. this,
  2900. filename
  2901. );
  2902. }
  2903. }
  2904. }
  2905. };
  2906. }
  2907. export { vuePlugin as default, parseVueRequest };