@deviltea/widget-inspector 0.0.0-stage → 0.0.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.
package/dist/agent.mjs ADDED
@@ -0,0 +1,1060 @@
1
+ import { INSPECT_ANCHOR_ID_ATTRIBUTE, INSPECT_ANCHOR_TYPE_ATTRIBUTE } from "./anchor.mjs";
2
+ import { encodeInspectableValue } from "./value.mjs";
3
+ import { n as isCompatibleProtocolVersion, s as parseInspectorRequestMessage, t as INSPECTOR_PROTOCOL_VERSION } from "./protocol-D1gtirOC.mjs";
4
+ import { inspectRuntime } from "@deviltea/widget-core/inspection";
5
+ //#region src/overlay.ts
6
+ /** Marks the Agent-owned overlay host so geometry observation can ignore Agent chrome. */
7
+ const INSPECTOR_OVERLAY_HOST_ATTRIBUTE = "data-widget-inspector-overlay";
8
+ const INSPECTOR_OVERLAY_HOST_SELECTOR = `[${INSPECTOR_OVERLAY_HOST_ATTRIBUTE}="true"]`;
9
+ const OVERLAY_STYLE = `
10
+ :host {
11
+ all: initial;
12
+ pointer-events: none;
13
+ }
14
+ * {
15
+ box-sizing: border-box;
16
+ pointer-events: none;
17
+ }
18
+ .rect {
19
+ position: fixed;
20
+ outline: 2px solid var(--widget-inspector-accent, #2563eb);
21
+ outline-offset: 1px;
22
+ background: var(--widget-inspector-fill, rgb(37 99 235 / 12%));
23
+ }
24
+ .badge {
25
+ position: fixed;
26
+ padding: 2px 6px;
27
+ font: 600 10px/1.4 system-ui, sans-serif;
28
+ white-space: nowrap;
29
+ border-radius: 4px;
30
+ background: var(--widget-inspector-accent, #2563eb);
31
+ color: var(--widget-inspector-accent-contrast, #fff);
32
+ transform: translateY(-100%);
33
+ }
34
+ .badge.inside {
35
+ transform: none;
36
+ }
37
+ `;
38
+ function signature(content) {
39
+ return `${content.label}|${content.rects.map((rect) => `${rect.x},${rect.y},${rect.width},${rect.height}`).join(";")}`;
40
+ }
41
+ /**
42
+ * Agent-owned highlight chrome. The overlay lives in a ShadowRoot attached to a single fixed,
43
+ * pointer-transparent host appended to the inspected document, outside the renderer's element tree:
44
+ * it never mutates renderer elements, and a renderer re-render cannot clear it. Rects are
45
+ * `preview-viewport` client rects, which coincide with the fixed host's coordinate space.
46
+ */
47
+ function createInspectorOverlay(ownerDocument) {
48
+ let host = null;
49
+ let content = null;
50
+ let lastSignature = null;
51
+ function ensureHost() {
52
+ if (host !== null && content !== null) {
53
+ if (!host.isConnected) (ownerDocument.body ?? ownerDocument.documentElement).append(host);
54
+ return content;
55
+ }
56
+ const created = ownerDocument.createElement("div");
57
+ created.setAttribute(INSPECTOR_OVERLAY_HOST_ATTRIBUTE, "true");
58
+ created.setAttribute("aria-hidden", "true");
59
+ created.style.cssText = "all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none;";
60
+ const shadow = created.attachShadow({ mode: "open" });
61
+ const style = ownerDocument.createElement("style");
62
+ style.textContent = OVERLAY_STYLE;
63
+ const container = ownerDocument.createElement("div");
64
+ shadow.append(style, container);
65
+ (ownerDocument.body ?? ownerDocument.documentElement).append(created);
66
+ host = created;
67
+ content = container;
68
+ return container;
69
+ }
70
+ return {
71
+ show(next) {
72
+ const nextSignature = signature(next);
73
+ if (host !== null && host.isConnected && nextSignature === lastSignature) return;
74
+ const container = ensureHost();
75
+ lastSignature = nextSignature;
76
+ const children = [];
77
+ for (const rect of next.rects) {
78
+ const box = ownerDocument.createElement("div");
79
+ box.className = "rect";
80
+ box.style.left = `${rect.x}px`;
81
+ box.style.top = `${rect.y}px`;
82
+ box.style.width = `${rect.width}px`;
83
+ box.style.height = `${rect.height}px`;
84
+ children.push(box);
85
+ }
86
+ const first = next.rects[0];
87
+ if (first !== void 0) {
88
+ const badge = ownerDocument.createElement("div");
89
+ badge.className = first.y < 20 ? "badge inside" : "badge";
90
+ badge.textContent = next.label;
91
+ badge.style.left = `${first.x}px`;
92
+ badge.style.top = `${first.y}px`;
93
+ children.push(badge);
94
+ }
95
+ container.replaceChildren(...children);
96
+ },
97
+ clear() {
98
+ host?.remove();
99
+ host = null;
100
+ content = null;
101
+ lastSignature = null;
102
+ }
103
+ };
104
+ }
105
+ //#endregion
106
+ //#region src/geometry.ts
107
+ const ANCHOR_SELECTOR = `[${INSPECT_ANCHOR_ID_ATTRIBUTE}][${INSPECT_ANCHOR_TYPE_ATTRIBUTE}]`;
108
+ /** Reads an element's anchor identity, or `null` when it does not carry both anchor attributes. */
109
+ function readAnchorIdentity(element) {
110
+ const widgetId = element.getAttribute(INSPECT_ANCHOR_ID_ATTRIBUTE);
111
+ const widgetType = element.getAttribute(INSPECT_ANCHOR_TYPE_ATTRIBUTE);
112
+ return widgetId === null || widgetType === null ? null : {
113
+ widgetId,
114
+ widgetType
115
+ };
116
+ }
117
+ function isInspectorOverlayNode(node) {
118
+ const element = node.nodeType === 1 ? node : node.parentElement;
119
+ return element != null && element.closest(INSPECTOR_OVERLAY_HOST_SELECTOR) !== null;
120
+ }
121
+ function isInspectorOverlayMutation(record) {
122
+ if (isInspectorOverlayNode(record.target)) return true;
123
+ if (record.type !== "childList") return false;
124
+ const changed = [...record.addedNodes, ...record.removedNodes];
125
+ return changed.length > 0 && changed.every(isInspectorOverlayNode);
126
+ }
127
+ function geometryRect(rect) {
128
+ return {
129
+ x: Number.isFinite(rect.x) ? rect.x : rect.left,
130
+ y: Number.isFinite(rect.y) ? rect.y : rect.top,
131
+ width: rect.width,
132
+ height: rect.height
133
+ };
134
+ }
135
+ function usableRect(rect) {
136
+ return Number.isFinite(rect.x) && Number.isFinite(rect.y) && Number.isFinite(rect.width) && Number.isFinite(rect.height) && rect.width > 0 && rect.height > 0;
137
+ }
138
+ function createSemanticGeometryController(options) {
139
+ const document = options.root.ownerDocument;
140
+ const window = document.defaultView;
141
+ const previewTreeRoot = options.root.getRootNode();
142
+ const shadowTreeRoot = previewTreeRoot.nodeType === 11 && "host" in previewTreeRoot ? previewTreeRoot : null;
143
+ const hitTestRoot = shadowTreeRoot ?? document;
144
+ let revision = 0;
145
+ let invalidationPending = false;
146
+ let frameHandle = null;
147
+ let disposed = false;
148
+ function viewportSize() {
149
+ return {
150
+ width: window?.innerWidth ?? document.documentElement.clientWidth,
151
+ height: window?.innerHeight ?? document.documentElement.clientHeight
152
+ };
153
+ }
154
+ function allAnchors() {
155
+ const result = [];
156
+ if (options.root.matches(ANCHOR_SELECTOR)) result.push(options.root);
157
+ result.push(...options.root.querySelectorAll(ANCHOR_SELECTOR));
158
+ return result;
159
+ }
160
+ function targetAnchors(target) {
161
+ return allAnchors().filter((element) => {
162
+ const identity = readAnchorIdentity(element);
163
+ return identity !== null && identity.widgetId === target.widgetId && identity.widgetType === target.widgetType;
164
+ });
165
+ }
166
+ function measureTarget(target) {
167
+ const anchors = targetAnchors(target);
168
+ const rects = [];
169
+ for (const element of anchors) for (const rect of element.getClientRects()) {
170
+ const projected = geometryRect(rect);
171
+ if (usableRect(projected)) rects.push(projected);
172
+ }
173
+ return {
174
+ anchorCount: anchors.length,
175
+ rects
176
+ };
177
+ }
178
+ function snapshotForTarget(target) {
179
+ if (target === null) return {
180
+ coordinateSpace: "preview-viewport",
181
+ revision,
182
+ visibility: "missing",
183
+ rects: []
184
+ };
185
+ const { rects } = measureTarget(target);
186
+ if (rects.length === 0) return {
187
+ coordinateSpace: "preview-viewport",
188
+ revision,
189
+ visibility: "hidden",
190
+ rects
191
+ };
192
+ const viewport = viewportSize();
193
+ const fullyInside = rects.every((rect) => rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= viewport.width && rect.y + rect.height <= viewport.height);
194
+ return {
195
+ coordinateSpace: "preview-viewport",
196
+ revision,
197
+ visibility: fullyInside ? "visible" : "clipped",
198
+ rects
199
+ };
200
+ }
201
+ function nearestSemanticAnchor(element) {
202
+ let anchor = element.closest(ANCHOR_SELECTOR);
203
+ while (anchor !== null && options.root.contains(anchor)) {
204
+ const target = options.resolveAnchor(anchor);
205
+ if (target !== null) return target;
206
+ if (anchor === options.root) break;
207
+ anchor = anchor.parentElement?.closest(ANCHOR_SELECTOR) ?? null;
208
+ }
209
+ return null;
210
+ }
211
+ function fallbackHitTarget(point) {
212
+ let selected = null;
213
+ for (const anchor of allAnchors()) {
214
+ if (![...anchor.getClientRects()].some((rawRect) => {
215
+ const rect = geometryRect(rawRect);
216
+ return usableRect(rect) && point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
217
+ }) || nearestSemanticAnchor(anchor) === null) continue;
218
+ if (selected === null || selected.contains(anchor)) selected = anchor;
219
+ }
220
+ return selected === null ? null : nearestSemanticAnchor(selected);
221
+ }
222
+ function hitTarget(point) {
223
+ const viewport = viewportSize();
224
+ if (point.x < 0 || point.y < 0 || point.x >= viewport.width || point.y >= viewport.height) return null;
225
+ const elementsFromPoint = hitTestRoot.elementsFromPoint?.bind(hitTestRoot);
226
+ if (elementsFromPoint !== void 0) {
227
+ const topmost = elementsFromPoint(point.x, point.y)[0];
228
+ return topmost === void 0 ? null : nearestSemanticAnchor(topmost);
229
+ }
230
+ const elementFromPoint = hitTestRoot.elementFromPoint?.bind(hitTestRoot);
231
+ if (elementFromPoint !== void 0) {
232
+ const element = elementFromPoint(point.x, point.y);
233
+ return element == null ? null : nearestSemanticAnchor(element);
234
+ }
235
+ return fallbackHitTarget(point);
236
+ }
237
+ function scheduleInvalidation() {
238
+ if (disposed || invalidationPending) return;
239
+ invalidationPending = true;
240
+ revision++;
241
+ if (window === null) {
242
+ queueMicrotask(() => {
243
+ if (disposed) return;
244
+ invalidationPending = false;
245
+ options.onInvalidated(revision);
246
+ });
247
+ return;
248
+ }
249
+ frameHandle = window.requestAnimationFrame(() => {
250
+ frameHandle = null;
251
+ if (disposed) return;
252
+ invalidationPending = false;
253
+ options.onInvalidated(revision);
254
+ });
255
+ }
256
+ const onScroll = () => scheduleInvalidation();
257
+ const onResize = () => scheduleInvalidation();
258
+ const onResourceSettled = () => scheduleInvalidation();
259
+ document.addEventListener("scroll", onScroll, true);
260
+ document.addEventListener("load", onResourceSettled, true);
261
+ document.addEventListener("error", onResourceSettled, true);
262
+ shadowTreeRoot?.addEventListener("scroll", onScroll, true);
263
+ shadowTreeRoot?.addEventListener("load", onResourceSettled, true);
264
+ shadowTreeRoot?.addEventListener("error", onResourceSettled, true);
265
+ window?.addEventListener("resize", onResize);
266
+ const mutationObserver = typeof MutationObserver === "function" ? new MutationObserver((records) => {
267
+ if (records.some((record) => !isInspectorOverlayMutation(record))) scheduleInvalidation();
268
+ }) : null;
269
+ const mutationOptions = {
270
+ subtree: true,
271
+ childList: true,
272
+ attributes: true,
273
+ characterData: true
274
+ };
275
+ mutationObserver?.observe(document.documentElement ?? options.root, mutationOptions);
276
+ if (previewTreeRoot !== document) mutationObserver?.observe(previewTreeRoot, mutationOptions);
277
+ const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(() => scheduleInvalidation()) : null;
278
+ function observeAnchorSizes() {
279
+ if (resizeObserver === null) return;
280
+ resizeObserver.disconnect();
281
+ resizeObserver.observe(options.root);
282
+ for (const anchor of allAnchors()) resizeObserver.observe(anchor);
283
+ }
284
+ observeAnchorSizes();
285
+ const anchorRefreshObserver = resizeObserver === null || typeof MutationObserver !== "function" ? null : new MutationObserver(() => observeAnchorSizes());
286
+ anchorRefreshObserver?.observe(options.root, {
287
+ subtree: true,
288
+ childList: true,
289
+ attributes: true,
290
+ attributeFilter: [INSPECT_ANCHOR_ID_ATTRIBUTE, INSPECT_ANCHOR_TYPE_ATTRIBUTE]
291
+ });
292
+ const fontSet = document.fonts;
293
+ const onFontLayout = () => scheduleInvalidation();
294
+ fontSet?.addEventListener("loadingdone", onFontLayout);
295
+ fontSet?.addEventListener("loadingerror", onFontLayout);
296
+ return {
297
+ get revision() {
298
+ return revision;
299
+ },
300
+ resolve(ref) {
301
+ return snapshotForTarget(options.resolveRef(ref));
302
+ },
303
+ measure: measureTarget,
304
+ hitTest(point) {
305
+ const target = hitTarget(point);
306
+ if (target === null) return { target: null };
307
+ return {
308
+ target,
309
+ geometry: snapshotForTarget(target)
310
+ };
311
+ },
312
+ invalidate: scheduleInvalidation,
313
+ dispose() {
314
+ if (disposed) return;
315
+ disposed = true;
316
+ document.removeEventListener("scroll", onScroll, true);
317
+ document.removeEventListener("load", onResourceSettled, true);
318
+ document.removeEventListener("error", onResourceSettled, true);
319
+ shadowTreeRoot?.removeEventListener("scroll", onScroll, true);
320
+ shadowTreeRoot?.removeEventListener("load", onResourceSettled, true);
321
+ shadowTreeRoot?.removeEventListener("error", onResourceSettled, true);
322
+ window?.removeEventListener("resize", onResize);
323
+ mutationObserver?.disconnect();
324
+ anchorRefreshObserver?.disconnect();
325
+ resizeObserver?.disconnect();
326
+ fontSet?.removeEventListener("loadingdone", onFontLayout);
327
+ fontSet?.removeEventListener("loadingerror", onFontLayout);
328
+ if (frameHandle !== null && window !== null) window.cancelAnimationFrame(frameHandle);
329
+ }
330
+ };
331
+ }
332
+ //#endregion
333
+ //#region src/projection.ts
334
+ function wireNodeId(nodeId) {
335
+ return nodeId;
336
+ }
337
+ function projectDependencyReference(reference) {
338
+ return {
339
+ target: { ...reference.target },
340
+ operation: { ...reference.operation }
341
+ };
342
+ }
343
+ function projectDependency(dependency) {
344
+ const base = {
345
+ path: [...dependency.path],
346
+ reference: projectDependencyReference(dependency.reference)
347
+ };
348
+ if (dependency.status === "resolved") return {
349
+ ...base,
350
+ status: "resolved",
351
+ target: {
352
+ nodeId: wireNodeId(dependency.target.nodeId),
353
+ member: { ...dependency.target.member }
354
+ }
355
+ };
356
+ if (dependency.status === "invalid") return {
357
+ ...base,
358
+ status: "invalid",
359
+ ...dependency.targetNodeId === void 0 ? {} : { targetNodeId: wireNodeId(dependency.targetNodeId) }
360
+ };
361
+ return {
362
+ ...base,
363
+ status: "absent"
364
+ };
365
+ }
366
+ function projectDiagnosticLocation(inspection, location) {
367
+ const nodeId = inspection.getNodeId(location.node);
368
+ if (nodeId === null) return null;
369
+ const wireId = wireNodeId(nodeId);
370
+ switch (location.type) {
371
+ case "widget": return {
372
+ type: "widget",
373
+ nodeId: wireId
374
+ };
375
+ case "slot": return {
376
+ type: "slot",
377
+ nodeId: wireId,
378
+ slot: location.slot
379
+ };
380
+ case "slot-child": return {
381
+ type: "slot-child",
382
+ nodeId: wireId,
383
+ slot: location.slot,
384
+ index: location.index
385
+ };
386
+ case "property": return {
387
+ type: "property",
388
+ nodeId: wireId,
389
+ name: location.name
390
+ };
391
+ case "method": return {
392
+ type: "method",
393
+ nodeId: wireId,
394
+ name: location.name
395
+ };
396
+ }
397
+ }
398
+ function projectDiagnostic(inspection, diagnostic) {
399
+ const location = projectDiagnosticLocation(inspection, diagnostic.location);
400
+ if (location === null) return null;
401
+ const related = "related" in diagnostic && diagnostic.related !== void 0 ? diagnostic.related.map((item) => projectDiagnosticLocation(inspection, item)).filter((item) => item !== null) : void 0;
402
+ return {
403
+ code: diagnostic.code,
404
+ message: diagnostic.message,
405
+ location,
406
+ ...related === void 0 ? {} : { related },
407
+ ..."path" in diagnostic && diagnostic.path !== void 0 ? { path: diagnostic.path.map((segment) => typeof segment === "symbol" ? segment.description ?? "Symbol()" : segment) } : {},
408
+ ..."reason" in diagnostic && typeof diagnostic.reason === "string" ? { reason: diagnostic.reason } : {},
409
+ ..."dependency" in diagnostic ? { dependency: projectDependencyReference(diagnostic.dependency) } : {}
410
+ };
411
+ }
412
+ function projectSourceSlots(sourceSlots) {
413
+ return sourceSlots.map((slot) => ({
414
+ name: slot.name,
415
+ placement: slot.placement,
416
+ children: slot.children.map(wireNodeId)
417
+ }));
418
+ }
419
+ function projectBlueprintSnapshot(runtimeId, inspection, protocolMinor = 2) {
420
+ return {
421
+ runtimeId,
422
+ rootNodeId: wireNodeId(inspection.rootNodeId),
423
+ nodes: inspection.nodes.map((node) => {
424
+ const diagnostics = node.node.diagnostics.map((diagnostic) => projectDiagnostic(inspection, diagnostic)).filter((diagnostic) => diagnostic !== null);
425
+ const base = {
426
+ nodeId: wireNodeId(node.nodeId),
427
+ resolved: node.resolved,
428
+ sourceSlots: projectSourceSlots(node.sourceSlots),
429
+ diagnostics
430
+ };
431
+ if (!node.resolved) return base;
432
+ return {
433
+ ...base,
434
+ widgetId: node.node.id,
435
+ widgetType: node.node.type,
436
+ capabilities: protocolMinor < 2 ? {
437
+ config: node.capabilities.config,
438
+ slots: node.capabilities.slots,
439
+ state: node.capabilities.state,
440
+ properties: node.capabilities.properties,
441
+ methods: node.capabilities.methods
442
+ } : { ...node.capabilities },
443
+ ...protocolMinor < 2 ? {} : {
444
+ config: node.config === null ? null : {
445
+ description: node.config.description,
446
+ schema: node.config.schema
447
+ },
448
+ events: node.events.map((event) => ({ ...event }))
449
+ },
450
+ semanticSlots: node.semanticSlots.map((slot) => ({
451
+ name: slot.name,
452
+ children: slot.children.map(wireNodeId)
453
+ })),
454
+ state: node.state.map((member) => ({ ...member })),
455
+ properties: node.properties.map((member) => ({
456
+ ...member,
457
+ dependencies: member.dependencies.map(projectDependency)
458
+ })),
459
+ methods: node.methods.map((member) => ({
460
+ ...member,
461
+ dependencies: member.dependencies.map(projectDependency)
462
+ }))
463
+ };
464
+ }),
465
+ invalidCycles: inspection.invalidCycles.map((cycle) => ({ members: cycle.members.map((member) => ({
466
+ nodeId: wireNodeId(member.nodeId),
467
+ member: { ...member.member }
468
+ })) }))
469
+ };
470
+ }
471
+ function projectRuntimeDiagnosticLocation(location) {
472
+ return {
473
+ type: location.type,
474
+ widgetId: location.widgetId,
475
+ name: location.type === "state" ? location.key : location.name
476
+ };
477
+ }
478
+ function projectRuntimeDiagnostic(diagnostic) {
479
+ return {
480
+ code: diagnostic.code,
481
+ message: diagnostic.message,
482
+ location: projectRuntimeDiagnosticLocation(diagnostic.location),
483
+ ..."path" in diagnostic && diagnostic.path !== void 0 ? { path: diagnostic.path.map((segment) => typeof segment === "symbol" ? segment.description ?? "Symbol()" : segment) } : {},
484
+ ..."reason" in diagnostic && typeof diagnostic.reason === "string" ? { reason: diagnostic.reason } : {},
485
+ ..."dependency" in diagnostic ? { dependency: projectDependencyReference(diagnostic.dependency) } : {},
486
+ ..."candidate" in diagnostic ? { candidate: encodeInspectableValue(diagnostic.candidate) } : {},
487
+ ..."received" in diagnostic ? { received: encodeInspectableValue(diagnostic.received) } : {},
488
+ ..."result" in diagnostic ? { result: encodeInspectableValue(diagnostic.result) } : {},
489
+ ..."args" in diagnostic ? { args: diagnostic.args.map((value) => encodeInspectableValue(value)) } : {},
490
+ ..."related" in diagnostic ? { related: diagnostic.related.map(projectRuntimeDiagnosticLocation) } : {},
491
+ ..."cause" in diagnostic ? { cause: projectRuntimeDiagnostic(diagnostic.cause) } : {}
492
+ };
493
+ }
494
+ function projectPropertySnapshot(name, snapshot) {
495
+ if (snapshot.status === "never-evaluated") return {
496
+ type: "property",
497
+ name,
498
+ snapshot: { status: "never-evaluated" }
499
+ };
500
+ return {
501
+ type: "property",
502
+ name,
503
+ snapshot: {
504
+ status: "completed",
505
+ result: snapshot.result.ok ? {
506
+ ok: true,
507
+ value: encodeInspectableValue(snapshot.result.value)
508
+ } : {
509
+ ok: false,
510
+ diagnostics: snapshot.result.failure.diagnostics.map(projectRuntimeDiagnostic)
511
+ }
512
+ }
513
+ };
514
+ }
515
+ function projectRuntimeMemberSnapshot(widget, member) {
516
+ if (member.type === "state") {
517
+ const inspection = widget.getState(member.name);
518
+ if (inspection === null) return null;
519
+ return {
520
+ type: "state",
521
+ name: member.name,
522
+ value: encodeInspectableValue(inspection.getSnapshot().value)
523
+ };
524
+ }
525
+ const inspection = widget.getProperty(member.name);
526
+ return inspection === null ? null : projectPropertySnapshot(member.name, inspection.getSnapshot());
527
+ }
528
+ function projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId) {
529
+ const widget = runtimeInspection.getWidget(nodeId);
530
+ if (widget === null || !widget.blueprintNode.resolved) return null;
531
+ const members = [];
532
+ for (const state of widget.blueprintNode.state) {
533
+ const projected = projectRuntimeMemberSnapshot(widget, state);
534
+ if (projected !== null) members.push(projected);
535
+ }
536
+ for (const property of widget.blueprintNode.properties) {
537
+ const projected = projectRuntimeMemberSnapshot(widget, property);
538
+ if (projected !== null) members.push(projected);
539
+ }
540
+ return {
541
+ ref: {
542
+ runtimeId,
543
+ nodeId: wireNodeId(nodeId)
544
+ },
545
+ widgetId: widget.blueprintNode.node.id,
546
+ widgetType: widget.blueprintNode.node.type,
547
+ members
548
+ };
549
+ }
550
+ function projectEventArgs(args) {
551
+ return args.map((value) => encodeInspectableValue(value));
552
+ }
553
+ //#endregion
554
+ //#region src/agent.ts
555
+ const PROTOCOL_0_1_METHODS = Object.freeze([
556
+ "handshake",
557
+ "runtime.list",
558
+ "blueprint.getSnapshot",
559
+ "runtime.getWidgetSnapshot",
560
+ "runtime.subscribeMember",
561
+ "runtime.unsubscribeMember",
562
+ "inspect.enable",
563
+ "inspect.disable",
564
+ "highlight.show",
565
+ "highlight.clear"
566
+ ]);
567
+ const PROTOCOL_0_2_METHODS = Object.freeze(["runtime.subscribeEvent", "runtime.unsubscribeEvent"]);
568
+ const PROTOCOL_0_2_GEOMETRY_METHODS = Object.freeze(["inspect.hitTest", "geometry.resolve"]);
569
+ const PROTOCOL_0_1_EVENTS = Object.freeze([
570
+ "runtime.memberChanged",
571
+ "inspect.hovered",
572
+ "inspect.selected",
573
+ "agent.status"
574
+ ]);
575
+ const PROTOCOL_0_2_EVENTS = Object.freeze(["runtime.eventOccurred"]);
576
+ const PROTOCOL_0_2_GEOMETRY_EVENTS = Object.freeze(["geometry.invalidated"]);
577
+ let runtimeSequence = 1;
578
+ let subscriptionSequence = 1;
579
+ function createRuntimeId() {
580
+ try {
581
+ if (typeof globalThis.crypto?.randomUUID === "function") return `runtime-${globalThis.crypto.randomUUID()}`;
582
+ } catch {}
583
+ return `runtime-${runtimeSequence++}`;
584
+ }
585
+ function protocolError(code, message) {
586
+ return {
587
+ code,
588
+ message
589
+ };
590
+ }
591
+ function createInspectorAgent(options) {
592
+ const maxSubscriptions = options.maxSubscriptions;
593
+ if (maxSubscriptions !== void 0 && !(Number.isSafeInteger(maxSubscriptions) && maxSubscriptions >= 1)) throw new RangeError("maxSubscriptions must be a positive safe integer when configured.");
594
+ const runtimeId = options.runtimeId ?? createRuntimeId();
595
+ const runtimeInspection = inspectRuntime(options.runtime);
596
+ const dom = options.dom;
597
+ const memberSubscriptions = /* @__PURE__ */ new Map();
598
+ const eventSubscriptions = /* @__PURE__ */ new Map();
599
+ let negotiatedMinor = INSPECTOR_PROTOCOL_VERSION.minor;
600
+ const envelopeVersion = () => ({
601
+ major: INSPECTOR_PROTOCOL_VERSION.major,
602
+ minor: negotiatedMinor
603
+ });
604
+ function capabilitiesForMinor(minor) {
605
+ if (minor < 2) return {
606
+ methods: PROTOCOL_0_1_METHODS,
607
+ events: PROTOCOL_0_1_EVENTS
608
+ };
609
+ return {
610
+ methods: dom === void 0 ? Object.freeze([...PROTOCOL_0_1_METHODS, ...PROTOCOL_0_2_METHODS]) : Object.freeze([
611
+ ...PROTOCOL_0_1_METHODS,
612
+ ...PROTOCOL_0_2_METHODS,
613
+ ...PROTOCOL_0_2_GEOMETRY_METHODS
614
+ ]),
615
+ events: dom === void 0 ? Object.freeze([...PROTOCOL_0_1_EVENTS, ...PROTOCOL_0_2_EVENTS]) : Object.freeze([
616
+ ...PROTOCOL_0_1_EVENTS,
617
+ ...PROTOCOL_0_2_EVENTS,
618
+ ...PROTOCOL_0_2_GEOMETRY_EVENTS
619
+ ])
620
+ };
621
+ }
622
+ let inspectEnabled = false;
623
+ let disposed = false;
624
+ const overlay = dom === void 0 ? null : createInspectorOverlay(dom.root.ownerDocument);
625
+ let highlightedTarget = null;
626
+ function emit(event, payload) {
627
+ if (disposed || options.transport.closed || !capabilitiesForMinor(negotiatedMinor).events.includes(event)) return;
628
+ options.transport.send({
629
+ protocol: envelopeVersion(),
630
+ kind: "event",
631
+ event,
632
+ payload
633
+ });
634
+ }
635
+ function sendSuccess(request, result) {
636
+ if (disposed || options.transport.closed) return;
637
+ options.transport.send({
638
+ protocol: envelopeVersion(),
639
+ kind: "response",
640
+ requestId: request.requestId,
641
+ ok: true,
642
+ result
643
+ });
644
+ }
645
+ function sendError(requestId, error) {
646
+ if (disposed || options.transport.closed) return;
647
+ options.transport.send({
648
+ protocol: envelopeVersion(),
649
+ kind: "response",
650
+ requestId,
651
+ ok: false,
652
+ error
653
+ });
654
+ }
655
+ function resolveNodeId(ref) {
656
+ if (ref.runtimeId !== runtimeId) return null;
657
+ return runtimeInspection.blueprint.nodes.find((node) => node.nodeId === ref.nodeId)?.nodeId ?? null;
658
+ }
659
+ function resolveWidget(ref) {
660
+ const nodeId = resolveNodeId(ref);
661
+ return nodeId === null ? null : runtimeInspection.getWidget(nodeId);
662
+ }
663
+ function nodeForAnchor(anchor) {
664
+ const node = runtimeInspection.blueprint.nodes.find((candidate) => candidate.resolved && candidate.node.id === anchor.widgetId && candidate.node.type === anchor.widgetType);
665
+ return node === void 0 ? null : {
666
+ runtimeId,
667
+ nodeId: node.nodeId
668
+ };
669
+ }
670
+ function resolveAnchor(target) {
671
+ if (dom === void 0 || !(target instanceof Element)) return null;
672
+ let element = target.closest(ANCHOR_SELECTOR);
673
+ while (element !== null && dom.root.contains(element)) {
674
+ const identity = readAnchorIdentity(element);
675
+ if (identity !== null && nodeForAnchor(identity) !== null) return {
676
+ element,
677
+ ...identity
678
+ };
679
+ if (element === dom.root) break;
680
+ element = element.parentElement?.closest(ANCHOR_SELECTOR) ?? null;
681
+ }
682
+ return null;
683
+ }
684
+ function semanticTargetForRef(ref) {
685
+ const nodeId = resolveNodeId(ref);
686
+ if (nodeId === null) return null;
687
+ const node = runtimeInspection.blueprint.getNode(nodeId);
688
+ if (node === null || !node.resolved) return null;
689
+ return {
690
+ ref,
691
+ widgetId: node.node.id,
692
+ widgetType: node.node.type
693
+ };
694
+ }
695
+ function semanticTargetForAnchorElement(element) {
696
+ if (dom === void 0 || !dom.root.contains(element)) return null;
697
+ const identity = readAnchorIdentity(element);
698
+ if (identity === null) return null;
699
+ const ref = nodeForAnchor(identity);
700
+ return ref === null ? null : {
701
+ ref,
702
+ ...identity
703
+ };
704
+ }
705
+ const geometry = dom === void 0 ? null : createSemanticGeometryController({
706
+ root: dom.root,
707
+ resolveRef: semanticTargetForRef,
708
+ resolveAnchor: semanticTargetForAnchorElement,
709
+ onInvalidated: (revision) => {
710
+ drawHighlight();
711
+ emit("geometry.invalidated", { revision });
712
+ }
713
+ });
714
+ function clearHighlight() {
715
+ highlightedTarget = null;
716
+ overlay?.clear();
717
+ }
718
+ /** Draws every fragment of the highlighted Widget; returns whether any anchor element exists. */
719
+ function drawHighlight() {
720
+ if (overlay === null || geometry === null || highlightedTarget === null) return false;
721
+ const measurement = geometry.measure(highlightedTarget);
722
+ if (measurement.rects.length === 0) overlay.clear();
723
+ else overlay.show({
724
+ label: `${highlightedTarget.widgetType}#${highlightedTarget.widgetId}`,
725
+ rects: measurement.rects
726
+ });
727
+ return measurement.anchorCount > 0;
728
+ }
729
+ function highlightTarget(target) {
730
+ if (geometry === null || overlay === null || geometry.measure(target).anchorCount === 0) return false;
731
+ highlightedTarget = target;
732
+ return drawHighlight();
733
+ }
734
+ function highlightRef(ref) {
735
+ const target = semanticTargetForRef(ref);
736
+ return target !== null && highlightTarget(target);
737
+ }
738
+ function disableInspect() {
739
+ if (!inspectEnabled) return;
740
+ inspectEnabled = false;
741
+ clearHighlight();
742
+ emit("inspect.hovered", { ref: null });
743
+ emit("agent.status", { inspectEnabled: false });
744
+ }
745
+ function onPointerOver(event) {
746
+ if (!inspectEnabled) return;
747
+ const anchor = resolveAnchor(event.target);
748
+ if (anchor === null) {
749
+ clearHighlight();
750
+ emit("inspect.hovered", { ref: null });
751
+ return;
752
+ }
753
+ const ref = nodeForAnchor(anchor);
754
+ if (ref === null) {
755
+ clearHighlight();
756
+ emit("inspect.hovered", { ref: null });
757
+ return;
758
+ }
759
+ highlightTarget({
760
+ ref,
761
+ widgetId: anchor.widgetId,
762
+ widgetType: anchor.widgetType
763
+ });
764
+ emit("inspect.hovered", {
765
+ ref,
766
+ widgetId: anchor.widgetId,
767
+ widgetType: anchor.widgetType
768
+ });
769
+ }
770
+ function onPointerLeave() {
771
+ if (!inspectEnabled) return;
772
+ clearHighlight();
773
+ emit("inspect.hovered", { ref: null });
774
+ }
775
+ function suppressPointerActivation(event) {
776
+ if (!inspectEnabled || resolveAnchor(event.target) === null) return;
777
+ event.preventDefault();
778
+ event.stopPropagation();
779
+ }
780
+ function onClick(event) {
781
+ if (!inspectEnabled) return;
782
+ const anchor = resolveAnchor(event.target);
783
+ if (anchor === null) return;
784
+ event.preventDefault();
785
+ event.stopPropagation();
786
+ const ref = nodeForAnchor(anchor);
787
+ if (ref === null) return;
788
+ emit("inspect.selected", {
789
+ ref,
790
+ widgetId: anchor.widgetId,
791
+ widgetType: anchor.widgetType
792
+ });
793
+ }
794
+ function onKeydown(event) {
795
+ if (event.key === "Escape" && inspectEnabled) {
796
+ event.preventDefault();
797
+ event.stopPropagation();
798
+ disableInspect();
799
+ }
800
+ }
801
+ function installDomListeners() {
802
+ if (dom === void 0) return () => {};
803
+ dom.root.addEventListener("pointerover", onPointerOver);
804
+ dom.root.addEventListener("pointerleave", onPointerLeave);
805
+ dom.root.addEventListener("pointerdown", suppressPointerActivation, true);
806
+ dom.root.addEventListener("pointerup", suppressPointerActivation, true);
807
+ dom.root.addEventListener("click", onClick, true);
808
+ dom.root.ownerDocument.addEventListener("keydown", onKeydown, true);
809
+ return () => {
810
+ dom.root.removeEventListener("pointerover", onPointerOver);
811
+ dom.root.removeEventListener("pointerleave", onPointerLeave);
812
+ dom.root.removeEventListener("pointerdown", suppressPointerActivation, true);
813
+ dom.root.removeEventListener("pointerup", suppressPointerActivation, true);
814
+ dom.root.removeEventListener("click", onClick, true);
815
+ dom.root.ownerDocument.removeEventListener("keydown", onKeydown, true);
816
+ };
817
+ }
818
+ /** With no configured cap this never rejects: unlimited is the default. */
819
+ function rejectAtSubscriptionLimit(request) {
820
+ if (maxSubscriptions === void 0 || memberSubscriptions.size + eventSubscriptions.size < maxSubscriptions) return false;
821
+ const message = `This Inspector Agent allows at most ${maxSubscriptions} live subscriptions.`;
822
+ sendError(request.requestId, protocolError(negotiatedMinor >= 3 ? "subscription-limit" : "internal-error", message));
823
+ return true;
824
+ }
825
+ function subscribeMember(request) {
826
+ if (request.params.ref.runtimeId !== runtimeId) {
827
+ sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
828
+ return;
829
+ }
830
+ const widget = resolveWidget(request.params.ref);
831
+ if (widget === null) {
832
+ sendError(request.requestId, protocolError("widget-not-found", "The requested widget does not exist in this Runtime snapshot."));
833
+ return;
834
+ }
835
+ const member = request.params.member;
836
+ const observable = member.type === "state" ? widget.getState(member.name) : widget.getProperty(member.name);
837
+ const projected = projectRuntimeMemberSnapshot(widget, member);
838
+ if (observable === null || projected === null) {
839
+ sendError(request.requestId, protocolError("member-not-found", "The requested Runtime member does not exist."));
840
+ return;
841
+ }
842
+ if (rejectAtSubscriptionLimit(request)) return;
843
+ const subscriptionId = `subscription-${subscriptionSequence++}`;
844
+ let unsubscribe;
845
+ try {
846
+ unsubscribe = observable.subscribe(() => {
847
+ const next = projectRuntimeMemberSnapshot(widget, member);
848
+ if (next !== null) emit("runtime.memberChanged", {
849
+ subscriptionId,
850
+ ref: request.params.ref,
851
+ member: next
852
+ });
853
+ });
854
+ } catch {
855
+ sendError(request.requestId, protocolError("internal-error", "Unable to subscribe to the Runtime member."));
856
+ return;
857
+ }
858
+ memberSubscriptions.set(subscriptionId, unsubscribe);
859
+ sendSuccess(request, {
860
+ subscriptionId,
861
+ member: projected
862
+ });
863
+ }
864
+ function subscribeEvent(request) {
865
+ if (request.params.ref.runtimeId !== runtimeId) {
866
+ sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
867
+ return;
868
+ }
869
+ const widget = resolveWidget(request.params.ref);
870
+ if (widget === null) {
871
+ sendError(request.requestId, protocolError("widget-not-found", "The requested widget does not exist in this Runtime snapshot."));
872
+ return;
873
+ }
874
+ const observable = widget.getEvent(request.params.event);
875
+ if (observable === null) {
876
+ sendError(request.requestId, protocolError("event-not-found", "The requested Runtime event does not exist."));
877
+ return;
878
+ }
879
+ if (rejectAtSubscriptionLimit(request)) return;
880
+ const subscriptionId = `event-subscription-${subscriptionSequence++}`;
881
+ let unsubscribe;
882
+ try {
883
+ unsubscribe = observable.subscribe((args) => {
884
+ emit("runtime.eventOccurred", {
885
+ subscriptionId,
886
+ ref: request.params.ref,
887
+ event: request.params.event,
888
+ args: projectEventArgs(args)
889
+ });
890
+ });
891
+ } catch {
892
+ sendError(request.requestId, protocolError("internal-error", "Unable to subscribe to the Runtime event."));
893
+ return;
894
+ }
895
+ eventSubscriptions.set(subscriptionId, unsubscribe);
896
+ sendSuccess(request, {
897
+ subscriptionId,
898
+ event: request.params.event
899
+ });
900
+ }
901
+ function handleRequest(request) {
902
+ if (!isCompatibleProtocolVersion(request.protocol)) {
903
+ sendError(request.requestId, protocolError("unsupported-version", `Unsupported Inspector protocol major ${request.protocol.major}.`));
904
+ return;
905
+ }
906
+ if (request.method !== "handshake") {
907
+ negotiatedMinor = Math.min(negotiatedMinor, request.protocol.minor);
908
+ if (!capabilitiesForMinor(negotiatedMinor).methods.includes(request.method)) {
909
+ sendError(request.requestId, protocolError("unknown-method", "Method unavailable in this Inspector protocol session."));
910
+ return;
911
+ }
912
+ }
913
+ switch (request.method) {
914
+ case "handshake": {
915
+ if (!isCompatibleProtocolVersion(request.params.protocol)) {
916
+ sendError(request.requestId, protocolError("unsupported-version", `Unsupported Inspector protocol major ${request.params.protocol.major}.`));
917
+ return;
918
+ }
919
+ negotiatedMinor = Math.min(INSPECTOR_PROTOCOL_VERSION.minor, request.protocol.minor, request.params.protocol.minor);
920
+ const capabilities = capabilitiesForMinor(negotiatedMinor);
921
+ sendSuccess(request, {
922
+ protocol: envelopeVersion(),
923
+ capabilities
924
+ });
925
+ return;
926
+ }
927
+ case "runtime.list":
928
+ sendSuccess(request, { runtimes: [{
929
+ runtimeId,
930
+ rootNodeId: runtimeInspection.blueprint.rootNodeId
931
+ }] });
932
+ return;
933
+ case "blueprint.getSnapshot":
934
+ if (request.params.runtimeId !== runtimeId) {
935
+ sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
936
+ return;
937
+ }
938
+ sendSuccess(request, projectBlueprintSnapshot(runtimeId, runtimeInspection.blueprint, negotiatedMinor));
939
+ return;
940
+ case "runtime.getWidgetSnapshot": {
941
+ if (request.params.ref.runtimeId !== runtimeId) {
942
+ sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
943
+ return;
944
+ }
945
+ const nodeId = resolveNodeId(request.params.ref);
946
+ const snapshot = nodeId === null ? null : projectRuntimeWidgetSnapshot(runtimeId, runtimeInspection, nodeId);
947
+ if (snapshot === null) {
948
+ sendError(request.requestId, protocolError("widget-not-found", "The requested widget does not exist in this Runtime snapshot."));
949
+ return;
950
+ }
951
+ sendSuccess(request, snapshot);
952
+ return;
953
+ }
954
+ case "runtime.subscribeMember":
955
+ subscribeMember(request);
956
+ return;
957
+ case "runtime.subscribeEvent":
958
+ subscribeEvent(request);
959
+ return;
960
+ case "runtime.unsubscribeMember": {
961
+ const unsubscribe = memberSubscriptions.get(request.params.subscriptionId);
962
+ if (unsubscribe === void 0) {
963
+ sendSuccess(request, { removed: false });
964
+ return;
965
+ }
966
+ memberSubscriptions.delete(request.params.subscriptionId);
967
+ unsubscribe();
968
+ sendSuccess(request, { removed: true });
969
+ return;
970
+ }
971
+ case "runtime.unsubscribeEvent": {
972
+ const unsubscribe = eventSubscriptions.get(request.params.subscriptionId);
973
+ if (unsubscribe === void 0) {
974
+ sendSuccess(request, { removed: false });
975
+ return;
976
+ }
977
+ eventSubscriptions.delete(request.params.subscriptionId);
978
+ unsubscribe();
979
+ sendSuccess(request, { removed: true });
980
+ return;
981
+ }
982
+ case "inspect.hitTest":
983
+ if (geometry === null) {
984
+ sendError(request.requestId, protocolError("internal-error", "DOM geometry is unavailable for this Inspector Agent."));
985
+ return;
986
+ }
987
+ sendSuccess(request, geometry.hitTest(request.params));
988
+ return;
989
+ case "geometry.resolve":
990
+ if (request.params.ref.runtimeId !== runtimeId) {
991
+ sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
992
+ return;
993
+ }
994
+ if (geometry === null) {
995
+ sendError(request.requestId, protocolError("internal-error", "DOM geometry is unavailable for this Inspector Agent."));
996
+ return;
997
+ }
998
+ sendSuccess(request, geometry.resolve(request.params.ref));
999
+ return;
1000
+ case "inspect.enable":
1001
+ inspectEnabled = true;
1002
+ emit("agent.status", { inspectEnabled: true });
1003
+ sendSuccess(request, { enabled: true });
1004
+ return;
1005
+ case "inspect.disable":
1006
+ disableInspect();
1007
+ sendSuccess(request, { enabled: false });
1008
+ return;
1009
+ case "highlight.show":
1010
+ if (request.params.ref.runtimeId !== runtimeId) {
1011
+ sendError(request.requestId, protocolError("runtime-not-found", "The requested Runtime is not registered."));
1012
+ return;
1013
+ }
1014
+ sendSuccess(request, { highlighted: highlightRef(request.params.ref) });
1015
+ return;
1016
+ case "highlight.clear":
1017
+ clearHighlight();
1018
+ sendSuccess(request, { highlighted: false });
1019
+ }
1020
+ }
1021
+ const removeDomListeners = installDomListeners();
1022
+ const unsubscribeTransport = options.transport.subscribe((raw) => {
1023
+ const request = parseInspectorRequestMessage(raw);
1024
+ if (request !== null) {
1025
+ handleRequest(request);
1026
+ return;
1027
+ }
1028
+ if (typeof raw === "object" && raw !== null && "kind" in raw && raw.kind === "request" && "requestId" in raw && typeof raw.requestId === "string") sendError(raw.requestId, protocolError("invalid-message", "Invalid Inspector protocol request."));
1029
+ });
1030
+ let unsubscribeClose = () => {};
1031
+ function cleanup(closeTransport) {
1032
+ if (disposed) return;
1033
+ disposed = true;
1034
+ for (const unsubscribe of memberSubscriptions.values()) unsubscribe();
1035
+ memberSubscriptions.clear();
1036
+ for (const unsubscribe of eventSubscriptions.values()) unsubscribe();
1037
+ eventSubscriptions.clear();
1038
+ removeDomListeners();
1039
+ geometry?.dispose();
1040
+ clearHighlight();
1041
+ unsubscribeTransport();
1042
+ unsubscribeClose();
1043
+ if (closeTransport && !options.transport.closed) options.transport.close();
1044
+ }
1045
+ unsubscribeClose = options.transport.subscribeClose(() => cleanup(false));
1046
+ return {
1047
+ runtimeId,
1048
+ get inspectEnabled() {
1049
+ return inspectEnabled;
1050
+ },
1051
+ invalidateGeometry() {
1052
+ geometry?.invalidate();
1053
+ },
1054
+ dispose() {
1055
+ cleanup(options.closeTransportOnDispose ?? true);
1056
+ }
1057
+ };
1058
+ }
1059
+ //#endregion
1060
+ export { createInspectorAgent };