index.cjs 80 KB

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