@vitejs/devtools-vite 0.0.0-alpha.9 → 0.4.3

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 (91) hide show
  1. package/dist/{dirs-K_XnRVOr.js → dirs.mjs} +1 -3
  2. package/dist/index.d.mts +101 -0
  3. package/dist/index.mjs +2254 -0
  4. package/dist/nitro.json +3 -3
  5. package/dist/public/200.html +1 -1
  6. package/dist/public/404.html +1 -1
  7. package/dist/public/_nuxt/0fZFclj2.js +2 -0
  8. package/dist/public/_nuxt/457Jr4Pr.js +1 -0
  9. package/dist/public/_nuxt/B1xYalZA.js +1 -0
  10. package/dist/public/_nuxt/BDNMzG2s.js +1 -0
  11. package/dist/public/_nuxt/BJv-YGcz.js +1 -0
  12. package/dist/public/_nuxt/BKuuhLmM.js +1 -0
  13. package/dist/public/_nuxt/BjJFp2QE.js +1 -0
  14. package/dist/public/_nuxt/C3lVFA1Q.js +1 -0
  15. package/dist/public/_nuxt/CAlSLYmJ.js +1 -0
  16. package/dist/public/_nuxt/CHXuaNaj.js +1 -0
  17. package/dist/public/_nuxt/CJwKXY9k.js +1 -0
  18. package/dist/public/_nuxt/CQYaOgKz.js +1 -0
  19. package/dist/public/_nuxt/CWPpjZx6.js +1 -0
  20. package/dist/public/_nuxt/CeVkPjP7.js +12 -0
  21. package/dist/public/_nuxt/D3MExTHO.js +3 -0
  22. package/dist/public/_nuxt/K3CNNOBf.js +2 -0
  23. package/dist/public/_nuxt/NLJpu4QF.js +1 -0
  24. package/dist/public/_nuxt/QSP1yWcH.js +1 -0
  25. package/dist/public/_nuxt/builds/latest.json +1 -1
  26. package/dist/public/_nuxt/builds/meta/d3f7ed61-b5b0-435f-9c70-ecd6f63b3201.json +1 -0
  27. package/dist/public/_nuxt/diff.worker-DFeiLCV8.js +10 -0
  28. package/dist/public/_nuxt/entry.CzwuNVVL.css +1 -0
  29. package/dist/public/_nuxt/error-404.YVLV_SWG.css +1 -0
  30. package/dist/public/_nuxt/error-500.DoVxOHYG.css +1 -0
  31. package/dist/public/_nuxt/filepath.CX8PXv9n.css +1 -0
  32. package/dist/public/_nuxt/graph.qvMalRQi.css +1 -0
  33. package/dist/public/_nuxt/plugins.CtM-Tp_V.css +1 -0
  34. package/dist/public/_nuxt/rpc.CVTFzytL.css +1 -0
  35. package/dist/public/favicon.svg +127 -12
  36. package/dist/public/fonts/dmmono-53a90e28.woff2 +0 -0
  37. package/dist/public/fonts/dmmono-cd6ed524.woff2 +0 -0
  38. package/dist/public/fonts/dmsans-54dbf8a8.woff2 +0 -0
  39. package/dist/public/fonts/dmsans-c55bbe7a.woff2 +0 -0
  40. package/dist/public/index.html +1 -1
  41. package/package.json +30 -51
  42. package/dist/dirs.js +0 -3
  43. package/dist/index.d.ts +0 -146
  44. package/dist/index.js +0 -1508
  45. package/dist/public/_nuxt/17ealR8P.js +0 -1
  46. package/dist/public/_nuxt/2OALqkc2.js +0 -1
  47. package/dist/public/_nuxt/AuXMpmu_.js +0 -1
  48. package/dist/public/_nuxt/B-LCQpq9.js +0 -2
  49. package/dist/public/_nuxt/B-MkobAt.js +0 -1
  50. package/dist/public/_nuxt/BFwdTbGt.js +0 -1
  51. package/dist/public/_nuxt/BQPGP7j8.js +0 -1
  52. package/dist/public/_nuxt/B_mZ82Ef.js +0 -1
  53. package/dist/public/_nuxt/BkcJ9YuP.js +0 -33
  54. package/dist/public/_nuxt/Bs1eUuZt.js +0 -1
  55. package/dist/public/_nuxt/C2Zn9dj_.js +0 -1
  56. package/dist/public/_nuxt/CIZ7KSXz.js +0 -1
  57. package/dist/public/_nuxt/CSwEzrF7.js +0 -11
  58. package/dist/public/_nuxt/CbzAqNxs.js +0 -1
  59. package/dist/public/_nuxt/ChaI2u-J.js +0 -1
  60. package/dist/public/_nuxt/CmZYssbg.js +0 -1
  61. package/dist/public/_nuxt/Cnct9GAr.js +0 -1
  62. package/dist/public/_nuxt/Cq2KqeQT.js +0 -1
  63. package/dist/public/_nuxt/Cql2HFZJ.js +0 -1
  64. package/dist/public/_nuxt/D-ZnEyqr.js +0 -1
  65. package/dist/public/_nuxt/D03ETnho.js +0 -1
  66. package/dist/public/_nuxt/D2Zr4_9a.js +0 -1
  67. package/dist/public/_nuxt/D7AVRXB9.js +0 -1
  68. package/dist/public/_nuxt/DL1ysgP5.js +0 -1
  69. package/dist/public/_nuxt/DP5rIU2b.js +0 -1
  70. package/dist/public/_nuxt/DQtLZa7C.js +0 -1
  71. package/dist/public/_nuxt/DcamI1aQ.js +0 -1
  72. package/dist/public/_nuxt/DnpfwSMy.js +0 -1
  73. package/dist/public/_nuxt/HzvsUJ0F.js +0 -1
  74. package/dist/public/_nuxt/Jdu9jmuG.js +0 -1
  75. package/dist/public/_nuxt/LMGHh3hZ.js +0 -1
  76. package/dist/public/_nuxt/SO3ppn9m.js +0 -1
  77. package/dist/public/_nuxt/VirtualList.lGV_3v2U.css +0 -1
  78. package/dist/public/_nuxt/X7aOo9pb.js +0 -1
  79. package/dist/public/_nuxt/_hSlj5r4.js +0 -1
  80. package/dist/public/_nuxt/_session_.B0BbH92J.css +0 -1
  81. package/dist/public/_nuxt/builds/meta/ef0d166a-8482-442c-9350-f2a451006de7.json +0 -1
  82. package/dist/public/_nuxt/diff.worker-DCsgdfuV.js +0 -10
  83. package/dist/public/_nuxt/entry.D6FiGaDn.css +0 -1
  84. package/dist/public/_nuxt/error-404.CCdr3eE4.css +0 -1
  85. package/dist/public/_nuxt/error-500.D-vBsHK_.css +0 -1
  86. package/dist/public/_nuxt/lxg2Cb0s.js +0 -1
  87. package/dist/public/_nuxt/mIZU4Om9.js +0 -1
  88. package/dist/public/_nuxt/qkzn-X0p.js +0 -1
  89. package/dist/public/_nuxt/vzoJapJG.js +0 -1
  90. package/dist/public/vite-devtools.svg +0 -17
  91. /package/dist/{dirs.d.ts → dirs.d.mts} +0 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,2254 @@
1
+ import { clientPublicDir } from "./dirs.mjs";
2
+ import { mkdirSync, rmSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { debounce } from "perfect-debounce";
5
+ import { createConsoleReporter, defineDiagnostics } from "nostics";
6
+ import { defineRpcFunction } from "@vitejs/devtools-kit";
7
+ import { createFilter } from "vite";
8
+ import { Buffer } from "node:buffer";
9
+ import { relative } from "pathe";
10
+ import { open } from "node:fs/promises";
11
+ import { AsyncLocalStorage } from "node:async_hooks";
12
+ import { DEVTOOLS_VITEPLUS_GROUP_ID } from "@vitejs/devtools-kit/constants";
13
+ //#region src/node/diagnostics.ts
14
+ const diagnostics = /* #__PURE__ */ defineDiagnostics({
15
+ docsBase: "https://devtools.vite.dev/errors",
16
+ reporters: [createConsoleReporter()],
17
+ codes: {
18
+ VDT0001: { why: "Vite inspect context is not available for this DevTools context." },
19
+ VDT0002: { why: (p) => `Vite inspect target "${p.id}" was not found in ${p.target}.` },
20
+ VDT0003: {
21
+ why: (p) => `Vite inspect storage failed while ${p.operation}.`,
22
+ fix: "Restart the Vite dev server. If the error persists, clear the Vite cache directory and reinstall dependencies."
23
+ }
24
+ }
25
+ });
26
+ //#endregion
27
+ //#region src/node/inspect/utils.ts
28
+ const DUMMY_LOAD_PLUGIN_NAME = "__load__";
29
+ function serializePlugin(plugin) {
30
+ return JSON.parse(JSON.stringify(plugin, (key, value) => {
31
+ if (typeof value === "function") {
32
+ let name = value.name;
33
+ if (name === "anonymous") name = "";
34
+ if (name === key) name = "";
35
+ return name ? `[Function ${name}]` : "[Function]";
36
+ }
37
+ if (key === "api" && value) return "[Object API]";
38
+ return value;
39
+ }));
40
+ }
41
+ function removeVersionQuery(url) {
42
+ if (!url.includes("v=")) return url;
43
+ return url.replace(/&v=\w+/, "").replace(/\?v=\w+/, "?").replace(/\?$/, "");
44
+ }
45
+ function normalizeModuleId(id, root) {
46
+ const normalizedId = id.replace(/%2F/gi, "/").replace(/\\/g, "/");
47
+ const normalizedRoot = root.replace(/%2F/gi, "/").replace(/\\/g, "/");
48
+ if (!(normalizedId.startsWith("/") || /^[a-z]:\//i.test(normalizedId)) || !normalizedId.includes("/node_modules/")) return normalizedId;
49
+ let result = relative(normalizedRoot, normalizedId);
50
+ if (!result.startsWith("./") && !result.startsWith("../")) result = `./${result}`;
51
+ return result;
52
+ }
53
+ function parseError(error) {
54
+ if (error instanceof Error) return {
55
+ message: error.message || String(error),
56
+ stack: typeof error.stack === "string" ? error.stack.split("\n").map((line) => line.trim()).filter(Boolean) : []
57
+ };
58
+ return {
59
+ message: String(error),
60
+ stack: []
61
+ };
62
+ }
63
+ function stringifyError(error) {
64
+ if (error instanceof Error) return error.stack || error.message;
65
+ return String(error);
66
+ }
67
+ function getAllQueryEnvs(ctx) {
68
+ const result = [];
69
+ for (const vite of ctx.idToInstances.values()) for (const envName of vite.environments.keys()) result.push({
70
+ vite: vite.id,
71
+ env: envName
72
+ });
73
+ return result;
74
+ }
75
+ async function getAllModuleIds(ctx) {
76
+ const result = [];
77
+ for (const vite of ctx.idToInstances.values()) for (const [envName, env] of vite.environments) {
78
+ const query = {
79
+ vite: vite.id,
80
+ env: envName
81
+ };
82
+ for (const id of await env.getModuleIds()) result.push([query, id]);
83
+ }
84
+ return result;
85
+ }
86
+ //#endregion
87
+ //#region src/node/inspect/module.ts
88
+ async function getModulesList(ctx, pluginCtx) {
89
+ const moduleGraph = ctx.env.mode === "dev" ? ctx.env.moduleGraph : void 0;
90
+ const getDeps = moduleGraph ? (id) => Array.from(moduleGraph.getModuleById(id)?.importedModules || []).map((module) => module.id || "").filter(Boolean) : pluginCtx ? (id) => Array.from(pluginCtx.getModuleInfo(id)?.importedIds || []) : () => [];
91
+ const getImporters = moduleGraph ? (id) => Array.from(moduleGraph.getModuleById(id)?.importers || []).map((module) => module.id || "").filter(Boolean) : pluginCtx ? (id) => Array.from(pluginCtx.getModuleInfo(id)?.importers || []) : () => [];
92
+ const transformList = await ctx.inspectContext.store.getTransformList(ctx.scope);
93
+ const resolveIdList = await ctx.inspectContext.store.getResolveIdList(ctx.scope);
94
+ const transformsById = transformList.reduce((map, transform) => {
95
+ (map[transform.moduleId] ||= []).push(transform);
96
+ return map;
97
+ }, {});
98
+ const transformedIdMap = resolveIdList.reduce((map, resolveId) => {
99
+ const result = ctx.normalizeId(resolveId.result);
100
+ (map[result] ||= []).push(resolveId);
101
+ return map;
102
+ }, {});
103
+ const ids = new Set(Object.keys(transformsById).concat(Object.keys(transformedIdMap)));
104
+ return Array.from(ids).sort().map((id) => {
105
+ let totalTime = 0;
106
+ const transforms = transformsById[id] || [];
107
+ const transformPlugins = transforms.filter((transform) => transform.hasResult).map((transform) => {
108
+ const delta = transform.end - transform.start;
109
+ totalTime += delta;
110
+ return {
111
+ name: transform.name,
112
+ transform: delta
113
+ };
114
+ });
115
+ const resolveIdPlugins = (transformedIdMap[id] || []).map((resolveId) => ({
116
+ name: resolveId.name,
117
+ resolveId: resolveId.end - resolveId.start
118
+ }));
119
+ const plugins = transformPlugins.concat(resolveIdPlugins);
120
+ const firstTransform = transforms[0];
121
+ const lastTransform = transforms.at(-1);
122
+ return {
123
+ id: ctx.getPublicModuleId(id),
124
+ deps: getDeps(id).map((dep) => ctx.getPublicModuleId(dep)),
125
+ importers: getImporters(id).map((importer) => ctx.getPublicModuleId(importer)),
126
+ plugins,
127
+ virtual: isVirtual(plugins[0]?.name || "", firstTransform?.name || ""),
128
+ totalTime,
129
+ invokeCount: firstTransform?.invokeCount || 0,
130
+ sourceSize: firstTransform?.hasResult ? firstTransform.resultSize : 0,
131
+ distSize: lastTransform?.hasResult ? lastTransform.resultSize : 0
132
+ };
133
+ });
134
+ }
135
+ function createGraphModuleIdResolver(moduleIds, extensions = []) {
136
+ const moduleIdMap = /* @__PURE__ */ new Map();
137
+ const sortedExtensions = extensions.slice().sort((a, b) => b.length - a.length);
138
+ for (const moduleId of moduleIds) {
139
+ addModuleId(moduleIdMap, moduleId, moduleId);
140
+ const extensionlessId = removeResolvedExtension(moduleId, sortedExtensions);
141
+ if (extensionlessId) addModuleId(moduleIdMap, extensionlessId, moduleId);
142
+ }
143
+ return (moduleId) => {
144
+ return moduleIdMap.get(moduleId) || void 0;
145
+ };
146
+ }
147
+ async function getModuleTransformInfo(ctx, id) {
148
+ const resolvedId = await ctx.resolveId(id);
149
+ return {
150
+ resolvedId,
151
+ transforms: await ctx.inspectContext.store.getModuleTransforms(ctx.scope, resolvedId)
152
+ };
153
+ }
154
+ function isVirtual(pluginName, transformName) {
155
+ return pluginName !== "__load__" && transformName !== "vite:load-fallback" && transformName !== "vite:build-load-fallback";
156
+ }
157
+ function addModuleId(moduleIdMap, key, target) {
158
+ const existing = moduleIdMap.get(key);
159
+ if (existing === void 0) moduleIdMap.set(key, target);
160
+ else if (existing !== target) moduleIdMap.set(key, false);
161
+ }
162
+ function removeResolvedExtension(id, extensions) {
163
+ const queryIndex = id.search(/[?#]/);
164
+ const path = queryIndex < 0 ? id : id.slice(0, queryIndex);
165
+ const query = queryIndex < 0 ? "" : id.slice(queryIndex);
166
+ const extension = extensions.find((extension) => path.endsWith(extension));
167
+ return extension ? `${path.slice(0, -extension.length)}${query}` : void 0;
168
+ }
169
+ //#endregion
170
+ //#region src/node/inspect/plugins.ts
171
+ async function getPluginMetrics(ctx) {
172
+ const map = {};
173
+ const defaultMetricInfo = () => ({
174
+ transform: {
175
+ invokeCount: 0,
176
+ totalTime: 0
177
+ },
178
+ resolveId: {
179
+ invokeCount: 0,
180
+ totalTime: 0
181
+ }
182
+ });
183
+ ctx.env.getTopLevelConfig().plugins.forEach((plugin, pluginId) => {
184
+ map[pluginId] = {
185
+ ...defaultMetricInfo(),
186
+ name: plugin.name,
187
+ plugin_id: pluginId,
188
+ enforce: plugin.enforce
189
+ };
190
+ });
191
+ for (const row of await ctx.inspectContext.store.getPluginTransformMetrics(ctx.scope)) {
192
+ const key = row.pluginId == null || row.pluginId < 0 ? row.pluginName : String(row.pluginId);
193
+ map[key] ||= {
194
+ ...defaultMetricInfo(),
195
+ name: row.pluginName,
196
+ plugin_id: row.pluginId
197
+ };
198
+ map[key].transform.totalTime += row.totalTime;
199
+ map[key].transform.invokeCount += row.invokeCount;
200
+ }
201
+ for (const row of await ctx.inspectContext.store.getPluginResolveIdMetrics(ctx.scope)) {
202
+ const key = row.pluginId == null || row.pluginId < 0 ? row.pluginName : String(row.pluginId);
203
+ map[key] ||= {
204
+ ...defaultMetricInfo(),
205
+ name: row.pluginName,
206
+ plugin_id: row.pluginId
207
+ };
208
+ map[key].resolveId.totalTime += row.totalTime;
209
+ map[key].resolveId.invokeCount += row.invokeCount;
210
+ }
211
+ return Object.values(map).filter(Boolean).sort((a, b) => a.name.localeCompare(b.name));
212
+ }
213
+ async function getPluginDetails(ctx, pluginId) {
214
+ const plugin = ctx.env.getTopLevelConfig().plugins[pluginId];
215
+ const calls = await withGraphModuleIds(ctx, await ctx.inspectContext.store.getPluginCalls(ctx.scope, pluginId));
216
+ return {
217
+ plugin_name: plugin?.name ?? calls[0]?.plugin_name ?? "",
218
+ plugin_id: pluginId,
219
+ calls,
220
+ resolveIdMetrics: calls.filter((call) => call.type === "resolve"),
221
+ loadMetrics: calls.filter((call) => call.type === "load"),
222
+ transformMetrics: calls.filter((call) => call.type === "transform")
223
+ };
224
+ }
225
+ async function withGraphModuleIds(ctx, calls) {
226
+ const resolveGraphModuleId = await ctx.getGraphModuleIdResolver();
227
+ return calls.map((call) => ({
228
+ ...call,
229
+ graphModuleId: resolveGraphModuleId(call.module)
230
+ }));
231
+ }
232
+ //#endregion
233
+ //#region src/node/inspect/store/payload.ts
234
+ async function createInspectPayloadStore(filename) {
235
+ if (!filename) return new MemoryInspectPayloadStore();
236
+ return new FileInspectPayloadStore(await open(filename, "w+"));
237
+ }
238
+ var MemoryInspectPayloadStore = class {
239
+ values = /* @__PURE__ */ new Map();
240
+ nextOffset = 0;
241
+ async write(values) {
242
+ return values.map((value) => {
243
+ if (value == null) return void 0;
244
+ const offset = this.nextOffset;
245
+ const length = Buffer.byteLength(value);
246
+ this.nextOffset += Math.max(length, 1);
247
+ this.values.set(offset, value);
248
+ return {
249
+ offset,
250
+ length
251
+ };
252
+ });
253
+ }
254
+ async read(range) {
255
+ const value = this.values.get(range.offset);
256
+ if (value == null) throw diagnostics.VDT0003({ operation: "reading an in-memory inspect payload" });
257
+ return value;
258
+ }
259
+ reclaim(ranges) {
260
+ for (const range of ranges) this.values.delete(range.offset);
261
+ }
262
+ async close() {
263
+ this.values.clear();
264
+ }
265
+ };
266
+ var FileInspectPayloadStore = class {
267
+ file;
268
+ nextOffset = 0;
269
+ freeRanges = [];
270
+ constructor(file) {
271
+ this.file = file;
272
+ }
273
+ async write(values) {
274
+ const ranges = [];
275
+ const writes = [];
276
+ for (const value of values) {
277
+ if (value == null) {
278
+ ranges.push(void 0);
279
+ continue;
280
+ }
281
+ const buffer = Buffer.from(value);
282
+ const range = this.allocate(buffer.length);
283
+ ranges.push(range);
284
+ if (buffer.length > 0) writes.push({
285
+ buffer,
286
+ range
287
+ });
288
+ }
289
+ await this.writeAllocatedPayloads(writes);
290
+ return ranges;
291
+ }
292
+ async read(range) {
293
+ if (range.length === 0) return "";
294
+ const buffer = Buffer.allocUnsafe(range.length);
295
+ let readOffset = 0;
296
+ while (readOffset < buffer.length) {
297
+ const { bytesRead } = await this.file.read(buffer, readOffset, buffer.length - readOffset, range.offset + readOffset);
298
+ if (bytesRead === 0) throw diagnostics.VDT0003({ operation: "reading the inspect payload archive" });
299
+ readOffset += bytesRead;
300
+ }
301
+ return buffer.toString();
302
+ }
303
+ async close() {
304
+ this.freeRanges.length = 0;
305
+ await this.file.close();
306
+ }
307
+ reclaim(ranges) {
308
+ this.freeRanges.push(...ranges.filter((range) => range.length > 0));
309
+ this.mergeFreeRanges();
310
+ }
311
+ allocate(length) {
312
+ if (length === 0) return {
313
+ offset: this.nextOffset,
314
+ length
315
+ };
316
+ let bestIndex = -1;
317
+ for (let index = 0; index < this.freeRanges.length; index++) {
318
+ const range = this.freeRanges[index];
319
+ if (range.length < length) continue;
320
+ if (bestIndex < 0 || range.length < this.freeRanges[bestIndex].length) bestIndex = index;
321
+ }
322
+ if (bestIndex >= 0) {
323
+ const range = this.freeRanges[bestIndex];
324
+ const allocated = {
325
+ offset: range.offset,
326
+ length
327
+ };
328
+ if (range.length === length) this.freeRanges.splice(bestIndex, 1);
329
+ else {
330
+ range.offset += length;
331
+ range.length -= length;
332
+ }
333
+ return allocated;
334
+ }
335
+ const allocated = {
336
+ offset: this.nextOffset,
337
+ length
338
+ };
339
+ this.nextOffset += length;
340
+ return allocated;
341
+ }
342
+ async writeAllocatedPayloads(writes) {
343
+ const ordered = writes.toSorted((a, b) => a.range.offset - b.range.offset);
344
+ let buffers = [];
345
+ let startOffset = 0;
346
+ let endOffset = 0;
347
+ for (const write of ordered) {
348
+ if (buffers.length > 0 && write.range.offset !== endOffset) {
349
+ await this.writeBuffers(buffers, startOffset);
350
+ buffers = [];
351
+ }
352
+ if (buffers.length === 0) startOffset = write.range.offset;
353
+ buffers.push(write.buffer);
354
+ endOffset = write.range.offset + write.range.length;
355
+ }
356
+ if (buffers.length > 0) await this.writeBuffers(buffers, startOffset);
357
+ }
358
+ async writeBuffers(input, startOffset) {
359
+ let buffers = input;
360
+ let offset = startOffset;
361
+ while (buffers.length > 0) {
362
+ const { bytesWritten } = await this.file.writev(buffers, offset);
363
+ if (bytesWritten === 0) throw diagnostics.VDT0003({ operation: "writing the inspect payload archive" });
364
+ buffers = consumeBuffers$1(buffers, bytesWritten);
365
+ offset += bytesWritten;
366
+ }
367
+ }
368
+ mergeFreeRanges() {
369
+ this.freeRanges.sort((a, b) => a.offset - b.offset);
370
+ const merged = [];
371
+ for (const range of this.freeRanges) {
372
+ const previous = merged.at(-1);
373
+ if (!previous || range.offset > previous.offset + previous.length) {
374
+ merged.push({ ...range });
375
+ continue;
376
+ }
377
+ previous.length = Math.max(previous.length, range.offset + range.length - previous.offset);
378
+ }
379
+ this.freeRanges = merged;
380
+ }
381
+ };
382
+ function consumeBuffers$1(input, bytes) {
383
+ const buffers = input.slice();
384
+ let consumed = bytes;
385
+ while (buffers.length > 0 && consumed >= buffers[0].length) {
386
+ consumed -= buffers[0].length;
387
+ buffers.shift();
388
+ }
389
+ if (buffers.length > 0 && consumed > 0) buffers[0] = buffers[0].subarray(consumed);
390
+ return buffers;
391
+ }
392
+ //#endregion
393
+ //#region src/node/inspect/store/plugin-calls.ts
394
+ const RECORD_SIZE = 40;
395
+ const RECORDS_PER_SEGMENT = 256;
396
+ const SEGMENT_HEADER_SIZE = 32;
397
+ const RECENT_SEGMENT_CACHE_SIZE = 64;
398
+ const SLOT_STATE_CHUNK_SIZE = 64 * 1024;
399
+ const NO_SEGMENT = 18446744073709551615n;
400
+ const TYPE_RESOLVE = 0;
401
+ const TYPE_LOAD = 1;
402
+ const TYPE_TRANSFORM = 2;
403
+ const FLAG_HAS_UNCHANGED = 1;
404
+ const FLAG_UNCHANGED = 2;
405
+ const OFFSET_HEADER_SCOPE_ID = 0;
406
+ const OFFSET_HEADER_PLUGIN_ID = 4;
407
+ const OFFSET_HEADER_PLUGIN_NAME_ID = 8;
408
+ const OFFSET_HEADER_TYPE = 12;
409
+ const OFFSET_HEADER_RECORD_COUNT = 16;
410
+ const OFFSET_HEADER_PREVIOUS_SEGMENT = 24;
411
+ const OFFSET_SLOT = 0;
412
+ const OFFSET_MODULE_ID = 4;
413
+ const OFFSET_SEQUENCE = 8;
414
+ const OFFSET_START = 16;
415
+ const OFFSET_END = 24;
416
+ const OFFSET_FLAGS = 32;
417
+ async function createInspectPluginCallStore(filename) {
418
+ return new BinaryInspectPluginCallStore(filename ? new FilePluginCallStorage(await open(filename, "w+")) : new MemoryPluginCallStorage());
419
+ }
420
+ var BinaryInspectPluginCallStore = class {
421
+ storage;
422
+ scopes = /* @__PURE__ */ new Map();
423
+ activeChunks = [];
424
+ nextSlotChunks = [];
425
+ nextScopeId = 0;
426
+ nextSlot = 0;
427
+ nextFileOffset = 0;
428
+ writeGate = Promise.resolve();
429
+ lastWriteError;
430
+ constructor(storage) {
431
+ this.storage = storage;
432
+ }
433
+ async write(calls) {
434
+ this.throwWriteError();
435
+ if (calls.length === 0) return;
436
+ const completedSegments = [];
437
+ for (const call of calls) {
438
+ validateCall(call.info);
439
+ const scope = this.getScope(call.scope);
440
+ const moduleId = internString(scope.moduleIds, scope.moduleNames, call.info.module);
441
+ const pluginNameId = internString(scope.pluginNameIds, scope.pluginNames, call.info.plugin_name);
442
+ const pluginType = this.getPluginType(scope, call.info.plugin_id, call.info.type);
443
+ if (pluginType.pendingCount > 0 && pluginType.pendingPluginNameId !== pluginNameId) completedSegments.push(this.takePendingSegment(scope, pluginType));
444
+ const slot = this.allocateSlot();
445
+ const offset = pluginType.pendingCount * RECORD_SIZE;
446
+ this.setNextSlot(slot, scope.moduleHeads[moduleId] ?? 0);
447
+ scope.moduleHeads[moduleId] = slot + 1;
448
+ scope.activeCalls += 1;
449
+ this.setActive(slot, true);
450
+ pluginType.pendingPluginNameId = pluginNameId;
451
+ encodeCall(pluginType.pendingRecords, offset, slot, moduleId, call.info);
452
+ pluginType.pendingCount += 1;
453
+ if (pluginType.pendingCount === RECORDS_PER_SEGMENT) completedSegments.push(this.takePendingSegment(scope, pluginType));
454
+ }
455
+ await this.writeSegments(completedSegments);
456
+ }
457
+ async read(scopeName, pluginId) {
458
+ const scope = this.scopes.get(scopeName);
459
+ if (!scope || scope.activeCalls === 0) return [];
460
+ const calls = [];
461
+ let processedRecords = 0;
462
+ for (const pluginType of scope.pluginTypes.values()) {
463
+ if (pluginType.pluginId !== pluginId) continue;
464
+ let segmentOffset = pluginType.headOffset;
465
+ const recentSegments = [];
466
+ for (let index = pluginType.recentSegments.length - 1; index >= 0; index--) {
467
+ const segment = pluginType.recentSegments[index];
468
+ if (segment.offset !== segmentOffset) break;
469
+ recentSegments.push(segment);
470
+ segmentOffset = segment.previousOffset;
471
+ }
472
+ const recentRecords = await Promise.all(recentSegments.map(async (segment) => {
473
+ const records = await this.storage.read(segment.offset + SEGMENT_HEADER_SIZE, segment.recordCount * RECORD_SIZE);
474
+ if (records.length < segment.recordCount * RECORD_SIZE) throw diagnostics.VDT0003({ operation: "reading the indexed inspect plugin call segment" });
475
+ return {
476
+ segment,
477
+ records
478
+ };
479
+ }));
480
+ for (const { segment, records } of recentRecords) {
481
+ this.decodeRecords(calls, records, segment.recordCount, pluginType.type, pluginType.pluginId, segment.pluginNameId, scope);
482
+ processedRecords += segment.recordCount;
483
+ }
484
+ if (processedRecords >= 4096) {
485
+ processedRecords = 0;
486
+ await yieldToEventLoop();
487
+ }
488
+ while (segmentOffset != null) {
489
+ const segment = await this.storage.read(segmentOffset, 10272);
490
+ const recordCount = segment.readUInt32LE(OFFSET_HEADER_RECORD_COUNT);
491
+ const requiredLength = SEGMENT_HEADER_SIZE + recordCount * RECORD_SIZE;
492
+ if (segment.length < requiredLength) throw diagnostics.VDT0003({ operation: "reading the inspect plugin call segment" });
493
+ const type = decodeType(segment.readUInt8(OFFSET_HEADER_TYPE));
494
+ const storedPluginId = segment.readUInt32LE(OFFSET_HEADER_PLUGIN_ID);
495
+ const pluginNameId = segment.readUInt32LE(OFFSET_HEADER_PLUGIN_NAME_ID);
496
+ this.decodeRecords(calls, segment.subarray(SEGMENT_HEADER_SIZE, requiredLength), recordCount, type, storedPluginId, pluginNameId, scope);
497
+ processedRecords += recordCount;
498
+ if (processedRecords >= 4096) {
499
+ processedRecords = 0;
500
+ await yieldToEventLoop();
501
+ }
502
+ const previousSegment = segment.readBigUInt64LE(OFFSET_HEADER_PREVIOUS_SEGMENT);
503
+ segmentOffset = previousSegment === NO_SEGMENT ? void 0 : Number(previousSegment);
504
+ }
505
+ }
506
+ calls.sort((a, b) => callSequence(a.id) - callSequence(b.id));
507
+ return calls;
508
+ }
509
+ invalidate(scopeName, modules) {
510
+ const scope = this.scopes.get(scopeName);
511
+ if (!scope) return;
512
+ for (const module of modules) {
513
+ const moduleId = scope.moduleIds.get(module);
514
+ if (moduleId == null) continue;
515
+ this.releaseModuleSlots(scope, moduleId);
516
+ }
517
+ }
518
+ clearScope(scopeName) {
519
+ const scope = this.scopes.get(scopeName);
520
+ if (!scope) return;
521
+ for (let moduleId = 0; moduleId < scope.moduleHeads.length; moduleId++) this.releaseModuleSlots(scope, moduleId);
522
+ this.scopes.delete(scopeName);
523
+ }
524
+ async flush() {
525
+ this.throwWriteError();
526
+ const pendingSegments = [];
527
+ for (const scope of this.scopes.values()) for (const pluginType of scope.pluginTypes.values()) if (pluginType.pendingCount > 0) pendingSegments.push(this.takePendingSegment(scope, pluginType));
528
+ if (pendingSegments.length > 0) await this.writeSegments(pendingSegments);
529
+ else await this.writeGate;
530
+ this.throwWriteError();
531
+ }
532
+ async close() {
533
+ let thrownError;
534
+ try {
535
+ await this.flush();
536
+ } catch (error) {
537
+ thrownError = error;
538
+ }
539
+ this.scopes.clear();
540
+ this.activeChunks.length = 0;
541
+ this.nextSlotChunks.length = 0;
542
+ try {
543
+ await this.storage.close();
544
+ } catch (error) {
545
+ thrownError ??= error;
546
+ }
547
+ if (thrownError) throw thrownError;
548
+ }
549
+ getScope(scopeName) {
550
+ let scope = this.scopes.get(scopeName);
551
+ if (scope) return scope;
552
+ if (this.nextScopeId > 4294967295) throw diagnostics.VDT0003({ operation: "allocating an inspect plugin call scope" });
553
+ scope = {
554
+ id: this.nextScopeId++,
555
+ activeCalls: 0,
556
+ moduleIds: /* @__PURE__ */ new Map(),
557
+ moduleNames: [],
558
+ moduleHeads: [],
559
+ pluginNameIds: /* @__PURE__ */ new Map(),
560
+ pluginNames: [],
561
+ pluginTypes: /* @__PURE__ */ new Map()
562
+ };
563
+ this.scopes.set(scopeName, scope);
564
+ return scope;
565
+ }
566
+ getPluginType(scope, pluginId, type) {
567
+ const key = `${pluginId}:${type}`;
568
+ let pluginType = scope.pluginTypes.get(key);
569
+ if (!pluginType) {
570
+ pluginType = {
571
+ pluginId,
572
+ type,
573
+ pendingRecords: Buffer.allocUnsafe(RECORDS_PER_SEGMENT * RECORD_SIZE),
574
+ pendingCount: 0,
575
+ recentSegments: []
576
+ };
577
+ scope.pluginTypes.set(key, pluginType);
578
+ }
579
+ return pluginType;
580
+ }
581
+ takePendingSegment(scope, pluginType) {
582
+ const recordCount = pluginType.pendingCount;
583
+ const records = pluginType.pendingRecords.subarray(0, recordCount * RECORD_SIZE);
584
+ const pluginNameId = pluginType.pendingPluginNameId;
585
+ pluginType.pendingRecords = Buffer.allocUnsafe(RECORDS_PER_SEGMENT * RECORD_SIZE);
586
+ pluginType.pendingCount = 0;
587
+ pluginType.pendingPluginNameId = void 0;
588
+ return {
589
+ scope,
590
+ pluginType,
591
+ pluginNameId,
592
+ records,
593
+ recordCount
594
+ };
595
+ }
596
+ async writeSegments(segments) {
597
+ if (segments.length === 0) return;
598
+ const buffers = [];
599
+ const startPosition = this.nextFileOffset;
600
+ for (const segment of segments) {
601
+ const segmentOffset = this.nextFileOffset;
602
+ const previousOffset = segment.pluginType.headOffset;
603
+ const header = Buffer.alloc(SEGMENT_HEADER_SIZE);
604
+ header.writeUInt32LE(segment.scope.id, OFFSET_HEADER_SCOPE_ID);
605
+ header.writeUInt32LE(segment.pluginType.pluginId, OFFSET_HEADER_PLUGIN_ID);
606
+ header.writeUInt32LE(segment.pluginNameId, OFFSET_HEADER_PLUGIN_NAME_ID);
607
+ header.writeUInt8(encodeType(segment.pluginType.type), OFFSET_HEADER_TYPE);
608
+ header.writeUInt32LE(segment.recordCount, OFFSET_HEADER_RECORD_COUNT);
609
+ header.writeBigUInt64LE(previousOffset == null ? NO_SEGMENT : BigInt(previousOffset), OFFSET_HEADER_PREVIOUS_SEGMENT);
610
+ segment.pluginType.headOffset = segmentOffset;
611
+ segment.pluginType.recentSegments.push({
612
+ offset: segmentOffset,
613
+ previousOffset,
614
+ pluginNameId: segment.pluginNameId,
615
+ recordCount: segment.recordCount
616
+ });
617
+ if (segment.pluginType.recentSegments.length > RECENT_SEGMENT_CACHE_SIZE) segment.pluginType.recentSegments.shift();
618
+ buffers.push(header, segment.records);
619
+ this.nextFileOffset += header.length + segment.records.length;
620
+ }
621
+ const write = this.writeGate.then(() => this.storage.write(buffers, startPosition));
622
+ this.writeGate = write.catch((error) => {
623
+ this.lastWriteError = toError$1(error);
624
+ });
625
+ await write;
626
+ }
627
+ allocateSlot() {
628
+ if (this.nextSlot > 4294967294) throw diagnostics.VDT0003({ operation: "allocating an inspect plugin call slot" });
629
+ const slot = this.nextSlot++;
630
+ this.ensureSlotState(slot);
631
+ return slot;
632
+ }
633
+ decodeRecords(calls, records, recordCount, type, pluginId, pluginNameId, scope) {
634
+ for (let index = 0; index < recordCount; index++) {
635
+ const offset = index * RECORD_SIZE;
636
+ const slot = records.readUInt32LE(offset + OFFSET_SLOT);
637
+ if (!this.isActive(slot)) continue;
638
+ calls.push(decodeCall(records, offset, type, pluginId, pluginNameId, scope));
639
+ }
640
+ }
641
+ releaseModuleSlots(scope, moduleId) {
642
+ let head = scope.moduleHeads[moduleId] ?? 0;
643
+ scope.moduleHeads[moduleId] = 0;
644
+ while (head > 0) {
645
+ const slot = head - 1;
646
+ const next = this.getNextSlot(slot);
647
+ if (this.isActive(slot)) {
648
+ this.setActive(slot, false);
649
+ scope.activeCalls -= 1;
650
+ }
651
+ head = next;
652
+ }
653
+ }
654
+ ensureSlotState(slot) {
655
+ const chunkIndex = Math.floor(slot / SLOT_STATE_CHUNK_SIZE);
656
+ while (this.activeChunks.length <= chunkIndex) {
657
+ this.activeChunks.push(new Uint8Array(SLOT_STATE_CHUNK_SIZE));
658
+ this.nextSlotChunks.push(new Uint32Array(SLOT_STATE_CHUNK_SIZE));
659
+ }
660
+ }
661
+ isActive(slot) {
662
+ const chunkIndex = Math.floor(slot / SLOT_STATE_CHUNK_SIZE);
663
+ return this.activeChunks[chunkIndex]?.[slot % SLOT_STATE_CHUNK_SIZE] === 1;
664
+ }
665
+ setActive(slot, active) {
666
+ this.ensureSlotState(slot);
667
+ this.activeChunks[Math.floor(slot / SLOT_STATE_CHUNK_SIZE)][slot % SLOT_STATE_CHUNK_SIZE] = active ? 1 : 0;
668
+ }
669
+ getNextSlot(slot) {
670
+ return this.nextSlotChunks[Math.floor(slot / SLOT_STATE_CHUNK_SIZE)][slot % SLOT_STATE_CHUNK_SIZE];
671
+ }
672
+ setNextSlot(slot, next) {
673
+ this.ensureSlotState(slot);
674
+ this.nextSlotChunks[Math.floor(slot / SLOT_STATE_CHUNK_SIZE)][slot % SLOT_STATE_CHUNK_SIZE] = next;
675
+ }
676
+ throwWriteError() {
677
+ if (this.lastWriteError) throw this.lastWriteError;
678
+ }
679
+ };
680
+ var FilePluginCallStorage = class {
681
+ file;
682
+ constructor(file) {
683
+ this.file = file;
684
+ }
685
+ async write(input, startPosition) {
686
+ let buffers = input;
687
+ let position = startPosition;
688
+ while (buffers.length > 0) {
689
+ const { bytesWritten } = await this.file.writev(buffers, position);
690
+ if (bytesWritten === 0) throw diagnostics.VDT0003({ operation: "writing the inspect plugin call archive" });
691
+ buffers = consumeBuffers(buffers, bytesWritten);
692
+ position += bytesWritten;
693
+ }
694
+ }
695
+ async read(position, length) {
696
+ const buffer = Buffer.allocUnsafe(length);
697
+ let offset = 0;
698
+ while (offset < buffer.length) {
699
+ const { bytesRead } = await this.file.read(buffer, offset, buffer.length - offset, position + offset);
700
+ if (bytesRead === 0) break;
701
+ offset += bytesRead;
702
+ }
703
+ return buffer.subarray(0, offset);
704
+ }
705
+ async close() {
706
+ await this.file.close();
707
+ }
708
+ };
709
+ var MemoryPluginCallStorage = class {
710
+ buffer = Buffer.alloc(0);
711
+ async write(buffers, position) {
712
+ const requiredBytes = position + buffers.reduce((total, buffer) => total + buffer.length, 0);
713
+ if (requiredBytes > this.buffer.length) {
714
+ const next = Buffer.allocUnsafe(Math.max(requiredBytes, this.buffer.length * 2, 64 * 1024));
715
+ this.buffer.copy(next);
716
+ this.buffer = next;
717
+ }
718
+ let offset = position;
719
+ for (const buffer of buffers) {
720
+ buffer.copy(this.buffer, offset);
721
+ offset += buffer.length;
722
+ }
723
+ }
724
+ async read(position, length) {
725
+ return this.buffer.subarray(position, position + length);
726
+ }
727
+ async close() {
728
+ this.buffer = Buffer.alloc(0);
729
+ }
730
+ };
731
+ function validateCall(info) {
732
+ const sequence = callSequence(info.id);
733
+ if (!Number.isSafeInteger(sequence) || sequence < 0 || info.plugin_id < 0 || info.plugin_id > 4294967295) throw diagnostics.VDT0003({ operation: "encoding an inspect plugin call" });
734
+ }
735
+ function encodeCall(buffer, offset, slot, moduleId, info) {
736
+ buffer.writeUInt32LE(slot, offset + OFFSET_SLOT);
737
+ buffer.writeUInt32LE(moduleId, offset + OFFSET_MODULE_ID);
738
+ buffer.writeDoubleLE(callSequence(info.id), offset + OFFSET_SEQUENCE);
739
+ buffer.writeDoubleLE(info.timestamp_start, offset + OFFSET_START);
740
+ buffer.writeDoubleLE(info.timestamp_end, offset + OFFSET_END);
741
+ buffer.writeUInt8(info.unchanged == null ? 0 : FLAG_HAS_UNCHANGED | (info.unchanged ? FLAG_UNCHANGED : 0), offset + OFFSET_FLAGS);
742
+ buffer.fill(0, offset + OFFSET_FLAGS + 1, offset + RECORD_SIZE);
743
+ }
744
+ function decodeCall(buffer, offset, type, pluginId, pluginNameId, scope) {
745
+ const moduleId = buffer.readUInt32LE(offset + OFFSET_MODULE_ID);
746
+ const flags = buffer.readUInt8(offset + OFFSET_FLAGS);
747
+ const sequence = buffer.readDoubleLE(offset + OFFSET_SEQUENCE);
748
+ const start = buffer.readDoubleLE(offset + OFFSET_START);
749
+ const end = buffer.readDoubleLE(offset + OFFSET_END);
750
+ return {
751
+ type,
752
+ id: `${type}:${pluginId}:${sequence}`,
753
+ duration: Math.max(0, end - start),
754
+ plugin_id: pluginId,
755
+ plugin_name: scope.pluginNames[pluginNameId],
756
+ module: scope.moduleNames[moduleId],
757
+ timestamp_start: start,
758
+ timestamp_end: end,
759
+ unchanged: flags & FLAG_HAS_UNCHANGED ? Boolean(flags & FLAG_UNCHANGED) : void 0
760
+ };
761
+ }
762
+ function consumeBuffers(input, bytes) {
763
+ const buffers = input.slice();
764
+ let consumed = bytes;
765
+ while (buffers.length > 0 && consumed >= buffers[0].length) {
766
+ consumed -= buffers[0].length;
767
+ buffers.shift();
768
+ }
769
+ if (buffers.length > 0 && consumed > 0) buffers[0] = buffers[0].subarray(consumed);
770
+ return buffers;
771
+ }
772
+ function internString(ids, values, value) {
773
+ const existing = ids.get(value);
774
+ if (existing != null) return existing;
775
+ if (values.length > 4294967295) throw diagnostics.VDT0003({ operation: "interning inspect plugin call metadata" });
776
+ const id = values.length;
777
+ ids.set(value, id);
778
+ values.push(value);
779
+ return id;
780
+ }
781
+ function callSequence(id) {
782
+ return Number(id.slice(id.lastIndexOf(":") + 1));
783
+ }
784
+ function encodeType(type) {
785
+ if (type === "resolve") return TYPE_RESOLVE;
786
+ if (type === "load") return TYPE_LOAD;
787
+ return TYPE_TRANSFORM;
788
+ }
789
+ function decodeType(type) {
790
+ if (type === TYPE_RESOLVE) return "resolve";
791
+ if (type === TYPE_LOAD) return "load";
792
+ if (type === TYPE_TRANSFORM) return "transform";
793
+ throw diagnostics.VDT0003({ operation: "decoding an inspect plugin call" });
794
+ }
795
+ function yieldToEventLoop() {
796
+ return new Promise((resolve) => setImmediate(resolve));
797
+ }
798
+ function toError$1(error) {
799
+ return error instanceof Error ? error : new Error(String(error));
800
+ }
801
+ //#endregion
802
+ //#region src/node/inspect/store/index.ts
803
+ const DEFAULT_MAX_BATCH_ITEMS = 256;
804
+ const DEFAULT_MAX_BATCH_BYTES = 8 * 1024 * 1024;
805
+ async function createViteInspectStore(options = {}) {
806
+ const filename = options.filename === ":memory:" ? void 0 : options.filename;
807
+ if (filename) mkdirSync(dirname(filename), { recursive: true });
808
+ let payloads;
809
+ try {
810
+ payloads = await createInspectPayloadStore(filename);
811
+ const pluginCalls = await createInspectPluginCallStore(filename ? join(dirname(filename), "plugin-calls.bin") : void 0);
812
+ return new PayloadViteInspectStore(payloads, pluginCalls, options);
813
+ } catch (error) {
814
+ await payloads?.close().catch(() => {});
815
+ reportStorageError("opening the inspect archives", error);
816
+ throw error;
817
+ }
818
+ }
819
+ var PayloadViteInspectStore = class {
820
+ maxBatchItems;
821
+ maxBatchBytes;
822
+ payloads;
823
+ pluginCalls;
824
+ scopes = /* @__PURE__ */ new Map();
825
+ queue = [];
826
+ queueHead = 0;
827
+ scheduledPump;
828
+ pumpPromise;
829
+ lastWriteError;
830
+ closing = false;
831
+ closed = false;
832
+ closePromise;
833
+ queuedItems = 0;
834
+ queuedBytes = 0;
835
+ inFlightItems = 0;
836
+ peakQueuedItems = 0;
837
+ peakQueuedBytes = 0;
838
+ writeBatches = 0;
839
+ activeReaders = 0;
840
+ readerWaiters = [];
841
+ constructor(payloads, pluginCalls, options) {
842
+ this.payloads = payloads;
843
+ this.pluginCalls = pluginCalls;
844
+ this.maxBatchItems = positiveInteger(options.maxBatchItems, DEFAULT_MAX_BATCH_ITEMS);
845
+ this.maxBatchBytes = positiveInteger(options.maxBatchBytes, DEFAULT_MAX_BATCH_BYTES);
846
+ }
847
+ recordTransform(scope, moduleId, publicModuleId, info, preTransformCode, pluginCall) {
848
+ this.enqueue({
849
+ operation: "recordTransform",
850
+ scope,
851
+ moduleId,
852
+ publicModuleId,
853
+ info,
854
+ preTransformCode,
855
+ pluginCall
856
+ });
857
+ }
858
+ recordLoad(scope, moduleId, publicModuleId, info, pluginCall) {
859
+ this.enqueue({
860
+ operation: "recordLoad",
861
+ scope,
862
+ moduleId,
863
+ publicModuleId,
864
+ info,
865
+ pluginCall
866
+ });
867
+ }
868
+ recordResolveId(scope, sourceId, sourcePublicId, info, resultPublicId, pluginCall) {
869
+ this.enqueue({
870
+ operation: "recordResolveId",
871
+ scope,
872
+ sourceId,
873
+ sourcePublicId,
874
+ info,
875
+ resultPublicId,
876
+ pluginCall
877
+ });
878
+ }
879
+ recordPluginCall(scope, info) {
880
+ this.enqueue({
881
+ operation: "recordPluginCall",
882
+ scope,
883
+ info
884
+ });
885
+ }
886
+ invalidate(scope, moduleId, publicModuleId) {
887
+ this.enqueue({
888
+ operation: "invalidate",
889
+ scope,
890
+ moduleId,
891
+ publicModuleId
892
+ });
893
+ }
894
+ clearScope(scope) {
895
+ this.enqueue({
896
+ operation: "clearScope",
897
+ scope
898
+ });
899
+ }
900
+ async getTransformList(scope) {
901
+ await this.flush();
902
+ const result = [];
903
+ for (const [moduleId, transforms] of this.scopes.get(scope)?.transforms ?? []) for (const transform of transforms.items) result.push({
904
+ moduleId,
905
+ publicModuleId: transforms.publicModuleId,
906
+ name: transform.name,
907
+ pluginId: transform.pluginId,
908
+ hasResult: transform.hasResult,
909
+ resultSize: transform.resultSize,
910
+ start: transform.start,
911
+ end: transform.end,
912
+ invokeCount: transforms.invokeCount
913
+ });
914
+ return result;
915
+ }
916
+ async getResolveIdList(scope) {
917
+ await this.flush();
918
+ return Array.from(this.scopes.get(scope)?.resolveIds.values() ?? []).flat();
919
+ }
920
+ async getPluginTransformMetrics(scope) {
921
+ await this.flush();
922
+ const metrics = /* @__PURE__ */ new Map();
923
+ for (const transforms of this.scopes.get(scope)?.transforms.values() ?? []) for (const transform of transforms.items) {
924
+ if (transform.name === "__load__") continue;
925
+ addMetric(metrics, transform.pluginId, transform.name, transform.end - transform.start);
926
+ }
927
+ return Array.from(metrics.values());
928
+ }
929
+ async getPluginResolveIdMetrics(scope) {
930
+ await this.flush();
931
+ const metrics = /* @__PURE__ */ new Map();
932
+ for (const resolveIds of this.scopes.get(scope)?.resolveIds.values() ?? []) for (const resolveId of resolveIds) addMetric(metrics, resolveId.pluginId, resolveId.name, resolveId.end - resolveId.start);
933
+ return Array.from(metrics.values());
934
+ }
935
+ async getModuleTransforms(scope, moduleId) {
936
+ return this.readSnapshot(async () => {
937
+ const transforms = this.scopes.get(scope)?.transforms.get(moduleId)?.items ?? [];
938
+ return Promise.all(transforms.map((transform) => this.restoreTransformInfo(transform)));
939
+ });
940
+ }
941
+ async getPluginCalls(scope, pluginId) {
942
+ return this.readSnapshot(() => this.pluginCalls.read(scope, pluginId));
943
+ }
944
+ async getFirstResolveResult(scope, sourceId) {
945
+ await this.flush();
946
+ return this.scopes.get(scope)?.resolveIds.get(sourceId)?.[0]?.result;
947
+ }
948
+ async findModuleId(scope, publicModuleId) {
949
+ await this.flush();
950
+ const data = this.scopes.get(scope);
951
+ if (!data) return void 0;
952
+ for (const [moduleId, transforms] of data.transforms) if (transforms.publicModuleId === publicModuleId) return moduleId;
953
+ for (const resolveIds of data.resolveIds.values()) {
954
+ const matched = resolveIds.find((resolveId) => resolveId.resultPublicId === publicModuleId);
955
+ if (matched) return matched.result;
956
+ }
957
+ }
958
+ async getModuleIds(scope) {
959
+ await this.flush();
960
+ const data = this.scopes.get(scope);
961
+ if (!data) return [];
962
+ const moduleIds = new Set(data.transforms.keys());
963
+ for (const resolveIds of data.resolveIds.values()) for (const resolveId of resolveIds) moduleIds.add(resolveId.result);
964
+ return Array.from(moduleIds);
965
+ }
966
+ getStats() {
967
+ return {
968
+ maxBatchItems: this.maxBatchItems,
969
+ maxBatchBytes: this.maxBatchBytes,
970
+ queuedItems: this.queuedItems,
971
+ queuedBytes: this.queuedBytes,
972
+ inFlightItems: this.inFlightItems,
973
+ peakQueuedItems: this.peakQueuedItems,
974
+ peakQueuedBytes: this.peakQueuedBytes,
975
+ writeBatches: this.writeBatches
976
+ };
977
+ }
978
+ async flush() {
979
+ this.throwWriteError();
980
+ while (this.queuedItems > 0 || this.scheduledPump || this.pumpPromise) {
981
+ if (this.scheduledPump) {
982
+ clearImmediate(this.scheduledPump);
983
+ this.scheduledPump = void 0;
984
+ }
985
+ this.startPump();
986
+ if (this.pumpPromise) await this.pumpPromise;
987
+ }
988
+ await this.pluginCalls.flush();
989
+ this.throwWriteError();
990
+ }
991
+ async close() {
992
+ this.closePromise ||= this.closeInternal();
993
+ await this.closePromise;
994
+ }
995
+ enqueue(write) {
996
+ if (this.closing || this.closed || this.lastWriteError) return;
997
+ const estimatedBytes = estimateWriteBytes(write);
998
+ this.queue.push({
999
+ write,
1000
+ estimatedBytes
1001
+ });
1002
+ this.queuedItems += 1;
1003
+ this.queuedBytes += estimatedBytes;
1004
+ this.peakQueuedItems = Math.max(this.peakQueuedItems, this.queuedItems);
1005
+ this.peakQueuedBytes = Math.max(this.peakQueuedBytes, this.queuedBytes);
1006
+ this.schedulePump();
1007
+ }
1008
+ schedulePump() {
1009
+ if (this.scheduledPump || this.pumpPromise || this.queuedItems === 0) return;
1010
+ this.scheduledPump = setImmediate(() => {
1011
+ this.scheduledPump = void 0;
1012
+ this.startPump();
1013
+ });
1014
+ }
1015
+ startPump() {
1016
+ if (this.pumpPromise || this.queuedItems === 0 || this.lastWriteError) return;
1017
+ this.pumpPromise = this.drainQueue().catch((error) => {
1018
+ this.lastWriteError = toError(error);
1019
+ reportStorageError("writing the inspect archives", error);
1020
+ }).finally(() => {
1021
+ this.pumpPromise = void 0;
1022
+ this.inFlightItems = 0;
1023
+ if (this.queuedItems > 0 && !this.lastWriteError) this.schedulePump();
1024
+ });
1025
+ }
1026
+ async drainQueue() {
1027
+ while (this.queuedItems > 0) {
1028
+ await this.waitForReaders();
1029
+ const batch = this.takeBatch();
1030
+ this.inFlightItems = batch.length;
1031
+ this.writeBatches += 1;
1032
+ await this.writeBatch(batch);
1033
+ this.inFlightItems = 0;
1034
+ }
1035
+ }
1036
+ takeBatch() {
1037
+ const batch = [];
1038
+ let batchBytes = 0;
1039
+ while (this.queueHead < this.queue.length && batch.length < this.maxBatchItems) {
1040
+ const pending = this.queue[this.queueHead];
1041
+ if (batch.length > 0 && batchBytes + pending.estimatedBytes > this.maxBatchBytes) break;
1042
+ batch.push(pending);
1043
+ batchBytes += pending.estimatedBytes;
1044
+ this.queue[this.queueHead] = void 0;
1045
+ this.queueHead += 1;
1046
+ }
1047
+ this.queuedItems -= batch.length;
1048
+ this.queuedBytes = Math.max(0, this.queuedBytes - batchBytes);
1049
+ if (this.queueHead === this.queue.length) {
1050
+ this.queue = [];
1051
+ this.queueHead = 0;
1052
+ } else if (this.queueHead >= 4096 && this.queueHead * 2 >= this.queue.length) {
1053
+ this.queue = this.queue.slice(this.queueHead);
1054
+ this.queueHead = 0;
1055
+ }
1056
+ return batch;
1057
+ }
1058
+ async writeBatch(batch) {
1059
+ let dataWrites = [];
1060
+ const flushDataWrites = async () => {
1061
+ if (dataWrites.length === 0) return;
1062
+ const current = dataWrites;
1063
+ dataWrites = [];
1064
+ await this.writeDataBatch(current);
1065
+ };
1066
+ for (const { write } of batch) if (write.operation === "invalidate") {
1067
+ await flushDataWrites();
1068
+ this.invalidateNow(write.scope, write.moduleId, write.publicModuleId);
1069
+ } else if (write.operation === "clearScope") {
1070
+ await flushDataWrites();
1071
+ this.clearScopeNow(write.scope);
1072
+ } else dataWrites.push(write);
1073
+ await flushDataWrites();
1074
+ }
1075
+ async writeDataBatch(writes) {
1076
+ const values = [];
1077
+ const prepared = [];
1078
+ const pluginCallWrites = [];
1079
+ const sourceState = /* @__PURE__ */ new Map();
1080
+ const hasSource = (scope, moduleId) => {
1081
+ const key = scopeKey(scope, moduleId);
1082
+ const pending = sourceState.get(key);
1083
+ if (pending != null) return pending;
1084
+ const stored = this.scopes.get(scope)?.transforms.get(moduleId)?.items.some((item) => item.hasResult) ?? false;
1085
+ sourceState.set(key, stored);
1086
+ return stored;
1087
+ };
1088
+ for (const write of writes) {
1089
+ const pluginCall = getQueuedPluginCall(write);
1090
+ if (pluginCall) pluginCallWrites.push({
1091
+ scope: write.scope,
1092
+ info: pluginCall
1093
+ });
1094
+ if (write.operation === "recordPluginCall") continue;
1095
+ const item = { write };
1096
+ if (write.operation === "recordTransform") {
1097
+ const key = scopeKey(write.scope, write.moduleId);
1098
+ if (!hasSource(write.scope, write.moduleId)) {
1099
+ item.sourceIndex = values.push(write.preTransformCode) - 1;
1100
+ sourceState.set(key, true);
1101
+ }
1102
+ item.resultIndex = values.push(write.info.result) - 1;
1103
+ item.sourcemapIndex = pushSerializedPayload(values, write.info.sourcemaps);
1104
+ } else if (write.operation === "recordLoad") {
1105
+ item.resultIndex = values.push(write.info.result) - 1;
1106
+ item.sourcemapIndex = pushSerializedPayload(values, write.info.sourcemaps);
1107
+ sourceState.set(scopeKey(write.scope, write.moduleId), write.info.result != null);
1108
+ }
1109
+ prepared.push(item);
1110
+ }
1111
+ const [ranges] = await Promise.all([values.length > 0 ? this.payloads.write(values) : Promise.resolve([]), this.pluginCalls.write(pluginCallWrites)]);
1112
+ for (const item of prepared) this.applyPreparedWrite(item, ranges);
1113
+ }
1114
+ applyPreparedWrite(prepared, ranges) {
1115
+ const { write } = prepared;
1116
+ if (write.operation === "recordTransform") this.applyTransform(write, rangeAt(ranges, prepared.resultIndex), rangeAt(ranges, prepared.sourceIndex), rangeAt(ranges, prepared.sourcemapIndex));
1117
+ else if (write.operation === "recordLoad") this.applyLoad(write, rangeAt(ranges, prepared.resultIndex), rangeAt(ranges, prepared.sourcemapIndex));
1118
+ else if (write.operation === "recordResolveId") {
1119
+ const data = this.getScope(write.scope);
1120
+ let resolveIds = data.resolveIds.get(write.sourceId);
1121
+ if (!resolveIds) {
1122
+ resolveIds = [];
1123
+ data.resolveIds.set(write.sourceId, resolveIds);
1124
+ }
1125
+ resolveIds.push({
1126
+ sourceId: write.sourceId,
1127
+ sourcePublicId: write.sourcePublicId,
1128
+ result: write.info.result,
1129
+ resultPublicId: write.resultPublicId,
1130
+ name: write.info.name,
1131
+ pluginId: write.info.plugin_id,
1132
+ start: write.info.start,
1133
+ end: write.info.end
1134
+ });
1135
+ }
1136
+ }
1137
+ applyTransform(write, result, source, sourcemaps) {
1138
+ const data = this.getScope(write.scope);
1139
+ let transforms = data.transforms.get(write.moduleId);
1140
+ if (!transforms) {
1141
+ transforms = {
1142
+ publicModuleId: write.publicModuleId,
1143
+ invokeCount: 0,
1144
+ items: []
1145
+ };
1146
+ data.transforms.set(write.moduleId, transforms);
1147
+ }
1148
+ if (!transforms.items.some((item) => item.hasResult)) {
1149
+ transforms.items.push({
1150
+ name: DUMMY_LOAD_PLUGIN_NAME,
1151
+ hasResult: true,
1152
+ result: source,
1153
+ resultSize: source?.length ?? 0,
1154
+ start: write.info.start,
1155
+ end: write.info.start,
1156
+ sourcemaps
1157
+ });
1158
+ transforms.invokeCount += 1;
1159
+ }
1160
+ transforms.items.push(toStoredTransformInfo(write.info, result, sourcemaps));
1161
+ }
1162
+ applyLoad(write, result, sourcemaps) {
1163
+ const data = this.getScope(write.scope);
1164
+ const existing = data.transforms.get(write.moduleId);
1165
+ if (existing) this.payloads.reclaim(collectPayloadRanges(existing.items));
1166
+ data.transforms.set(write.moduleId, {
1167
+ publicModuleId: write.publicModuleId,
1168
+ invokeCount: (existing?.invokeCount ?? 0) + 1,
1169
+ items: [toStoredTransformInfo(write.info, result, sourcemaps)]
1170
+ });
1171
+ }
1172
+ invalidateNow(scope, moduleId, publicModuleId) {
1173
+ const data = this.scopes.get(scope);
1174
+ if (!data) {
1175
+ this.pluginCalls.invalidate(scope, /* @__PURE__ */ new Set([publicModuleId]));
1176
+ return;
1177
+ }
1178
+ const invalidIds = /* @__PURE__ */ new Set([moduleId]);
1179
+ const invalidPublicIds = /* @__PURE__ */ new Set([publicModuleId]);
1180
+ let changed = true;
1181
+ while (changed) {
1182
+ changed = false;
1183
+ for (const [id, transforms] of data.transforms) if (invalidIds.has(id) || invalidPublicIds.has(transforms.publicModuleId)) changed = addInvalidId(invalidIds, invalidPublicIds, id, transforms.publicModuleId) || changed;
1184
+ for (const resolveIds of data.resolveIds.values()) for (const resolveId of resolveIds) {
1185
+ if (!matchesInvalid(resolveId.sourceId, resolveId.sourcePublicId, invalidIds, invalidPublicIds) && !matchesInvalid(resolveId.result, resolveId.resultPublicId, invalidIds, invalidPublicIds)) continue;
1186
+ changed = addInvalidId(invalidIds, invalidPublicIds, resolveId.sourceId, resolveId.sourcePublicId) || changed;
1187
+ changed = addInvalidId(invalidIds, invalidPublicIds, resolveId.result, resolveId.resultPublicId) || changed;
1188
+ }
1189
+ }
1190
+ const reclaimed = [];
1191
+ for (const [id, transforms] of data.transforms) {
1192
+ if (!matchesInvalid(id, transforms.publicModuleId, invalidIds, invalidPublicIds)) continue;
1193
+ reclaimed.push(...collectPayloadRanges(transforms.items));
1194
+ data.transforms.delete(id);
1195
+ }
1196
+ this.payloads.reclaim(reclaimed);
1197
+ for (const [sourceId, resolveIds] of data.resolveIds) {
1198
+ const remaining = resolveIds.filter((resolveId) => {
1199
+ return !matchesInvalid(sourceId, resolveId.sourcePublicId, invalidIds, invalidPublicIds) && !matchesInvalid(resolveId.result, resolveId.resultPublicId, invalidIds, invalidPublicIds);
1200
+ });
1201
+ if (remaining.length > 0) data.resolveIds.set(sourceId, remaining);
1202
+ else data.resolveIds.delete(sourceId);
1203
+ }
1204
+ this.pluginCalls.invalidate(scope, invalidPublicIds);
1205
+ }
1206
+ clearScopeNow(scope) {
1207
+ const data = this.scopes.get(scope);
1208
+ if (!data) {
1209
+ this.pluginCalls.clearScope(scope);
1210
+ return;
1211
+ }
1212
+ const ranges = [];
1213
+ for (const transforms of data.transforms.values()) ranges.push(...collectPayloadRanges(transforms.items));
1214
+ this.payloads.reclaim(ranges);
1215
+ this.pluginCalls.clearScope(scope);
1216
+ this.scopes.delete(scope);
1217
+ }
1218
+ async restoreTransformInfo(info) {
1219
+ const [result, sourcemaps] = await Promise.all([info.result ? this.payloads.read(info.result) : void 0, info.sourcemaps ? this.payloads.read(info.sourcemaps) : void 0]);
1220
+ return {
1221
+ name: info.name,
1222
+ plugin_id: info.pluginId,
1223
+ result: info.hasResult ? result : void 0,
1224
+ start: info.start,
1225
+ end: info.end,
1226
+ order: info.order,
1227
+ sourcemaps: sourcemaps == null ? void 0 : parsePayload(sourcemaps),
1228
+ error: info.error
1229
+ };
1230
+ }
1231
+ async readSnapshot(read) {
1232
+ await this.flush();
1233
+ this.activeReaders += 1;
1234
+ try {
1235
+ return await read();
1236
+ } finally {
1237
+ this.activeReaders -= 1;
1238
+ if (this.activeReaders === 0) for (const resolve of this.readerWaiters.splice(0)) resolve();
1239
+ }
1240
+ }
1241
+ waitForReaders() {
1242
+ if (this.activeReaders === 0) return void 0;
1243
+ return new Promise((resolve) => {
1244
+ this.readerWaiters.push(resolve);
1245
+ });
1246
+ }
1247
+ getScope(scope) {
1248
+ let data = this.scopes.get(scope);
1249
+ if (!data) {
1250
+ data = {
1251
+ transforms: /* @__PURE__ */ new Map(),
1252
+ resolveIds: /* @__PURE__ */ new Map()
1253
+ };
1254
+ this.scopes.set(scope, data);
1255
+ }
1256
+ return data;
1257
+ }
1258
+ async closeInternal() {
1259
+ this.closing = true;
1260
+ let thrownError;
1261
+ try {
1262
+ await this.flush();
1263
+ } catch (error) {
1264
+ thrownError = error;
1265
+ }
1266
+ if (this.scheduledPump) {
1267
+ clearImmediate(this.scheduledPump);
1268
+ this.scheduledPump = void 0;
1269
+ }
1270
+ try {
1271
+ await this.payloads.close();
1272
+ } catch (error) {
1273
+ thrownError ??= error;
1274
+ reportStorageError("closing the payload archive", error);
1275
+ }
1276
+ try {
1277
+ await this.pluginCalls.close();
1278
+ } catch (error) {
1279
+ thrownError ??= error;
1280
+ reportStorageError("closing the plugin call archive", error);
1281
+ }
1282
+ this.queue = [];
1283
+ this.queueHead = 0;
1284
+ this.queuedItems = 0;
1285
+ this.queuedBytes = 0;
1286
+ this.scopes.clear();
1287
+ this.closed = true;
1288
+ if (thrownError) throw thrownError;
1289
+ }
1290
+ throwWriteError() {
1291
+ if (this.lastWriteError) throw this.lastWriteError;
1292
+ }
1293
+ };
1294
+ function addMetric(metrics, pluginId, pluginName, duration) {
1295
+ const key = pluginId == null || pluginId < 0 ? pluginName : String(pluginId);
1296
+ let metric = metrics.get(key);
1297
+ if (!metric) {
1298
+ metric = {
1299
+ pluginId,
1300
+ pluginName,
1301
+ invokeCount: 0,
1302
+ totalTime: 0
1303
+ };
1304
+ metrics.set(key, metric);
1305
+ }
1306
+ metric.invokeCount += 1;
1307
+ metric.totalTime += duration;
1308
+ }
1309
+ function addInvalidId(ids, publicIds, id, publicId) {
1310
+ const idSize = ids.size;
1311
+ const publicIdSize = publicIds.size;
1312
+ ids.add(id);
1313
+ publicIds.add(publicId);
1314
+ return ids.size !== idSize || publicIds.size !== publicIdSize;
1315
+ }
1316
+ function matchesInvalid(id, publicId, ids, publicIds) {
1317
+ return ids.has(id) || publicIds.has(publicId);
1318
+ }
1319
+ function collectPayloadRanges(items) {
1320
+ const ranges = /* @__PURE__ */ new Map();
1321
+ for (const item of items) for (const range of [item.result, item.sourcemaps]) if (range) ranges.set(`${range.offset}:${range.length}`, range);
1322
+ return Array.from(ranges.values());
1323
+ }
1324
+ function toStoredTransformInfo(info, result, sourcemaps) {
1325
+ return {
1326
+ name: info.name,
1327
+ pluginId: info.plugin_id,
1328
+ hasResult: info.result != null,
1329
+ result,
1330
+ resultSize: result?.length ?? 0,
1331
+ start: info.start,
1332
+ end: info.end,
1333
+ order: info.order,
1334
+ sourcemaps,
1335
+ error: info.error
1336
+ };
1337
+ }
1338
+ function pushSerializedPayload(values, value) {
1339
+ const serialized = serializePayload(value);
1340
+ if (serialized == null) return void 0;
1341
+ return values.push(serialized) - 1;
1342
+ }
1343
+ function serializePayload(value) {
1344
+ if (value == null) return void 0;
1345
+ try {
1346
+ return JSON.stringify(value);
1347
+ } catch {
1348
+ return JSON.stringify(String(value));
1349
+ }
1350
+ }
1351
+ function parsePayload(value) {
1352
+ try {
1353
+ return JSON.parse(value);
1354
+ } catch {
1355
+ return;
1356
+ }
1357
+ }
1358
+ function rangeAt(ranges, index) {
1359
+ return index == null ? void 0 : ranges[index];
1360
+ }
1361
+ function scopeKey(scope, moduleId) {
1362
+ return `${scope}\0${moduleId}`;
1363
+ }
1364
+ function positiveInteger(value, fallback) {
1365
+ return Number.isFinite(value) && value > 0 ? Math.max(1, Math.floor(value)) : fallback;
1366
+ }
1367
+ function estimateWriteBytes(write) {
1368
+ const pluginCall = write.operation === "invalidate" || write.operation === "clearScope" ? void 0 : getQueuedPluginCall(write);
1369
+ const pluginCallBytes = pluginCall ? 48 + estimateStringBytes(pluginCall.id) + estimateStringBytes(pluginCall.plugin_name) + estimateStringBytes(pluginCall.module) : 0;
1370
+ if (write.operation === "recordTransform") return pluginCallBytes + estimateStringBytes(write.info.result) + estimateStringBytes(write.preTransformCode) + estimateTopLevelSourcemapBytes(write.info.sourcemaps);
1371
+ if (write.operation === "recordLoad") return pluginCallBytes + estimateStringBytes(write.info.result) + estimateTopLevelSourcemapBytes(write.info.sourcemaps);
1372
+ return pluginCallBytes;
1373
+ }
1374
+ function getQueuedPluginCall(write) {
1375
+ return write.operation === "recordPluginCall" ? write.info : write.pluginCall;
1376
+ }
1377
+ function estimateStringBytes(value) {
1378
+ return typeof value === "string" ? value.length * 2 : 0;
1379
+ }
1380
+ function estimateTopLevelSourcemapBytes(value) {
1381
+ if (value == null) return 0;
1382
+ if (typeof value === "string") return value.length * 2;
1383
+ if (typeof value !== "object") return 0;
1384
+ const mappings = value.mappings;
1385
+ return estimateStringBytes(mappings);
1386
+ }
1387
+ function reportStorageError(operation, error) {
1388
+ diagnostics.VDT0003({
1389
+ operation,
1390
+ cause: toError(error)
1391
+ }, { method: "error" });
1392
+ }
1393
+ function toError(error) {
1394
+ return error instanceof Error ? error : new Error(String(error));
1395
+ }
1396
+ //#endregion
1397
+ //#region src/node/inspect/context.ts
1398
+ let viteCount = 0;
1399
+ const contextMap = /* @__PURE__ */ new WeakMap();
1400
+ function setViteInspectContext(devtoolsCtx, ctx) {
1401
+ contextMap.set(devtoolsCtx, ctx);
1402
+ }
1403
+ function getViteInspectContext(devtoolsCtx) {
1404
+ const ctx = contextMap.get(devtoolsCtx);
1405
+ if (!ctx) throw diagnostics.VDT0001();
1406
+ return ctx;
1407
+ }
1408
+ var ViteInspectContext = class ViteInspectContext {
1409
+ store;
1410
+ filter = createFilter();
1411
+ configToInstances = /* @__PURE__ */ new Map();
1412
+ idToInstances = /* @__PURE__ */ new Map();
1413
+ static async create(options = {}) {
1414
+ return new ViteInspectContext(await createViteInspectStore(options));
1415
+ }
1416
+ constructor(store) {
1417
+ this.store = store;
1418
+ }
1419
+ async close() {
1420
+ await this.store.close();
1421
+ }
1422
+ getMetadata() {
1423
+ return {
1424
+ instances: Array.from(this.idToInstances.values(), (vite) => ({
1425
+ root: vite.config.root,
1426
+ vite: vite.id,
1427
+ plugins: vite.config.plugins.map((plugin) => serializePlugin(plugin)),
1428
+ environments: [.../* @__PURE__ */ new Set([...vite.environmentNames, ...vite.environments.keys()])],
1429
+ environmentPlugins: Object.fromEntries(Array.from(vite.environments.entries(), ([name, env]) => {
1430
+ return [name, env.env.getTopLevelConfig().plugins.map((plugin) => vite.config.plugins.indexOf(plugin))];
1431
+ }))
1432
+ })),
1433
+ embedded: false
1434
+ };
1435
+ }
1436
+ getViteContext(configOrId) {
1437
+ if (typeof configOrId === "string") {
1438
+ const vite = this.idToInstances.get(configOrId);
1439
+ if (!vite) throw diagnostics.VDT0002({
1440
+ target: "Vite inspect instances",
1441
+ id: configOrId
1442
+ });
1443
+ return vite;
1444
+ }
1445
+ const existing = this.configToInstances.get(configOrId);
1446
+ if (existing) return existing;
1447
+ const id = `vite${++viteCount}`;
1448
+ const vite = new ViteInspectViteContext(id, this, configOrId);
1449
+ this.idToInstances.set(id, vite);
1450
+ this.configToInstances.set(configOrId, vite);
1451
+ return vite;
1452
+ }
1453
+ getEnvContext(env) {
1454
+ if (!env) return void 0;
1455
+ return this.getViteContext(env.getTopLevelConfig()).getEnvContext(env);
1456
+ }
1457
+ queryEnv(query) {
1458
+ return this.getViteContext(query.vite).getEnvContext(query.env);
1459
+ }
1460
+ };
1461
+ var ViteInspectViteContext = class {
1462
+ id;
1463
+ context;
1464
+ config;
1465
+ environmentNames = /* @__PURE__ */ new Set();
1466
+ environments = /* @__PURE__ */ new Map();
1467
+ data = { serverMetrics: { middleware: {} } };
1468
+ constructor(id, context, config) {
1469
+ this.id = id;
1470
+ this.context = context;
1471
+ this.config = config;
1472
+ }
1473
+ registerEnvironmentNames(names) {
1474
+ for (const name of names) this.environmentNames.add(name);
1475
+ }
1476
+ getEnvContext(env) {
1477
+ if (typeof env === "string") {
1478
+ const envContext = this.environments.get(env);
1479
+ if (!envContext) throw diagnostics.VDT0002({
1480
+ target: `Vite inspect environments for ${this.id}`,
1481
+ id: env
1482
+ });
1483
+ return envContext;
1484
+ }
1485
+ if (env.getTopLevelConfig() !== this.config) throw diagnostics.VDT0002({
1486
+ target: "the current Vite config environments",
1487
+ id: env.name
1488
+ });
1489
+ this.environmentNames.add(env.name);
1490
+ let envContext = this.environments.get(env.name);
1491
+ if (!envContext) {
1492
+ envContext = new ViteInspectEnvironmentContext(this.context, this, env);
1493
+ this.environments.set(env.name, envContext);
1494
+ }
1495
+ return envContext;
1496
+ }
1497
+ };
1498
+ var ViteInspectEnvironmentContext = class {
1499
+ inspectContext;
1500
+ viteContext;
1501
+ env;
1502
+ scope;
1503
+ pluginCallCount = 0;
1504
+ graphModuleIdResolver;
1505
+ constructor(inspectContext, viteContext, env) {
1506
+ this.inspectContext = inspectContext;
1507
+ this.viteContext = viteContext;
1508
+ this.env = env;
1509
+ this.scope = `${viteContext.id}:${env.name}`;
1510
+ }
1511
+ recordTransform(id, info, preTransformCode, plugin) {
1512
+ this.invalidateGraphModuleIdResolver();
1513
+ id = this.normalizeId(id);
1514
+ const publicModuleId = this.getPublicModuleId(id);
1515
+ const pluginId = this.getPluginId(plugin, info.name);
1516
+ const pluginCall = this.createPluginCall({
1517
+ type: "transform",
1518
+ pluginId,
1519
+ pluginName: info.name,
1520
+ module: publicModuleId,
1521
+ start: info.start,
1522
+ end: info.end,
1523
+ unchanged: info.result == null || info.result === preTransformCode
1524
+ });
1525
+ this.inspectContext.store.recordTransform(this.scope, id, publicModuleId, {
1526
+ ...info,
1527
+ plugin_id: pluginId
1528
+ }, preTransformCode, pluginCall);
1529
+ }
1530
+ recordLoad(id, info, plugin) {
1531
+ this.invalidateGraphModuleIdResolver();
1532
+ id = this.normalizeId(id);
1533
+ const publicModuleId = this.getPublicModuleId(id);
1534
+ const pluginId = this.getPluginId(plugin, info.name);
1535
+ const pluginCall = this.createPluginCall({
1536
+ type: "load",
1537
+ pluginId,
1538
+ pluginName: info.name,
1539
+ module: publicModuleId,
1540
+ start: info.start,
1541
+ end: info.end,
1542
+ unchanged: info.result == null
1543
+ });
1544
+ this.inspectContext.store.recordLoad(this.scope, id, publicModuleId, {
1545
+ ...info,
1546
+ plugin_id: pluginId
1547
+ }, pluginCall);
1548
+ }
1549
+ recordLoadCall(id, info, plugin) {
1550
+ id = this.normalizeId(id);
1551
+ const publicModuleId = this.getPublicModuleId(id);
1552
+ const pluginCall = this.createPluginCall({
1553
+ type: "load",
1554
+ pluginId: this.getPluginId(plugin, info.name),
1555
+ pluginName: info.name,
1556
+ module: publicModuleId,
1557
+ start: info.start,
1558
+ end: info.end,
1559
+ unchanged: true
1560
+ });
1561
+ if (!pluginCall) return;
1562
+ this.inspectContext.store.recordPluginCall(this.scope, pluginCall);
1563
+ }
1564
+ recordResolveId(id, info, plugin) {
1565
+ this.invalidateGraphModuleIdResolver();
1566
+ id = this.normalizeId(id);
1567
+ const pluginId = this.getPluginId(plugin, info.name);
1568
+ const normalizedResult = this.normalizeId(info.result);
1569
+ const sourcePublicId = this.getPublicModuleId(id);
1570
+ const resultPublicId = this.getPublicModuleId(normalizedResult);
1571
+ const pluginCall = this.createPluginCall({
1572
+ type: "resolve",
1573
+ pluginId,
1574
+ pluginName: info.name,
1575
+ module: resultPublicId,
1576
+ start: info.start,
1577
+ end: info.end
1578
+ });
1579
+ this.inspectContext.store.recordResolveId(this.scope, id, sourcePublicId, {
1580
+ ...info,
1581
+ plugin_id: pluginId,
1582
+ result: normalizedResult
1583
+ }, resultPublicId, pluginCall);
1584
+ }
1585
+ recordResolveIdCall(id, info, plugin) {
1586
+ id = this.normalizeId(id);
1587
+ const result = info.result ? this.normalizeId(info.result) : id;
1588
+ const resultPublicId = this.getPublicModuleId(result);
1589
+ const pluginCall = this.createPluginCall({
1590
+ type: "resolve",
1591
+ pluginId: this.getPluginId(plugin, info.name),
1592
+ pluginName: info.name,
1593
+ module: resultPublicId,
1594
+ start: info.start,
1595
+ end: info.end
1596
+ });
1597
+ if (!pluginCall) return;
1598
+ this.inspectContext.store.recordPluginCall(this.scope, pluginCall);
1599
+ }
1600
+ invalidate(id) {
1601
+ this.invalidateGraphModuleIdResolver();
1602
+ const normalizedId = this.normalizeId(id);
1603
+ const publicModuleId = this.getPublicModuleId(normalizedId);
1604
+ this.inspectContext.store.invalidate(this.scope, normalizedId, publicModuleId);
1605
+ }
1606
+ clearScope() {
1607
+ this.invalidateGraphModuleIdResolver();
1608
+ this.inspectContext.store.clearScope(this.scope);
1609
+ }
1610
+ normalizeId(id) {
1611
+ return removeVersionQuery(id);
1612
+ }
1613
+ getModuleIdBaseRoot() {
1614
+ return this.env.getTopLevelConfig().root;
1615
+ }
1616
+ getPublicModuleId(id) {
1617
+ return normalizeModuleId(this.normalizeId(id), this.getModuleIdBaseRoot());
1618
+ }
1619
+ async getModuleId(id) {
1620
+ const normalizedId = this.getPublicModuleId(id);
1621
+ const moduleId = await this.inspectContext.store.findModuleId(this.scope, normalizedId);
1622
+ if (moduleId) return moduleId;
1623
+ if (normalizedId.startsWith("./") || normalizedId.startsWith("../")) return resolve(this.getModuleIdBaseRoot(), normalizedId).replace(/\\/g, "/");
1624
+ return normalizedId;
1625
+ }
1626
+ getModuleIds() {
1627
+ return this.inspectContext.store.getModuleIds(this.scope);
1628
+ }
1629
+ getPluginId(plugin, name) {
1630
+ if (plugin) {
1631
+ const index = this.env.getTopLevelConfig().plugins.indexOf(plugin);
1632
+ if (index >= 0) return index;
1633
+ }
1634
+ return this.env.getTopLevelConfig().plugins.findIndex((item) => item.name === name);
1635
+ }
1636
+ createPluginCall(options) {
1637
+ if (options.pluginId < 0) return void 0;
1638
+ return {
1639
+ type: options.type,
1640
+ id: `${options.type}:${options.pluginId}:${this.pluginCallCount++}`,
1641
+ duration: Math.max(0, options.end - options.start),
1642
+ plugin_id: options.pluginId,
1643
+ plugin_name: options.pluginName,
1644
+ module: options.module,
1645
+ timestamp_start: options.start,
1646
+ timestamp_end: options.end,
1647
+ unchanged: options.unchanged
1648
+ };
1649
+ }
1650
+ async getModulesList(pluginCtx) {
1651
+ const modules = await getModulesList(this, pluginCtx);
1652
+ this.graphModuleIdResolver = createGraphModuleIdResolver(modules.map((module) => module.id), this.env.getTopLevelConfig().resolve?.extensions ?? []);
1653
+ return modules;
1654
+ }
1655
+ async getGraphModuleIdResolver() {
1656
+ if (!this.graphModuleIdResolver) await this.getModulesList();
1657
+ return this.graphModuleIdResolver;
1658
+ }
1659
+ async resolveId(id = "") {
1660
+ id = await this.getModuleId(id);
1661
+ if (id.startsWith("./")) id = resolve(this.getModuleIdBaseRoot(), id).replace(/\\/g, "/");
1662
+ return this.resolveIdRecursive(id);
1663
+ }
1664
+ async resolveIdRecursive(id, seen = /* @__PURE__ */ new Set()) {
1665
+ if (seen.has(id)) return id;
1666
+ seen.add(id);
1667
+ const resolved = await this.inspectContext.store.getFirstResolveResult(this.scope, id);
1668
+ return resolved ? this.resolveIdRecursive(this.normalizeId(resolved), seen) : id;
1669
+ }
1670
+ async getPluginMetrics() {
1671
+ return getPluginMetrics(this);
1672
+ }
1673
+ async getModuleTransformInfo(id) {
1674
+ return getModuleTransformInfo(this, id);
1675
+ }
1676
+ async getPluginDetails(pluginId) {
1677
+ return getPluginDetails(this, pluginId);
1678
+ }
1679
+ async clearModuleTransform(id) {
1680
+ await this.clearId(id);
1681
+ try {
1682
+ if (this.env.mode === "dev") await this.env.transformRequest(id);
1683
+ } catch {}
1684
+ }
1685
+ async clearId(moduleId) {
1686
+ const id = await this.resolveId(moduleId);
1687
+ if (!id) return;
1688
+ const moduleGraph = this.env.mode === "dev" ? this.env.moduleGraph : void 0;
1689
+ const mod = moduleGraph?.getModuleById(id);
1690
+ if (mod) moduleGraph?.invalidateModule(mod);
1691
+ else this.invalidate(id);
1692
+ }
1693
+ invalidateGraphModuleIdResolver() {
1694
+ this.graphModuleIdResolver = void 0;
1695
+ }
1696
+ };
1697
+ //#endregion
1698
+ //#region src/node/rpc/functions/vite-clear-module-transform.ts
1699
+ const viteClearModuleTransform = defineRpcFunction({
1700
+ name: "vite:inspect:clear-module-transform",
1701
+ type: "action",
1702
+ jsonSerializable: true,
1703
+ setup: (devtoolsCtx) => {
1704
+ const ctx = getViteInspectContext(devtoolsCtx);
1705
+ return { handler: async (query, id) => {
1706
+ await ctx.queryEnv(query).clearModuleTransform(id);
1707
+ } };
1708
+ }
1709
+ });
1710
+ //#endregion
1711
+ //#region src/node/rpc/functions/vite-env-info.ts
1712
+ const viteEnvInfo = defineRpcFunction({
1713
+ name: "vite:env-info",
1714
+ type: "query",
1715
+ jsonSerializable: true,
1716
+ setup: () => {
1717
+ return { handler: async () => {
1718
+ const { default: { helpers } } = await import("envinfo");
1719
+ const [cpu, os, memory, node, bun, npm, pnpm, yarn] = await Promise.all([
1720
+ helpers.getCPUInfo().then(([, res]) => res),
1721
+ helpers.getOSInfo().then(([, res]) => res),
1722
+ helpers.getMemoryInfo().then(([, res]) => res),
1723
+ helpers.getNodeInfo().then(([, res]) => res),
1724
+ helpers.getbunInfo().then(([, res]) => res),
1725
+ helpers.getnpmInfo().then(([, res]) => res),
1726
+ helpers.getpnpmInfo().then(([, res]) => res),
1727
+ helpers.getYarnInfo().then(([, res]) => res)
1728
+ ]);
1729
+ return {
1730
+ cpu,
1731
+ os,
1732
+ memory,
1733
+ node,
1734
+ bun,
1735
+ npm,
1736
+ pnpm,
1737
+ yarn
1738
+ };
1739
+ } };
1740
+ }
1741
+ });
1742
+ //#endregion
1743
+ //#region src/node/rpc/functions/vite-get-metadata.ts
1744
+ const viteGetMetadata = defineRpcFunction({
1745
+ name: "vite:inspect:get-metadata",
1746
+ type: "query",
1747
+ jsonSerializable: true,
1748
+ dump: async () => ({ inputs: [[]] }),
1749
+ setup: (devtoolsCtx) => {
1750
+ const ctx = getViteInspectContext(devtoolsCtx);
1751
+ return { handler: async () => ctx.getMetadata() };
1752
+ }
1753
+ });
1754
+ //#endregion
1755
+ //#region src/node/rpc/functions/vite-get-module-transform-info.ts
1756
+ const viteGetModuleTransformInfo = defineRpcFunction({
1757
+ name: "vite:inspect:get-module-transform-info",
1758
+ type: "query",
1759
+ jsonSerializable: true,
1760
+ dump: async (devtoolsCtx) => {
1761
+ return { inputs: (await getAllModuleIds(getViteInspectContext(devtoolsCtx))).map(([query, id]) => [query, id]) };
1762
+ },
1763
+ setup: (devtoolsCtx) => {
1764
+ const ctx = getViteInspectContext(devtoolsCtx);
1765
+ return { handler: async (query, id) => ctx.queryEnv(query).getModuleTransformInfo(id) };
1766
+ }
1767
+ });
1768
+ //#endregion
1769
+ //#region src/node/rpc/functions/vite-get-modules-list.ts
1770
+ const viteGetModulesList = defineRpcFunction({
1771
+ name: "vite:inspect:get-modules-list",
1772
+ type: "query",
1773
+ jsonSerializable: true,
1774
+ dump: async (devtoolsCtx) => {
1775
+ return { inputs: getAllQueryEnvs(getViteInspectContext(devtoolsCtx)).map((query) => [query]) };
1776
+ },
1777
+ setup: (devtoolsCtx) => {
1778
+ const ctx = getViteInspectContext(devtoolsCtx);
1779
+ return { handler: async (query) => ctx.queryEnv(query).getModulesList() };
1780
+ }
1781
+ });
1782
+ //#endregion
1783
+ //#region src/node/rpc/functions/vite-get-plugin-details.ts
1784
+ const viteGetPluginDetails = defineRpcFunction({
1785
+ name: "vite:inspect:get-plugin-details",
1786
+ type: "query",
1787
+ jsonSerializable: true,
1788
+ setup: (devtoolsCtx) => {
1789
+ const ctx = getViteInspectContext(devtoolsCtx);
1790
+ return { handler: async (query, id) => ctx.queryEnv(query).getPluginDetails(Number(id)) };
1791
+ }
1792
+ });
1793
+ //#endregion
1794
+ //#region src/node/rpc/functions/vite-get-plugin-metrics.ts
1795
+ const viteGetPluginMetrics = defineRpcFunction({
1796
+ name: "vite:inspect:get-plugin-metrics",
1797
+ type: "query",
1798
+ jsonSerializable: true,
1799
+ dump: async (devtoolsCtx) => {
1800
+ return { inputs: getAllQueryEnvs(getViteInspectContext(devtoolsCtx)).map((query) => [query]) };
1801
+ },
1802
+ setup: (devtoolsCtx) => {
1803
+ const ctx = getViteInspectContext(devtoolsCtx);
1804
+ return { handler: async (query) => ctx.queryEnv(query).getPluginMetrics() };
1805
+ }
1806
+ });
1807
+ //#endregion
1808
+ //#region src/node/rpc/functions/vite-get-server-metrics.ts
1809
+ const viteGetServerMetrics = defineRpcFunction({
1810
+ name: "vite:inspect:get-server-metrics",
1811
+ type: "query",
1812
+ jsonSerializable: true,
1813
+ dump: async (devtoolsCtx) => {
1814
+ return { inputs: getAllQueryEnvs(getViteInspectContext(devtoolsCtx)).map((query) => [query]) };
1815
+ },
1816
+ setup: (devtoolsCtx) => {
1817
+ const ctx = getViteInspectContext(devtoolsCtx);
1818
+ return { handler: async (query) => ctx.getViteContext(query.vite).data.serverMetrics };
1819
+ }
1820
+ });
1821
+ //#endregion
1822
+ //#region src/node/rpc/functions/vite-meta-info.ts
1823
+ const viteMetaInfo = defineRpcFunction({
1824
+ name: "vite:meta-info",
1825
+ type: "query",
1826
+ jsonSerializable: true,
1827
+ setup: (context) => {
1828
+ return { handler: async () => {
1829
+ const { root, base, plugins } = context.viteConfig;
1830
+ return {
1831
+ root,
1832
+ base,
1833
+ plugins: plugins.map((p) => p.name)
1834
+ };
1835
+ } };
1836
+ }
1837
+ });
1838
+ //#endregion
1839
+ //#region src/node/rpc/functions/vite-resolve-id.ts
1840
+ const viteResolveId = defineRpcFunction({
1841
+ name: "vite:inspect:resolve-id",
1842
+ type: "query",
1843
+ jsonSerializable: true,
1844
+ dump: async (devtoolsCtx) => {
1845
+ return { inputs: (await getAllModuleIds(getViteInspectContext(devtoolsCtx))).map(([query, id]) => [query, id]) };
1846
+ },
1847
+ setup: (devtoolsCtx) => {
1848
+ const ctx = getViteInspectContext(devtoolsCtx);
1849
+ return { handler: async (query, id) => ctx.queryEnv(query).resolveId(id) };
1850
+ }
1851
+ });
1852
+ //#endregion
1853
+ //#region src/node/rpc/index.ts
1854
+ const VITE_INSPECT_MODULE_UPDATED_STATE_KEY = "vite:inspect:module-updated";
1855
+ const viteRpcFunctions = [viteMetaInfo, viteEnvInfo];
1856
+ const inspectRpcFunctions = [
1857
+ viteClearModuleTransform,
1858
+ viteGetMetadata,
1859
+ viteGetModulesList,
1860
+ viteGetPluginMetrics,
1861
+ viteGetPluginDetails,
1862
+ viteGetModuleTransformInfo,
1863
+ viteResolveId,
1864
+ viteGetServerMetrics
1865
+ ];
1866
+ [...viteRpcFunctions, ...inspectRpcFunctions];
1867
+ //#endregion
1868
+ //#region src/node/inspect/server.ts
1869
+ const timestampRE = /\bt=\d{13}&?\b/;
1870
+ const trailingSeparatorRE = /[?&]$/;
1871
+ const transformRequestStorage = new AsyncLocalStorage();
1872
+ const environmentInvalidationStates = /* @__PURE__ */ new WeakMap();
1873
+ function trackTransformRequestId(id) {
1874
+ const request = transformRequestStorage.getStore();
1875
+ if (request?.active) request.ids.add(normalizeRequestId(id));
1876
+ return request?.active ? request : void 0;
1877
+ }
1878
+ function isTransformRequestStale(request) {
1879
+ return request?.stale === true;
1880
+ }
1881
+ function setupEnvironmentInvalidation(server, vite) {
1882
+ Object.values(server.environments).forEach((env) => {
1883
+ const envContext = vite.getEnvContext(env);
1884
+ const existingState = environmentInvalidationStates.get(env);
1885
+ if (existingState) {
1886
+ existingState.contexts.add(envContext);
1887
+ return;
1888
+ }
1889
+ const state = {
1890
+ activeRequests: /* @__PURE__ */ new Set(),
1891
+ contexts: /* @__PURE__ */ new Set([envContext])
1892
+ };
1893
+ environmentInvalidationStates.set(env, state);
1894
+ const transformRequest = env.transformRequest;
1895
+ env.transformRequest = function(...args) {
1896
+ const request = {
1897
+ active: true,
1898
+ ids: /* @__PURE__ */ new Set([normalizeRequestId(args[0])]),
1899
+ stale: false
1900
+ };
1901
+ state.activeRequests.add(request);
1902
+ return transformRequestStorage.run(request, () => transformRequest.apply(this, args)).finally(() => {
1903
+ request.active = false;
1904
+ request.ids.clear();
1905
+ state.activeRequests.delete(request);
1906
+ });
1907
+ };
1908
+ const invalidateModule = env.moduleGraph.invalidateModule;
1909
+ env.moduleGraph.invalidateModule = function(...args) {
1910
+ const mod = args[0];
1911
+ const seen = args[1];
1912
+ const softInvalidate = args[4] === true;
1913
+ const alreadyHardInvalidated = mod?.invalidationState === "HARD_INVALIDATED";
1914
+ const shouldInvalidateInspect = !softInvalidate && (!seen?.has(mod) || !alreadyHardInvalidated);
1915
+ if (mod) {
1916
+ markStaleRequests(state.activeRequests, mod.id, mod.url);
1917
+ if (mod.id && shouldInvalidateInspect) for (const context of state.contexts) context.invalidate(mod.id);
1918
+ }
1919
+ return invalidateModule.apply(this, args);
1920
+ };
1921
+ });
1922
+ }
1923
+ function markStaleRequests(requests, ...ids) {
1924
+ const normalizedIds = ids.filter((id) => id != null).map(normalizeRequestId);
1925
+ for (const request of requests) if (normalizedIds.some((id) => request.ids.has(id))) request.stale = true;
1926
+ }
1927
+ function normalizeRequestId(id) {
1928
+ return id.replace(timestampRE, "").replace(trailingSeparatorRE, "");
1929
+ }
1930
+ function setupMiddlewarePerformance(vite, middlewares) {
1931
+ let firstMiddlewareIndex = -1;
1932
+ middlewares.forEach((middleware, index) => {
1933
+ const originalHandle = middleware.handle;
1934
+ if (typeof originalHandle !== "function" || !originalHandle.name) return;
1935
+ middleware.handle = function(...middlewareArgs) {
1936
+ let req;
1937
+ if (middlewareArgs.length === 4) req = middlewareArgs[1];
1938
+ else req = middlewareArgs[0];
1939
+ const start = Date.now();
1940
+ const url = req.url?.replace(timestampRE, "").replace(trailingSeparatorRE, "") || "/";
1941
+ const metrics = vite.data.serverMetrics.middleware[url] ||= [];
1942
+ if (firstMiddlewareIndex < 0) firstMiddlewareIndex = index;
1943
+ if (index === firstMiddlewareIndex) metrics.length = 0;
1944
+ const result = originalHandle.apply(this, middlewareArgs);
1945
+ Promise.resolve(result).then(() => {
1946
+ const total = Date.now() - start;
1947
+ metrics.push({
1948
+ self: metrics.length ? Math.max(total - (metrics.at(-1)?.total || 0), 0) : total,
1949
+ total,
1950
+ name: originalHandle.name
1951
+ });
1952
+ });
1953
+ return result;
1954
+ };
1955
+ Object.defineProperty(middleware.handle, "name", {
1956
+ value: originalHandle.name,
1957
+ configurable: true,
1958
+ enumerable: true
1959
+ });
1960
+ });
1961
+ }
1962
+ //#endregion
1963
+ //#region src/node/inspect/hijack.ts
1964
+ function hijackHook(plugin, name, wrapper) {
1965
+ const hook = plugin[name];
1966
+ if (!hook) return;
1967
+ let order = `${plugin.order || plugin.enforce || "normal"}`;
1968
+ if (typeof hook === "object" && "handler" in hook) {
1969
+ const oldFn = hook.handler;
1970
+ order += `-${hook.order || hook.enforce || "normal"}`;
1971
+ hook.handler = function(...args) {
1972
+ return wrapper(oldFn, this, args, order);
1973
+ };
1974
+ } else if (typeof hook === "object" && "transform" in hook) {
1975
+ const oldFn = hook.transform;
1976
+ order += `-${hook.order || hook.enforce || "normal"}`;
1977
+ hook.transform = function(...args) {
1978
+ return wrapper(oldFn, this, args, order);
1979
+ };
1980
+ } else {
1981
+ const oldFn = hook;
1982
+ const mutablePlugin = plugin;
1983
+ mutablePlugin[name] = function(...args) {
1984
+ return wrapper(oldFn, this, args, order);
1985
+ };
1986
+ }
1987
+ }
1988
+ const hijackedPlugins = /* @__PURE__ */ new WeakSet();
1989
+ function hijackPlugin(plugin, ctx) {
1990
+ if (hijackedPlugins.has(plugin)) return;
1991
+ hijackedPlugins.add(plugin);
1992
+ hijackHook(plugin, "transform", async (fn, context, args, order) => {
1993
+ const code = args[0];
1994
+ const id = args[1];
1995
+ const transformRequest = trackTransformRequestId(id);
1996
+ const envContext = ctx.filter(id) ? ctx.getEnvContext(context?.environment) : void 0;
1997
+ let resultValue;
1998
+ let error;
1999
+ const start = Date.now();
2000
+ try {
2001
+ resultValue = await fn.apply(context, args);
2002
+ } catch (err) {
2003
+ error = err;
2004
+ }
2005
+ const end = Date.now();
2006
+ const result = error ? "[Error]" : typeof resultValue === "string" ? resultValue : resultValue?.code?.toString();
2007
+ if (envContext && !isTransformRequestStale(transformRequest)) {
2008
+ const sourcemaps = typeof resultValue === "string" ? null : resultValue?.map;
2009
+ envContext.recordTransform(id, {
2010
+ name: plugin.name,
2011
+ result,
2012
+ start,
2013
+ end,
2014
+ order,
2015
+ sourcemaps,
2016
+ error: error ? parseError(error) : void 0
2017
+ }, code, plugin);
2018
+ }
2019
+ if (error) throw error;
2020
+ return resultValue;
2021
+ });
2022
+ hijackHook(plugin, "load", async (fn, context, args) => {
2023
+ const id = args[0];
2024
+ const transformRequest = trackTransformRequestId(id);
2025
+ const envContext = ctx.getEnvContext(context?.environment);
2026
+ let resultValue;
2027
+ let error;
2028
+ const start = Date.now();
2029
+ try {
2030
+ resultValue = await fn.apply(context, args);
2031
+ } catch (err) {
2032
+ error = err;
2033
+ }
2034
+ const end = Date.now();
2035
+ const result = error ? "[Error]" : typeof resultValue === "string" ? resultValue : resultValue?.code;
2036
+ const sourcemaps = typeof resultValue === "string" ? null : resultValue?.map;
2037
+ const info = {
2038
+ name: plugin.name,
2039
+ result,
2040
+ start,
2041
+ end,
2042
+ sourcemaps,
2043
+ error: error ? parseError(error) : void 0
2044
+ };
2045
+ if (result != null && envContext && !isTransformRequestStale(transformRequest)) envContext.recordLoad(id, {
2046
+ ...info,
2047
+ result
2048
+ }, plugin);
2049
+ else if (envContext && !isTransformRequestStale(transformRequest)) envContext.recordLoadCall(id, {
2050
+ name: plugin.name,
2051
+ start,
2052
+ end,
2053
+ error: error ? parseError(error) : void 0
2054
+ }, plugin);
2055
+ if (error) throw error;
2056
+ return resultValue;
2057
+ });
2058
+ hijackHook(plugin, "resolveId", async (fn, context, args) => {
2059
+ const id = args[0];
2060
+ const transformRequest = trackTransformRequestId(id);
2061
+ const envContext = ctx.filter(id) ? ctx.getEnvContext(context?.environment) : void 0;
2062
+ let resultValue;
2063
+ let error;
2064
+ const start = Date.now();
2065
+ try {
2066
+ resultValue = await fn.apply(context, args);
2067
+ } catch (err) {
2068
+ error = err;
2069
+ }
2070
+ const end = Date.now();
2071
+ if (!envContext) {
2072
+ if (error) throw error;
2073
+ return resultValue;
2074
+ }
2075
+ if (isTransformRequestStale(transformRequest)) {
2076
+ if (error) throw error;
2077
+ return resultValue;
2078
+ }
2079
+ const result = error ? stringifyError(error) : typeof resultValue === "object" ? resultValue?.id : resultValue;
2080
+ if (result && result !== id) envContext.recordResolveId(id, {
2081
+ name: plugin.name,
2082
+ result,
2083
+ start,
2084
+ end,
2085
+ error
2086
+ }, plugin);
2087
+ else envContext.recordResolveIdCall(id, {
2088
+ name: plugin.name,
2089
+ result,
2090
+ start,
2091
+ end,
2092
+ error
2093
+ }, plugin);
2094
+ if (error) throw error;
2095
+ return resultValue;
2096
+ });
2097
+ }
2098
+ //#endregion
2099
+ //#region src/node/inspect/plugin.ts
2100
+ function DevToolsViteInspect() {
2101
+ let inspectContext;
2102
+ let inspectContextPromise;
2103
+ let closingInspectContext;
2104
+ let inspectStorageDir;
2105
+ let inspectModuleUpdatedState;
2106
+ function notifyInspectModuleUpdated(ids = null) {
2107
+ inspectModuleUpdatedState?.mutate((state) => {
2108
+ state.version += 1;
2109
+ state.ids = ids;
2110
+ state.updatedAt = Date.now();
2111
+ });
2112
+ }
2113
+ async function createInspectContext(config) {
2114
+ const storageDir = join(config.cacheDir || join(config.root, "node_modules/.vite"), "devtools", "inspect");
2115
+ inspectStorageDir = storageDir;
2116
+ removeInspectStorage();
2117
+ try {
2118
+ const ctx = await ViteInspectContext.create({ filename: join(storageDir, "payloads.bin") });
2119
+ inspectContext = ctx;
2120
+ return ctx;
2121
+ } catch (error) {
2122
+ removeInspectStorage();
2123
+ throw error;
2124
+ }
2125
+ }
2126
+ function ensureInspectContext(config) {
2127
+ if (config.command !== "serve") return Promise.resolve(void 0);
2128
+ inspectContextPromise ??= createInspectContext(config);
2129
+ return inspectContextPromise;
2130
+ }
2131
+ async function closeInspectContext() {
2132
+ const ctx = inspectContext ?? await inspectContextPromise;
2133
+ if (!ctx) return;
2134
+ closingInspectContext ??= (async () => {
2135
+ await ctx.close();
2136
+ })();
2137
+ await closingInspectContext;
2138
+ }
2139
+ function removeInspectStorage() {
2140
+ if (inspectStorageDir) rmSync(inspectStorageDir, {
2141
+ recursive: true,
2142
+ force: true
2143
+ });
2144
+ }
2145
+ async function resolveInspectContext() {
2146
+ if (inspectContext) return inspectContext;
2147
+ return inspectContextPromise;
2148
+ }
2149
+ return {
2150
+ name: "vite:devtools:vite-inspect",
2151
+ enforce: "pre",
2152
+ devtools: { async setup(ctx) {
2153
+ ctx.diagnostics.register(diagnostics);
2154
+ for (const fn of viteRpcFunctions) ctx.rpc.register(fn);
2155
+ const currentInspectContext = await resolveInspectContext();
2156
+ if (currentInspectContext) {
2157
+ setViteInspectContext(ctx, currentInspectContext);
2158
+ for (const fn of inspectRpcFunctions) ctx.rpc.register(fn);
2159
+ inspectModuleUpdatedState = await ctx.rpc.sharedState.get(VITE_INSPECT_MODULE_UPDATED_STATE_KEY, { initialValue: {
2160
+ version: 0,
2161
+ ids: null,
2162
+ updatedAt: 0
2163
+ } });
2164
+ if (ctx.viteServer) {
2165
+ const debouncedNotify = debounce(() => {
2166
+ notifyInspectModuleUpdated();
2167
+ }, 100);
2168
+ ctx.viteServer.middlewares.use((_req, _res, next) => {
2169
+ debouncedNotify();
2170
+ next();
2171
+ });
2172
+ }
2173
+ }
2174
+ } },
2175
+ async configResolved(config) {
2176
+ const ctx = await ensureInspectContext(config);
2177
+ if (!ctx) return;
2178
+ const vite = ctx.getViteContext(config);
2179
+ vite.registerEnvironmentNames(Object.keys(config.environments));
2180
+ config.plugins.forEach((plugin) => hijackPlugin(plugin, ctx));
2181
+ const mutableConfig = config;
2182
+ const createResolver = mutableConfig.createResolver;
2183
+ mutableConfig.createResolver = function(...args) {
2184
+ const resolver = createResolver.apply(this, args);
2185
+ return async (...resolverArgs) => {
2186
+ const [id, , aliasOnly, ssr] = resolverArgs;
2187
+ const transformRequest = trackTransformRequestId(id);
2188
+ const start = Date.now();
2189
+ const result = await resolver(...resolverArgs);
2190
+ const end = Date.now();
2191
+ if (result && result !== id && !isTransformRequestStale(transformRequest)) {
2192
+ const pluginName = aliasOnly ? "alias" : "vite:resolve (+alias)";
2193
+ const envName = ssr ? "ssr" : "client";
2194
+ vite.environments.get(envName)?.recordResolveId(id, {
2195
+ name: pluginName,
2196
+ result,
2197
+ start,
2198
+ end
2199
+ });
2200
+ }
2201
+ return result;
2202
+ };
2203
+ };
2204
+ },
2205
+ configureServer(server) {
2206
+ const ctx = inspectContext;
2207
+ if (!ctx) return;
2208
+ const closeServer = server.close.bind(server);
2209
+ server.close = async () => {
2210
+ try {
2211
+ await closeServer();
2212
+ } finally {
2213
+ await closeInspectContext();
2214
+ }
2215
+ };
2216
+ const vite = ctx.getViteContext(server.config);
2217
+ Object.values(server.environments).forEach((env) => vite.getEnvContext(env));
2218
+ setupEnvironmentInvalidation(server, vite);
2219
+ return () => {
2220
+ setupMiddlewarePerformance(vite, server.middlewares.stack);
2221
+ };
2222
+ },
2223
+ hotUpdate({ modules }) {
2224
+ if (!inspectContext) return;
2225
+ notifyInspectModuleUpdated(modules.map((module) => module.id).filter((id) => id != null));
2226
+ },
2227
+ sharedDuringBuild: true
2228
+ };
2229
+ }
2230
+ //#endregion
2231
+ //#region src/node/plugin.ts
2232
+ const VITE_DEVTOOLS_BASE = "/__devtools-vite/";
2233
+ function DevToolsViteUI() {
2234
+ return [DevToolsViteInspect(), DevToolsViteUIPlugin()];
2235
+ }
2236
+ function DevToolsViteUIPlugin() {
2237
+ return {
2238
+ name: "vite:devtools:vite-ui",
2239
+ enforce: "pre",
2240
+ devtools: { setup(ctx) {
2241
+ ctx.views.hostStatic(VITE_DEVTOOLS_BASE, clientPublicDir);
2242
+ ctx.docks.register({
2243
+ id: "vite",
2244
+ title: "Vite",
2245
+ icon: `${VITE_DEVTOOLS_BASE}favicon.svg`,
2246
+ groupId: DEVTOOLS_VITEPLUS_GROUP_ID,
2247
+ type: "iframe",
2248
+ url: VITE_DEVTOOLS_BASE
2249
+ });
2250
+ } }
2251
+ };
2252
+ }
2253
+ //#endregion
2254
+ export { DevToolsViteInspect, DevToolsViteUI, DevToolsViteUIPlugin };