@frondruntime/devtools 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,458 @@
1
+ import { Schema } from "effect";
2
+ import { Rpc, RpcGroup } from "effect/unstable/rpc";
3
+
4
+ /**
5
+ * Wire contract between an attached Frond runtime and the hub.
6
+ *
7
+ * Direction of the RPC roles is deliberate and inverted from who dials: the
8
+ * hub listens and is the RPC *server*, the app dials out and is the RPC
9
+ * *client*. That keeps the app free of any listening socket, and it is the only
10
+ * arrangement both `RpcServer.layerHttp` and `RpcClient.layerProtocolSocket`
11
+ * support without a hand-written socket adapter on either side.
12
+ *
13
+ * Hub-to-app work (state reads, and later refresh and action invocation)
14
+ * therefore does not travel as a plain RPC call. It rides the `Attach` response
15
+ * stream as a `Query` command, and the app answers with a separate unary
16
+ * `Reply` correlated by `requestId`. `Attach` is the only long-lived call.
17
+ *
18
+ * Version equality is exact, on both sides, and there is no capability
19
+ * negotiation. That is a deliberate choice rather than an omission: `HubCommand`
20
+ * is a schema union, so an app one version behind would fail to decode a command
21
+ * it has never heard of and drop its socket — presenting as "the runtime stopped
22
+ * emitting", which is the most expensive way this can fail. Refusing the
23
+ * attachment outright says the same thing immediately and in words.
24
+ *
25
+ * The number counts published generations of *this contract*, and moves on its
26
+ * own schedule — it is not derived from, and does not track, the npm version of
27
+ * any package. Tying the two was the earlier arrangement and it was wrong in
28
+ * both directions: a release that touched nothing on the wire still moved the
29
+ * number and refused every app that had not upgraded, while a genuine schema
30
+ * change inside one release moved nothing and let two builds that disagreed
31
+ * attach to each other. Starting at 1 with the first published hub, so what the
32
+ * number counts is generations anyone could have installed.
33
+ */
34
+ export const HUB_PROTOCOL_VERSION = 1;
35
+
36
+ /**
37
+ * Unregistered, and chosen for the band rather than the number.
38
+ *
39
+ * Above 9999 to clear the entire dev-server zone — Vite, Metro, Expo, CRA,
40
+ * Django, Storybook, the node inspector — and below 32768 so it can never
41
+ * collide with an ephemeral source port on Linux, whose range starts there.
42
+ *
43
+ * Stable on purpose. Apps hardcode it, so a hub that drifted to the next free
44
+ * port on a collision would leave them dialing nothing, which presents as "the
45
+ * runtime is not emitting" — the most expensive way to fail.
46
+ */
47
+ export const HUB_DEFAULT_PORT = 17391;
48
+
49
+ export const HUB_DEFAULT_HOST = "127.0.0.1";
50
+
51
+ export const HUB_ATTACH_PATH = "/attach";
52
+
53
+ /** Where an app dials when it was given no explicit URL. */
54
+ export const HUB_DEFAULT_ATTACH_URL = `ws://${HUB_DEFAULT_HOST}:${HUB_DEFAULT_PORT}${HUB_ATTACH_PATH}`;
55
+
56
+ /**
57
+ * How much of a value crosses the wire.
58
+ *
59
+ * Negotiated in one direction only: the hub asks, and the app answers with the
60
+ * lesser of the request and its own ceiling. The ceiling defaults to `"shape"`,
61
+ * so an app sends structure until someone deliberately decides otherwise — the
62
+ * decision to put real values on a socket should be one somebody made, not one
63
+ * that came with the default.
64
+ */
65
+ export const ValuePolicy = Schema.Literals(["none", "shape", "full"]);
66
+ export type ValuePolicy = typeof ValuePolicy.Type;
67
+
68
+ export const RuntimeEventCategory = Schema.Literals([
69
+ "command",
70
+ "diagnostic",
71
+ "input",
72
+ "lifecycle",
73
+ "operation",
74
+ "state",
75
+ ]);
76
+
77
+ export const RuntimeEventSeverity = Schema.Literals(["debug", "error", "info", "warning"]);
78
+
79
+ export const RuntimeEventTimeline = Schema.Literals(["live", "state", "system", "work"]);
80
+
81
+ export const RuntimeWorkSource = Schema.Literals([
82
+ "react",
83
+ "mobx",
84
+ "node",
85
+ "manual",
86
+ "devtools",
87
+ "runtime",
88
+ "signal",
89
+ "test",
90
+ ]);
91
+
92
+ export const RuntimeWorkReason = Schema.Literals([
93
+ "start",
94
+ "stop",
95
+ "readiness",
96
+ "retry",
97
+ "preload",
98
+ "refresh",
99
+ "action",
100
+ "args-update",
101
+ "live",
102
+ "release",
103
+ "eviction",
104
+ "unsafe-update",
105
+ "input",
106
+ "signal",
107
+ ]);
108
+
109
+ export const RuntimeWorkPriority = Schema.Literals(["blocking", "visible", "background", "idle"]);
110
+
111
+ /**
112
+ * Who is attaching.
113
+ *
114
+ * `runtimeId` is the runtime's own `runtime-N` counter and collides freely
115
+ * across tabs, reloads, and processes; `instanceId` is minted once per
116
+ * `attachDevtools` call and is the only field safe to use as an identity key.
117
+ */
118
+ export const AttachmentInfo = Schema.Struct({
119
+ protocolVersion: Schema.Number,
120
+ /** Stable for the life of the attaching runtime, including across reconnects. */
121
+ instanceId: Schema.String,
122
+ runtimeId: Schema.String,
123
+ /**
124
+ * How many times this runtime had already attached before this connection.
125
+ *
126
+ * Zero on a first attach; anything higher means the socket dropped and came
127
+ * back, which is the same thing as saying the events in between are gone.
128
+ * Devtools are not durable by design — nothing bridges that gap — so this
129
+ * field exists to make the gap visible rather than to let anyone close it.
130
+ */
131
+ generation: Schema.Number,
132
+ /** Human label for the CLI list, e.g. the host app's package name. */
133
+ name: Schema.String,
134
+ /** Free-form origin hint: "bun", "browser", "expo-ios", … */
135
+ platform: Schema.String,
136
+ startedAt: Schema.Number,
137
+ /** The strongest value policy this app is willing to honor. */
138
+ values: ValuePolicy,
139
+ });
140
+ export type AttachmentInfo = typeof AttachmentInfo.Type;
141
+
142
+ /**
143
+ * A runtime event, flattened and already redacted by the sender.
144
+ *
145
+ * `fields` holds JSON-safe shape descriptors, not live values — encoding
146
+ * happens at observe time, because a `RuntimeEventRecord` carries live
147
+ * references that keep mutating after the record is handed out. The descriptor
148
+ * vocabulary is written down once, in `descriptors.ts`, and what each policy
149
+ * produces lives with the walk that produces it — `describeShape` in `shape.ts`,
150
+ * `describeFull` in `full.ts`, `describeError` in `cause.ts`. Nothing on this
151
+ * side should restate any of it and drift.
152
+ */
153
+ export const EncodedEventRecord = Schema.Struct({
154
+ sequence: Schema.Number,
155
+ recordedAt: Schema.Number,
156
+ /** The `RuntimeEvent` `_tag`, e.g. "GraphNodeLiveDemandChanged". */
157
+ tag: Schema.String,
158
+ category: RuntimeEventCategory,
159
+ severity: RuntimeEventSeverity,
160
+ timeline: RuntimeEventTimeline,
161
+ reportable: Schema.Boolean,
162
+ workId: Schema.Number,
163
+ parentWorkId: Schema.optional(Schema.Number),
164
+ source: RuntimeWorkSource,
165
+ reason: RuntimeWorkReason,
166
+ priority: RuntimeWorkPriority,
167
+ nodeIds: Schema.Array(Schema.String),
168
+ /**
169
+ * Keyed by the event's own field names, minus `_tag`.
170
+ *
171
+ * A record rather than `Unknown`: every consumer — the UI, and shortly the
172
+ * MCP reader — looks fields up by name, and typing the container as unknown
173
+ * only moves that cast to each of them. The *values* stay unknown, which is
174
+ * the honest part: what a field holds depends on the negotiated policy.
175
+ */
176
+ fields: Schema.Record(Schema.String, Schema.Unknown),
177
+ /**
178
+ * What went wrong, as chains of causes rather than as single errors.
179
+ *
180
+ * Each entry is `{_: "error", message, causes}`, outermost cause first. The
181
+ * runtime lifts these off the event's own fields, so the same failure also
182
+ * appears in `fields` — encoded identically, so one failure never reads as
183
+ * two. Present at every policy: `"none"` is a statement about values, and a
184
+ * feed that cannot say what is failing is not worth reading.
185
+ */
186
+ failures: Schema.Array(Schema.Unknown),
187
+ });
188
+ export type EncodedEventRecord = typeof EncodedEventRecord.Type;
189
+
190
+ /**
191
+ * One node, as it is right now.
192
+ *
193
+ * Split the same way `EncodedEventRecord` is: the fields a reader filters and
194
+ * branches on are typed, and anything that came out of the app's own data is
195
+ * `Unknown`, because what it holds depends on the negotiated policy. Giving
196
+ * `NodeStatus`, `NodeOperation` and the rest real schemas here would copy core's
197
+ * type surface into the wire contract and guarantee the two drift apart.
198
+ *
199
+ * Every field here has to earn its place in *every row* of a graph read, which
200
+ * is why core's `label` and `key` are not among them: `label` is a formatting of
201
+ * `tag` and `key` is already inside `nodeId`, so both are the same fact charged
202
+ * twice, a few hundred times per snapshot.
203
+ */
204
+ export const EncodedNodeSnapshot = Schema.Struct({
205
+ nodeId: Schema.String,
206
+ /** The spec's tag, e.g. `"orders"`. Shared by every key; `nodeId` is the identity. */
207
+ tag: Schema.String,
208
+ /**
209
+ * `"node"`, `"service"`, `"resource"` or `"facade"` — the one identity field
210
+ * nothing else here implies.
211
+ *
212
+ * It says whether this row owns a release: a resource holds something the app
213
+ * has to give back, and a reader deciding what a leak looks like cannot get
214
+ * that from `tag` or `nodeId`.
215
+ *
216
+ * Carried as a string rather than a literal union so a hub can read an app
217
+ * built against a core that has since grown a kind. Version equality already
218
+ * gates the wire; making this field the second thing that can reject a
219
+ * snapshot would buy nothing.
220
+ */
221
+ kind: Schema.String,
222
+ /**
223
+ * Which arm of core's `NodeSnapshot` this is: `Unwired`, `Idle`, `Pending`,
224
+ * `Ready`, `ReadinessError`, `Releasing`, `Invalid`.
225
+ *
226
+ * Typed and hoisted because it is the one field every reader branches on.
227
+ * Left inside the encoded `status` it would oblige an agent to understand this
228
+ * encoder's descriptors before it could ask which nodes are broken.
229
+ */
230
+ state: Schema.String,
231
+ /**
232
+ * Core's per-node write counter, carried verbatim.
233
+ *
234
+ * The cheap way to tell "still the value I saw last time" from "recomputed,
235
+ * and happens to look the same" — which no amount of comparing encoded
236
+ * results can answer once a policy has redacted them.
237
+ */
238
+ revision: Schema.Number,
239
+ status: Schema.Unknown,
240
+ liveDemand: Schema.Unknown,
241
+ operation: Schema.Unknown,
242
+ resultValidity: Schema.optional(Schema.Unknown),
243
+ /**
244
+ * Why this node is not usable, as a chain of causes.
245
+ *
246
+ * Same encoding as `EncodedEventRecord.failures`, deliberately: a node failed
247
+ * in the snapshot and the event that failed it should read identically.
248
+ */
249
+ failure: Schema.optional(Schema.Unknown),
250
+ /**
251
+ * The last operation that failed, as `{operationId, kind, at, error}`.
252
+ *
253
+ * Distinct from `failure`, and the difference is the whole point of keeping
254
+ * it: a node can be `Ready` on a stale-but-valid result while its most recent
255
+ * refresh failed. `failure` would be absent and everything would look fine.
256
+ */
257
+ operationFailure: Schema.optional(Schema.Unknown),
258
+ /** Why live demand could not be served, as `{at, failures}`. */
259
+ liveFailure: Schema.optional(Schema.Unknown),
260
+ /**
261
+ * The node's current value.
262
+ *
263
+ * Only ever present on a single-node query. A graph read of a few hundred
264
+ * nodes is a topology question, and answering it with every result attached
265
+ * would put the whole application state on the wire to draw a diagram.
266
+ */
267
+ result: Schema.optional(Schema.Unknown),
268
+ });
269
+ export type EncodedNodeSnapshot = typeof EncodedNodeSnapshot.Type;
270
+
271
+ export const EncodedGraphEdge = Schema.Struct({
272
+ from: Schema.String,
273
+ to: Schema.String,
274
+ /** The dependency name the dependent declared, not the target's tag. */
275
+ dependency: Schema.String,
276
+ });
277
+ export type EncodedGraphEdge = typeof EncodedGraphEdge.Type;
278
+
279
+ /**
280
+ * The graph at one instant.
281
+ *
282
+ * The counterpart to the event stream rather than a replacement for it: events
283
+ * say what happened, this says what is true. `capturedAt` and `sequence` are
284
+ * what let a reader hold both at once — a snapshot taken "as of sequence 4412"
285
+ * can be lined up against the log the reader already has, instead of being a
286
+ * second account of the same system with no way to relate them.
287
+ */
288
+ export const GraphSnapshot = Schema.Struct({
289
+ capturedAt: Schema.Number,
290
+ /**
291
+ * The last event sequence the runtime had recorded when this was taken.
292
+ *
293
+ * Absent on a runtime that has not emitted yet, which is the only honest
294
+ * answer — zero would claim a position in a log that has none.
295
+ */
296
+ sequence: Schema.optional(Schema.Number),
297
+ runtimeId: Schema.String,
298
+ runtimeStatus: Schema.String,
299
+ graphStatus: Schema.String,
300
+ observedInputs: Schema.Number,
301
+ /**
302
+ * The policy the app actually applied, which may be less than was asked for.
303
+ *
304
+ * Stated per snapshot rather than inferred from the attachment: a reader that
305
+ * finds no `result` on a node needs to tell "redacted" from "not ready", and
306
+ * those are the same absence.
307
+ */
308
+ values: ValuePolicy,
309
+ nodes: Schema.Array(EncodedNodeSnapshot),
310
+ edges: Schema.Array(EncodedGraphEdge),
311
+ });
312
+ export type GraphSnapshot = typeof GraphSnapshot.Type;
313
+
314
+ /** Every node and edge, with statuses but without results. */
315
+ export const GraphQuery = Schema.Struct({ _tag: Schema.tag("Graph") });
316
+
317
+ /** One node, with its result and the edges incident on it. */
318
+ export const NodeQuery = Schema.Struct({
319
+ _tag: Schema.tag("Node"),
320
+ nodeId: Schema.String,
321
+ });
322
+
323
+ export const StateQuery = Schema.Union([GraphQuery, NodeQuery]);
324
+ export type StateQuery = typeof StateQuery.Type;
325
+
326
+ /**
327
+ * The app's answer to one query.
328
+ *
329
+ * `Failed` rather than an RPC error because the reply is a separate call from
330
+ * the request: an error on this channel would fail the *reply*, which is not
331
+ * the thing that went wrong, and would leave the hub waiting out its timeout
332
+ * for an answer that already came back.
333
+ */
334
+ export const QueryOutcome = Schema.Union([
335
+ Schema.Struct({ _tag: Schema.tag("Snapshot"), snapshot: GraphSnapshot }),
336
+ Schema.Struct({ _tag: Schema.tag("Failed"), reason: Schema.String }),
337
+ ]);
338
+ export type QueryOutcome = typeof QueryOutcome.Type;
339
+
340
+ /** Hub accepted the attachment and assigned it an id. */
341
+ export const HubAttached = Schema.Struct({
342
+ _tag: Schema.tag("Attached"),
343
+ attachmentId: Schema.String,
344
+ /** What the hub is asking for. The app may downgrade, never upgrade. */
345
+ values: ValuePolicy,
346
+ });
347
+
348
+ /** Liveness probe; the app answers by continuing to hold the stream open. */
349
+ export const HubPing = Schema.Struct({
350
+ _tag: Schema.tag("Ping"),
351
+ at: Schema.Number,
352
+ });
353
+
354
+ /**
355
+ * Asks the app what is true right now.
356
+ *
357
+ * Rides this stream because the hub has no way to call the app — it listens and
358
+ * the app dials, so the only open channel in this direction is the `Attach`
359
+ * response. The answer comes back as a separate `Reply` call rather than in
360
+ * band, which is why `requestId` exists.
361
+ *
362
+ * `values` is requested per query, not per attachment. A stream of events and a
363
+ * deliberate read of one node are different acts: the first is a firehose worth
364
+ * keeping cheap, the second is someone asking a specific question. Both are
365
+ * still clamped by the app's own ceiling, so this widens nothing the app has not
366
+ * already agreed to.
367
+ */
368
+ export const HubQuery = Schema.Struct({
369
+ _tag: Schema.tag("Query"),
370
+ requestId: Schema.String,
371
+ query: StateQuery,
372
+ values: ValuePolicy,
373
+ });
374
+
375
+ /** Server-to-client commands. */
376
+ export const HubCommand = Schema.Union([HubAttached, HubPing, HubQuery]);
377
+ export type HubCommand = typeof HubCommand.Type;
378
+
379
+ /**
380
+ * The hub refused the attachment.
381
+ *
382
+ * `reason` is prose for a terminal, not a code to branch on. It is the last
383
+ * thing said on a connection that is about to close, and the symptom on the
384
+ * other end — devtools that quietly never appear — carries no information at
385
+ * all, so the string has to carry the diagnosis and the next step instead. The
386
+ * hub's version mismatch names both versions and which side to upgrade.
387
+ *
388
+ * Specific on purpose, where a rejection elsewhere would be deliberately vague:
389
+ * there is no authentication on this call (see `Attach`), so an uninvited
390
+ * caller learns nothing here it could not learn by dialing and observing, and
391
+ * vagueness would cost only the developer who is actually trying to attach.
392
+ */
393
+ export class HubRejection extends Schema.TaggedErrorClass<HubRejection>("HubRejection")(
394
+ "HubRejection",
395
+ { reason: Schema.String }
396
+ ) {}
397
+
398
+ /**
399
+ * Opens the attachment and holds it open.
400
+ *
401
+ * The stream's lifetime *is* the attachment's lifetime: when the socket drops,
402
+ * the handler is interrupted, which is how the hub learns about detachment.
403
+ * There is no explicit detach call and there should not be one — a crashed app
404
+ * cannot send it.
405
+ *
406
+ * Unauthenticated on purpose. Browsers do not apply CORS to WebSockets, so any
407
+ * page a developer visits can dial a loopback port — but this direction only
408
+ * carries data *into* the hub, so the worst an uninvited caller achieves is
409
+ * putting junk in a dashboard. The direction where app data leaves is the MCP
410
+ * endpoint, and a secret on this half while that one is open would buy nothing
411
+ * and cost every host app a value to configure.
412
+ *
413
+ * The consequence, stated plainly because something downstream has to honour
414
+ * it: records arriving here are not proof of their own origin, and a consumer
415
+ * that feeds them to an agent is feeding it untrusted text.
416
+ */
417
+ export class Attach extends Rpc.make("Frond.Attach", {
418
+ payload: { info: AttachmentInfo },
419
+ success: HubCommand,
420
+ error: HubRejection,
421
+ stream: true,
422
+ }) {}
423
+
424
+ /**
425
+ * Pushes a batch of events.
426
+ *
427
+ * `droppedSince` is the sender's count of records it could not buffer since the
428
+ * previous batch. It is not optional and not a nicety: a devtools feed that
429
+ * silently loses events is worse than one that admits to a gap, because an
430
+ * agent reasoning over the stream cannot tell "did not happen" from "was
431
+ * dropped".
432
+ */
433
+ export class Ingest extends Rpc.make("Frond.Ingest", {
434
+ payload: {
435
+ attachmentId: Schema.String,
436
+ records: Schema.Array(EncodedEventRecord),
437
+ droppedSince: Schema.Number,
438
+ },
439
+ }) {}
440
+
441
+ /**
442
+ * Answers one `Query`.
443
+ *
444
+ * A unary call in the app-to-hub direction, correlated by `requestId`, because
445
+ * the RPC roles only run that way — see the note at the top of this file. The
446
+ * consequence worth naming: a reply is not causally tied to the stream that
447
+ * asked for it, so the hub has to time its requests out. An app that dies
448
+ * mid-query simply never calls this.
449
+ */
450
+ export class Reply extends Rpc.make("Frond.Reply", {
451
+ payload: {
452
+ attachmentId: Schema.String,
453
+ requestId: Schema.String,
454
+ outcome: QueryOutcome,
455
+ },
456
+ }) {}
457
+
458
+ export const FrondHubRpcs = RpcGroup.make(Attach, Ingest, Reply);
package/src/shape.ts ADDED
@@ -0,0 +1,161 @@
1
+ import { describeError } from "./cause.ts";
2
+ import { type ShapeDescriptor, UNREADABLE } from "./descriptors.ts";
3
+
4
+ const MAX_STRING_LENGTH = 256;
5
+ const MAX_KEYS = 32;
6
+ const MAX_DEPTH = 3;
7
+
8
+ /**
9
+ * Reduces a value to something JSON-safe that cannot carry user data.
10
+ *
11
+ * Small primitives pass through, because in a runtime event they are ids, tags,
12
+ * timestamps, and flags — the entire signal. Anything structured becomes a
13
+ * descriptor: a node result or an action input is exactly the kind of value
14
+ * that must not leave the process, and it is always an object or an array.
15
+ *
16
+ * ## The shape vocabulary
17
+ *
18
+ * One line per value, in a syntax that says what it is without a legend:
19
+ *
20
+ * ```text
21
+ * {} a plain object, no own keys
22
+ * {id,name,total} a plain object with those keys, in order
23
+ * {id,name,…} …and more keys than {@link MAX_KEYS}
24
+ * Wired{_tag,run} the same object, discriminated: its `_tag` is "Wired"
25
+ * AccountModel{?} a class instance — the type, and no claim about fields
26
+ * string[42] an array of 42, named by its first element
27
+ * {id,name}[3] the same, where that element is an object
28
+ * unknown[0] an empty array: nothing to name it by
29
+ * Map(3) / Set(3) collections, by size
30
+ * function / symbol / bigint values with no JSON form
31
+ * {…} / […] the depth bound stopped the walk here
32
+ * ```
33
+ *
34
+ * Strings rather than the `{_: "object", keys, truncated}` objects this used to
35
+ * emit, and the reason is the reader rather than the wire: this feed is read by
36
+ * an agent through MCP, where each descriptor arrived as several lines of
37
+ * pretty-printed JSON to say one thing about one field. A node result rendered
38
+ * as forty lines that contain no data is worse than one rendered as `{id,name}`.
39
+ *
40
+ * Lossless, which is the part that makes it safe: a shape descriptor is only
41
+ * ever produced once the policy has decided the value itself is not crossing, so
42
+ * there is nothing behind it that a richer encoding could have expanded to.
43
+ *
44
+ * The residual ambiguity is named rather than defended: a short app string that
45
+ * happens to read `"function"` crosses verbatim at this policy and is
46
+ * indistinguishable from the descriptor. Structured values are not ambiguous —
47
+ * none of them cross — and paying an object per field to fix a collision with a
48
+ * literal `"function"` is the wrong trade.
49
+ */
50
+ export function describeShape(value: unknown, depth: number): unknown {
51
+ if (value === null || value === undefined) {
52
+ return value ?? null;
53
+ }
54
+
55
+ switch (typeof value) {
56
+ case "boolean":
57
+ case "number": {
58
+ return value;
59
+ }
60
+ case "bigint":
61
+ case "function":
62
+ case "symbol": {
63
+ return typeof value;
64
+ }
65
+ case "string": {
66
+ // The one descriptor that stays an object at this policy, because it is
67
+ // the one carrying content: `head` is app data, and a reader has to be
68
+ // able to tell it from a string that crossed whole.
69
+ return value.length <= MAX_STRING_LENGTH
70
+ ? value
71
+ : ({
72
+ _: "string",
73
+ length: value.length,
74
+ head: value.slice(0, MAX_STRING_LENGTH),
75
+ } satisfies ShapeDescriptor);
76
+ }
77
+ default: {
78
+ return describeStructure(value, depth);
79
+ }
80
+ }
81
+ }
82
+
83
+ /** See {@link UNREADABLE} for why this cannot be allowed to throw. */
84
+ function describeStructure(value: object, depth: number): unknown {
85
+ try {
86
+ return describeStructureUnguarded(value, depth);
87
+ } catch {
88
+ return UNREADABLE;
89
+ }
90
+ }
91
+
92
+ function describeStructureUnguarded(value: object, depth: number): unknown {
93
+ // Before the depth check: a failure nested past the limit is still the reason
94
+ // the event exists, and "an object, elided" is not worth the bytes it saves.
95
+ if (value instanceof Error) {
96
+ return describeError(value, "shape");
97
+ }
98
+
99
+ if (depth >= MAX_DEPTH) {
100
+ return Array.isArray(value) ? "[…]" : "{…}";
101
+ }
102
+
103
+ if (Array.isArray(value)) {
104
+ const first = value[0];
105
+
106
+ // Named by its first element rather than by every one of them: a
107
+ // homogeneous array is the common case and the first entry settles it, and
108
+ // a heterogeneous one is not summarizable at any length worth spending.
109
+ return `${first === undefined ? "unknown" : shapeName(first, depth + 1)}[${value.length}]`;
110
+ }
111
+
112
+ if (value instanceof Map) {
113
+ return `Map(${value.size})`;
114
+ }
115
+
116
+ if (value instanceof Set) {
117
+ return `Set(${value.size})`;
118
+ }
119
+
120
+ const prototype = Object.getPrototypeOf(value) as unknown;
121
+
122
+ // Class instances are app domain objects by construction; the type name is as
123
+ // far as this encoder is willing to go, and `{?}` says the fields exist rather
124
+ // than letting a bare type name read as "it has none".
125
+ if (prototype !== null && prototype !== Object.prototype) {
126
+ return `${(value.constructor as { readonly name?: string } | undefined)?.name ?? "object"}{?}`;
127
+ }
128
+
129
+ const keys = Object.keys(value);
130
+ const shown = keys.length > MAX_KEYS ? [...keys.slice(0, MAX_KEYS), "…"] : keys;
131
+ // `_tag` is the one nested field that survives verbatim. A discriminant is
132
+ // structure, not data — and a failure feed that says "an object with these
133
+ // keys" instead of "GraphNodeAcquireFailed" is not worth reading.
134
+ const tag = (value as { readonly _tag?: unknown })._tag;
135
+
136
+ return `${typeof tag === "string" ? tag : ""}{${shown.join(",")}}`;
137
+ }
138
+
139
+ /**
140
+ * What an array is an array of.
141
+ *
142
+ * Distinct from {@link describeShape} because that answers with the value where
143
+ * it can — a number stays a number — and a position naming a type needs the
144
+ * type. `typeof` supplies every primitive name; structured entries recurse, so
145
+ * an array of objects reads `{id,name}[3]` and inherits the depth bound with it.
146
+ */
147
+ function shapeName(value: unknown, depth: number): string {
148
+ if (value === null) {
149
+ return "null";
150
+ }
151
+
152
+ if (typeof value !== "object") {
153
+ return typeof value;
154
+ }
155
+
156
+ const described = describeStructure(value, depth);
157
+
158
+ // An `Error` element describes as a cause chain, which is an object. Its
159
+ // descriptor names it `error`, so the array says the same.
160
+ return typeof described === "string" ? described : "error";
161
+ }