@dcloudio/uni-cli-shared 3.0.0-4080720251210001 → 3.0.0-5000320260312001

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