index.cjs 85 KB

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