@shadow-js/devtools 1.0.0 → 1.0.2
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/CHANGELOG.md +22 -0
- package/dist/dev/agent.js +9 -5
- package/dist/dev/agent.js.map +1 -1
- package/dist/dev/backend.d.ts +6 -0
- package/dist/dev/backend.js.map +1 -1
- package/dist/dev/hook.js +6 -5
- package/dist/dev/hook.js.map +1 -1
- package/dist/dev/internal/describe-element.js +109 -0
- package/dist/dev/internal/describe-element.js.map +1 -0
- package/dist/dev/internal/wire-guard.js +143 -0
- package/dist/dev/internal/wire-guard.js.map +1 -0
- package/dist/dev/model.d.ts +2 -0
- package/dist/dev/model.js +10 -4
- package/dist/dev/model.js.map +1 -1
- package/dist/dev/transport.d.ts +62 -2
- package/dist/dev/transport.js +294 -20
- package/dist/dev/transport.js.map +1 -1
- package/dist/prod/agent.js +1 -1
- package/dist/prod/agent.js.map +1 -1
- package/dist/prod/backend.js.map +1 -1
- package/dist/prod/hook.js.map +1 -1
- package/dist/prod/internal/describe-element.js +2 -0
- package/dist/prod/internal/describe-element.js.map +1 -0
- package/dist/prod/internal/wire-guard.js +2 -0
- package/dist/prod/internal/wire-guard.js.map +1 -0
- package/dist/prod/model.js +1 -1
- package/dist/prod/model.js.map +1 -1
- package/dist/prod/transport.js +1 -1
- package/dist/prod/transport.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.2
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- The extension bridge forwards the answers a panel asked for up to 16 million characters (the complete state of a page that ran a few thousand effects used to be dropped, so the panel never became ready) and replaces a larger answer with an error answer instead of dropping it.
|
|
8
|
+
- A panel follows the inspected page across a reload: a batch whose sequence numbers start again from 1 is taken as a new agent and the panel asks for its state.
|
|
9
|
+
- `connectRemote` skips events and states that do not have the shape of an event or a state, and holds at most 50,000 events while it waits for the first state.
|
|
10
|
+
- The panel's graveyard is cut to its limit when a state from a larger model is imported.
|
|
11
|
+
- A failing subscriber of an agent no longer keeps the other subscribers from receiving a batch.
|
|
12
|
+
- A sink that detaches while the hook delivers an event no longer makes the next sink miss it.
|
|
13
|
+
- A snapshot the panel cannot get (an answer over the bridge's size cap, or a state it cannot read) now shows "Could not load the page: <reason>" in the panel instead of "Connecting" for good; `Backend` has an optional `error()` for it.
|
|
14
|
+
- Every message of `serveAgent` carries an `instance` id (random per served agent), and the bridge asks the agent to say `hello` after it reopens a port: a panel that sees another id discards its state and asks for a new one, even when the reloaded page's sequence numbers start above the old ones.
|
|
15
|
+
- The agent describes an element in a hydration issue from its first nodes instead of serializing the whole `outerHTML` to keep 200 characters.
|
|
16
|
+
- The extension build and zip scripts take their default version from `package.json` instead of a fixed `1.0.0`.
|
|
17
|
+
- A snapshot whose JSON text is longer than 15 million characters (the complete state of a very busy page) no longer ends in "Could not load the page": the agent sends it as numbered chunks of at most 400,000 characters (`chunk` messages carrying the request id, the piece number, the count, the total size and the instance id), the extension bridge forwards each one, and `connectRemote` joins them. Answers up to that size keep the single `response` message, so an older panel or bridge sees no change for them. The panel assembles at most 4 answers at a time, 1024 pieces and 256 million characters each, ignores duplicate pieces, pieces for requests it did not make and pieces of another agent instance, and gives an answer up with an error after 30 seconds without a new piece (`RemoteOptions.chunkTimeoutMs`). `ServeOptions` has `chunkChars` and `singleResponseChars` to change the two sizes.
|
|
18
|
+
|
|
19
|
+
## 1.0.1
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- Released at 1.0.1 with the other packages, which share one version. No change to this package.
|
|
24
|
+
|
|
3
25
|
## 1.0.0
|
|
4
26
|
|
|
5
27
|
### Added
|
package/dist/dev/agent.js
CHANGED
|
@@ -2,6 +2,7 @@ import { EVENT } from "./protocol.js";
|
|
|
2
2
|
import { errorMessage, parseEditableText, preview, toEditableText } from "./preview.js";
|
|
3
3
|
import { readInspections } from "./inspection.js";
|
|
4
4
|
import { snapshotOf } from "./inspector.js";
|
|
5
|
+
import { describeElement } from "./internal/describe-element.js";
|
|
5
6
|
import { RingBuffer } from "./ring.js";
|
|
6
7
|
import { InspectorModel } from "./model.js";
|
|
7
8
|
//#region src/agent.ts
|
|
@@ -17,10 +18,7 @@ function toNumber(value) {
|
|
|
17
18
|
function describeSide(value) {
|
|
18
19
|
if (typeof value === "string") return value.length > 200 ? `${value.slice(0, 199)}…` : value;
|
|
19
20
|
if (typeof Node !== "undefined" && value instanceof Node) {
|
|
20
|
-
if (value instanceof Element)
|
|
21
|
-
const html = value.outerHTML;
|
|
22
|
-
return html.length > 200 ? `${html.slice(0, 199)}…` : html;
|
|
23
|
-
}
|
|
21
|
+
if (value instanceof Element) return describeElement(value, 200);
|
|
24
22
|
return `#${value.nodeName}`;
|
|
25
23
|
}
|
|
26
24
|
return preview(value, 200);
|
|
@@ -91,7 +89,13 @@ function createAgent(options = {}) {
|
|
|
91
89
|
if (pending.length === 0) return;
|
|
92
90
|
const batch = pending;
|
|
93
91
|
pending = [];
|
|
94
|
-
|
|
92
|
+
let failure;
|
|
93
|
+
for (const listener of [...listeners]) try {
|
|
94
|
+
listener(batch);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
failure ??= { error };
|
|
97
|
+
}
|
|
98
|
+
if (failure !== void 0) throw failure.error;
|
|
95
99
|
};
|
|
96
100
|
/** Stamps, records and fans out one event. */
|
|
97
101
|
function emit(event, at) {
|
package/dist/dev/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","names":[],"sources":["../../src/agent.ts"],"sourcesContent":["import { readInspections } from \"./inspection\";\nimport { type GraphSnapshot, snapshotOf } from \"./inspector\";\nimport { InspectorModel, type ModelLimits, type ModelState, type NodeRecord } from \"./model\";\nimport { errorMessage, parseEditableText, preview, toEditableText } from \"./preview\";\nimport {\n type DevtoolsHook,\n EVENT,\n type HookSink,\n NO_ID,\n type StoreHandle,\n type WireEvent,\n} from \"./protocol\";\nimport { RingBuffer } from \"./ring\";\n\n/**\n * Options of {@link createAgent}. Every field is optional.\n *\n * @since 1.0.0\n */\nexport interface AgentOptions {\n /** Capacities of the model's buffers. The values left out take the defaults of `DEFAULT_LIMITS`. */\n limits?: Partial<ModelLimits>;\n /**\n * Raw events kept for the events log. The newest are kept; older ones are overwritten and counted\n * in `dropped`.\n *\n * @default 10000\n */\n events?: number;\n /**\n * Most events waiting for subscribers. When this many are pending they are delivered at once,\n * instead of at the end of the current microtask.\n *\n * @default 10000\n */\n maxPending?: number;\n /**\n * Maximum length of a value preview, in characters.\n *\n * @default 80\n */\n previewLength?: number;\n /**\n * The clock, in milliseconds. Defaults to `performance.now` (or `Date.now` where it is missing).\n */\n now?: () => number;\n /**\n * Writes a signal node for the value editor. Pass `writeSignal` from `@shadow-js/core/extend`.\n * Without it signals are shown but not editable: a write is refused with \"Editing is not enabled.\".\n */\n writeSignal?: (node: never, value: never) => unknown;\n}\n\n/**\n * Counters of what the agent saw. They keep growing while the agent runs; {@link Agent.clear} does not\n * reset them.\n *\n * @since 1.0.0\n */\nexport interface AgentStats {\n /** Events the agent was offered while it was not paused. */\n received: number;\n /** Events turned into wire events. */\n recorded: number;\n /**\n * Events the agent skipped on purpose: objects created inside {@link Agent.quiet} (the tools' own\n * UI), dispose and unmount events for objects it never named, malformed store handles, and event\n * kinds from a newer runtime.\n */\n ignored: number;\n /**\n * Writes, runs and mounts about objects the agent never saw created (reported before it attached,\n * when the hook's replay buffer had been released).\n */\n unknown: number;\n}\n\n/**\n * A command a panel sends to the agent, answered by {@link Agent.handle}. All fields are plain data,\n * so a command can cross a message channel:\n *\n * - `snapshot`: the model's state.\n * - `value` and `write`: read a signal as editable text, or write it.\n * - `store` and `store-set`: read a store as editable text, or write one path of it.\n * - `highlight`: the agent acknowledges it; the page draws the highlight (see `createLocalBackend`).\n * - `pause`, `resume`, `clear`: control recording. `stats`: the counters.\n * - `inspect`: every inspection source registered with `registerInspection`, read now.\n *\n * @since 1.0.0\n */\nexport type AgentRequest =\n | { type: \"snapshot\" }\n | { type: \"value\"; id: number }\n | { type: \"write\"; id: number; text: string }\n | { type: \"store\"; id: number }\n | { type: \"store-set\"; id: number; path: Array<string | number>; text: string }\n | { type: \"highlight\"; id: number | null }\n | { type: \"pause\" }\n | { type: \"resume\" }\n | { type: \"clear\" }\n | { type: \"stats\" }\n | { type: \"inspect\" };\n\n/**\n * The answer to an {@link AgentRequest}: the result, or an error message to show the user.\n *\n * @since 1.0.0\n */\nexport type AgentResponse = { ok: true; result: unknown } | { ok: false; error: string };\n\n/**\n * The value of a node, as text, for the value editor.\n *\n * @since 1.0.0\n */\nexport interface ValueResult {\n /** The node that was asked for. */\n id: number;\n /** `signal` for a signal, `store` for a store. */\n kind: \"signal\" | \"store\";\n /** The value as editable text (see {@link toEditableText}). */\n text: string;\n /** True when the panel may write it: a store always, a signal only when `writeSignal` is set. */\n editable: boolean;\n}\n\n/**\n * The agent. It receives the runtime's own objects from the hook, turns them into id-based\n * {@link WireEvent}s and folds them into an {@link InspectorModel}. Recording is O(1) per event and\n * every buffer is bounded: the raw event ring, the model's run, write and flush rings, the disposed-node\n * graveyard and the live node count.\n *\n * A development tool: the hook it attaches to is installed only in development builds (see\n * `installHook`).\n *\n * @since 1.0.0\n */\nexport interface Agent extends HookSink {\n /** The model the events are folded into. */\n readonly model: InspectorModel;\n /** The newest raw events, as many as the `events` option holds (default 10000). */\n readonly events: RingBuffer<WireEvent>;\n /** Counters of what the agent saw. */\n readonly stats: Readonly<AgentStats>;\n /** True while the agent drops the events the runtime reports (see {@link Agent.pause}). */\n readonly paused: boolean;\n /**\n * Attaches the agent to `hook`, so that the hook delivers its events to the agent. Pass the hook\n * from `installHook` or `getHook`.\n *\n * @param hook The hook to listen to.\n * @returns A function that detaches the agent from the hook.\n */\n attach(hook: DevtoolsHook): () => void;\n /**\n * Calls `listener` with batches of new events: once per microtask, or sooner when `maxPending`\n * events are waiting. Only events recorded after the call are delivered.\n *\n * @param listener Receives each batch, oldest first.\n * @returns A function that unsubscribes the listener.\n */\n subscribe(listener: (events: readonly WireEvent[]) => void): () => void;\n /** Delivers the pending events to the subscribers now, instead of at the end of the microtask. */\n flush(): void;\n /**\n * Runs `fn` while the agent ignores everything the runtime creates, and everything created under\n * those nodes. Use it to mount the tools' own UI, so that the tools never inspect themselves. An error\n * thrown by `fn` propagates.\n *\n * @param fn The work to run.\n * @returns What `fn` returns.\n */\n quiet<T>(fn: () => T): T;\n /** Stops recording: events the runtime reports are dropped until {@link Agent.resume}. */\n pause(): void;\n /** Resumes recording after {@link Agent.pause}. */\n resume(): void;\n /**\n * Forgets everything recorded so far: the model's nodes and records, the event ring, and the\n * references to live nodes. Nodes created later are tracked; live ones are not, and later events about\n * them count as unknown. {@link AgentStats} are not reset.\n */\n clear(): void;\n /** The graph snapshot of the model (see `snapshotOf`). Each call builds a new object. */\n snapshot(): GraphSnapshot;\n /** The model state, for sending to a remote panel. */\n state(): ModelState;\n /**\n * Answers a panel command. Never throws: a failure, such as an error from writing user state, comes\n * back as `ok: false`, and so does an unknown command.\n *\n * @param request The command.\n * @returns The answer.\n */\n handle(request: AgentRequest): AgentResponse;\n /**\n * The connected DOM nodes that the component `id` rendered, for highlighting. Empty when the\n * component is unknown or its nodes left the page. The agent holds the nodes weakly.\n *\n * @param id The component's node id.\n * @returns The nodes.\n */\n nodesOf(id: number): Node[];\n /**\n * Detaches from every hook it was attached to, and drops the listeners and the references to live\n * signals, components and stores. The model and the event ring keep what they recorded.\n */\n dispose(): void;\n}\n\n/**\n * Store handles by node id, held weakly: the handle lives as long as the store it reads, because the\n * runtime keeps it reachable from the store's root (see `createDeepStore` in `@shadow-js/core`).\n */\ntype Registry = Map<number, WeakRef<StoreHandle>>;\n\nfunction now(): number {\n return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction isObject(value: unknown): value is object {\n return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n\nfunction toNumber(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction describeSide(value: unknown): string {\n if (typeof value === \"string\") return value.length > 200 ? `${value.slice(0, 199)}…` : value;\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n if (value instanceof Element) {\n const html = value.outerHTML;\n return html.length > 200 ? `${html.slice(0, 199)}…` : html;\n }\n return `#${value.nodeName}`;\n }\n return preview(value, 200);\n}\n\n/**\n * Creates an agent that records the runtime's events. Attach it to a hook with `agent.attach(hook)`.\n * A development tool: the events come only from development builds, where the hook is installed.\n *\n * @param options Buffer sizes, clock and the signal writer. Every field is optional.\n * @returns The agent.\n * @example\n * import { createAgent, installHook } from \"@shadow-js/devtools\";\n * import { writeSignal } from \"@shadow-js/core/extend\";\n *\n * const hook = installHook();\n * const agent = createAgent({ writeSignal });\n * if (hook !== undefined) agent.attach(hook);\n * agent.snapshot().counts.nodes;\n * @since 1.0.0\n */\nexport function createAgent(options: AgentOptions = {}): Agent {\n const clock = options.now ?? now;\n const previewLength = options.previewLength ?? 80;\n const maxPending = options.maxPending ?? 10_000;\n const model = new InspectorModel(options.limits);\n const events = new RingBuffer<WireEvent>(options.events ?? 10_000);\n const stats: AgentStats = { received: 0, recorded: 0, ignored: 0, unknown: 0 };\n\n // Objects are named by id through weak maps: the agent never keeps the runtime's nodes alive.\n const ids = new WeakMap<object, number>();\n const ignored = new WeakSet<object>();\n const signals = new Map<number, WeakRef<object>>();\n const components = new Map<number, WeakRef<Node>[]>();\n const stores: Registry = new Map();\n let nextId = 1;\n let seq = 0;\n let paused = false;\n let quietDepth = 0;\n /** The hook the agent listens to: its registry of inspection sources answers `inspect`. */\n let inspectionHook: DevtoolsHook | undefined;\n let pending: WireEvent[] = [];\n let scheduled = false;\n /** A flush that started but has not recorded any run yet: empty flushes are not worth a record. */\n let queuedFlush: { render: number; user: number; t: number } | null = null;\n let flushOpen = false;\n const listeners = new Set<(events: readonly WireEvent[]) => void>();\n const detachers = new Set<() => void>();\n // Signals, stores and resources have no dispose event of their own when nothing owns them (or their\n // owner never disposes): the finalizer retires their node once the runtime has collected them. It is\n // registered once per object, so a resource that reports many states is not registered many times.\n const finalizer: FinalizationRegistry<number> | undefined =\n typeof FinalizationRegistry === \"function\"\n ? new FinalizationRegistry<number>((id) => {\n signals.delete(id);\n stores.delete(id);\n if (model.nodes.has(id)) emit({ k: \"owner-\", seq: 0, t: 0, id });\n })\n : undefined;\n\n model.onBury = (record: NodeRecord) => {\n signals.delete(record.id);\n components.delete(record.id);\n stores.delete(record.id);\n };\n\n const deliver = (): void => {\n scheduled = false;\n if (pending.length === 0) return;\n const batch = pending;\n pending = [];\n for (const listener of listeners) listener(batch);\n };\n\n /** Stamps, records and fans out one event. */\n function emit(event: WireEvent, at?: number): void {\n seq += 1;\n event.seq = seq;\n event.t = at ?? clock();\n stats.recorded += 1;\n events.push(event);\n model.apply(event);\n if (listeners.size === 0) return;\n pending.push(event);\n if (pending.length >= maxPending) {\n deliver();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(deliver);\n }\n }\n\n /** Emits the held-back flush start before the first event that belongs to it. */\n const openFlush = (): void => {\n if (queuedFlush === null) return;\n const held = queuedFlush;\n queuedFlush = null;\n flushOpen = true;\n emit({ k: \"flush+\", seq: 0, t: 0, render: held.render, user: held.user }, held.t);\n };\n\n const lookup = (value: unknown): number => {\n if (!isObject(value)) return NO_ID;\n return ids.get(value) ?? NO_ID;\n };\n\n const register = (value: object): number => {\n const existing = ids.get(value);\n if (existing !== undefined) return existing;\n const id = nextId;\n nextId += 1;\n ids.set(value, id);\n return id;\n };\n\n /**\n * Like `register`, for a leaf node (signal, store, resource): the finalizer retires it once the runtime\n * has collected the object. Owners and computations are not registered: an owner can be unreachable\n * while its signals are still in use, and retiring it would bury them too.\n */\n const registerLeaf = (value: object): number => {\n const existing = ids.get(value);\n if (existing !== undefined) return existing;\n const id = register(value);\n finalizer?.register(value, id);\n return id;\n };\n\n /** True (and remembered) when the object belongs to the tools' own UI. */\n const isIgnored = (value: unknown, parent: unknown): boolean => {\n if (!isObject(value)) return false;\n if (quietDepth > 0 || (isObject(parent) && ignored.has(parent))) {\n ignored.add(value);\n return true;\n }\n return ignored.has(value);\n };\n\n const mapIds = (values: unknown): number[] => {\n const out: number[] = [];\n if (!Array.isArray(values)) return out;\n for (let i = 0; i < values.length; i += 1) {\n const id = lookup(values[i]);\n if (id !== NO_ID) out.push(id);\n }\n return out;\n };\n\n const nodesIn = (value: unknown): WeakRef<Node>[] => {\n const out: WeakRef<Node>[] = [];\n if (typeof Node === \"undefined\") return out;\n const push = (candidate: unknown): void => {\n if (candidate instanceof DocumentFragment) {\n for (const child of Array.from(candidate.childNodes)) out.push(new WeakRef(child));\n } else if (candidate instanceof Node) {\n out.push(new WeakRef(candidate));\n }\n };\n if (Array.isArray(value)) for (const entry of value) push(entry);\n else push(value);\n return out;\n };\n\n function receive(kind: number, a: unknown, b: unknown, c: unknown, d: unknown, e: unknown): void {\n if (paused) return;\n stats.received += 1;\n switch (kind) {\n case EVENT.OWNER_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof d === \"string\" ? d : undefined;\n emit({\n k: \"owner+\",\n seq: 0,\n t: 0,\n id: register(a),\n parent: lookup(b),\n label: typeof c === \"string\" ? c : \"owner\",\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.OWNER_DISPOSED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n emit({ k: \"owner-\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.SIGNAL_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const id = registerLeaf(a);\n signals.set(id, new WeakRef(a));\n const name = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"signal+\",\n seq: 0,\n t: 0,\n id,\n owner: lookup(b),\n preview: preview(d, previewLength),\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.SIGNAL_WRITTEN: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n emit({\n k: \"write\",\n seq: 0,\n t: 0,\n id,\n preview: preview(b, previewLength),\n writer: lookup(c),\n observers: mapIds(d),\n });\n return;\n }\n case EVENT.COMPUTATION_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof d === \"string\" ? d : undefined;\n emit({\n k: \"comp+\",\n seq: 0,\n t: 0,\n id: register(a),\n owner: lookup(b),\n kind: c === \"memo\" ? \"memo\" : \"effect\",\n render: e === true,\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.COMPUTATION_RUN: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n openFlush();\n emit({\n k: \"run\",\n seq: 0,\n t: 0,\n id,\n start: toNumber(b),\n duration: toNumber(c),\n changed: d === true,\n sources: mapIds(e),\n });\n return;\n }\n case EVENT.COMPUTATION_DISPOSED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n emit({ k: \"comp-\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.COMPONENT_MOUNTED: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n const refs = nodesIn(c);\n if (refs.length > 0) components.set(id, refs);\n emit({ k: \"mount\", seq: 0, t: 0, id, name: typeof b === \"string\" ? b : \"Component\" });\n // A node beyond maxNodes is never buried, so its entry would never be removed: forget it.\n if (!model.nodes.has(id)) components.delete(id);\n return;\n }\n case EVENT.COMPONENT_UNMOUNTED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n components.delete(id);\n emit({ k: \"unmount\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.RESOURCE_STATE: {\n if (!isObject(a) || isIgnored(a, d)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"resource\",\n seq: 0,\n t: 0,\n id: registerLeaf(a),\n owner: lookup(d),\n state: typeof b === \"string\" ? b : String(b),\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.ERROR: {\n const code = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"error\",\n seq: 0,\n t: 0,\n id: lookup(a),\n message: errorMessage(b),\n ...(code === undefined ? {} : { code }),\n });\n return;\n }\n case EVENT.HYDRATION_MISMATCH:\n emit({\n k: \"hydration\",\n seq: 0,\n t: 0,\n message: typeof a === \"string\" ? a : errorMessage(a),\n expected: describeSide(b),\n actual: describeSide(c),\n });\n return;\n case EVENT.FLUSH_START:\n queuedFlush = { render: toNumber(a), user: toNumber(b), t: clock() };\n return;\n case EVENT.FLUSH_END:\n queuedFlush = null;\n if (flushOpen) {\n flushOpen = false;\n emit({ k: \"flush-\", seq: 0, t: 0, runs: toNumber(a) });\n }\n return;\n case EVENT.STORE_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const handle = readStoreHandle(a);\n if (handle === null) {\n stats.ignored += 1;\n return;\n }\n const id = registerLeaf(a);\n stores.set(id, new WeakRef(handle));\n emit({ k: \"store+\", seq: 0, t: 0, id, owner: lookup(b), name: handle.name });\n // A store beyond maxNodes is never buried: nothing else would forget its handle.\n if (!model.nodes.has(id)) stores.delete(id);\n return;\n }\n default:\n // An event kind from a newer runtime: ignore it.\n stats.ignored += 1;\n }\n }\n\n const readStoreHandle = (value: object): StoreHandle | null => {\n const name: unknown = Reflect.get(value, \"name\");\n const snapshot: unknown = Reflect.get(value, \"snapshot\");\n const set: unknown = Reflect.get(value, \"set\");\n if (typeof name !== \"string\" || typeof snapshot !== \"function\" || typeof set !== \"function\") {\n return null;\n }\n return value as StoreHandle;\n };\n\n const signalValue = (id: number): { found: true; value: unknown } | { found: false } => {\n const node = signals.get(id)?.deref();\n if (node === undefined) return { found: false };\n return { found: true, value: Reflect.get(node, \"value\") };\n };\n\n const fail = (error: string): AgentResponse => ({ ok: false, error });\n\n function handle(request: AgentRequest): AgentResponse {\n try {\n switch (request.type) {\n case \"snapshot\":\n return { ok: true, result: model.exportState() };\n case \"stats\":\n return { ok: true, result: { ...stats, events: events.size, dropped: events.dropped } };\n case \"value\": {\n const read = signalValue(request.id);\n if (!read.found) return fail(\"The signal is gone.\");\n const result: ValueResult = {\n id: request.id,\n kind: \"signal\",\n text: toEditableText(read.value),\n editable: options.writeSignal !== undefined,\n };\n return { ok: true, result };\n }\n case \"write\": {\n const node = signals.get(request.id)?.deref();\n if (node === undefined) return fail(\"The signal is gone.\");\n if (options.writeSignal === undefined) return fail(\"Editing is not enabled.\");\n const parsed = parseEditableText(request.text);\n if (!parsed.ok) return fail(parsed.error);\n const write = options.writeSignal as (node: object, value: unknown) => unknown;\n write(node, parsed.value);\n return { ok: true, result: null };\n }\n case \"store\": {\n const store = stores.get(request.id)?.deref();\n if (store === undefined) return fail(\"The store is gone.\");\n const result: ValueResult = {\n id: request.id,\n kind: \"store\",\n text: toEditableText(store.snapshot()),\n editable: true,\n };\n return { ok: true, result };\n }\n case \"store-set\": {\n const store = stores.get(request.id)?.deref();\n if (store === undefined) return fail(\"The store is gone.\");\n const parsed = parseEditableText(request.text);\n if (!parsed.ok) return fail(parsed.error);\n store.set(request.path, parsed.value);\n return { ok: true, result: null };\n }\n case \"pause\":\n paused = true;\n return { ok: true, result: null };\n case \"resume\":\n paused = false;\n return { ok: true, result: null };\n case \"clear\":\n clear();\n return { ok: true, result: null };\n case \"highlight\":\n // Drawing needs the page; the page side draws it (see createLocalBackend).\n return { ok: true, result: null };\n case \"inspect\":\n return {\n ok: true,\n result: { sources: readInspections(inspectionHook?.inspections?.() ?? []) },\n };\n default:\n return fail(\"Unknown command.\");\n }\n } catch (error) {\n // Writing user state can throw (a validation in the app): report it to the panel.\n return fail(errorMessage(error));\n }\n }\n\n function clear(): void {\n model.importState({\n lastSeq: model.lastSeq,\n overflow: 0,\n unknown: 0,\n nodes: [],\n graveyard: [],\n runs: [],\n writes: [],\n flushes: [],\n errors: [],\n hydration: [],\n });\n events.clear();\n pending = [];\n queuedFlush = null;\n flushOpen = false;\n signals.clear();\n components.clear();\n stores.clear();\n }\n\n const agent: Agent = {\n model,\n events,\n stats,\n get paused(): boolean {\n return paused;\n },\n receive,\n attach(hook): () => void {\n inspectionHook = hook;\n const detach = hook.attach(agent);\n detachers.add(detach);\n return () => {\n detachers.delete(detach);\n detach();\n };\n },\n subscribe(listener): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n flush: deliver,\n quiet<T>(fn: () => T): T {\n quietDepth += 1;\n try {\n return fn();\n } finally {\n quietDepth -= 1;\n }\n },\n pause(): void {\n paused = true;\n },\n resume(): void {\n paused = false;\n },\n clear,\n snapshot: () => snapshotOf(model),\n state: () => model.exportState(),\n handle,\n nodesOf(id): Node[] {\n const out: Node[] = [];\n const own = components.get(id);\n if (own !== undefined) {\n for (const ref of own) {\n const node = ref.deref();\n if (node?.isConnected === true) out.push(node);\n }\n }\n return out;\n },\n dispose(): void {\n for (const detach of detachers) detach();\n detachers.clear();\n inspectionHook = undefined;\n listeners.clear();\n pending = [];\n signals.clear();\n components.clear();\n stores.clear();\n model.onBury = undefined;\n },\n };\n return agent;\n}\n"],"mappings":";;;;;;;AAwNA,SAAS,MAAc;CACrB,OAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAQ,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAC3E;AAEA,SAAS,SAAS,OAAwB;CACxC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AA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;EACF;EACA,OAAO;EACP,MAAS,IAAgB;GACvB,cAAc;GACd,IAAI;IACF,OAAO,GAAG;GACZ,UAAU;IACR,cAAc;GAChB;EACF;EACA,QAAc;GACZ,SAAS;EACX;EACA,SAAe;GACb,SAAS;EACX;EACA;EACA,gBAAgB,WAAW,KAAK;EAChC,aAAa,MAAM,YAAY;EAC/B;EACA,QAAQ,IAAY;GAClB,MAAM,MAAc,CAAC;GACrB,MAAM,MAAM,WAAW,IAAI,EAAE;GAC7B,IAAI,QAAQ,KAAA,GACV,KAAK,MAAM,OAAO,KAAK;IACrB,MAAM,OAAO,IAAI,MAAM;IACvB,IAAI,MAAM,gBAAgB,MAAM,IAAI,KAAK,IAAI;GAC/C;GAEF,OAAO;EACT;EACA,UAAgB;GACd,KAAK,MAAM,UAAU,WAAW,OAAO;GACvC,UAAU,MAAM;GAChB,iBAAiB,KAAA;GACjB,UAAU,MAAM;GAChB,UAAU,CAAC;GACX,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,OAAO,MAAM;GACb,MAAM,SAAS,KAAA;EACjB;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"agent.js","names":[],"sources":["../../src/agent.ts"],"sourcesContent":["import { readInspections } from \"./inspection\";\nimport { type GraphSnapshot, snapshotOf } from \"./inspector\";\nimport { describeElement } from \"./internal/describe-element\";\nimport { InspectorModel, type ModelLimits, type ModelState, type NodeRecord } from \"./model\";\nimport { errorMessage, parseEditableText, preview, toEditableText } from \"./preview\";\nimport {\n type DevtoolsHook,\n EVENT,\n type HookSink,\n NO_ID,\n type StoreHandle,\n type WireEvent,\n} from \"./protocol\";\nimport { RingBuffer } from \"./ring\";\n\n/**\n * Options of {@link createAgent}. Every field is optional.\n *\n * @since 1.0.0\n */\nexport interface AgentOptions {\n /** Capacities of the model's buffers. The values left out take the defaults of `DEFAULT_LIMITS`. */\n limits?: Partial<ModelLimits>;\n /**\n * Raw events kept for the events log. The newest are kept; older ones are overwritten and counted\n * in `dropped`.\n *\n * @default 10000\n */\n events?: number;\n /**\n * Most events waiting for subscribers. When this many are pending they are delivered at once,\n * instead of at the end of the current microtask.\n *\n * @default 10000\n */\n maxPending?: number;\n /**\n * Maximum length of a value preview, in characters.\n *\n * @default 80\n */\n previewLength?: number;\n /**\n * The clock, in milliseconds. Defaults to `performance.now` (or `Date.now` where it is missing).\n */\n now?: () => number;\n /**\n * Writes a signal node for the value editor. Pass `writeSignal` from `@shadow-js/core/extend`.\n * Without it signals are shown but not editable: a write is refused with \"Editing is not enabled.\".\n */\n writeSignal?: (node: never, value: never) => unknown;\n}\n\n/**\n * Counters of what the agent saw. They keep growing while the agent runs; {@link Agent.clear} does not\n * reset them.\n *\n * @since 1.0.0\n */\nexport interface AgentStats {\n /** Events the agent was offered while it was not paused. */\n received: number;\n /** Events turned into wire events. */\n recorded: number;\n /**\n * Events the agent skipped on purpose: objects created inside {@link Agent.quiet} (the tools' own\n * UI), dispose and unmount events for objects it never named, malformed store handles, and event\n * kinds from a newer runtime.\n */\n ignored: number;\n /**\n * Writes, runs and mounts about objects the agent never saw created (reported before it attached,\n * when the hook's replay buffer had been released).\n */\n unknown: number;\n}\n\n/**\n * A command a panel sends to the agent, answered by {@link Agent.handle}. All fields are plain data,\n * so a command can cross a message channel:\n *\n * - `snapshot`: the model's state.\n * - `value` and `write`: read a signal as editable text, or write it.\n * - `store` and `store-set`: read a store as editable text, or write one path of it.\n * - `highlight`: the agent acknowledges it; the page draws the highlight (see `createLocalBackend`).\n * - `pause`, `resume`, `clear`: control recording. `stats`: the counters.\n * - `inspect`: every inspection source registered with `registerInspection`, read now.\n *\n * @since 1.0.0\n */\nexport type AgentRequest =\n | { type: \"snapshot\" }\n | { type: \"value\"; id: number }\n | { type: \"write\"; id: number; text: string }\n | { type: \"store\"; id: number }\n | { type: \"store-set\"; id: number; path: Array<string | number>; text: string }\n | { type: \"highlight\"; id: number | null }\n | { type: \"pause\" }\n | { type: \"resume\" }\n | { type: \"clear\" }\n | { type: \"stats\" }\n | { type: \"inspect\" };\n\n/**\n * The answer to an {@link AgentRequest}: the result, or an error message to show the user.\n *\n * @since 1.0.0\n */\nexport type AgentResponse = { ok: true; result: unknown } | { ok: false; error: string };\n\n/**\n * The value of a node, as text, for the value editor.\n *\n * @since 1.0.0\n */\nexport interface ValueResult {\n /** The node that was asked for. */\n id: number;\n /** `signal` for a signal, `store` for a store. */\n kind: \"signal\" | \"store\";\n /** The value as editable text (see {@link toEditableText}). */\n text: string;\n /** True when the panel may write it: a store always, a signal only when `writeSignal` is set. */\n editable: boolean;\n}\n\n/**\n * The agent. It receives the runtime's own objects from the hook, turns them into id-based\n * {@link WireEvent}s and folds them into an {@link InspectorModel}. Recording is O(1) per event and\n * every buffer is bounded: the raw event ring, the model's run, write and flush rings, the disposed-node\n * graveyard and the live node count.\n *\n * A development tool: the hook it attaches to is installed only in development builds (see\n * `installHook`).\n *\n * @since 1.0.0\n */\nexport interface Agent extends HookSink {\n /** The model the events are folded into. */\n readonly model: InspectorModel;\n /** The newest raw events, as many as the `events` option holds (default 10000). */\n readonly events: RingBuffer<WireEvent>;\n /** Counters of what the agent saw. */\n readonly stats: Readonly<AgentStats>;\n /** True while the agent drops the events the runtime reports (see {@link Agent.pause}). */\n readonly paused: boolean;\n /**\n * Attaches the agent to `hook`, so that the hook delivers its events to the agent. Pass the hook\n * from `installHook` or `getHook`.\n *\n * @param hook The hook to listen to.\n * @returns A function that detaches the agent from the hook.\n */\n attach(hook: DevtoolsHook): () => void;\n /**\n * Calls `listener` with batches of new events: once per microtask, or sooner when `maxPending`\n * events are waiting. Only events recorded after the call are delivered.\n *\n * @param listener Receives each batch, oldest first.\n * @returns A function that unsubscribes the listener.\n */\n subscribe(listener: (events: readonly WireEvent[]) => void): () => void;\n /** Delivers the pending events to the subscribers now, instead of at the end of the microtask. */\n flush(): void;\n /**\n * Runs `fn` while the agent ignores everything the runtime creates, and everything created under\n * those nodes. Use it to mount the tools' own UI, so that the tools never inspect themselves. An error\n * thrown by `fn` propagates.\n *\n * @param fn The work to run.\n * @returns What `fn` returns.\n */\n quiet<T>(fn: () => T): T;\n /** Stops recording: events the runtime reports are dropped until {@link Agent.resume}. */\n pause(): void;\n /** Resumes recording after {@link Agent.pause}. */\n resume(): void;\n /**\n * Forgets everything recorded so far: the model's nodes and records, the event ring, and the\n * references to live nodes. Nodes created later are tracked; live ones are not, and later events about\n * them count as unknown. {@link AgentStats} are not reset.\n */\n clear(): void;\n /** The graph snapshot of the model (see `snapshotOf`). Each call builds a new object. */\n snapshot(): GraphSnapshot;\n /** The model state, for sending to a remote panel. */\n state(): ModelState;\n /**\n * Answers a panel command. Never throws: a failure, such as an error from writing user state, comes\n * back as `ok: false`, and so does an unknown command.\n *\n * @param request The command.\n * @returns The answer.\n */\n handle(request: AgentRequest): AgentResponse;\n /**\n * The connected DOM nodes that the component `id` rendered, for highlighting. Empty when the\n * component is unknown or its nodes left the page. The agent holds the nodes weakly.\n *\n * @param id The component's node id.\n * @returns The nodes.\n */\n nodesOf(id: number): Node[];\n /**\n * Detaches from every hook it was attached to, and drops the listeners and the references to live\n * signals, components and stores. The model and the event ring keep what they recorded.\n */\n dispose(): void;\n}\n\n/**\n * Store handles by node id, held weakly: the handle lives as long as the store it reads, because the\n * runtime keeps it reachable from the store's root (see `createDeepStore` in `@shadow-js/core`).\n */\ntype Registry = Map<number, WeakRef<StoreHandle>>;\n\nfunction now(): number {\n return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction isObject(value: unknown): value is object {\n return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n\nfunction toNumber(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction describeSide(value: unknown): string {\n if (typeof value === \"string\") return value.length > 200 ? `${value.slice(0, 199)}…` : value;\n if (typeof Node !== \"undefined\" && value instanceof Node) {\n // Built from the first nodes only: `outerHTML` would serialize the whole subtree to keep 200 characters.\n if (value instanceof Element) return describeElement(value, 200);\n return `#${value.nodeName}`;\n }\n return preview(value, 200);\n}\n\n/**\n * Creates an agent that records the runtime's events. Attach it to a hook with `agent.attach(hook)`.\n * A development tool: the events come only from development builds, where the hook is installed.\n *\n * @param options Buffer sizes, clock and the signal writer. Every field is optional.\n * @returns The agent.\n * @example\n * import { createAgent, installHook } from \"@shadow-js/devtools\";\n * import { writeSignal } from \"@shadow-js/core/extend\";\n *\n * const hook = installHook();\n * const agent = createAgent({ writeSignal });\n * if (hook !== undefined) agent.attach(hook);\n * agent.snapshot().counts.nodes;\n * @since 1.0.0\n */\nexport function createAgent(options: AgentOptions = {}): Agent {\n const clock = options.now ?? now;\n const previewLength = options.previewLength ?? 80;\n const maxPending = options.maxPending ?? 10_000;\n const model = new InspectorModel(options.limits);\n const events = new RingBuffer<WireEvent>(options.events ?? 10_000);\n const stats: AgentStats = { received: 0, recorded: 0, ignored: 0, unknown: 0 };\n\n // Objects are named by id through weak maps: the agent never keeps the runtime's nodes alive.\n const ids = new WeakMap<object, number>();\n const ignored = new WeakSet<object>();\n const signals = new Map<number, WeakRef<object>>();\n const components = new Map<number, WeakRef<Node>[]>();\n const stores: Registry = new Map();\n let nextId = 1;\n let seq = 0;\n let paused = false;\n let quietDepth = 0;\n /** The hook the agent listens to: its registry of inspection sources answers `inspect`. */\n let inspectionHook: DevtoolsHook | undefined;\n let pending: WireEvent[] = [];\n let scheduled = false;\n /** A flush that started but has not recorded any run yet: empty flushes are not worth a record. */\n let queuedFlush: { render: number; user: number; t: number } | null = null;\n let flushOpen = false;\n const listeners = new Set<(events: readonly WireEvent[]) => void>();\n const detachers = new Set<() => void>();\n // Signals, stores and resources have no dispose event of their own when nothing owns them (or their\n // owner never disposes): the finalizer retires their node once the runtime has collected them. It is\n // registered once per object, so a resource that reports many states is not registered many times.\n const finalizer: FinalizationRegistry<number> | undefined =\n typeof FinalizationRegistry === \"function\"\n ? new FinalizationRegistry<number>((id) => {\n signals.delete(id);\n stores.delete(id);\n if (model.nodes.has(id)) emit({ k: \"owner-\", seq: 0, t: 0, id });\n })\n : undefined;\n\n model.onBury = (record: NodeRecord) => {\n signals.delete(record.id);\n components.delete(record.id);\n stores.delete(record.id);\n };\n\n const deliver = (): void => {\n scheduled = false;\n if (pending.length === 0) return;\n const batch = pending;\n pending = [];\n // Every subscriber gets the batch, even when an earlier one throws (a closed port, a view that\n // failed): the first error is rethrown afterward, so it is still reported.\n let failure: { error: unknown } | undefined;\n for (const listener of [...listeners]) {\n try {\n listener(batch);\n } catch (error) {\n failure ??= { error };\n }\n }\n if (failure !== undefined) throw failure.error;\n };\n\n /** Stamps, records and fans out one event. */\n function emit(event: WireEvent, at?: number): void {\n seq += 1;\n event.seq = seq;\n event.t = at ?? clock();\n stats.recorded += 1;\n events.push(event);\n model.apply(event);\n if (listeners.size === 0) return;\n pending.push(event);\n if (pending.length >= maxPending) {\n deliver();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(deliver);\n }\n }\n\n /** Emits the held-back flush start before the first event that belongs to it. */\n const openFlush = (): void => {\n if (queuedFlush === null) return;\n const held = queuedFlush;\n queuedFlush = null;\n flushOpen = true;\n emit({ k: \"flush+\", seq: 0, t: 0, render: held.render, user: held.user }, held.t);\n };\n\n const lookup = (value: unknown): number => {\n if (!isObject(value)) return NO_ID;\n return ids.get(value) ?? NO_ID;\n };\n\n const register = (value: object): number => {\n const existing = ids.get(value);\n if (existing !== undefined) return existing;\n const id = nextId;\n nextId += 1;\n ids.set(value, id);\n return id;\n };\n\n /**\n * Like `register`, for a leaf node (signal, store, resource): the finalizer retires it once the runtime\n * has collected the object. Owners and computations are not registered: an owner can be unreachable\n * while its signals are still in use, and retiring it would bury them too.\n */\n const registerLeaf = (value: object): number => {\n const existing = ids.get(value);\n if (existing !== undefined) return existing;\n const id = register(value);\n finalizer?.register(value, id);\n return id;\n };\n\n /** True (and remembered) when the object belongs to the tools' own UI. */\n const isIgnored = (value: unknown, parent: unknown): boolean => {\n if (!isObject(value)) return false;\n if (quietDepth > 0 || (isObject(parent) && ignored.has(parent))) {\n ignored.add(value);\n return true;\n }\n return ignored.has(value);\n };\n\n const mapIds = (values: unknown): number[] => {\n const out: number[] = [];\n if (!Array.isArray(values)) return out;\n for (let i = 0; i < values.length; i += 1) {\n const id = lookup(values[i]);\n if (id !== NO_ID) out.push(id);\n }\n return out;\n };\n\n const nodesIn = (value: unknown): WeakRef<Node>[] => {\n const out: WeakRef<Node>[] = [];\n if (typeof Node === \"undefined\") return out;\n const push = (candidate: unknown): void => {\n if (candidate instanceof DocumentFragment) {\n for (const child of Array.from(candidate.childNodes)) out.push(new WeakRef(child));\n } else if (candidate instanceof Node) {\n out.push(new WeakRef(candidate));\n }\n };\n if (Array.isArray(value)) for (const entry of value) push(entry);\n else push(value);\n return out;\n };\n\n function receive(kind: number, a: unknown, b: unknown, c: unknown, d: unknown, e: unknown): void {\n if (paused) return;\n stats.received += 1;\n switch (kind) {\n case EVENT.OWNER_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof d === \"string\" ? d : undefined;\n emit({\n k: \"owner+\",\n seq: 0,\n t: 0,\n id: register(a),\n parent: lookup(b),\n label: typeof c === \"string\" ? c : \"owner\",\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.OWNER_DISPOSED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n emit({ k: \"owner-\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.SIGNAL_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const id = registerLeaf(a);\n signals.set(id, new WeakRef(a));\n const name = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"signal+\",\n seq: 0,\n t: 0,\n id,\n owner: lookup(b),\n preview: preview(d, previewLength),\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.SIGNAL_WRITTEN: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n emit({\n k: \"write\",\n seq: 0,\n t: 0,\n id,\n preview: preview(b, previewLength),\n writer: lookup(c),\n observers: mapIds(d),\n });\n return;\n }\n case EVENT.COMPUTATION_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof d === \"string\" ? d : undefined;\n emit({\n k: \"comp+\",\n seq: 0,\n t: 0,\n id: register(a),\n owner: lookup(b),\n kind: c === \"memo\" ? \"memo\" : \"effect\",\n render: e === true,\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.COMPUTATION_RUN: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n openFlush();\n emit({\n k: \"run\",\n seq: 0,\n t: 0,\n id,\n start: toNumber(b),\n duration: toNumber(c),\n changed: d === true,\n sources: mapIds(e),\n });\n return;\n }\n case EVENT.COMPUTATION_DISPOSED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n emit({ k: \"comp-\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.COMPONENT_MOUNTED: {\n const id = lookup(a);\n if (id === NO_ID) {\n if (isObject(a) && ignored.has(a)) stats.ignored += 1;\n else stats.unknown += 1;\n return;\n }\n const refs = nodesIn(c);\n if (refs.length > 0) components.set(id, refs);\n emit({ k: \"mount\", seq: 0, t: 0, id, name: typeof b === \"string\" ? b : \"Component\" });\n // A node beyond maxNodes is never buried, so its entry would never be removed: forget it.\n if (!model.nodes.has(id)) components.delete(id);\n return;\n }\n case EVENT.COMPONENT_UNMOUNTED: {\n const id = lookup(a);\n if (id === NO_ID) {\n stats.ignored += 1;\n return;\n }\n components.delete(id);\n emit({ k: \"unmount\", seq: 0, t: 0, id });\n return;\n }\n case EVENT.RESOURCE_STATE: {\n if (!isObject(a) || isIgnored(a, d)) {\n stats.ignored += 1;\n return;\n }\n const name = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"resource\",\n seq: 0,\n t: 0,\n id: registerLeaf(a),\n owner: lookup(d),\n state: typeof b === \"string\" ? b : String(b),\n ...(name === undefined ? {} : { name }),\n });\n return;\n }\n case EVENT.ERROR: {\n const code = typeof c === \"string\" ? c : undefined;\n emit({\n k: \"error\",\n seq: 0,\n t: 0,\n id: lookup(a),\n message: errorMessage(b),\n ...(code === undefined ? {} : { code }),\n });\n return;\n }\n case EVENT.HYDRATION_MISMATCH:\n emit({\n k: \"hydration\",\n seq: 0,\n t: 0,\n message: typeof a === \"string\" ? a : errorMessage(a),\n expected: describeSide(b),\n actual: describeSide(c),\n });\n return;\n case EVENT.FLUSH_START:\n queuedFlush = { render: toNumber(a), user: toNumber(b), t: clock() };\n return;\n case EVENT.FLUSH_END:\n queuedFlush = null;\n if (flushOpen) {\n flushOpen = false;\n emit({ k: \"flush-\", seq: 0, t: 0, runs: toNumber(a) });\n }\n return;\n case EVENT.STORE_CREATED: {\n if (!isObject(a) || isIgnored(a, b)) {\n stats.ignored += 1;\n return;\n }\n const handle = readStoreHandle(a);\n if (handle === null) {\n stats.ignored += 1;\n return;\n }\n const id = registerLeaf(a);\n stores.set(id, new WeakRef(handle));\n emit({ k: \"store+\", seq: 0, t: 0, id, owner: lookup(b), name: handle.name });\n // A store beyond maxNodes is never buried: nothing else would forget its handle.\n if (!model.nodes.has(id)) stores.delete(id);\n return;\n }\n default:\n // An event kind from a newer runtime: ignore it.\n stats.ignored += 1;\n }\n }\n\n const readStoreHandle = (value: object): StoreHandle | null => {\n const name: unknown = Reflect.get(value, \"name\");\n const snapshot: unknown = Reflect.get(value, \"snapshot\");\n const set: unknown = Reflect.get(value, \"set\");\n if (typeof name !== \"string\" || typeof snapshot !== \"function\" || typeof set !== \"function\") {\n return null;\n }\n return value as StoreHandle;\n };\n\n const signalValue = (id: number): { found: true; value: unknown } | { found: false } => {\n const node = signals.get(id)?.deref();\n if (node === undefined) return { found: false };\n return { found: true, value: Reflect.get(node, \"value\") };\n };\n\n const fail = (error: string): AgentResponse => ({ ok: false, error });\n\n function handle(request: AgentRequest): AgentResponse {\n try {\n switch (request.type) {\n case \"snapshot\":\n return { ok: true, result: model.exportState() };\n case \"stats\":\n return { ok: true, result: { ...stats, events: events.size, dropped: events.dropped } };\n case \"value\": {\n const read = signalValue(request.id);\n if (!read.found) return fail(\"The signal is gone.\");\n const result: ValueResult = {\n id: request.id,\n kind: \"signal\",\n text: toEditableText(read.value),\n editable: options.writeSignal !== undefined,\n };\n return { ok: true, result };\n }\n case \"write\": {\n const node = signals.get(request.id)?.deref();\n if (node === undefined) return fail(\"The signal is gone.\");\n if (options.writeSignal === undefined) return fail(\"Editing is not enabled.\");\n const parsed = parseEditableText(request.text);\n if (!parsed.ok) return fail(parsed.error);\n const write = options.writeSignal as (node: object, value: unknown) => unknown;\n write(node, parsed.value);\n return { ok: true, result: null };\n }\n case \"store\": {\n const store = stores.get(request.id)?.deref();\n if (store === undefined) return fail(\"The store is gone.\");\n const result: ValueResult = {\n id: request.id,\n kind: \"store\",\n text: toEditableText(store.snapshot()),\n editable: true,\n };\n return { ok: true, result };\n }\n case \"store-set\": {\n const store = stores.get(request.id)?.deref();\n if (store === undefined) return fail(\"The store is gone.\");\n const parsed = parseEditableText(request.text);\n if (!parsed.ok) return fail(parsed.error);\n store.set(request.path, parsed.value);\n return { ok: true, result: null };\n }\n case \"pause\":\n paused = true;\n return { ok: true, result: null };\n case \"resume\":\n paused = false;\n return { ok: true, result: null };\n case \"clear\":\n clear();\n return { ok: true, result: null };\n case \"highlight\":\n // Drawing needs the page; the page side draws it (see createLocalBackend).\n return { ok: true, result: null };\n case \"inspect\":\n return {\n ok: true,\n result: { sources: readInspections(inspectionHook?.inspections?.() ?? []) },\n };\n default:\n return fail(\"Unknown command.\");\n }\n } catch (error) {\n // Writing user state can throw (a validation in the app): report it to the panel.\n return fail(errorMessage(error));\n }\n }\n\n function clear(): void {\n model.importState({\n lastSeq: model.lastSeq,\n overflow: 0,\n unknown: 0,\n nodes: [],\n graveyard: [],\n runs: [],\n writes: [],\n flushes: [],\n errors: [],\n hydration: [],\n });\n events.clear();\n pending = [];\n queuedFlush = null;\n flushOpen = false;\n signals.clear();\n components.clear();\n stores.clear();\n }\n\n const agent: Agent = {\n model,\n events,\n stats,\n get paused(): boolean {\n return paused;\n },\n receive,\n attach(hook): () => void {\n inspectionHook = hook;\n const detach = hook.attach(agent);\n detachers.add(detach);\n return () => {\n detachers.delete(detach);\n detach();\n };\n },\n subscribe(listener): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n flush: deliver,\n quiet<T>(fn: () => T): T {\n quietDepth += 1;\n try {\n return fn();\n } finally {\n quietDepth -= 1;\n }\n },\n pause(): void {\n paused = true;\n },\n resume(): void {\n paused = false;\n },\n clear,\n snapshot: () => snapshotOf(model),\n state: () => model.exportState(),\n handle,\n nodesOf(id): Node[] {\n const out: Node[] = [];\n const own = components.get(id);\n if (own !== undefined) {\n for (const ref of own) {\n const node = ref.deref();\n if (node?.isConnected === true) out.push(node);\n }\n }\n return out;\n },\n dispose(): void {\n for (const detach of detachers) detach();\n detachers.clear();\n inspectionHook = undefined;\n listeners.clear();\n pending = [];\n signals.clear();\n components.clear();\n stores.clear();\n model.onBury = undefined;\n },\n };\n return agent;\n}\n"],"mappings":";;;;;;;;AAyNA,SAAS,MAAc;CACrB,OAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAQ,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAC3E;AAEA,SAAS,SAAS,OAAwB;CACxC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,aAAa,OAAwB;CAC5C,IAAI,OAAO,UAAU,UAAU,OAAO,MAAM,SAAS,MAAM,GAAG,MAAM,MAAM,GAAG,GAAG,EAAE,KA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IACF,OAAO,GAAG;GACZ,UAAU;IACR,cAAc;GAChB;EACF;EACA,QAAc;GACZ,SAAS;EACX;EACA,SAAe;GACb,SAAS;EACX;EACA;EACA,gBAAgB,WAAW,KAAK;EAChC,aAAa,MAAM,YAAY;EAC/B;EACA,QAAQ,IAAY;GAClB,MAAM,MAAc,CAAC;GACrB,MAAM,MAAM,WAAW,IAAI,EAAE;GAC7B,IAAI,QAAQ,KAAA,GACV,KAAK,MAAM,OAAO,KAAK;IACrB,MAAM,OAAO,IAAI,MAAM;IACvB,IAAI,MAAM,gBAAgB,MAAM,IAAI,KAAK,IAAI;GAC/C;GAEF,OAAO;EACT;EACA,UAAgB;GACd,KAAK,MAAM,UAAU,WAAW,OAAO;GACvC,UAAU,MAAM;GAChB,iBAAiB,KAAA;GACjB,UAAU,MAAM;GAChB,UAAU,CAAC;GACX,QAAQ,MAAM;GACd,WAAW,MAAM;GACjB,OAAO,MAAM;GACb,MAAM,SAAS,KAAA;EACjB;CACF;CACA,OAAO;AACT"}
|
package/dist/dev/backend.d.ts
CHANGED
|
@@ -13,6 +13,12 @@ export interface Backend {
|
|
|
13
13
|
readonly model: InspectorModel;
|
|
14
14
|
/** Resolves once the first complete state is available. */
|
|
15
15
|
readonly ready: Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Why the first complete state could not be loaded, or `undefined`. A remote backend sets it when the
|
|
18
|
+
* agent refuses or cannot send its state (for example an answer over the bridge's size cap) and notifies
|
|
19
|
+
* its subscribers; `ready` then stays pending. It clears when a state arrives. A local backend never fails.
|
|
20
|
+
*/
|
|
21
|
+
readonly error?: () => string | undefined;
|
|
16
22
|
/** Calls `listener` after the model changed (batched). Returns the unsubscribe function. */
|
|
17
23
|
subscribe(listener: () => void): () => void;
|
|
18
24
|
/** Sends a command to the agent. Resolves with its answer; rejects only when the backend is disposed. */
|
package/dist/dev/backend.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"backend.js","names":[],"sources":["../../src/backend.ts"],"sourcesContent":["import type { Agent, AgentRequest, AgentResponse } from \"./agent\";\nimport type { InspectorModel } from \"./model\";\n\n/**\n * What a panel talks to: a model that stays up to date, and requests. The panel never knows\n * whether the agent is in the same page ({@link createLocalBackend}) or behind a transport\n * (`connectRemote`), so the same UI serves the floating overlay and a browser-extension panel.\n *\n * @since 1.0.0\n */\nexport interface Backend {\n /** The inspector model, kept current. Read it; do not apply events to it yourself. */\n readonly model: InspectorModel;\n /** Resolves once the first complete state is available. */\n readonly ready: Promise<void>;\n /** Calls `listener` after the model changed (batched). Returns the unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Sends a command to the agent. Resolves with its answer; rejects only when the backend is disposed. */\n request(request: AgentRequest): Promise<AgentResponse>;\n /** Stops listening. */\n dispose(): void;\n}\n\n/**\n * Page-side behavior that a backend cannot do through the agent alone.\n *\n * @since 1.0.0\n */\nexport interface PageHooks {\n /**\n * Highlights a component on the page. `null` clears the highlight. Without this hook a highlight\n * request is acknowledged and nothing is drawn.\n */\n highlight?(id: number | null): void;\n}\n\n/**\n * A backend for an agent in the same page: the model is the agent's own model, and the requests go to\n * the agent. A development tool: the page-side panel (`mountDevtools`) uses it in development builds.\n *\n * @param agent The agent.\n * @param page Page-side behavior such as the highlight overlay.\n * @returns The backend.\n * @example\n * import { createAgent, createLocalBackend } from \"@shadow-js/devtools\";\n *\n * const agent = createAgent();\n * const backend = createLocalBackend(agent, {\n * highlight: (id) => console.info(\"highlight\", id),\n * });\n * @since 1.0.0\n */\nexport function createLocalBackend(agent: Agent, page: PageHooks = {}): Backend {\n const unsubscribers = new Set<() => void>();\n let disposed = false;\n return {\n model: agent.model,\n ready: Promise.resolve(),\n subscribe(listener): () => void {\n const off = agent.subscribe(() => listener());\n unsubscribers.add(off);\n return () => {\n unsubscribers.delete(off);\n off();\n };\n },\n request(request): Promise<AgentResponse> {\n if (disposed) return Promise.reject(new Error(\"The devtools backend was disposed.\"));\n if (request.type === \"highlight\") {\n page.highlight?.(request.id);\n return Promise.resolve({ ok: true, result: null });\n }\n return Promise.resolve(agent.handle(request));\n },\n dispose(): void {\n disposed = true;\n for (const off of unsubscribers) off();\n unsubscribers.clear();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"backend.js","names":[],"sources":["../../src/backend.ts"],"sourcesContent":["import type { Agent, AgentRequest, AgentResponse } from \"./agent\";\nimport type { InspectorModel } from \"./model\";\n\n/**\n * What a panel talks to: a model that stays up to date, and requests. The panel never knows\n * whether the agent is in the same page ({@link createLocalBackend}) or behind a transport\n * (`connectRemote`), so the same UI serves the floating overlay and a browser-extension panel.\n *\n * @since 1.0.0\n */\nexport interface Backend {\n /** The inspector model, kept current. Read it; do not apply events to it yourself. */\n readonly model: InspectorModel;\n /** Resolves once the first complete state is available. */\n readonly ready: Promise<void>;\n /**\n * Why the first complete state could not be loaded, or `undefined`. A remote backend sets it when the\n * agent refuses or cannot send its state (for example an answer over the bridge's size cap) and notifies\n * its subscribers; `ready` then stays pending. It clears when a state arrives. A local backend never fails.\n */\n readonly error?: () => string | undefined;\n /** Calls `listener` after the model changed (batched). Returns the unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Sends a command to the agent. Resolves with its answer; rejects only when the backend is disposed. */\n request(request: AgentRequest): Promise<AgentResponse>;\n /** Stops listening. */\n dispose(): void;\n}\n\n/**\n * Page-side behavior that a backend cannot do through the agent alone.\n *\n * @since 1.0.0\n */\nexport interface PageHooks {\n /**\n * Highlights a component on the page. `null` clears the highlight. Without this hook a highlight\n * request is acknowledged and nothing is drawn.\n */\n highlight?(id: number | null): void;\n}\n\n/**\n * A backend for an agent in the same page: the model is the agent's own model, and the requests go to\n * the agent. A development tool: the page-side panel (`mountDevtools`) uses it in development builds.\n *\n * @param agent The agent.\n * @param page Page-side behavior such as the highlight overlay.\n * @returns The backend.\n * @example\n * import { createAgent, createLocalBackend } from \"@shadow-js/devtools\";\n *\n * const agent = createAgent();\n * const backend = createLocalBackend(agent, {\n * highlight: (id) => console.info(\"highlight\", id),\n * });\n * @since 1.0.0\n */\nexport function createLocalBackend(agent: Agent, page: PageHooks = {}): Backend {\n const unsubscribers = new Set<() => void>();\n let disposed = false;\n return {\n model: agent.model,\n ready: Promise.resolve(),\n subscribe(listener): () => void {\n const off = agent.subscribe(() => listener());\n unsubscribers.add(off);\n return () => {\n unsubscribers.delete(off);\n off();\n };\n },\n request(request): Promise<AgentResponse> {\n if (disposed) return Promise.reject(new Error(\"The devtools backend was disposed.\"));\n if (request.type === \"highlight\") {\n page.highlight?.(request.id);\n return Promise.resolve({ ok: true, result: null });\n }\n return Promise.resolve(agent.handle(request));\n },\n dispose(): void {\n disposed = true;\n for (const off of unsubscribers) off();\n unsubscribers.clear();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0DA,SAAgB,mBAAmB,OAAc,OAAkB,CAAC,GAAY;CAC9E,MAAM,gCAAgB,IAAI,IAAgB;CAC1C,IAAI,WAAW;CACf,OAAO;EACL,OAAO,MAAM;EACb,OAAO,QAAQ,QAAQ;EACvB,UAAU,UAAsB;GAC9B,MAAM,MAAM,MAAM,gBAAgB,SAAS,CAAC;GAC5C,cAAc,IAAI,GAAG;GACrB,aAAa;IACX,cAAc,OAAO,GAAG;IACxB,IAAI;GACN;EACF;EACA,QAAQ,SAAiC;GACvC,IAAI,UAAU,OAAO,QAAQ,uBAAO,IAAI,MAAM,oCAAoC,CAAC;GACnF,IAAI,QAAQ,SAAS,aAAa;IAChC,KAAK,YAAY,QAAQ,EAAE;IAC3B,OAAO,QAAQ,QAAQ;KAAE,IAAI;KAAM,QAAQ;IAAK,CAAC;GACnD;GACA,OAAO,QAAQ,QAAQ,MAAM,OAAO,OAAO,CAAC;EAC9C;EACA,UAAgB;GACd,WAAW;GACX,KAAK,MAAM,OAAO,eAAe,IAAI;GACrC,cAAc,MAAM;EACtB;CACF;AACF"}
|
package/dist/dev/hook.js
CHANGED
|
@@ -31,7 +31,7 @@ function installHook(options = {}) {
|
|
|
31
31
|
const existing = lookup(target);
|
|
32
32
|
if (existing !== void 0) return isHook(existing) && existing.version === 1 ? existing : void 0;
|
|
33
33
|
const limit = options.buffer ?? 5e3;
|
|
34
|
-
|
|
34
|
+
let sinks = [];
|
|
35
35
|
const registry = /* @__PURE__ */ new Map();
|
|
36
36
|
let buffer = [];
|
|
37
37
|
let faults = 0;
|
|
@@ -67,8 +67,9 @@ function installHook(options = {}) {
|
|
|
67
67
|
]);
|
|
68
68
|
return;
|
|
69
69
|
}
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
const current = sinks;
|
|
71
|
+
for (let i = 0; i < current.length; i += 1) {
|
|
72
|
+
const sink = current[i];
|
|
72
73
|
if (sink !== void 0) deliver(sink, kind, a, b, c, d, e);
|
|
73
74
|
}
|
|
74
75
|
},
|
|
@@ -84,7 +85,7 @@ function installHook(options = {}) {
|
|
|
84
85
|
}));
|
|
85
86
|
},
|
|
86
87
|
attach(sink) {
|
|
87
|
-
sinks
|
|
88
|
+
sinks = [...sinks, sink];
|
|
88
89
|
if (buffer !== null) {
|
|
89
90
|
const replay = buffer;
|
|
90
91
|
buffer = null;
|
|
@@ -92,7 +93,7 @@ function installHook(options = {}) {
|
|
|
92
93
|
}
|
|
93
94
|
return () => {
|
|
94
95
|
const index = sinks.indexOf(sink);
|
|
95
|
-
if (index !== -1) sinks.
|
|
96
|
+
if (index !== -1) sinks = [...sinks.slice(0, index), ...sinks.slice(index + 1)];
|
|
96
97
|
};
|
|
97
98
|
}
|
|
98
99
|
};
|
package/dist/dev/hook.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook.js","names":[],"sources":["../../src/hook.ts"],"sourcesContent":["import type { InspectionEntry, InspectionSource } from \"./inspection\";\nimport {\n type DevtoolsHook,\n HOOK_KEY,\n type HookSink,\n MAX_INSPECTIONS,\n PROTOCOL_VERSION,\n} from \"./protocol\";\n\n/**\n * Options of {@link installHook}. Every field is optional.\n *\n * @since 1.0.0\n */\nexport interface InstallHookOptions {\n /**\n * The object to install the hook on.\n *\n * @default globalThis\n */\n target?: object;\n /**\n * How many events to keep for a sink that attaches later. The first events reported are kept and\n * later ones are dropped. The buffer is released when the first sink attaches, so a hook that nobody\n * listens to cannot grow without bound.\n *\n * @default 5000\n */\n buffer?: number;\n}\n\n/**\n * The hook that {@link installHook} installs: a {@link DevtoolsHook} with the counters of its sinks.\n *\n * @since 1.0.0\n */\nexport interface InstalledHook extends DevtoolsHook {\n /** Number of times a sink threw while receiving an event. The hook swallows each error so the app keeps running. */\n readonly faults: number;\n /** The last error a sink threw, or `undefined` when none did. */\n readonly lastFault: unknown;\n}\n\ntype Buffered = readonly [number, unknown, unknown, unknown, unknown, unknown];\n\nfunction lookup(target: object): unknown {\n return Reflect.get(target, HOOK_KEY);\n}\n\nfunction isHook(value: unknown): value is InstalledHook {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof Reflect.get(value, \"report\") === \"function\" &&\n typeof Reflect.get(value, \"attach\") === \"function\" &&\n typeof Reflect.get(value, \"version\") === \"number\"\n );\n}\n\n/**\n * Installs the dev hook on `globalThis.__SHADOWJS_DEVTOOLS_HOOK__` (or on `options.target`), once, and\n * returns it. A development tool: in production builds (`__DEV__` false) it installs nothing and returns\n * `undefined`. The runtime looks the global up on each event, so call this before the application code\n * runs: events reported earlier are lost, and those reported before a sink attaches are buffered.\n *\n * When a hook with the same protocol version is already installed, it is returned. When the global holds\n * a hook of another version (or anything that is not a hook), nothing is installed and `undefined` is\n * returned.\n *\n * @param options Target object and replay buffer size. Every field is optional.\n * @returns The installed hook, or `undefined`.\n * @example\n * import { createAgent, installHook } from \"@shadow-js/devtools\";\n *\n * const hook = installHook();\n * const agent = createAgent();\n * if (hook !== undefined) agent.attach(hook);\n * @since 1.0.0\n */\nexport function installHook(options: InstallHookOptions = {}): InstalledHook | undefined {\n if (!__DEV__) return undefined;\n const target = options.target ?? globalThis;\n const existing = lookup(target);\n if (existing !== undefined) {\n return isHook(existing) && existing.version === PROTOCOL_VERSION ? existing : undefined;\n }\n const limit = options.buffer ?? 5000;\n
|
|
1
|
+
{"version":3,"file":"hook.js","names":[],"sources":["../../src/hook.ts"],"sourcesContent":["import type { InspectionEntry, InspectionSource } from \"./inspection\";\nimport {\n type DevtoolsHook,\n HOOK_KEY,\n type HookSink,\n MAX_INSPECTIONS,\n PROTOCOL_VERSION,\n} from \"./protocol\";\n\n/**\n * Options of {@link installHook}. Every field is optional.\n *\n * @since 1.0.0\n */\nexport interface InstallHookOptions {\n /**\n * The object to install the hook on.\n *\n * @default globalThis\n */\n target?: object;\n /**\n * How many events to keep for a sink that attaches later. The first events reported are kept and\n * later ones are dropped. The buffer is released when the first sink attaches, so a hook that nobody\n * listens to cannot grow without bound.\n *\n * @default 5000\n */\n buffer?: number;\n}\n\n/**\n * The hook that {@link installHook} installs: a {@link DevtoolsHook} with the counters of its sinks.\n *\n * @since 1.0.0\n */\nexport interface InstalledHook extends DevtoolsHook {\n /** Number of times a sink threw while receiving an event. The hook swallows each error so the app keeps running. */\n readonly faults: number;\n /** The last error a sink threw, or `undefined` when none did. */\n readonly lastFault: unknown;\n}\n\ntype Buffered = readonly [number, unknown, unknown, unknown, unknown, unknown];\n\nfunction lookup(target: object): unknown {\n return Reflect.get(target, HOOK_KEY);\n}\n\nfunction isHook(value: unknown): value is InstalledHook {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof Reflect.get(value, \"report\") === \"function\" &&\n typeof Reflect.get(value, \"attach\") === \"function\" &&\n typeof Reflect.get(value, \"version\") === \"number\"\n );\n}\n\n/**\n * Installs the dev hook on `globalThis.__SHADOWJS_DEVTOOLS_HOOK__` (or on `options.target`), once, and\n * returns it. A development tool: in production builds (`__DEV__` false) it installs nothing and returns\n * `undefined`. The runtime looks the global up on each event, so call this before the application code\n * runs: events reported earlier are lost, and those reported before a sink attaches are buffered.\n *\n * When a hook with the same protocol version is already installed, it is returned. When the global holds\n * a hook of another version (or anything that is not a hook), nothing is installed and `undefined` is\n * returned.\n *\n * @param options Target object and replay buffer size. Every field is optional.\n * @returns The installed hook, or `undefined`.\n * @example\n * import { createAgent, installHook } from \"@shadow-js/devtools\";\n *\n * const hook = installHook();\n * const agent = createAgent();\n * if (hook !== undefined) agent.attach(hook);\n * @since 1.0.0\n */\nexport function installHook(options: InstallHookOptions = {}): InstalledHook | undefined {\n if (!__DEV__) return undefined;\n const target = options.target ?? globalThis;\n const existing = lookup(target);\n if (existing !== undefined) {\n return isHook(existing) && existing.version === PROTOCOL_VERSION ? existing : undefined;\n }\n const limit = options.buffer ?? 5000;\n // Replaced, never changed in place: a sink that detaches while an event is delivered must not make\n // the loop skip the sink after it.\n let sinks: readonly HookSink[] = [];\n const registry = new Map<string, InspectionSource>();\n let buffer: Buffered[] | null = [];\n let faults = 0;\n let lastFault: unknown;\n\n const deliver = (\n sink: HookSink,\n kind: number,\n a: unknown,\n b: unknown,\n c: unknown,\n d: unknown,\n e: unknown,\n ): void => {\n try {\n sink.receive(kind, a, b, c, d, e);\n } catch (error) {\n // A broken tool must never break the application: count the fault and keep the error.\n faults += 1;\n lastFault = error;\n }\n };\n\n const hook: InstalledHook = {\n version: PROTOCOL_VERSION,\n get sinks(): number {\n return sinks.length;\n },\n get faults(): number {\n return faults;\n },\n get lastFault(): unknown {\n return lastFault;\n },\n report(kind, a, b, c, d, e): void {\n if (sinks.length === 0) {\n if (buffer !== null && buffer.length < limit) buffer.push([kind, a, b, c, d, e]);\n return;\n }\n const current = sinks;\n for (let i = 0; i < current.length; i += 1) {\n const sink = current[i];\n if (sink !== undefined) deliver(sink, kind, a, b, c, d, e);\n }\n },\n inspect(name, source): boolean {\n if (!registry.has(name) && registry.size >= MAX_INSPECTIONS) return false;\n registry.set(name, source);\n return true;\n },\n inspections(): readonly InspectionEntry[] {\n return [...registry].map(([name, source]) => ({ name, source }));\n },\n attach(sink): () => void {\n sinks = [...sinks, sink];\n if (buffer !== null) {\n const replay = buffer;\n buffer = null;\n for (const entry of replay)\n deliver(sink, entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]);\n }\n return () => {\n const index = sinks.indexOf(sink);\n if (index !== -1) sinks = [...sinks.slice(0, index), ...sinks.slice(index + 1)];\n };\n },\n };\n Reflect.set(target, HOOK_KEY, hook);\n return hook;\n}\n\n/**\n * The hook that {@link installHook} installed, or `undefined` when none is installed or its protocol\n * version differs. A development tool: production builds never install a hook.\n *\n * @param target Object to look at (default `globalThis`).\n * @returns The installed hook, or `undefined`.\n * @example\n * import { getHook } from \"@shadow-js/devtools\";\n *\n * const sinks = getHook()?.sinks ?? 0;\n * @since 1.0.0\n */\nexport function getHook(target: object = globalThis): InstalledHook | undefined {\n const existing = lookup(target);\n return isHook(existing) && existing.version === PROTOCOL_VERSION ? existing : undefined;\n}\n\n/**\n * Removes the installed hook, so that a later {@link installHook} installs a new one. For tests and for\n * hot reloading the tools; a development tool, and a no-op in production builds. Sinks stay attached to\n * the old hook object.\n *\n * @param target Object to remove it from (default `globalThis`).\n * @example\n * import { uninstallHook } from \"@shadow-js/devtools\";\n *\n * uninstallHook();\n * @since 1.0.0\n */\nexport function uninstallHook(target: object = globalThis): void {\n Reflect.deleteProperty(target, HOOK_KEY);\n}\n"],"mappings":";;AA6CA,SAAS,OAAO,QAAyB;CACvC,OAAO,QAAQ,IAAI,QAAQ,QAAQ;AACrC;AAEA,SAAS,OAAO,OAAwC;CACtD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,QAAQ,IAAI,OAAO,QAAQ,MAAM,cACxC,OAAO,QAAQ,IAAI,OAAO,QAAQ,MAAM,cACxC,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM;AAE7C;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,YAAY,UAA8B,CAAC,GAA8B;CAEvF,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,WAAW,OAAO,MAAM;CAC9B,IAAI,aAAa,KAAA,GACf,OAAO,OAAO,QAAQ,KAAK,SAAS,YA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T,KAAK,MAAM,SAAS,QAClB,QAAQ,MAAM,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,EAAE;GAC5E;GACA,aAAa;IACX,MAAM,QAAQ,MAAM,QAAQ,IAAI;IAChC,IAAI,UAAU,IAAI,QAAQ,CAAC,GAAG,MAAM,MAAM,GAAG,KAAK,GAAG,GAAG,MAAM,MAAM,QAAQ,CAAC,CAAC;GAChF;EACF;CACF;CACA,QAAQ,IAAI,QAAQ,UAAU,IAAI;CAClC,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,QAAQ,SAAiB,YAAuC;CAC9E,MAAM,WAAW,OAAO,MAAM;CAC9B,OAAO,OAAO,QAAQ,KAAK,SAAS,YAAA,IAA+B,WAAW,KAAA;AAChF;;;;;;;;;;;;;AAcA,SAAgB,cAAc,SAAiB,YAAkB;CAC/D,QAAQ,eAAe,QAAQ,QAAQ;AACzC"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
//#region src/internal/describe-element.ts
|
|
2
|
+
/**
|
|
3
|
+
* Markup of an element for a message, cut after `limit` characters.
|
|
4
|
+
*
|
|
5
|
+
* `outerHTML` serializes the whole subtree before anything can be cut, so describing the root of a big
|
|
6
|
+
* page cost time and memory proportional to the page. This walk produces the same text as `outerHTML`
|
|
7
|
+
* for small elements (tags, attributes, text, comments, void elements, raw-text elements) and stops as
|
|
8
|
+
* soon as more than `limit` characters exist, so it visits only the nodes at the start of the subtree.
|
|
9
|
+
* It is iterative (a deep tree cannot overflow the stack) and slices every attribute value and text node
|
|
10
|
+
* to the room that is left before it escapes it.
|
|
11
|
+
*
|
|
12
|
+
* @param root The element to describe.
|
|
13
|
+
* @param limit The most characters the result may have; a longer markup ends with `…` at this length.
|
|
14
|
+
* @returns The markup, or its first `limit - 1` characters and `…`.
|
|
15
|
+
*/
|
|
16
|
+
function describeElement(root, limit) {
|
|
17
|
+
let out = "";
|
|
18
|
+
const room = () => limit + 1 - out.length;
|
|
19
|
+
const full = () => out.length > limit;
|
|
20
|
+
const stack = [];
|
|
21
|
+
const open = (element) => {
|
|
22
|
+
const name = element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`;
|
|
23
|
+
out += `<${name}`;
|
|
24
|
+
const attributes = element.attributes;
|
|
25
|
+
for (let index = 0; index < attributes.length && !full(); index += 1) {
|
|
26
|
+
const attribute = attributes.item(index);
|
|
27
|
+
if (attribute === null) continue;
|
|
28
|
+
out += ` ${attribute.name}="${escapeAttribute(attribute.value.slice(0, room()))}"`;
|
|
29
|
+
}
|
|
30
|
+
out += ">";
|
|
31
|
+
if (VOID.has(name)) return;
|
|
32
|
+
const first = name === "template" && "content" in element && isNode(element.content) ? element.content.firstChild : element.firstChild;
|
|
33
|
+
stack.push({
|
|
34
|
+
next: first,
|
|
35
|
+
close: `</${name}>`
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
open(root);
|
|
39
|
+
while (stack.length > 0 && !full()) {
|
|
40
|
+
const frame = stack[stack.length - 1];
|
|
41
|
+
if (frame === void 0) break;
|
|
42
|
+
const node = frame.next;
|
|
43
|
+
if (node === null) {
|
|
44
|
+
stack.pop();
|
|
45
|
+
out += frame.close;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
frame.next = node.nextSibling;
|
|
49
|
+
switch (node.nodeType) {
|
|
50
|
+
case 1:
|
|
51
|
+
open(node);
|
|
52
|
+
break;
|
|
53
|
+
case 3:
|
|
54
|
+
case 4: {
|
|
55
|
+
const text = node.data.slice(0, room());
|
|
56
|
+
out += RAW_TEXT.has(node.parentNode?.localName ?? "") ? text : escapeText(text);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
case 8:
|
|
60
|
+
out += `<!--${node.data.slice(0, room())}-->`;
|
|
61
|
+
break;
|
|
62
|
+
case 7: out += `<?${node.target} ${node.data.slice(0, room())}>`;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return out.length > limit ? `${out.slice(0, limit - 1)}…` : out;
|
|
66
|
+
}
|
|
67
|
+
const VOID = /* @__PURE__ */ new Set([
|
|
68
|
+
"area",
|
|
69
|
+
"base",
|
|
70
|
+
"basefont",
|
|
71
|
+
"bgsound",
|
|
72
|
+
"br",
|
|
73
|
+
"col",
|
|
74
|
+
"embed",
|
|
75
|
+
"frame",
|
|
76
|
+
"hr",
|
|
77
|
+
"img",
|
|
78
|
+
"input",
|
|
79
|
+
"keygen",
|
|
80
|
+
"link",
|
|
81
|
+
"meta",
|
|
82
|
+
"param",
|
|
83
|
+
"source",
|
|
84
|
+
"track",
|
|
85
|
+
"wbr"
|
|
86
|
+
]);
|
|
87
|
+
/** Elements whose text the HTML serializer writes without escaping. */
|
|
88
|
+
const RAW_TEXT = /* @__PURE__ */ new Set([
|
|
89
|
+
"style",
|
|
90
|
+
"script",
|
|
91
|
+
"xmp",
|
|
92
|
+
"iframe",
|
|
93
|
+
"noembed",
|
|
94
|
+
"noframes",
|
|
95
|
+
"plaintext"
|
|
96
|
+
]);
|
|
97
|
+
function isNode(value) {
|
|
98
|
+
return typeof value === "object" && value !== null && "firstChild" in value;
|
|
99
|
+
}
|
|
100
|
+
function escapeText(text) {
|
|
101
|
+
return text.replace(/[& <>]/g, (char) => char === "&" ? "&" : char === "<" ? "<" : char === ">" ? ">" : " ");
|
|
102
|
+
}
|
|
103
|
+
function escapeAttribute(text) {
|
|
104
|
+
return text.replace(/[& "]/g, (char) => char === "&" ? "&" : char === "\"" ? """ : " ");
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
export { describeElement };
|
|
108
|
+
|
|
109
|
+
//# sourceMappingURL=describe-element.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"describe-element.js","names":[],"sources":["../../../src/internal/describe-element.ts"],"sourcesContent":["/**\n * Markup of an element for a message, cut after `limit` characters.\n *\n * `outerHTML` serializes the whole subtree before anything can be cut, so describing the root of a big\n * page cost time and memory proportional to the page. This walk produces the same text as `outerHTML`\n * for small elements (tags, attributes, text, comments, void elements, raw-text elements) and stops as\n * soon as more than `limit` characters exist, so it visits only the nodes at the start of the subtree.\n * It is iterative (a deep tree cannot overflow the stack) and slices every attribute value and text node\n * to the room that is left before it escapes it.\n *\n * @param root The element to describe.\n * @param limit The most characters the result may have; a longer markup ends with `…` at this length.\n * @returns The markup, or its first `limit - 1` characters and `…`.\n */\nexport function describeElement(root: Element, limit: number): string {\n let out = \"\";\n const room = (): number => limit + 1 - out.length;\n const full = (): boolean => out.length > limit;\n const stack: Array<{ next: Node | null; close: string }> = [];\n\n const open = (element: Element): void => {\n const name =\n element.prefix === null ? element.localName : `${element.prefix}:${element.localName}`;\n out += `<${name}`;\n const attributes = element.attributes;\n for (let index = 0; index < attributes.length && !full(); index += 1) {\n const attribute = attributes.item(index);\n if (attribute === null) continue;\n out += ` ${attribute.name}=\"${escapeAttribute(attribute.value.slice(0, room()))}\"`;\n }\n out += \">\";\n if (VOID.has(name)) return;\n const first =\n name === \"template\" && \"content\" in element && isNode(element.content)\n ? element.content.firstChild\n : element.firstChild;\n stack.push({ next: first, close: `</${name}>` });\n };\n\n open(root);\n while (stack.length > 0 && !full()) {\n const frame = stack[stack.length - 1];\n if (frame === undefined) break;\n const node = frame.next;\n if (node === null) {\n stack.pop();\n out += frame.close;\n continue;\n }\n frame.next = node.nextSibling;\n switch (node.nodeType) {\n case 1:\n open(node as Element);\n break;\n case 3:\n case 4: {\n const text = (node as CharacterData).data.slice(0, room());\n out += RAW_TEXT.has((node.parentNode as Element | null)?.localName ?? \"\")\n ? text\n : escapeText(text);\n break;\n }\n case 8:\n out += `<!--${(node as CharacterData).data.slice(0, room())}-->`;\n break;\n case 7:\n out += `<?${(node as ProcessingInstruction).target} ${(node as CharacterData).data.slice(0, room())}>`;\n break;\n default:\n break;\n }\n }\n return out.length > limit ? `${out.slice(0, limit - 1)}…` : out;\n}\n\nconst VOID = new Set([\n \"area\",\n \"base\",\n \"basefont\",\n \"bgsound\",\n \"br\",\n \"col\",\n \"embed\",\n \"frame\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Elements whose text the HTML serializer writes without escaping. */\nconst RAW_TEXT = new Set([\"style\", \"script\", \"xmp\", \"iframe\", \"noembed\", \"noframes\", \"plaintext\"]);\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === \"object\" && value !== null && \"firstChild\" in value;\n}\n\nfunction escapeText(text: string): string {\n return text.replace(/[& <>]/g, (char) =>\n char === \"&\" ? \"&\" : char === \"<\" ? \"<\" : char === \">\" ? \">\" : \" \",\n );\n}\n\nfunction escapeAttribute(text: string): string {\n return text.replace(/[& \"]/g, (char) =>\n char === \"&\" ? \"&\" : char === '\"' ? \""\" : \" \",\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,MAAe,OAAuB;CACpE,IAAI,MAAM;CACV,MAAM,aAAqB,QAAQ,IAAI,IAAI;CAC3C,MAAM,aAAsB,IAAI,SAAS;CACzC,MAAM,QAAqD,CAAC;CAE5D,MAAM,QAAQ,YAA2B;EACvC,MAAM,OACJ,QAAQ,WAAW,OAAO,QAAQ,YAAY,GAAG,QAAQ,OAAO,GAAG,QAAQ;EAC7E,OAAO,IAAI;EACX,MAAM,aAAa,QAAQ;EAC3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,UAAU,CAAC,KAAK,GAAG,SAAS,GAAG;GACpE,MAAM,YAAY,WAAW,KAAK,KAAK;GACvC,IAAI,cAAc,MAAM;GACxB,OAAO,IAAI,UAAU,KAAK,IAAI,gBAAgB,UAAU,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,EAAE;EAClF;EACA,OAAO;EACP,IAAI,KAAK,IAAI,IAAI,GAAG;EACpB,MAAM,QACJ,SAAS,cAAc,aAAa,WAAW,OAAO,QAAQ,OAAO,IACjE,QAAQ,QAAQ,aAChB,QAAQ;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