@warlock.js/devtools 5.25.0

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 (68) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +35 -0
  4. package/cjs/index.cjs +694 -0
  5. package/cjs/index.cjs.map +1 -0
  6. package/cjs/server-DHYSVive.cjs +286 -0
  7. package/cjs/server-DHYSVive.cjs.map +1 -0
  8. package/esm/caller-location.mjs +33 -0
  9. package/esm/caller-location.mjs.map +1 -0
  10. package/esm/collector.mjs +185 -0
  11. package/esm/collector.mjs.map +1 -0
  12. package/esm/current-request-id.mjs +24 -0
  13. package/esm/current-request-id.mjs.map +1 -0
  14. package/esm/devtools-connector.d.mts +26 -0
  15. package/esm/devtools-connector.d.mts.map +1 -0
  16. package/esm/devtools-connector.mjs +112 -0
  17. package/esm/devtools-connector.mjs.map +1 -0
  18. package/esm/index.d.mts +3 -0
  19. package/esm/index.mjs +3 -0
  20. package/esm/n-plus-one.mjs +36 -0
  21. package/esm/n-plus-one.mjs.map +1 -0
  22. package/esm/options.mjs +19 -0
  23. package/esm/options.mjs.map +1 -0
  24. package/esm/query-shape.mjs +27 -0
  25. package/esm/query-shape.mjs.map +1 -0
  26. package/esm/safe-value.mjs +63 -0
  27. package/esm/safe-value.mjs.map +1 -0
  28. package/esm/server/background-routes.mjs +9 -0
  29. package/esm/server/background-routes.mjs.map +1 -0
  30. package/esm/server/explain-route.mjs +37 -0
  31. package/esm/server/explain-route.mjs.map +1 -0
  32. package/esm/server/guard.mjs +30 -0
  33. package/esm/server/guard.mjs.map +1 -0
  34. package/esm/server/index.mjs +37 -0
  35. package/esm/server/index.mjs.map +1 -0
  36. package/esm/server/log-routes.mjs +12 -0
  37. package/esm/server/log-routes.mjs.map +1 -0
  38. package/esm/server/mail-routes.mjs +27 -0
  39. package/esm/server/mail-routes.mjs.map +1 -0
  40. package/esm/server/requests-routes.mjs +21 -0
  41. package/esm/server/requests-routes.mjs.map +1 -0
  42. package/esm/server/route-routes.mjs +9 -0
  43. package/esm/server/route-routes.mjs.map +1 -0
  44. package/esm/server/stream-route.mjs +32 -0
  45. package/esm/server/stream-route.mjs.map +1 -0
  46. package/esm/server/ui-assets.mjs +38 -0
  47. package/esm/server/ui-assets.mjs.map +1 -0
  48. package/esm/sources/cache-source.mjs +51 -0
  49. package/esm/sources/cache-source.mjs.map +1 -0
  50. package/esm/sources/log-source.mjs +46 -0
  51. package/esm/sources/log-source.mjs.map +1 -0
  52. package/esm/sources/mail-source.mjs +48 -0
  53. package/esm/sources/mail-source.mjs.map +1 -0
  54. package/esm/sources/query-source.mjs +52 -0
  55. package/esm/sources/query-source.mjs.map +1 -0
  56. package/esm/sources/tracing-source.mjs +47 -0
  57. package/esm/sources/tracing-source.mjs.map +1 -0
  58. package/esm/types.d.mts +213 -0
  59. package/esm/types.d.mts.map +1 -0
  60. package/esm/ui-root.mjs +40 -0
  61. package/esm/ui-root.mjs.map +1 -0
  62. package/llms-full.txt +78 -0
  63. package/llms.txt +9 -0
  64. package/package.json +52 -0
  65. package/skills/devtools-overview/SKILL.md +68 -0
  66. package/ui/app.css +354 -0
  67. package/ui/app.js +520 -0
  68. package/ui/index.html +24 -0
package/cjs/index.cjs ADDED
@@ -0,0 +1,694 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _warlock_js_core = require("@warlock.js/core");
3
+ let _warlock_js_logger = require("@warlock.js/logger");
4
+ let node_url = require("node:url");
5
+
6
+ //#region ../devtools/src/n-plus-one.ts
7
+ /** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */
8
+ function detectNPlusOne(queries, threshold) {
9
+ const groups = /* @__PURE__ */ new Map();
10
+ for (const query of queries) groups.set(query.shape, [...groups.get(query.shape) ?? [], query]);
11
+ return [...groups.entries()].filter(([, grouped]) => grouped.length >= threshold).sort(([, left], [, right]) => right.length - left.length).map(([shape, grouped]) => ({
12
+ type: "n+1",
13
+ shape,
14
+ count: grouped.length,
15
+ message: `N+1: ${grouped.length}× "${truncate(shape, 120)}"`,
16
+ ...mostFrequentCaller(grouped) ? { caller: mostFrequentCaller(grouped) } : {}
17
+ }));
18
+ }
19
+ function truncate(value, maximum) {
20
+ return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;
21
+ }
22
+ function mostFrequentCaller(queries) {
23
+ const callers = /* @__PURE__ */ new Map();
24
+ for (const query of queries) {
25
+ if (!query.caller) continue;
26
+ const key = `${query.caller.file}:${query.caller.line}`;
27
+ const found = callers.get(key);
28
+ callers.set(key, found ? {
29
+ ...found,
30
+ count: found.count + 1
31
+ } : {
32
+ caller: query.caller,
33
+ count: 1
34
+ });
35
+ }
36
+ return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;
37
+ }
38
+
39
+ //#endregion
40
+ //#region ../devtools/src/query-shape.ts
41
+ const numericLiteral = /(?<![\w$])[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?![\w$])/g;
42
+ const quotedLiteral = /'(?:''|[^'])*'/g;
43
+ /** Returns a binding-independent shape for a database query. */
44
+ function queryShape(query) {
45
+ if (query.driver === "postgres") return (query.sql ?? "").replace(quotedLiteral, "?").replace(numericLiteral, "?").replace(/\s+/g, " ").trim();
46
+ return `${query.collection ?? ""}.${query.command ?? ""} ${JSON.stringify(normalizeMongoValue(query.pipeline))}`;
47
+ }
48
+ function normalizeMongoValue(value) {
49
+ if (isMongoLeaf(value)) return "?";
50
+ if (Array.isArray(value)) {
51
+ if (value.every(isMongoLeaf)) return ["?"];
52
+ return value.map(normalizeMongoValue);
53
+ }
54
+ const record = value;
55
+ return Object.fromEntries(Object.keys(record).map((key) => [key, normalizeMongoValue(record[key])]));
56
+ }
57
+ function isMongoLeaf(value) {
58
+ if (value === null || typeof value !== "object") return true;
59
+ if (value instanceof Date) return true;
60
+ const record = value;
61
+ return typeof record.toHexString === "function" || typeof record.$oid === "string";
62
+ }
63
+
64
+ //#endregion
65
+ //#region ../devtools/src/collector.ts
66
+ const mailLimit = 100;
67
+ const logLimit = 1e3;
68
+ const backgroundLimit = 500;
69
+ /**
70
+ * Creates the in-memory devtools store.
71
+ *
72
+ * Read methods return shallow structural copies, including copied arrays, so consumers
73
+ * cannot mutate collector-owned arrays. The individual nested entries are retained.
74
+ */
75
+ function createCollector(options) {
76
+ const requests = /* @__PURE__ */ new Map();
77
+ const mails = /* @__PURE__ */ new Map();
78
+ const logs = [];
79
+ const background = {
80
+ queries: [],
81
+ cache: [],
82
+ logs: []
83
+ };
84
+ const listeners = /* @__PURE__ */ new Set();
85
+ let querySequence = 0;
86
+ const emit = (event) => {
87
+ for (const listener of listeners) try {
88
+ listener(event);
89
+ } catch {}
90
+ };
91
+ const addBackground = (list, value) => {
92
+ list.push(value);
93
+ if (list.length > backgroundLimit) list.shift();
94
+ };
95
+ return {
96
+ startRequest(request) {
97
+ requests.delete(request.id);
98
+ requests.set(request.id, {
99
+ ...request,
100
+ phases: [],
101
+ queries: [],
102
+ cache: [],
103
+ logs: [],
104
+ mails: [],
105
+ warnings: []
106
+ });
107
+ while (requests.size > options.maxRequests) requests.delete(requests.keys().next().value);
108
+ },
109
+ endRequest(id, result) {
110
+ const request = requests.get(id);
111
+ if (!request) return;
112
+ request.status = result.status;
113
+ request.durationMs = result.durationMs;
114
+ request.error = result.error;
115
+ if (result.route !== void 0) request.route = result.route;
116
+ request.warnings = detectNPlusOne(request.queries, options.nPlusOneThreshold);
117
+ emit({
118
+ type: "request",
119
+ data: summary(request)
120
+ });
121
+ },
122
+ addPhase(requestId, phase) {
123
+ requests.get(requestId)?.phases.push(phase);
124
+ },
125
+ addQuery(requestId, query) {
126
+ const stored = {
127
+ ...query,
128
+ id: `q${++querySequence}`,
129
+ shape: queryShape(query)
130
+ };
131
+ const request = requestId ? requests.get(requestId) : void 0;
132
+ if (request) request.queries.push(stored);
133
+ else addBackground(background.queries, stored);
134
+ return stored;
135
+ },
136
+ addCacheOperation(requestId, operation) {
137
+ const request = requestId ? requests.get(requestId) : void 0;
138
+ if (request) request.cache.push(operation);
139
+ else addBackground(background.cache, operation);
140
+ },
141
+ addLog(requestId, entry) {
142
+ const request = requestId ? requests.get(requestId) : void 0;
143
+ if (request) request.logs.push(entry);
144
+ else addBackground(background.logs, entry);
145
+ logs.unshift(entry);
146
+ if (logs.length > logLimit) logs.pop();
147
+ emit({
148
+ type: "log",
149
+ data: entry
150
+ });
151
+ },
152
+ addMail(mail) {
153
+ mails.delete(mail.id);
154
+ mails.set(mail.id, mail);
155
+ while (mails.size > mailLimit) mails.delete(mails.keys().next().value);
156
+ if (mail.requestId) requests.get(mail.requestId)?.mails.push(mail.id);
157
+ emit({
158
+ type: "mail",
159
+ data: mailSummary(mail)
160
+ });
161
+ },
162
+ listRequests() {
163
+ return [...requests.values()].reverse().map(summary);
164
+ },
165
+ getRequest(id) {
166
+ const request = requests.get(id);
167
+ return request && copyRequest(request);
168
+ },
169
+ listMails() {
170
+ return [...mails.values()].reverse().map(mailSummary);
171
+ },
172
+ getMail(id) {
173
+ const mail = mails.get(id);
174
+ return mail && {
175
+ ...mail,
176
+ to: [...mail.to],
177
+ cc: [...mail.cc],
178
+ bcc: [...mail.bcc],
179
+ headers: { ...mail.headers },
180
+ attachments: [...mail.attachments]
181
+ };
182
+ },
183
+ listLogs(filter = {}) {
184
+ const module = filter.module?.toLowerCase();
185
+ return logs.filter((entry) => (!filter.level || entry.level === filter.level) && (!module || entry.module.toLowerCase().includes(module))).map((entry) => ({ ...entry }));
186
+ },
187
+ getBackground() {
188
+ return {
189
+ queries: [...background.queries],
190
+ cache: [...background.cache],
191
+ logs: [...background.logs]
192
+ };
193
+ },
194
+ subscribe(listener) {
195
+ listeners.add(listener);
196
+ return () => listeners.delete(listener);
197
+ },
198
+ clear() {
199
+ requests.clear();
200
+ mails.clear();
201
+ logs.length = 0;
202
+ background.queries.length = 0;
203
+ background.cache.length = 0;
204
+ background.logs.length = 0;
205
+ }
206
+ };
207
+ }
208
+ function summary(request) {
209
+ const { id, method, path, route, status, startedAt, durationMs } = request;
210
+ return {
211
+ id,
212
+ method,
213
+ path,
214
+ route,
215
+ status,
216
+ startedAt,
217
+ durationMs,
218
+ queryCount: request.queries.length,
219
+ warningCount: request.warnings.length
220
+ };
221
+ }
222
+ function mailSummary(mail) {
223
+ const { id, requestId, capturedAt, to, subject } = mail;
224
+ return {
225
+ id,
226
+ requestId,
227
+ capturedAt,
228
+ to: [...to],
229
+ subject
230
+ };
231
+ }
232
+ function copyRequest(request) {
233
+ return {
234
+ ...request,
235
+ phases: [...request.phases],
236
+ queries: [...request.queries],
237
+ cache: [...request.cache],
238
+ logs: [...request.logs],
239
+ mails: [...request.mails],
240
+ warnings: [...request.warnings]
241
+ };
242
+ }
243
+
244
+ //#endregion
245
+ //#region ../devtools/src/options.ts
246
+ /** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */
247
+ function resolveDevtoolsOptions(options = {}) {
248
+ const path = (options.path ?? "/__warlock").replace(/\/+$/, "");
249
+ const maxRequests = options.maxRequests ?? 200;
250
+ const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;
251
+ if (!path || !path.startsWith("/")) throw new Error("Devtools option \"path\" must be a non-root path starting with \"/\".");
252
+ if (maxRequests < 1) throw new Error("Devtools option \"maxRequests\" must be at least 1.");
253
+ if (nPlusOneThreshold < 2) throw new Error("Devtools option \"nPlusOneThreshold\" must be at least 2.");
254
+ return {
255
+ path,
256
+ maxRequests,
257
+ nPlusOneThreshold
258
+ };
259
+ }
260
+
261
+ //#endregion
262
+ //#region ../devtools/src/current-request-id.ts
263
+ /**
264
+ * The current request's id (core's `request.id`, threaded through
265
+ * `AsyncLocalStorage`), or `undefined` outside a request — sources feed
266
+ * devtools' background bucket in that case.
267
+ *
268
+ * Only ever reached through `./sources/*`, which the connector imports
269
+ * dynamically inside `boot()` — by then core is already running, so this
270
+ * static import never drags core's runtime graph into config-load time (see
271
+ * `devtools-connector.ts`).
272
+ */
273
+ function currentRequestId() {
274
+ try {
275
+ return _warlock_js_core.requestContext.getRequest()?.id;
276
+ } catch {
277
+ return;
278
+ }
279
+ }
280
+
281
+ //#endregion
282
+ //#region ../devtools/src/sources/cache-source.ts
283
+ /** Cache events the dashboard's waterfall and background bucket care about. */
284
+ const EVENT_TYPES = [
285
+ "hit",
286
+ "miss",
287
+ "set",
288
+ "removed",
289
+ "invalidated",
290
+ "flushed"
291
+ ];
292
+ /**
293
+ * Feeds cache hits, misses and mutations, from `@warlock.js/cache`, into the
294
+ * collector. A no-op when `@warlock.js/cache` isn't installed — it is an
295
+ * optional peer.
296
+ */
297
+ async function attachCacheSource(collector) {
298
+ let cache;
299
+ try {
300
+ ({cache} = await import("@warlock.js/cache"));
301
+ } catch {
302
+ return () => {};
303
+ }
304
+ const handlers = EVENT_TYPES.map((type) => {
305
+ const handler = (data) => {
306
+ const operation = {
307
+ type,
308
+ driver: data.driver,
309
+ key: data.key,
310
+ tags: data.tags,
311
+ keys: data.keys,
312
+ at: Date.now(),
313
+ durationMs: data.durationMs
314
+ };
315
+ collector.addCacheOperation(currentRequestId(), operation);
316
+ };
317
+ cache.on(type, handler);
318
+ return {
319
+ type,
320
+ handler
321
+ };
322
+ });
323
+ return () => {
324
+ for (const { type, handler } of handlers) cache.off(type, handler);
325
+ };
326
+ }
327
+
328
+ //#endregion
329
+ //#region ../devtools/src/safe-value.ts
330
+ const MAX_DEPTH = 6;
331
+ /**
332
+ * A JSON-safe snapshot of a value devtools keeps for later display.
333
+ *
334
+ * Log contexts and phase attributes are app data: they can hold live objects
335
+ * (a request, its socket) whose graphs are circular and which must not be kept
336
+ * alive by the collector anyway. Plain objects and arrays are copied; anything
337
+ * with a `toJSON()` is serialized through it; other class instances collapse
338
+ * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to
339
+ * `[Object]` / `[Array]`.
340
+ */
341
+ function toSafeValue(value) {
342
+ return snapshot(value, 0, /* @__PURE__ */ new WeakSet());
343
+ }
344
+ function snapshot(value, depth, seen) {
345
+ if (value === null || value === void 0) return value;
346
+ switch (typeof value) {
347
+ case "string":
348
+ case "number":
349
+ case "boolean": return value;
350
+ case "bigint": return value.toString();
351
+ case "symbol": return value.toString();
352
+ case "function": return;
353
+ }
354
+ const object = value;
355
+ if (seen.has(object)) return "[Circular]";
356
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
357
+ if (value instanceof Error) return {
358
+ name: value.name,
359
+ message: value.message
360
+ };
361
+ if (depth >= MAX_DEPTH) return Array.isArray(value) ? "[Array]" : "[Object]";
362
+ seen.add(object);
363
+ try {
364
+ if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));
365
+ const prototype = Object.getPrototypeOf(object);
366
+ if (prototype !== Object.prototype && prototype !== null) {
367
+ const toJSON = object.toJSON;
368
+ if (typeof toJSON === "function") try {
369
+ return snapshot(toJSON.call(object), depth + 1, seen);
370
+ } catch {
371
+ return `[${constructorName(object)}]`;
372
+ }
373
+ return `[${constructorName(object)}]`;
374
+ }
375
+ const copy = {};
376
+ for (const [key, entry] of Object.entries(object)) {
377
+ const safe = snapshot(entry, depth + 1, seen);
378
+ if (safe !== void 0) copy[key] = safe;
379
+ }
380
+ return copy;
381
+ } finally {
382
+ seen.delete(object);
383
+ }
384
+ }
385
+ function constructorName(object) {
386
+ return object.constructor?.name || "Object";
387
+ }
388
+
389
+ //#endregion
390
+ //#region ../devtools/src/sources/log-source.ts
391
+ /** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */
392
+ function toDevtoolsLevel(type) {
393
+ return type === "fatal" ? "error" : type;
394
+ }
395
+ var DevtoolsLogChannel = class extends _warlock_js_logger.LogChannel {
396
+ constructor(collector) {
397
+ super();
398
+ this.collector = collector;
399
+ this.name = "devtools";
400
+ this.active = true;
401
+ }
402
+ log(data) {
403
+ if (!this.active) return;
404
+ const entry = {
405
+ level: toDevtoolsLevel(data.type),
406
+ module: data.module,
407
+ action: data.action,
408
+ message: data.message,
409
+ at: Date.now(),
410
+ context: toSafeValue(data.context)
411
+ };
412
+ this.collector.addLog(currentRequestId(), entry);
413
+ }
414
+ };
415
+ /**
416
+ * Feeds every log entry, from `@warlock.js/logger`, into the collector by
417
+ * registering an additional channel. `Logger` has no way to remove a
418
+ * channel, so the disposer flag-ignores further entries instead — the
419
+ * channel stays registered for the process's lifetime.
420
+ */
421
+ async function attachLogSource(collector) {
422
+ const channel = new DevtoolsLogChannel(collector);
423
+ _warlock_js_logger.log.addChannel(channel);
424
+ return () => {
425
+ channel.active = false;
426
+ };
427
+ }
428
+
429
+ //#endregion
430
+ //#region ../devtools/src/sources/mail-source.ts
431
+ function addressToString(address) {
432
+ if (!address) return void 0;
433
+ return typeof address === "string" ? address : `${address.name} <${address.address}>`;
434
+ }
435
+ function attachmentSize(attachment) {
436
+ if (typeof attachment.content === "string") return Buffer.byteLength(attachment.content);
437
+ if (Buffer.isBuffer(attachment.content)) return attachment.content.length;
438
+ }
439
+ function toDevtoolsAttachment(attachment) {
440
+ return {
441
+ filename: attachment.filename,
442
+ contentType: attachment.contentType,
443
+ size: attachmentSize(attachment)
444
+ };
445
+ }
446
+ /**
447
+ * Feeds mails captured in development mode, from core's `mailEvents`, into
448
+ * the collector. The captured attachments carry their content, but only
449
+ * metadata is stored — the bytes are never kept.
450
+ */
451
+ async function attachMailSource(collector) {
452
+ const { mailEvents } = await import("@warlock.js/core");
453
+ const subscription = mailEvents.onCaptured((mail) => {
454
+ const { normalized } = mail;
455
+ collector.addMail({
456
+ id: mail.id,
457
+ requestId: currentRequestId(),
458
+ capturedAt: mail.timestamp.getTime(),
459
+ from: addressToString(normalized.from),
460
+ to: normalized.to,
461
+ cc: normalized.cc,
462
+ bcc: normalized.bcc,
463
+ subject: normalized.subject,
464
+ html: normalized.html,
465
+ text: normalized.text,
466
+ headers: normalized.headers,
467
+ attachments: normalized.attachments.map(toDevtoolsAttachment)
468
+ });
469
+ });
470
+ return () => subscription.unsubscribe();
471
+ }
472
+
473
+ //#endregion
474
+ //#region ../devtools/src/caller-location.ts
475
+ const packageDirectory = normalizePath((0, node_url.fileURLToPath)(new URL("../", require("url").pathToFileURL(__filename).href)));
476
+ /** Returns the first non-runtime, non-devtools frame in a V8 stack trace. */
477
+ function captureCallerLocation(stack = (/* @__PURE__ */ new Error()).stack ?? "") {
478
+ for (const line of stack.split("\n")) {
479
+ const frame = parseFrame(line);
480
+ if (!frame || shouldSkip(frame.file)) continue;
481
+ return frame;
482
+ }
483
+ }
484
+ function parseFrame(frame) {
485
+ const [, rawFile, line, column] = frame.match(/\bat\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?\s*$/) ?? [];
486
+ if (!rawFile || !line || !column) return void 0;
487
+ return {
488
+ file: normalizePath(rawFile),
489
+ line: Number(line),
490
+ column: Number(column)
491
+ };
492
+ }
493
+ /** A drive-letter file URL names a Windows path on whichever host decodes it. */
494
+ const WINDOWS_DRIVE_FILE_URL = /^file:\/\/\/[A-Za-z]:/;
495
+ function normalizePath(path) {
496
+ return (!path.startsWith("file:") ? path : WINDOWS_DRIVE_FILE_URL.test(path) ? (0, node_url.fileURLToPath)(path, { windows: true }) : (0, node_url.fileURLToPath)(path)).replace(/\\/g, "/");
497
+ }
498
+ function shouldSkip(file) {
499
+ return file.startsWith("node:") || file.includes("/node_modules/") || file.startsWith("internal/") || file.startsWith(packageDirectory);
500
+ }
501
+
502
+ //#endregion
503
+ //#region ../devtools/src/sources/query-source.ts
504
+ /** Redacts query bindings through the logger's redaction rules. */
505
+ function redactBindings(bindings) {
506
+ if (!bindings) return bindings;
507
+ return (0, _warlock_js_logger.applyRedact)({
508
+ type: "debug",
509
+ module: "devtools",
510
+ action: "query",
511
+ message: void 0,
512
+ context: { bindings }
513
+ }, _warlock_js_logger.log.getRedact()).context.bindings;
514
+ }
515
+ /**
516
+ * Feeds every settled database query, from cascade's data source registry,
517
+ * into the collector. A no-op when `@warlock.js/cascade` isn't installed —
518
+ * it is an optional peer.
519
+ */
520
+ async function attachQuerySource(collector) {
521
+ let dataSourceRegistry;
522
+ try {
523
+ ({dataSourceRegistry} = await import("@warlock.js/cascade"));
524
+ } catch {
525
+ return () => {};
526
+ }
527
+ const listener = (event) => {
528
+ collector.addQuery(currentRequestId(), {
529
+ connection: event.connection,
530
+ driver: event.driver,
531
+ sql: event.sql,
532
+ bindings: toSafeValue(redactBindings(event.bindings)),
533
+ collection: event.collection,
534
+ command: event.command,
535
+ pipeline: event.pipeline,
536
+ startedAt: event.startedAt,
537
+ durationMs: event.durationMs,
538
+ rowCount: event.rowCount,
539
+ error: event.error === void 0 ? void 0 : event.error instanceof Error ? event.error.message : String(event.error),
540
+ caller: captureCallerLocation()
541
+ });
542
+ };
543
+ dataSourceRegistry.on("query", listener);
544
+ return () => dataSourceRegistry.off("query", listener);
545
+ }
546
+
547
+ //#endregion
548
+ //#region ../devtools/src/sources/tracing-source.ts
549
+ /**
550
+ * Feeds request timelines from core's tracing hooks into the collector: one
551
+ * `startRequest`/`endRequest` pair per HTTP request, with every named phase
552
+ * in between. Requests to the dashboard's own path are never recorded, so
553
+ * the dashboard never watches itself.
554
+ */
555
+ async function attachTracingSource(collector, options) {
556
+ const { registerTracingHooks } = await import("@warlock.js/core");
557
+ const isDashboardPath = (path) => path.startsWith(options.path);
558
+ return registerTracingHooks({
559
+ onRequestStart(ctx) {
560
+ if (isDashboardPath(ctx.path)) return;
561
+ collector.startRequest({
562
+ id: ctx.requestId,
563
+ method: ctx.method,
564
+ path: ctx.path,
565
+ route: ctx.route,
566
+ startedAt: performance.timeOrigin + performance.now()
567
+ });
568
+ },
569
+ onPhase(ctx, phase) {
570
+ if (isDashboardPath(ctx.path)) return;
571
+ collector.addPhase(ctx.requestId, {
572
+ name: phase.name,
573
+ durationMs: phase.durationMs,
574
+ startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,
575
+ attrs: phase.attrs === void 0 ? void 0 : toSafeValue(phase.attrs)
576
+ });
577
+ },
578
+ onRequestEnd(ctx, result) {
579
+ if (isDashboardPath(ctx.path)) return;
580
+ collector.endRequest(ctx.requestId, {
581
+ status: result.status,
582
+ durationMs: result.durationMs,
583
+ error: result.error === void 0 ? void 0 : result.error instanceof Error ? result.error.message : String(result.error),
584
+ route: ctx.route
585
+ });
586
+ }
587
+ });
588
+ }
589
+
590
+ //#endregion
591
+ //#region ../devtools/src/devtools-connector.ts
592
+ /**
593
+ * Boots after the queue connector (priority 11), which is the last
594
+ * built-in/framework connector to claim a priority; devtools has nothing
595
+ * that depends on it, so it simply goes last.
596
+ */
597
+ const DEVTOOLS_CONNECTOR_PRIORITY = 12;
598
+ /**
599
+ * Construct the devtools connector.
600
+ *
601
+ * Refuses to run outside development: `boot()` checks
602
+ * `Application.runtimeStrategy` and, when it isn't `"development"`, logs one
603
+ * warning and returns without mounting a route or subscribing to anything.
604
+ * In development it attaches every source (tracing, queries, cache, mail,
605
+ * logs), then mounts the dashboard's routes on the HTTP server — before it
606
+ * starts listening, the only point in the boot sequence where mounting is
607
+ * possible (see `queue/src/dashboard-boot.ts` for the same constraint).
608
+ *
609
+ * Apps don't call this: `warlock dev` registers it automatically when the
610
+ * package is installed (`warlock add devtools`). Keep it OUT of
611
+ * `warlock.config.ts` — devtools is a dev dependency, so a production
612
+ * install doesn't have it and a config import of it would fail there.
613
+ */
614
+ function devtoolsConnector(options = {}) {
615
+ let active = false;
616
+ const disposers = [];
617
+ const connector = {
618
+ name: "devtools",
619
+ priority: 12,
620
+ lifecyclePhase: "late",
621
+ isActive: () => active,
622
+ async boot() {
623
+ const { Application, getHttpServer } = await import("@warlock.js/core");
624
+ const { log } = await import("@warlock.js/logger");
625
+ if (Application.runtimeStrategy !== "development") {
626
+ log.warn("devtools", "disabled", "@warlock.js/devtools only runs in development; it is not mounted");
627
+ return;
628
+ }
629
+ const resolved = resolveDevtoolsOptions(options);
630
+ const collector = createCollector(resolved);
631
+ await attachSource(log, "tracing", () => attachTracingSource(collector, resolved));
632
+ await attachSource(log, "query", () => attachQuerySource(collector));
633
+ await attachSource(log, "cache", () => attachCacheSource(collector));
634
+ await attachSource(log, "mail", () => attachMailSource(collector));
635
+ await attachSource(log, "log", () => attachLogSource(collector));
636
+ const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-DHYSVive.cjs"));
637
+ mountDevtoolsRoutes(getHttpServer(), {
638
+ collector,
639
+ options: resolved,
640
+ isDevelopment: () => Application.runtimeStrategy === "development",
641
+ explain: (query) => explainQuery(query),
642
+ listRoutes: () => listRoutes()
643
+ });
644
+ disposers.push(collector.subscribe((event) => {
645
+ if (event.type !== "request" || event.data.warningCount === 0) return;
646
+ for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {
647
+ const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : "";
648
+ log.warn("devtools", "n+1", `${warning.message}${where} (${event.data.method} ${event.data.path})`);
649
+ }
650
+ }));
651
+ active = true;
652
+ log.info("devtools", "ready", `devtools ready at ${resolved.path}`);
653
+ },
654
+ async start() {},
655
+ async restart() {
656
+ await connector.shutdown();
657
+ await connector.start();
658
+ },
659
+ async shutdown() {
660
+ for (const dispose of disposers.splice(0)) dispose();
661
+ active = false;
662
+ },
663
+ shouldRestart: () => false
664
+ };
665
+ /** Attaches one source, logging and continuing when it fails to attach. */
666
+ async function attachSource(logger, name, attach) {
667
+ try {
668
+ disposers.push(await attach());
669
+ } catch (error) {
670
+ logger.warn("devtools", "source-failed", `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`);
671
+ }
672
+ }
673
+ return connector;
674
+ }
675
+ /** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */
676
+ async function explainQuery(query) {
677
+ const { dataSourceRegistry } = await import("@warlock.js/cascade");
678
+ const { rows } = await dataSourceRegistry.get(query.connection).raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);
679
+ return rows;
680
+ }
681
+ /** Lists every registered HTTP route — the same source `warlock routes --json` reads. */
682
+ async function listRoutes() {
683
+ const { router } = await import("@warlock.js/core");
684
+ return router.list().map((route) => ({
685
+ method: route.method.toUpperCase(),
686
+ path: route.path,
687
+ name: route.name,
688
+ middleware: route.middleware?.map((middleware) => middleware.name || "anonymous")
689
+ }));
690
+ }
691
+
692
+ //#endregion
693
+ exports.devtoolsConnector = devtoolsConnector;
694
+ //# sourceMappingURL=index.cjs.map