index.mjs 84 KB

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