@frondruntime/devtools 0.5.0 → 0.6.0-rc.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.
- package/dist/index.d.ts +10 -4
- package/dist/index.js +494 -117
- package/dist/index.js.map +8 -8
- package/package.json +2 -2
- package/src/attach.ts +40 -6
- package/src/cause.ts +241 -64
- package/src/descriptors.ts +70 -3
- package/src/encode.ts +208 -80
- package/src/full.ts +327 -39
- package/src/shape.ts +71 -15
package/dist/index.js.map
CHANGED
|
@@ -2,17 +2,17 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/attach.ts", "../src/cause.ts", "../src/descriptors.ts", "../src/full.ts", "../src/shape.ts", "../src/encode.ts", "../src/policy.ts", "../src/snapshot.ts", "../src/attachDevtools.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type { Runtime } from \"@frondruntime/core\";\nimport { Clock, Effect, Layer, Stream } from \"effect\";\nimport { RpcClient, RpcSerialization } from \"effect/rpc\";\nimport { Socket } from \"effect/socket\";\nimport { encodeRecord } from \"./encode.ts\";\nimport { type EncodePolicy, resolvePolicy } from \"./policy.ts\";\nimport {\n type AttachmentInfo,\n type EncodedEventRecord,\n FrondHubRpcs,\n HUB_PROTOCOL_VERSION,\n type HubCommand,\n type QueryOutcome,\n type ValuePolicy,\n} from \"./protocol.ts\";\nimport { encodeGraphSnapshot } from \"./snapshot.ts\";\n\n/**\n * How many encoded records are held between flushes.\n *\n * When this fills, further records are counted and discarded rather than\n * buffered without bound: an attached app must never be slowed down, let alone\n * grow unboundedly, because a devtools consumer stopped reading. The count\n * travels as `droppedSince`, so the hub always knows a gap happened.\n */\nconst MAX_BUFFERED_RECORDS = 4096;\n\nconst FLUSH_INTERVAL = \"250 millis\";\n\nexport type AttachOptions = {\n readonly runtime: Runtime.Runtime;\n readonly attachUrl: string;\n /** Human label for the hub's list, e.g. the host app's package name. */\n readonly name: string;\n readonly platform: string;\n /**\n * The most this app will ever disclose, whatever the hub asks for.\n *\n * `\"shape\"` by default: structure, key names, lengths and types, but no\n * values. Sending real values is a decision worth making per app rather than\n * inheriting — the runtimes worth debugging are the ones holding tokens and\n * account state, and a default that ships them is a default that ships them\n * the first time someone forgets.\n */\n readonly values?: ValuePolicy | undefined;\n /**\n * Stable identity for this attachment, unique across processes.\n *\n * Defaults to a fresh UUID, which is right for an ordinary app. The hub sets\n * it explicitly so it can recognise its own self-attachment in the list it\n * serves — `runtimeId` cannot do that job, because it comes from a\n * per-process counter and every runtime's first one is `runtime-1`.\n *\n * Minted per *call*, not per attempt: `attachDevtools` reuses one across\n * reconnects, so an app that outlives a hub restart comes back as itself.\n */\n readonly instanceId?: string;\n /** How many times this runtime has already attached. See `AttachmentInfo`. */\n readonly generation?: number;\n /**\n * Called once the hub has accepted this attempt.\n *\n * Exists so the caller can count reconnections without having to guess from\n * the outside which attempts got as far as being accepted.\n */\n readonly onAttached?: (() => void) | undefined;\n /**\n * Return false to leave a record out of the stream entirely.\n *\n * Distinct from the drop counter below, and the difference matters: a drop is\n * a gap the hub must be told about, because an agent reading the feed has to\n * be able to tell \"did not happen\" from \"was lost\". A record excluded here\n * was never in scope, so it is not a gap and is not counted as one.\n *\n * Exists for one caller — the hub, which observes the runtime it is also\n * writing into and would otherwise feed itself forever. An ordinary app has\n * no reason to pass this.\n */\n readonly include?: (record: Runtime.RuntimeEventRecord) => boolean;\n};\n\n/**\n * Mints the id that identifies this runtime for the life of the process.\n *\n * Deliberately not `crypto.randomUUID`, which this used to be. That call is not\n * available everywhere a Frond app runs — React Native has no global `crypto`\n * until a polyfill installs one — and reaching for it meant either a startup\n * crash on the runtime least able to explain it, or a guard, and a guard is a\n * branch whose two halves nobody exercises together.\n *\n * The entropy was never the requirement. This id has to be unique among the\n * handful of apps attached to one local hub at one time, and stable across that\n * process's own reconnects. Nothing authenticates with it, nothing persists it,\n * and it dies with the hub. A timestamp for cross-process separation and a short\n * random suffix for anything started inside the same millisecond covers that\n * with room to spare; the timestamp is the half that matters, because\n * `Math.random` is seeded per process and two processes launched together is\n * exactly where bare randomness is weakest.\n *\n * If this ever fronts something that is not a local devtools socket, it needs a\n * real generator — but then it also needs a real identity, not this.\n */\nexport function newInstanceId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/**\n * Transport for one attachment.\n *\n * Exported because the hub dials itself over exactly this layer — same\n * protocol, same serialization, same socket code path as a real app. If\n * self-attach works, the transport works.\n */\nexport function attachLayer(attachUrl: string): Layer.Layer<RpcClient.Protocol> {\n return RpcClient.layerProtocolSocket().pipe(\n Layer.provide(Socket.layerWebSocket(attachUrl)),\n Layer.provide(Socket.layerWebSocketConstructorGlobal),\n Layer.provide(RpcSerialization.layerNdjson)\n );\n}\n\n/**\n * Streams a runtime's events to a hub for as long as the connection lives.\n *\n * The returned Effect does not settle while attached — it *is* the attachment.\n * Fork it into a scope and close the scope to detach; the hub learns about the\n * detachment from the socket dying, which is the only mechanism that also works\n * when the app crashes.\n */\nexport const attachRuntime = Effect.fnUntraced(function* (options: AttachOptions) {\n const client = yield* RpcClient.make(FrondHubRpcs);\n\n const ceiling: ValuePolicy = options.values ?? \"shape\";\n\n let buffer: Array<EncodedEventRecord> = [];\n let dropped = 0;\n // Events fire between the socket opening and the `Attached` command arriving,\n // and the conservative reading of an unanswered negotiation is the narrow\n // one. Still clamped, so a ceiling of `\"none\"` holds from the first record.\n let policy: EncodePolicy = resolvePolicy(\"shape\", ceiling);\n let attachmentId: string | undefined;\n\n // Encoding happens here, at observe time, not at flush time: a\n // `RuntimeEventRecord` carries live references that keep mutating after the\n // record is handed out, so a record buffered raw would describe the graph as\n // it is when flushed, not as it was when the event fired.\n const subscription = options.runtime.observe((record) => {\n // Before the buffer check, so an excluded record cannot be counted as a\n // drop, and before encoding, so it costs nothing to exclude one.\n if (options.include !== undefined && !options.include(record)) {\n return;\n }\n\n if (buffer.length >= MAX_BUFFERED_RECORDS) {\n dropped += 1;\n return;\n }\n\n buffer.push(encodeRecord(record, policy));\n });\n\n yield* Effect.addFinalizer(() => Effect.sync(() => subscription.unsubscribe()));\n\n const info: AttachmentInfo = {\n protocolVersion: HUB_PROTOCOL_VERSION,\n instanceId: options.instanceId ?? newInstanceId(),\n runtimeId: options.runtime.getSnapshotSync().runtimeId,\n generation: options.generation ?? 0,\n name: options.name,\n platform: options.platform,\n startedAt: yield* Clock.currentTimeMillis,\n // Advertised so the hub can show what it is going to get. Advisory only:\n // `resolvePolicy` below is what actually enforces it, because a ceiling a\n // sender merely announces is one the sender can forget to apply.\n values: ceiling,\n };\n\n const flushOnce = Effect.gen(function* () {\n yield* Effect.sleep(FLUSH_INTERVAL);\n\n const id = attachmentId;\n\n if (id === undefined || (buffer.length === 0 && dropped === 0)) {\n return;\n }\n\n // Swapped, not drained: `observe` runs on whatever fiber produced the\n // event, so anything appended during the send lands in the next batch\n // instead of being lost to a splice race.\n const records = buffer;\n const droppedSince = dropped;\n buffer = [];\n dropped = 0;\n\n yield* client[\"Frond.Ingest\"]({ attachmentId: id, records, droppedSince });\n });\n\n yield* Effect.forkScoped(Effect.forever(flushOnce));\n\n /**\n * Answers one query, on its own fiber.\n *\n * Forked rather than awaited inline because this runs on the command stream:\n * a snapshot of a large graph is the most expensive thing this client does,\n * and blocking here would stall the heartbeat and every query behind it\n * behind one slow answer.\n *\n * Nothing in here is allowed to fail outward. A query that throws comes back\n * as `Failed`, because the alternative is an error escaping into the stream\n * handler and taking down an attachment over a question that was only ever\n * advisory.\n */\n const answer = (command: Extract<HubCommand, { readonly _tag: \"Query\" }>) =>\n Effect.gen(function* () {\n const id = attachmentId;\n\n if (id === undefined) {\n return;\n }\n\n const capturedAt = yield* Clock.currentTimeMillis;\n\n const outcome = yield* Effect.map(\n Effect.exit(\n Effect.sync(() => {\n // Clamped against the ceiling, not against the stream's policy. A\n // deliberate read may ask for more than the firehose gets, and may\n // never ask for more than the app agreed to disclose.\n const requested = resolvePolicy(command.values, ceiling);\n\n return encodeGraphSnapshot(options.runtime.getSnapshotSync(), {\n policy: requested,\n capturedAt,\n nodeId: command.query._tag === \"Node\" ? command.query.nodeId : undefined,\n });\n })\n ),\n (exit): QueryOutcome =>\n exit._tag === \"Success\"\n ? { _tag: \"Snapshot\", snapshot: exit.value }\n : { _tag: \"Failed\", reason: failureReason(exit.cause) }\n );\n\n yield* Effect.ignore(\n client[\"Frond.Reply\"]({ attachmentId: id, requestId: command.requestId, outcome })\n );\n });\n\n yield* Stream.runForEach(client[\"Frond.Attach\"]({ info }), (command) => {\n if (command._tag === \"Attached\") {\n return Effect.sync(() => {\n attachmentId = command.attachmentId;\n policy = resolvePolicy(command.values, ceiling);\n options.onAttached?.();\n });\n }\n\n if (command._tag === \"Query\") {\n return Effect.forkScoped(answer(command));\n }\n\n return Effect.void;\n });\n});\n\n/**\n * A reason string for a query that could not be answered.\n *\n * Deliberately thin. This travels to a hub that will show it to whoever asked,\n * and the useful cases — an unstarted runtime, a node id that does not resolve —\n * already say so in their message. Serializing a cause chain here would mean a\n * second, competing account of failures next to the one the event stream\n * already carries.\n */\nfunction failureReason(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.message === \"\" ? cause.name : cause.message;\n }\n\n return String(cause);\n}\n",
|
|
6
|
-
"import { Diagnostics } from \"@frondruntime/core\";\nimport type { ErrorDescriptor } from \"./descriptors.ts\";\nimport type { EncodePolicy } from \"./policy.ts\";\n\n/**\n * Failures, as chains of causes.\n *\n * Kept apart from the two value encoders because it is not one: a failure is\n * described the same way at every policy, and what varies is only how much of\n * each frame crosses. The value encoders call in here; nothing here calls back\n * out to them except through {@link FullContext}, which is what keeps this\n * module a leaf.\n */\n\n/**\n * How far up a `cause` chain to walk. Matches the core default.\n *\n * Chains this long are rare and the frames are small; the expensive parts of a\n * frame — its stack and its payload — are bounded separately below.\n */\nconst CAUSE_MAX_DEPTH = 8;\nconst SHAPE_CAUSE_STRING_LENGTH = 256;\nconst FULL_CAUSE_STRING_LENGTH = 1024;\n/**\n * How much stack to take from core before selecting frames out of it.\n *\n * Deliberately far above anything a real stack reaches: cutting here cuts by\n * character, which is the thing {@link abridgeStack} exists to stop doing. This\n * is a guard against a fabricated `stack` string, not a budget.\n */\nconst CAUSE_STACK_SOURCE_LENGTH = 32768;\n/**\n * How many frames survive selection.\n *\n * The frame that names app code is almost always within the first few once the\n * library frames are gone; fifteen is room for a couple of layers of wrapping on\n * top of that without the trace becoming the record.\n */\nconst KEPT_STACK_FRAMES = 15;\n/** Kept from a trace that is library frames all the way down. See {@link abridgeStack}. */\nconst LIBRARY_ONLY_STACK_FRAMES = 2;\n/** The fallback bound, for a `stack` this cannot read as frames at all. */\nconst FULL_CAUSE_STACK_LENGTH = 2048;\n\n/**\n * Frames, in the two formats a JS runtime produces.\n *\n * V8 (Node, Bun, Chromium) indents every frame with `at `; JSC and SpiderMonkey\n * write `name@url:line:column`. Matched rather than assumed because the header\n * of a stack is the error's own message, which is app text and must not be\n * mistaken for a frame and dropped.\n */\nconst V8_STACK_FRAME = /^\\s*at\\s\\S/;\n// Anchored and whitespace-free on both sides of the `@`, because a JSC stack has\n// no header line to protect it: a message like `Cannot find module\n// /app/node_modules/x/index.js:1:1` ends the way a frame ends, and an unanchored\n// pattern would call line 0 a frame, leaving `header` empty and feeding the\n// message itself to the library filter.\nconst AT_STACK_FRAME = /^\\S*@\\S*:\\d+:\\d+\\s*$/;\n\n/**\n * Frames that belong to someone else's code.\n *\n * `node_modules` is the whole point; the rest are the same idea for code that\n * has no file in the tree at all — Node's builtins, Bun's, and native frames.\n * Bun writes its own native frames as `at moduleEvaluation (native:1:11)` rather\n * than in either of the parenthesized spellings, hence the bare `native:`.\n */\nconst LIBRARY_STACK_FRAME = /node_modules|node:|bun:|native:|\\(native\\)|\\[native code]/;\n\n/**\n * What the `\"full\"` policy needs in order to encode an error's own payload.\n *\n * `encodeValue` is injected rather than imported. The full encoder descends into\n * errors and errors descend into their payloads, so calling that encoder by name\n * from here would make the two modules mutually recursive at module scope for no\n * gain — the caller already holds the depth, the `seen` set and the budget that\n * such a call would need, and closing over them is both shorter and the only\n * arrangement in which this file has no dependency on either value encoder.\n *\n * `seen` is still passed through, because this function adds to it: every link\n * of the chain joins the ancestor path for the duration of the walk below it.\n */\nexport type FullContext = {\n readonly seen: Set<object>;\n readonly encodeValue: (value: unknown) => unknown;\n};\n\n/**\n * Serializes a failure and everything that caused it.\n *\n * Thin over `Diagnostics.serializeCauseChain`, which is already the runtime's\n * own answer to \"what went wrong\" and is already defensive about it — getters\n * that throw, cycles, absent fields. Reusing it means the devtools feed and a\n * runtime sink describe the same failure the same way; hand-rolling a second\n * walk here would eventually mean two accounts of one error that disagree.\n *\n * `preview` is dropped from every frame. Core builds it for a human reading a\n * report, and for an `Error` it is name, message, stack and cause — all of\n * which the frame already carries, one of them recursively, so keeping it would\n * send the chain once per link and add nothing.\n *\n * Two things are `\"full\"`-only, for the same reason the rest of this encoder\n * withholds things. A `stack` is bulk at `\"shape\"`: a wall of Effect internals\n * around the two frames that name app code. And `fields` is the error's own\n * payload — `status`, `endpoint`, whatever the app put on it — which is app\n * data by any other name. What survives at `\"shape\"` is what the chain names\n * explicitly: `tag`, `nodeId`, `operation`, `dependency`, `path`.\n */\nexport function describeError(\n value: unknown,\n policy: EncodePolicy,\n full?: FullContext\n): ErrorDescriptor {\n const disclose = policy === \"full\";\n\n const frames = Diagnostics.serializeCauseChain(value, {\n maxDepth: CAUSE_MAX_DEPTH,\n maxStringLength: disclose ? FULL_CAUSE_STRING_LENGTH : SHAPE_CAUSE_STRING_LENGTH,\n // Asked for whole, then abridged by frame below. Core can only cut by\n // character, which is exactly the cut that loses the frame worth keeping.\n maxStackLength: CAUSE_STACK_SOURCE_LENGTH,\n maxObjectKeys: disclose ? 20 : 8,\n });\n\n if (full === undefined) {\n // `path` and `valueKind` are the two frame fields that describe the app's\n // data rather than the runtime's: a path is a list of the app's own key\n // names, and a value kind says whether what failed was an array or an\n // object. Both are shape by any definition, so `\"none\"` — whose whole\n // contract is that no shape crosses — drops them. The message still\n // crosses at every policy; that is deliberate, and it is the one thing a\n // reader cannot diagnose without.\n const shed = policy === \"none\" ? { path: undefined, valueKind: undefined } : {};\n\n return {\n _: \"error\",\n message: rootMessage(frames),\n causes: frames.map((frame) =>\n compact({ ...frame, ...shed, stack: undefined, preview: undefined })\n ),\n };\n }\n\n // Every link joins the ancestor path for the duration, so a payload field\n // pointing back at an error already on the chain is a cycle rather than a\n // second trip through this function.\n //\n // Only what this call actually inserted comes back out. A link an enclosing\n // frame is still standing on has to stay marked: an error reached through an\n // app object whose payload points back at that object is the ordinary shape of\n // a wrapped failure, and un-marking it there would let the walk descend into\n // the ancestor instead of naming the cycle.\n const links = causeValues(value, frames.length);\n const marked = links.filter(\n (link): link is object => typeof link === \"object\" && link !== null && !full.seen.has(link)\n );\n\n for (const link of marked) {\n full.seen.add(link);\n }\n\n try {\n return {\n _: \"error\",\n message: rootMessage(frames),\n causes: frames.map((frame, index) =>\n compact({\n ...frame,\n preview: undefined,\n stack: frame.stack === undefined ? undefined : abridgeStack(frame.stack),\n fields: errorFields(links[index], full.encodeValue),\n })\n ),\n };\n } finally {\n for (const link of marked) {\n full.seen.delete(link);\n }\n }\n}\n\n/**\n * A stack, selected by frame instead of cut by character.\n *\n * A raw stack is mostly other people's code — Effect's fiber runtime, the test\n * runner, the module loader — and the frames that name the app are scattered\n * through it rather than at the top. Truncating at a character count therefore\n * spends the budget on internals and can cut the one frame a reader needed, so\n * this drops library frames outright and keeps the first {@link\n * KEPT_STACK_FRAMES} of what is left.\n *\n * The dropped count is not decoration. An abridged trace that does not say it is\n * abridged reads as \"this is where it came from\", and a reader who then cannot\n * find the caller concludes the wrong thing about the code rather than about the\n * trace.\n *\n * Two cases deliberately do not select. A trace that is library frames all the\n * way down — a failure raised entirely inside a dependency — still says where in\n * that dependency, and an empty stack would throw that away for nothing. And a\n * `stack` with no recognizable frames is not a stack this can reason about, so\n * it falls back to the character bound rather than guessing.\n */\nfunction abridgeStack(stack: string): string {\n const lines = stack.split(\"\\n\");\n const first = lines.findIndex(isStackFrame);\n\n if (first === -1) {\n return stack.length <= FULL_CAUSE_STACK_LENGTH\n ? stack\n : `${stack.slice(0, FULL_CAUSE_STACK_LENGTH)}…`;\n }\n\n // Everything above the first frame is the error's own header, kept whole: it\n // is the name and message, which is the part a reader reads first.\n const header = lines.slice(0, first);\n // Counted against everything below the header, not just the lines the two\n // patterns recognize. JSC writes frames this cannot parse — `promiseReactionJob@[native code]`\n // has no `:line:col` — and dropping those out of the denominator would let the\n // trace claim it accounted for what it removed while quietly removing more.\n const body = lines.slice(first).filter((line) => line.trim() !== \"\");\n const frames = body.filter(isStackFrame);\n const own = frames.filter((line) => !LIBRARY_STACK_FRAME.test(line));\n const kept = (own.length === 0 ? frames.slice(0, LIBRARY_ONLY_STACK_FRAMES) : own).slice(\n 0,\n KEPT_STACK_FRAMES\n );\n const dropped = body.length - kept.length;\n\n if (dropped === 0) {\n return [...header, ...kept].join(\"\\n\");\n }\n\n return [\n ...header,\n ...kept,\n ` … ${dropped} frame${dropped === 1 ? \"\" : \"s\"} dropped: library internals, unrecognized lines, and any past the first ${KEPT_STACK_FRAMES}`,\n ].join(\"\\n\");\n}\n\nfunction isStackFrame(line: string): boolean {\n return V8_STACK_FRAME.test(line) || AT_STACK_FRAME.test(line);\n}\n\n/**\n * Re-walks the chain for the values behind the frames.\n *\n * Bounded by `count`, which is the frame count rather than a limit of its own:\n * two walks of the same chain that could stop in different places would\n * eventually pair a frame with the wrong value.\n */\nfunction causeValues(root: unknown, count: number): ReadonlyArray<unknown> {\n const values: Array<unknown> = [];\n let current: unknown = root;\n\n for (let index = 0; index < count; index += 1) {\n values.push(current);\n\n if (typeof current !== \"object\" || current === null) {\n break;\n }\n\n try {\n current = (current as Record<string, unknown>)[\"cause\"];\n } catch {\n break;\n }\n }\n\n return values;\n}\n\n/**\n * Keys a frame already accounts for, by name, and should not repeat.\n *\n * `cause` is the next frame. The rest are what `serializeCauseChain` lifts out\n * of a failure into named fields — sometimes renamed, as `tag` is to `nodeTag`,\n * which is why this list is written against the *source* keys and has to stay\n * in step with that function rather than with the frame type.\n */\nconst NAMED_ERROR_KEYS = new Set([\n \"boundary\",\n \"cancellation\",\n \"cause\",\n \"dependency\",\n \"invariant\",\n \"kind\",\n \"message\",\n \"name\",\n \"nodeId\",\n \"operation\",\n \"path\",\n \"stack\",\n \"tag\",\n \"timeout\",\n \"_tag\",\n]);\n\n/**\n * What a failure carries beyond being a failure.\n *\n * The half of an error a cause chain cannot name in advance: an HTTP status, a\n * request id, the arguments the call was made with. `undefined` when there is\n * none, which is the common case — a wrapper carries nothing but the fields\n * above — and {@link compact} drops the key on the way out.\n */\nfunction errorFields(value: unknown, encodeValue: (value: unknown) => unknown): unknown {\n if (typeof value !== \"object\" || value === null) {\n // A thrown string or number is its own payload, and the frame's `message`\n // only got a rendering of it.\n return encodeValue(value);\n }\n\n const own: Record<string, unknown> = {};\n\n try {\n for (const key of Object.keys(value)) {\n if (!NAMED_ERROR_KEYS.has(key)) {\n own[key] = (value as Record<string, unknown>)[key];\n }\n }\n } catch {\n return undefined;\n }\n\n return Object.keys(own).length === 0 ? undefined : encodeValue(own);\n}\n\n/**\n * The innermost thing that had something to say.\n *\n * Two kinds of frame have nothing: a `Data.TaggedError` wrapper, whose message\n * is empty, and a failure that is not an error at all — a node status, say —\n * for which core falls back to the value's kind. Both are skipped, the second\n * because `\"object\"` in a field called `message` reads as a message and is not\n * one. When the whole chain is like that, the outermost frame's own name is the\n * most this can honestly say, and the frames below it carry the rest.\n */\nfunction rootMessage(frames: ReadonlyArray<Diagnostics.SerializedCauseFrame>): string {\n for (let index = frames.length - 1; index >= 0; index -= 1) {\n const frame = frames[index];\n const message = frame?.message;\n\n if (message !== undefined && message !== \"\" && message !== frame?.valueKind) {\n return message;\n }\n }\n\n return frames[0]?.tag ?? frames[0]?.name ?? \"\";\n}\n\n/**\n * Drops absent keys.\n *\n * A cause frame declares every field any failure might carry, so most of them\n * are `undefined` on any given one. JSON would drop those anyway; doing it here\n * means the in-memory record the hub retains and renders matches the wire.\n */\nfunction compact(frame: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(frame)) {\n if (value !== undefined) {\n out[key] = value;\n }\n }\n\n return out;\n}\n",
|
|
7
|
-
"/**\n * The vocabulary both encoders emit where a value did not survive whole.\n *\n * Shared rather than duplicated because the two encoders disagree about almost\n * everything else — `\"shape\"` says as little as it can and `\"full\"` says as much\n * as it can — and the one thing they must agree on is how a reader tells a\n * marker from data.\n */\n\n/**\n * A failure, as its chain of causes rather than as its outermost link.\n *\n * The outermost link is almost never the interesting one. Frond wraps failures\n * as it unwinds — `RefreshFailed` around `ActionFailed` around whatever the app\n * actually threw — and those wrappers are `Data.TaggedError`s, whose `message`\n * is the empty string. Encoding one as `{name, message}` therefore yields\n * `{\"RefreshFailed\", \"\"}`: the shape of an answer with none of the content.\n *\n * Deliberately not a *projection*. Core can also produce one of those, with a\n * headline, a severity guess and a retryability guess, and it is the right thing\n * to put in front of a human or into an error reporter. This feed is read by an\n * agent, which is better served by the frames themselves — every wrapper, in\n * order, with the fields each one carries — than by someone else's summary of\n * them.\n */\nexport type ErrorDescriptor = {\n readonly _: \"error\";\n /**\n * The deepest non-empty message in the chain: what actually went wrong.\n *\n * A selection, not a synthesis — it is one of the messages in `causes`,\n * hoisted because it is the field worth reading first and it is otherwise\n * buried under however many wrappers the unwinding added.\n */\n readonly message: string;\n /** Outermost first. Frame `n + 1` is frame `n`'s `cause`. */\n readonly causes: ReadonlyArray<Record<string, unknown>>;\n};\n\n/**\n * A marker that survived where a value did not.\n *\n * Only ever emitted alongside real data — at `\"full\"`, and at `\"shape\"` for a\n * string long enough to be cut — which is why these stay objects while the
|
|
8
|
-
"import { describeError } from \"./cause.ts\";\nimport { type ShapeDescriptor, UNREADABLE } from \"./descriptors.ts\";\n\n/**\n * Bounds for `\"full\"`. Termination guards, not a byte budget.\n *\n * This encoder runs against a loopback socket, so bytes are close to free; what\n * these stop is a cycle the `seen` set cannot catch, a proxy that manufactures\n * keys on demand, or a linked list a few hundred thousand long — cases where the\n * walk would hang the observed app inside its own devtools. Set them where a\n * pathological structure trips them and a large-but-real one does not, and every\n * one of them announces itself in the output. A cap an agent cannot see is worse\n * than a low cap: it turns \"there was more\" into \"that was all\", which is the\n * one thing this feed must never say.\n */\nconst FULL_MAX_DEPTH = 24;\nconst FULL_MAX_STRING_LENGTH = 65536;\nconst FULL_MAX_ENTRIES = 4096;\n/**\n * Total encoded values per record, across the whole tree.\n *\n * Counts values, not characters: one 64k string spends the same allowance as\n * `true`. So this bounds how long the walk runs, and only loosely bounds what it\n * produces — which is the right trade here, where the walk is the expensive half\n * and the wire is a socket to the same machine.\n */\nexport const FULL_MAX_NODES = 50000;\n\nexport type Budget = { remaining: number };\n\n/**\n * Reduces a value to JSON-safe form while keeping its contents.\n *\n * The counterpart to `describeShape`, and the opposite default: where the shape\n * encoder asks \"what can I say without revealing this\", this one asks \"what is\n * the least I can leave out\".\n *\n * Which is also why it does not share that encoder's string vocabulary. Here the\n * values around a marker are real data, so a marker has to stay\n * distinguishable from one — hence `{_: \"elided\"}` rather than a word. There,\n * nothing structured is real, so there is nothing for a word to collide with.\n *\n * `seen` is the ancestor path, not every value visited. A value that appears\n * twice in a result — a shared config object, the same node referenced by two\n * dependents — is legitimately encoded twice; only a value containing *itself*\n * is a cycle. Tracking all visited values instead would silently blank out\n * shared structure and read as data loss.\n */\nexport function describeFull(\n value: unknown,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n if (budget.remaining <= 0) {\n return { _: \"elided\", by: \"budget\" } satisfies ShapeDescriptor;\n }\n\n budget.remaining -= 1;\n\n if (value === null || value === undefined) {\n return value ?? null;\n }\n\n switch (typeof value) {\n case \"boolean\":\n case \"number\": {\n return value;\n }\n // Not JSON-safe, and no rendering of them is more useful than saying what\n // they were.\n case \"bigint\": {\n return { _: \"opaque\", type: `bigint:${value.toString()}` } satisfies ShapeDescriptor;\n }\n case \"function\": {\n return {\n _: \"opaque\",\n type: `function:${(value as { readonly name?: string }).name || \"anonymous\"}`,\n } satisfies ShapeDescriptor;\n }\n case \"symbol\": {\n return { _: \"opaque\", type: value.toString() } satisfies ShapeDescriptor;\n }\n case \"string\": {\n return value.length <= FULL_MAX_STRING_LENGTH\n ? value\n : ({\n _: \"string\",\n length: value.length,\n head: value.slice(0, FULL_MAX_STRING_LENGTH),\n } satisfies ShapeDescriptor);\n }\n default: {\n return describeFullStructure(value as object, depth, seen, budget);\n }\n }\n}\n\nfunction describeFullStructure(\n value: object,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n try {\n return describeFullStructureUnguarded(value, depth, seen, budget);\n } catch {\n // See {@link UNREADABLE}. The `seen` set is left as this call found it: the\n // one place that adds to it deletes in a `finally`.\n return UNREADABLE;\n }\n}\n\nfunction describeFullStructureUnguarded(\n value: object,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n if (seen.has(value)) {\n return { _: \"cycle\" } satisfies ShapeDescriptor;\n }\n\n if (value instanceof Error) {\n const described = describeError(value, \"full\", {\n seen,\n encodeValue: (own) => describeFull(own, depth + 1, seen, budget),\n });\n\n // Charged against the record's allowance like any other subtree, so one\n // deeply-wrapped failure cannot spend the whole budget on itself.\n budget.remaining -= described.causes.length;\n\n return described;\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (depth >= FULL_MAX_DEPTH) {\n return { _: \"elided\", by: \"depth\" } satisfies ShapeDescriptor;\n }\n\n seen.add(value);\n\n try {\n if (Array.isArray(value)) {\n const kept = value.slice(0, FULL_MAX_ENTRIES);\n const encoded: Array<unknown> = kept.map((entry) =>\n describeFull(entry, depth + 1, seen, budget)\n );\n\n if (value.length > FULL_MAX_ENTRIES) {\n encoded.push({\n _: \"elided\",\n by: \"entries\",\n length: value.length,\n } satisfies ShapeDescriptor);\n }\n\n return encoded;\n }\n\n if (value instanceof Map) {\n return {\n _: \"map\",\n entries: [...value.entries()]\n .slice(0, FULL_MAX_ENTRIES)\n .map(\n ([key, entry]) =>\n [\n describeFull(key, depth + 1, seen, budget),\n describeFull(entry, depth + 1, seen, budget),\n ] as const\n ),\n size: value.size,\n } satisfies ShapeDescriptor;\n }\n\n if (value instanceof Set) {\n return {\n _: \"set\",\n values: [...value.values()]\n .slice(0, FULL_MAX_ENTRIES)\n .map((entry) => describeFull(entry, depth + 1, seen, budget)),\n size: value.size,\n } satisfies ShapeDescriptor;\n }\n\n const out: Record<string, unknown> = {};\n\n // Own enumerable keys only. Walking the prototype chain would drag in\n // methods and framework internals, which is noise rather than visibility.\n const allKeys = Object.keys(value);\n const keys = allKeys.slice(0, FULL_MAX_ENTRIES);\n\n for (const key of keys) {\n out[key] = describeFull((value as Record<string, unknown>)[key], depth + 1, seen, budget);\n }\n\n // An array that gets truncated pushes a marker; an object has to carry one\n // as a key, and a silently short key list is the failure this whole encoder\n // is written against — it reads as \"the object had 256 keys\", which is a lie\n // the consumer has no way to detect.\n //\n // A real key named `_elided` loses to the marker. Preferred over a mangled\n // name: the collision is vanishingly rare, and a marker under a name nobody\n // reads is the same as no marker.\n if (allKeys.length > keys.length) {\n out[\"_elided\"] = {\n _: \"elided\",\n by: \"entries\",\n length: allKeys.length,\n } satisfies ShapeDescriptor;\n }\n\n const prototype = Object.getPrototypeOf(value) as unknown;\n\n // Class instances keep their type name alongside their fields: knowing a\n // value is a `HubServerResult` and not a bag of keys is most of what makes\n // a graph result readable.\n if (prototype !== null && prototype !== Object.prototype) {\n out[\"_type\"] =\n (value.constructor as { readonly name?: string } | undefined)?.name ?? \"object\";\n }\n\n return out;\n } finally {\n seen.delete(value);\n }\n}\n",
|
|
9
|
-
"import { describeError } from \"./cause.ts\";\nimport {
|
|
10
|
-
"import type { Runtime } from \"@frondruntime/core\";\nimport { describeError } from \"./cause.ts\";\nimport { WITHHELD } from \"./descriptors.ts\";\nimport { type Budget, describeFull, FULL_MAX_NODES } from \"./full.ts\";\nimport type { EncodePolicy } from \"./policy.ts\";\nimport type { EncodedEventRecord } from \"./protocol.ts\";\nimport { describeShape } from \"./shape.ts\";\n\n/**\n * Applies a policy to a value.\n *\n * The three encoders this composes are deliberately separate modules: the clamp\n * that decides disclosure (`policy.ts`), the walk that says as little as it can\n * (`shape.ts`), the walk that says as much as it can (`full.ts`), and the one\n * that describes failures the same way at every policy (`cause.ts`). What is\n * left here is the wiring — which walk a policy gets, and how one runtime event\n * is laid out on the wire.\n */\n\n/**\n * A policy, applied to one answer.\n *\n * One of these per record and per snapshot, because the budget it closes over\n * is the thing worth bounding: what a single answer costs the wire. A record\n * with one enormous field should spend its own allowance rather than be judged\n * field by field, and two records should never be able to spend each other's.\n */\nexport type ValueEncoder = {\n /** Ordinary app data, redacted according to the policy. */\n readonly value: (value: unknown) => unknown;\n /**\n * A failure, as a chain of causes.\n *\n * Separate from {@link value} because the runtime already knows which is\n * which, and sniffing would get it wrong: a failure that is not an `Error`\n * instance — an Effect `Cause`, a node status — reaches the value encoder as\n * an anonymous bag of keys.\n */\n readonly failure: (value: unknown) => unknown;\n};\n\nexport function createValueEncoder(policy: EncodePolicy): ValueEncoder {\n // Spelled out rather than folded into the `\"shape\"` branch. Falling through\n // was the bug: `\"none\"` reached the shape encoder and emitted key lists for\n // every node in a graph snapshot, which is a description of app data by an\n // app that had said it would send none.\n if (policy === \"none\") {\n return {\n value: () => WITHHELD,\n // Still a chain, because \"there is an error here\" is not the value's\n // data. What crosses is what the failure names about itself — its tags,\n // its node, the innermost message — and never its payload or its stack,\n // which `describeError` withholds at anything below `\"full\"`.\n failure: (value) => describeError(value, policy),\n };\n }\n\n if (policy === \"shape\") {\n return {\n value: (value) => describeShape(value, 0),\n failure: (value) => describeError(value, policy),\n };\n }\n\n const budget: Budget = { remaining: FULL_MAX_NODES };\n\n return {\n value: (value) => describeFull(value, 0, new Set<object>(), budget),\n // The `seen` set is per call and shared between the two halves of that call:\n // `describeError` marks each link of the chain as an ancestor, and the\n // payload walk it hands off to has to see those marks or it will descend\n // back into an error it is already standing on.\n failure: (value) => {\n const seen = new Set<object>();\n\n return describeError(value, policy, {\n seen,\n encodeValue: (own) => describeFull(own, 1, seen, budget),\n });\n },\n };\n}\n\n/**\n * Encodes one runtime event for the wire.\n *\n * Classification, work context, and node ids are metadata the runtime already\n * owns and are copied verbatim — they are ids and enum members, never user\n * data. A signal's channel and name join them, on the reasoning\n * `EncodedEventRecord` gives for the two fields. Only the event body goes\n * through the value encoder.\n */\nexport function encodeRecord(\n record: Runtime.RuntimeEventRecord,\n policy: EncodePolicy\n): EncodedEventRecord {\n const encoder = createValueEncoder(policy);\n\n // The runtime pulls `failures` straight off the event's own fields, so the\n // same object arrives twice — once as `fields.error`, once as `failures[0]`.\n // Matched by identity so both come out as the same thing; a record that\n // described one failure two different ways would read as two.\n const known = new Set(\n record.failures.filter(\n (failure): failure is object => typeof failure === \"object\" && failure !== null\n )\n );\n\n const encodeField = (value: unknown): unknown =>\n typeof value === \"object\" && value !== null && known.has(value)\n ? encoder.failure(value)\n : encoder.value(value);\n\n return {\n sequence: record.sequence,\n recordedAt: record.recordedAt,\n tag: record.event._tag,\n category: record.classification.category,\n severity: record.classification.severity,\n timeline: record.classification.timeline,\n reportable: record.classification.reportable,\n workId: record.work.workId,\n parentWorkId: record.work.parentWorkId,\n source: record.work.source,\n reason: record.work.reason,\n priority: record.work.priority,\n nodeIds: record.nodeIds,\n // Unclamped, like every routing field above it. A signal's channel and name\n // are how a reader addresses one — the filters `frond_read_events` exposes —\n // and they are authored as constants next to the code that publishes, the\n // same standing as `tag` and `nodeIds`. What the payload holds is the value,\n // and that is what `fields` withholds a line below.\n ...signalIdentity(record.event),\n fields: policy === \"none\" ? {} : describeFields(record.event, encodeField),\n // Failures are causes, not results: their messages are what makes a\n // devtools feed worth reading, so they are described rather than dropped —\n // including under `\"none\"`, whose subject is values, not what broke.\n //\n // Encoded as failures rather than as values, because that is what the\n // runtime says they are — no sniffing required. Which matters for the ones\n // that are not `Error` instances: an Effect `Cause` reaching the value\n // encoder comes out as a bag of key names.\n failures: record.failures.map(encoder.failure),\n };\n}\n\n/**\n * Names the signal an event is about, where it is about one.\n *\n * Two tags, written out, rather than a rule the field walk could apply to any\n * event: a general \"promote a field called `channel`\" would promote whatever an\n * app happened to name that way, which is app data crossing the policy that was\n * meant to clamp it. Only these two events have a channel the runtime itself put\n * there, and `RuntimeSignalSubscriberFailureObserved` is here for the same\n * reason as the publication — a subscriber failure that cannot say which signal\n * it was handling is a failure with no subject.\n *\n * Absent rather than empty on everything else. `channel: \"\"` is a record\n * claiming a channel it does not have, and a reader filtering on the field would\n * have to know to treat one string as meaning \"no\".\n */\nfunction signalIdentity(event: Runtime.RuntimeEvent): {\n readonly channel?: string;\n readonly name?: string;\n} {\n const signal =\n event._tag === \"RuntimeSignalPublished\"\n ? event.record.signal\n : event._tag === \"RuntimeSignalSubscriberFailureObserved\"\n ? event.signal.signal\n : undefined;\n\n return signal === undefined ? {} : { channel: signal.channel, name: signal.name };\n}\n\nfunction describeFields(\n event: Runtime.RuntimeEvent,\n encodeValue: (value: unknown) => unknown\n): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(event)) {\n if (key === \"_tag\") {\n continue;\n }\n\n fields[key] = encodeValue(value);\n }\n\n return fields;\n}\n",
|
|
5
|
+
"import type { Runtime } from \"@frondruntime/core\";\nimport { Clock, Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport { RpcClient, RpcSerialization } from \"effect/rpc\";\nimport { Socket } from \"effect/socket\";\nimport { encodeRecord } from \"./encode.ts\";\nimport { type EncodePolicy, resolvePolicy } from \"./policy.ts\";\nimport {\n type AttachmentInfo,\n EncodedEventRecord,\n FrondHubRpcs,\n HUB_PROTOCOL_VERSION,\n type HubCommand,\n type QueryOutcome,\n type ValuePolicy,\n} from \"./protocol.ts\";\nimport { encodeGraphSnapshot } from \"./snapshot.ts\";\n\n/**\n * How many encoded records are held between flushes.\n *\n * When this fills, further records are counted and discarded rather than\n * buffered without bound: an attached app must never be slowed down, let alone\n * grow unboundedly, because a devtools consumer stopped reading. The count\n * travels as `droppedSince`, so the hub always knows a gap happened.\n */\nconst MAX_BUFFERED_RECORDS = 4096;\n\nconst FLUSH_INTERVAL = \"250 millis\";\n\nexport type AttachOptions = {\n readonly runtime: Runtime.Runtime;\n readonly attachUrl: string;\n /** Human label for the hub's list, e.g. the host app's package name. */\n readonly name: string;\n readonly platform: string;\n /**\n * The most this app will ever disclose, whatever the hub asks for.\n *\n * `\"shape\"` by default: structure, key names, lengths and types, but no\n * values. Sending real values is a decision worth making per app rather than\n * inheriting — the runtimes worth debugging are the ones holding tokens and\n * account state, and a default that ships them is a default that ships them\n * the first time someone forgets.\n */\n readonly values?: ValuePolicy | undefined;\n /**\n * Stable identity for this attachment, unique across processes.\n *\n * Defaults to a fresh UUID, which is right for an ordinary app. The hub sets\n * it explicitly so it can recognise its own self-attachment in the list it\n * serves — `runtimeId` cannot do that job, because it comes from a\n * per-process counter and every runtime's first one is `runtime-1`.\n *\n * Minted per *call*, not per attempt: `attachDevtools` reuses one across\n * reconnects, so an app that outlives a hub restart comes back as itself.\n */\n readonly instanceId?: string;\n /** How many times this runtime has already attached. See `AttachmentInfo`. */\n readonly generation?: number;\n /**\n * Called once the hub has accepted this attempt.\n *\n * Exists so the caller can count reconnections without having to guess from\n * the outside which attempts got as far as being accepted.\n */\n readonly onAttached?: (() => void) | undefined;\n /**\n * Return false to leave a record out of the stream entirely.\n *\n * Distinct from the drop counter below, and the difference matters: a drop is\n * a gap the hub must be told about, because an agent reading the feed has to\n * be able to tell \"did not happen\" from \"was lost\". A record excluded here\n * was never in scope, so it is not a gap and is not counted as one.\n *\n * Exists for one caller — the hub, which observes the runtime it is also\n * writing into and would otherwise feed itself forever. An ordinary app has\n * no reason to pass this.\n */\n readonly include?: (record: Runtime.RuntimeEventRecord) => boolean;\n};\n\n/**\n * Mints the id that identifies this runtime for the life of the process.\n *\n * Deliberately not `crypto.randomUUID`, which this used to be. That call is not\n * available everywhere a Frond app runs — React Native has no global `crypto`\n * until a polyfill installs one — and reaching for it meant either a startup\n * crash on the runtime least able to explain it, or a guard, and a guard is a\n * branch whose two halves nobody exercises together.\n *\n * The entropy was never the requirement. This id has to be unique among the\n * handful of apps attached to one local hub at one time, and stable across that\n * process's own reconnects. Nothing authenticates with it, nothing persists it,\n * and it dies with the hub. A timestamp for cross-process separation and a short\n * random suffix for anything started inside the same millisecond covers that\n * with room to spare; the timestamp is the half that matters, because\n * `Math.random` is seeded per process and two processes launched together is\n * exactly where bare randomness is weakest.\n *\n * If this ever fronts something that is not a local devtools socket, it needs a\n * real generator — but then it also needs a real identity, not this.\n */\nexport function newInstanceId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/**\n * Transport for one attachment.\n *\n * Exported because the hub dials itself over exactly this layer — same\n * protocol, same serialization, same socket code path as a real app. If\n * self-attach works, the transport works.\n */\nexport function attachLayer(attachUrl: string): Layer.Layer<RpcClient.Protocol> {\n return RpcClient.layerProtocolSocket().pipe(\n Layer.provide(Socket.layerWebSocket(attachUrl)),\n Layer.provide(Socket.layerWebSocketConstructorGlobal),\n Layer.provide(RpcSerialization.layerNdjson)\n );\n}\n\n/**\n * Streams a runtime's events to a hub for as long as the connection lives.\n *\n * The returned Effect does not settle while attached — it *is* the attachment.\n * Fork it into a scope and close the scope to detach; the hub learns about the\n * detachment from the socket dying, which is the only mechanism that also works\n * when the app crashes.\n */\nexport const attachRuntime = Effect.fnUntraced(function* (options: AttachOptions) {\n const client = yield* RpcClient.make(FrondHubRpcs);\n // The transport's own codec, so the check below rejects exactly what a send\n // would. Built once; it runs only after a batch has already failed.\n const { codecFor } = yield* RpcClient.Protocol;\n const encodeForWire = Schema.encodeUnknownOption(codecFor(EncodedEventRecord));\n const crossesTheWire = (record: EncodedEventRecord): boolean =>\n Option.isSome(encodeForWire(record));\n\n const ceiling: ValuePolicy = options.values ?? \"shape\";\n\n let buffer: Array<EncodedEventRecord> = [];\n let dropped = 0;\n // Events fire between the socket opening and the `Attached` command arriving,\n // and the conservative reading of an unanswered negotiation is the narrow\n // one. Still clamped, so a ceiling of `\"none\"` holds from the first record.\n let policy: EncodePolicy = resolvePolicy(\"shape\", ceiling);\n let attachmentId: string | undefined;\n\n // Encoding happens here, at observe time, not at flush time: a\n // `RuntimeEventRecord` carries live references that keep mutating after the\n // record is handed out, so a record buffered raw would describe the graph as\n // it is when flushed, not as it was when the event fired.\n const subscription = options.runtime.observe((record) => {\n // Before the buffer check, so an excluded record cannot be counted as a\n // drop, and before encoding, so it costs nothing to exclude one.\n if (options.include !== undefined && !options.include(record)) {\n return;\n }\n\n if (buffer.length >= MAX_BUFFERED_RECORDS) {\n dropped += 1;\n return;\n }\n\n buffer.push(encodeRecord(record, policy));\n });\n\n yield* Effect.addFinalizer(() => Effect.sync(() => subscription.unsubscribe()));\n\n const info: AttachmentInfo = {\n protocolVersion: HUB_PROTOCOL_VERSION,\n instanceId: options.instanceId ?? newInstanceId(),\n runtimeId: options.runtime.getSnapshotSync().runtimeId,\n generation: options.generation ?? 0,\n name: options.name,\n platform: options.platform,\n startedAt: yield* Clock.currentTimeMillis,\n // Advertised so the hub can show what it is going to get. Advisory only:\n // `resolvePolicy` below is what actually enforces it, because a ceiling a\n // sender merely announces is one the sender can forget to apply.\n values: ceiling,\n };\n\n const flushOnce = Effect.gen(function* () {\n yield* Effect.sleep(FLUSH_INTERVAL);\n\n const id = attachmentId;\n\n if (id === undefined || (buffer.length === 0 && dropped === 0)) {\n return;\n }\n\n // Swapped, not drained: `observe` runs on whatever fiber produced the\n // event, so anything appended during the send lands in the next batch\n // instead of being lost to a splice race.\n const records = buffer;\n const droppedSince = dropped;\n buffer = [];\n dropped = 0;\n\n // One record the codec rejects fails the send of the whole batch, and a\n // failure here ends the attachment (see below), which would make every\n // such record cost a reconnect and the batch around it. So a failed batch\n // is checked record by record, against the transport's own codec, and sent\n // again without the records that cannot cross; those are counted as\n // dropped, because to the hub they are the same gap. A batch in which every\n // record crosses failed for some other reason, and that failure goes on to\n // end the attachment.\n yield* Effect.catchCause(\n client[\"Frond.Ingest\"]({ attachmentId: id, records, droppedSince }),\n (cause) => {\n const sendable = records.filter(crossesTheWire);\n\n return sendable.length === records.length\n ? Effect.failCause(cause)\n : client[\"Frond.Ingest\"]({\n attachmentId: id,\n records: sendable,\n droppedSince: droppedSince + records.length - sendable.length,\n });\n }\n );\n });\n\n /**\n * Answers one query, on its own fiber.\n *\n * Forked rather than awaited inline because this runs on the command stream:\n * a snapshot of a large graph is the most expensive thing this client does,\n * and blocking here would stall the heartbeat and every query behind it\n * behind one slow answer.\n *\n * Nothing in here is allowed to fail outward. A query that throws comes back\n * as `Failed`, because the alternative is an error escaping into the stream\n * handler and taking down an attachment over a question that was only ever\n * advisory.\n */\n const answer = (command: Extract<HubCommand, { readonly _tag: \"Query\" }>) =>\n Effect.gen(function* () {\n const id = attachmentId;\n\n if (id === undefined) {\n return;\n }\n\n const capturedAt = yield* Clock.currentTimeMillis;\n\n const outcome = yield* Effect.map(\n Effect.exit(\n Effect.sync(() => {\n // Clamped against the ceiling, not against the stream's policy. A\n // deliberate read may ask for more than the firehose gets, and may\n // never ask for more than the app agreed to disclose.\n const requested = resolvePolicy(command.values, ceiling);\n\n return encodeGraphSnapshot(options.runtime.getSnapshotSync(), {\n policy: requested,\n capturedAt,\n nodeId: command.query._tag === \"Node\" ? command.query.nodeId : undefined,\n });\n })\n ),\n (exit): QueryOutcome =>\n exit._tag === \"Success\"\n ? { _tag: \"Snapshot\", snapshot: exit.value }\n : { _tag: \"Failed\", reason: failureReason(exit.cause) }\n );\n\n yield* Effect.ignore(\n client[\"Frond.Reply\"]({ attachmentId: id, requestId: command.requestId, outcome })\n );\n });\n\n const commands = Stream.runForEach(client[\"Frond.Attach\"]({ info }), (command) => {\n if (command._tag === \"Attached\") {\n return Effect.sync(() => {\n attachmentId = command.attachmentId;\n policy = resolvePolicy(command.values, ceiling);\n options.onAttached?.();\n });\n }\n\n if (command._tag === \"Query\") {\n return Effect.forkScoped(answer(command));\n }\n\n return Effect.void;\n });\n\n // The flusher and the command stream are one attachment, and whichever ends\n // first ends it. A send that fails, on a socket whose write side broke while\n // its read side still answers, ends neither the stream nor its heartbeat,\n // and a flusher left to die on its own would leave the app attached and\n // sending nothing for good. Ending the attachment hands the failure to\n // whoever runs it, which for `attachDevtools` is a reconnect. The flusher\n // never succeeds, so a stream the hub closes still ends it the way it did.\n yield* Effect.raceFirst(commands, Effect.forever(flushOnce));\n});\n\n/**\n * A reason string for a query that could not be answered.\n *\n * Deliberately thin. This travels to a hub that will show it to whoever asked,\n * and the useful cases — an unstarted runtime, a node id that does not resolve —\n * already say so in their message. Serializing a cause chain here would mean a\n * second, competing account of failures next to the one the event stream\n * already carries.\n */\nfunction failureReason(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.message === \"\" ? cause.name : cause.message;\n }\n\n return String(cause);\n}\n",
|
|
6
|
+
"import { Diagnostics } from \"@frondruntime/core\";\nimport {\n describeNonFiniteNumber,\n type ErrorDescriptor,\n setField,\n UNREADABLE,\n} from \"./descriptors.ts\";\nimport type { EncodePolicy } from \"./policy.ts\";\n\n/**\n * Failures, as chains of causes.\n *\n * Kept apart from the two value encoders because it is not one: a failure is\n * described the same way at every policy, and what varies is only how much of\n * each frame crosses. The value encoders call in here; nothing here calls back\n * out to them except through {@link FullContext}, which is what keeps this\n * module a leaf.\n */\n\n/**\n * How far up a `cause` chain to walk. Matches the core default.\n *\n * Chains this long are rare and the frames are small; the expensive parts of a\n * frame — its stack and its payload — are bounded separately below.\n */\nconst CAUSE_MAX_DEPTH = 8;\nconst SHAPE_CAUSE_STRING_LENGTH = 256;\nconst FULL_CAUSE_STRING_LENGTH = 1024;\n/**\n * How much stack to take from core before selecting frames out of it.\n *\n * Deliberately far above anything a real stack reaches: cutting here cuts by\n * character, which is the thing {@link abridgeStack} exists to stop doing. This\n * is a guard against a fabricated `stack` string, not a budget.\n */\nconst CAUSE_STACK_SOURCE_LENGTH = 32768;\n/**\n * How many frames survive selection.\n *\n * The frame that names app code is almost always within the first few once the\n * library frames are gone; fifteen is room for a couple of layers of wrapping on\n * top of that without the trace becoming the record.\n */\nconst KEPT_STACK_FRAMES = 15;\n/** Kept from a trace that is library frames all the way down. See {@link abridgeStack}. */\nconst LIBRARY_ONLY_STACK_FRAMES = 2;\n/** The fallback bound, for a `stack` this cannot read as frames at all. */\nconst FULL_CAUSE_STACK_LENGTH = 2048;\n\n/**\n * Frames, in the two formats a JS runtime produces.\n *\n * V8 (Node, Bun, Chromium) indents every frame with `at `; JSC and SpiderMonkey\n * write `name@url:line:column`. Matched rather than assumed because the header\n * of a stack is the error's own message, which is app text and must not be\n * mistaken for a frame and dropped.\n */\nconst V8_STACK_FRAME = /^\\s*at\\s\\S/;\n// Anchored and whitespace-free on both sides of the `@`, because a JSC stack has\n// no header line to protect it: a message like `Cannot find module\n// /app/node_modules/x/index.js:1:1` ends the way a frame ends, and an unanchored\n// pattern would call line 0 a frame, leaving `header` empty and feeding the\n// message itself to the library filter.\nconst AT_STACK_FRAME = /^\\S*@\\S*:\\d+:\\d+\\s*$/;\n\n/**\n * Frames that belong to someone else's code.\n *\n * `node_modules` is the whole point; the rest are the same idea for code that\n * has no file in the tree at all — Node's builtins, Bun's, and native frames.\n * Bun writes its own native frames as `at moduleEvaluation (native:1:11)` rather\n * than in either of the parenthesized spellings, hence the bare `native:`.\n */\nconst LIBRARY_STACK_FRAME = /node_modules|node:|bun:|native:|\\(native\\)|\\[native code]/;\n\n/**\n * What the `\"full\"` policy needs in order to encode an error's own payload.\n *\n * `encodeValue` is injected rather than imported. The full encoder descends into\n * errors and errors descend into their payloads, so calling that encoder by name\n * from here would make the two modules mutually recursive at module scope for no\n * gain — the caller already holds the depth, the `seen` set and the budget that\n * such a call would need, and closing over them is both shorter and the only\n * arrangement in which this file has no dependency on either value encoder.\n *\n * `seen` is still passed through, because this function adds to it: every link\n * of the chain joins the ancestor path for the duration of the walk below it.\n */\nexport type FullContext = {\n readonly seen: Set<object>;\n readonly encodeValue: (value: unknown) => unknown;\n};\n\n/**\n * Serializes a failure and everything that caused it.\n *\n * Thin over `Diagnostics.serializeCauseChain`, which is already the runtime's\n * own answer to \"what went wrong\" and is already defensive about it — getters\n * that throw, cycles, absent fields. Reusing it means the devtools feed and a\n * runtime sink describe the same failure the same way; hand-rolling a second\n * walk here would eventually mean two accounts of one error that disagree.\n *\n * `preview` is dropped from every frame. Core builds it for a human reading a\n * report, and for an `Error` it is name, message, stack and cause — all of\n * which the frame already carries, one of them recursively, so keeping it would\n * send the chain once per link and add nothing.\n *\n * Two things are `\"full\"`-only, for the same reason the rest of this encoder\n * withholds things. A `stack` is bulk at `\"shape\"`: a wall of Effect internals\n * around the two frames that name app code. And `fields` is the error's own\n * payload — `status`, `endpoint`, whatever the app put on it — which is app\n * data by any other name. What survives at `\"shape\"` is what the chain names\n * explicitly: `tag`, `nodeId`, `operation`, `dependency`, `path`.\n */\nexport function describeError(\n value: unknown,\n policy: EncodePolicy,\n full?: FullContext\n): ErrorDescriptor {\n const disclose = policy === \"full\";\n\n const frames = Diagnostics.serializeCauseChain(value, {\n maxDepth: CAUSE_MAX_DEPTH,\n maxStringLength: disclose ? FULL_CAUSE_STRING_LENGTH : SHAPE_CAUSE_STRING_LENGTH,\n // Asked for whole, then abridged by frame below. Core can only cut by\n // character, which is exactly the cut that loses the frame worth keeping.\n maxStackLength: CAUSE_STACK_SOURCE_LENGTH,\n maxObjectKeys: disclose ? 20 : 8,\n });\n\n if (full === undefined) {\n return {\n _: \"error\",\n message: rootMessage(frames),\n causes: reduceChain(frames, policy),\n };\n }\n\n // Every link joins the ancestor path for the duration, so a payload field\n // pointing back at an error already on the chain is a cycle rather than a\n // second trip through this function.\n //\n // Only what this call actually inserted comes back out. A link an enclosing\n // frame is still standing on has to stay marked: an error reached through an\n // app object whose payload points back at that object is the ordinary shape of\n // a wrapped failure, and un-marking it there would let the walk descend into\n // the ancestor instead of naming the cycle.\n //\n // Which links this call inserted is a bit per link, in place of an array of\n // them: there are at most `CAUSE_MAX_DEPTH` links, well under 31.\n const links = causeValues(value, frames.length);\n let marked = 0;\n\n for (let index = 0; index < links.length; index++) {\n const link = links[index];\n\n if (typeof link === \"object\" && link !== null && !full.seen.has(link)) {\n full.seen.add(link);\n marked |= 1 << index;\n }\n }\n\n try {\n const causes = reduceChain(frames, policy);\n\n for (let index = 0; index < causes.length; index++) {\n const fields = errorFields(links[index], full.encodeValue);\n\n if (fields !== undefined) {\n // Index-aligned: `reduceChain` keeps one frame per frame it is given.\n (causes[index] as Record<string, unknown>)[\"fields\"] = fields;\n }\n }\n\n return { _: \"error\", message: rootMessage(frames), causes };\n } finally {\n for (let index = 0; index < links.length; index++) {\n if ((marked & (1 << index)) !== 0) {\n full.seen.delete(links[index] as object);\n }\n }\n }\n}\n\n/**\n * A chain of frames, each cut down by {@link reduceFrame}.\n *\n * Indexed loops rather than `map`, here and in `reduceFrame`: this runs once\n * per failure in every record, nested once per member of an aggregate, and on\n * Hermes a callback and an entry array per frame are a cost worth not paying.\n */\nfunction reduceChain(\n chain: ReadonlyArray<Diagnostics.SerializedCauseFrame>,\n policy: EncodePolicy\n): Array<Record<string, unknown>> {\n const reduced: Array<Record<string, unknown>> = [];\n\n for (let index = 0; index < chain.length; index++) {\n reduced.push(reduceFrame(chain[index] as Diagnostics.SerializedCauseFrame, policy));\n }\n\n return reduced;\n}\n\n/**\n * One frame, cut down to what its policy lets cross.\n *\n * The one place a frame is reduced, so the frames of an aggregate's member\n * chains, which core nests under `failures`, get exactly what the chain that\n * holds them gets. A member frame comes from the same walk as any other and\n * carries the same `preview`, `stack` and absent keys.\n *\n * `path` and `valueKind` are the two frame fields that describe the app's data\n * rather than the runtime's: a path is a list of the app's own key names, and a\n * value kind says whether what failed was an array or an object. Both are shape\n * by any definition, so `\"none\"` — whose whole contract is that no shape\n * crosses — drops them. The message still crosses at every policy; that is\n * deliberate, and it is the one thing a reader cannot diagnose without.\n *\n * `fields` is not added here: it needs the value behind the frame, which only\n * the outermost chain keeps (see {@link causeValues}).\n */\nfunction reduceFrame(\n frame: Diagnostics.SerializedCauseFrame,\n policy: EncodePolicy\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n // `Object.prototype.hasOwnProperty.call` rather than `Object.hasOwn`, which\n // Hermes does not ship.\n for (const key in frame) {\n if (!Object.prototype.hasOwnProperty.call(frame, key)) {\n continue;\n }\n\n const value = (frame as Record<string, unknown>)[key];\n\n if (value === undefined || key === \"preview\") {\n continue;\n }\n\n if (key === \"stack\") {\n if (policy === \"full\" && typeof value === \"string\") {\n out[key] = abridgeStack(value);\n }\n } else if (key === \"path\") {\n if (policy !== \"none\") {\n out[key] = Array.isArray(value) ? pathOf(value) : value;\n }\n } else if (key === \"valueKind\") {\n if (policy !== \"none\") {\n out[key] = value;\n }\n } else if (key === \"failures\" && Array.isArray(value)) {\n const chains: ReadonlyArray<ReadonlyArray<Diagnostics.SerializedCauseFrame>> = value;\n const reduced: Array<Array<Record<string, unknown>>> = [];\n\n for (let index = 0; index < chains.length; index++) {\n reduced.push(\n reduceChain(chains[index] as ReadonlyArray<Diagnostics.SerializedCauseFrame>, policy)\n );\n }\n\n out[key] = reduced;\n } else if (key === \"cancellation\" && typeof value === \"object\" && value !== null) {\n // Core fills both of its keys whether the failure had them or not.\n out[key] = compact(value as Record<string, unknown>);\n } else if (typeof value === \"number\") {\n out[key] = value - value === 0 ? value : describeNonFiniteNumber(value);\n } else {\n out[key] = value;\n }\n }\n\n return out;\n}\n\n/**\n * A frame's `path`, with no holes.\n *\n * Core writes each key name as a string and an `undefined` one as\n * `\"undefined\"`, but keeps a hole where the failure's own list had one. A hole\n * reads as `undefined`, so it goes out as core writes that: the codec rejects a\n * hole as it rejects `undefined`, and one would fail the whole batch.\n */\nfunction pathOf(path: ReadonlyArray<unknown>): Array<unknown> {\n const out: Array<unknown> = [];\n\n for (let index = 0; index < path.length; index++) {\n const entry = path[index];\n\n out.push(entry === undefined ? \"undefined\" : entry);\n }\n\n return out;\n}\n\n/**\n * A stack, selected by frame instead of cut by character.\n *\n * A raw stack is mostly other people's code — Effect's fiber runtime, the test\n * runner, the module loader — and the frames that name the app are scattered\n * through it rather than at the top. Truncating at a character count therefore\n * spends the budget on internals and can cut the one frame a reader needed, so\n * this drops library frames outright and keeps the first {@link\n * KEPT_STACK_FRAMES} of what is left.\n *\n * The dropped count is not decoration. An abridged trace that does not say it is\n * abridged reads as \"this is where it came from\", and a reader who then cannot\n * find the caller concludes the wrong thing about the code rather than about the\n * trace.\n *\n * Two cases deliberately do not select. A trace that is library frames all the\n * way down — a failure raised entirely inside a dependency — still says where in\n * that dependency, and an empty stack would throw that away for nothing. And a\n * `stack` with no recognizable frames is not a stack this can reason about, so\n * it falls back to the character bound rather than guessing.\n */\nfunction abridgeStack(stack: string): string {\n const lines = stack.split(\"\\n\");\n let first = -1;\n\n for (let index = 0; index < lines.length; index++) {\n if (isStackFrame(lines[index] as string)) {\n first = index;\n break;\n }\n }\n\n if (first === -1) {\n return stack.length <= FULL_CAUSE_STACK_LENGTH\n ? stack\n : `${stack.slice(0, FULL_CAUSE_STACK_LENGTH)}…`;\n }\n\n // One pass over everything below the header, in loops rather than callbacks\n // and spreads, for the reason `reduceChain` gives.\n //\n // Counted against everything below the header, not just the lines the two\n // patterns recognize. JSC writes frames this cannot parse — `promiseReactionJob@[native code]`\n // has no `:line:col` — and dropping those out of the denominator would let the\n // trace claim it accounted for what it removed while quietly removing more.\n let body = 0;\n // Only as many of each as can be kept: the top library frames for a trace\n // with no app frames, and the first app frames otherwise.\n const leading: Array<string> = [];\n const own: Array<string> = [];\n\n for (let index = first; index < lines.length; index++) {\n const line = lines[index] as string;\n\n if (line.trim() === \"\") {\n continue;\n }\n\n body++;\n\n if (!isStackFrame(line)) {\n continue;\n }\n\n if (leading.length < LIBRARY_ONLY_STACK_FRAMES) {\n leading.push(line);\n }\n\n if (own.length < KEPT_STACK_FRAMES && !LIBRARY_STACK_FRAME.test(line)) {\n own.push(line);\n }\n }\n\n const kept = own.length === 0 ? leading : own;\n // Everything above the first frame is the error's own header, kept whole: it\n // is the name and message, which is the part a reader reads first.\n const out = lines.slice(0, first);\n\n for (let index = 0; index < kept.length; index++) {\n out.push(kept[index] as string);\n }\n\n const dropped = body - kept.length;\n\n if (dropped !== 0) {\n out.push(\n ` … ${dropped} frame${dropped === 1 ? \"\" : \"s\"} dropped: library internals, unrecognized lines, and any past the first ${KEPT_STACK_FRAMES}`\n );\n }\n\n return out.join(\"\\n\");\n}\n\nfunction isStackFrame(line: string): boolean {\n return V8_STACK_FRAME.test(line) || AT_STACK_FRAME.test(line);\n}\n\n/**\n * Re-walks the chain for the values behind the frames.\n *\n * Bounded by `count`, which is the frame count rather than a limit of its own:\n * two walks of the same chain that could stop in different places would\n * eventually pair a frame with the wrong value.\n */\nfunction causeValues(root: unknown, count: number): ReadonlyArray<unknown> {\n const values: Array<unknown> = [];\n let current: unknown = root;\n\n for (let index = 0; index < count; index += 1) {\n values.push(current);\n\n if (typeof current !== \"object\" || current === null) {\n break;\n }\n\n try {\n current = (current as Record<string, unknown>)[\"cause\"];\n } catch {\n break;\n }\n }\n\n return values;\n}\n\n/**\n * Keys a frame already accounts for, by name, and should not repeat.\n *\n * `cause` is the next frame. The rest are what `serializeCauseChain` lifts out\n * of a failure into named fields — sometimes renamed, as `tag` is to `nodeTag`,\n * which is why this list is written against the *source* keys and has to stay\n * in step with that function rather than with the frame type.\n */\nconst NAMED_ERROR_KEYS = new Set([\n \"boundary\",\n \"cancellation\",\n \"cause\",\n \"dependency\",\n \"invariant\",\n \"kind\",\n \"message\",\n \"name\",\n \"nodeId\",\n \"operation\",\n \"path\",\n \"stack\",\n \"tag\",\n \"timeout\",\n \"_tag\",\n]);\n\n/**\n * What a failure carries beyond being a failure.\n *\n * The half of an error a cause chain cannot name in advance: an HTTP status, a\n * request id, the arguments the call was made with. `undefined` when there is\n * none, which is the common case — a wrapper carries nothing but the fields\n * above — and {@link compact} drops the key on the way out.\n */\nfunction errorFields(value: unknown, encodeValue: (value: unknown) => unknown): unknown {\n if (typeof value !== \"object\" || value === null) {\n // A thrown string or number is its own payload, and the frame's `message`\n // only got a rendering of it.\n return encodeValue(value);\n }\n\n let keys: ReadonlyArray<string>;\n\n try {\n keys = Object.keys(value);\n } catch {\n return undefined;\n }\n\n const own: Record<string, unknown> = {};\n let copied = 0;\n\n // Each read guarded on its own, like the payload walk this hands off to: a\n // getter that throws costs its own field rather than every readable one.\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index] as string;\n\n if (NAMED_ERROR_KEYS.has(key)) {\n continue;\n }\n\n let field: unknown;\n\n try {\n field = (value as Record<string, unknown>)[key];\n } catch {\n field = UNREADABLE;\n }\n\n setField(own, key, field);\n copied++;\n }\n\n return copied === 0 ? undefined : encodeValue(own);\n}\n\n/**\n * The innermost thing that had something to say.\n *\n * Two kinds of frame have nothing: a `Data.TaggedError` wrapper, whose message\n * is empty, and a failure that is not an error at all — a node status, say —\n * for which core falls back to the value's kind. Both are skipped, the second\n * because `\"object\"` in a field called `message` reads as a message and is not\n * one. When the whole chain is like that, the outermost frame's own name is the\n * most this can honestly say, and the frames below it carry the rest.\n */\nfunction rootMessage(frames: ReadonlyArray<Diagnostics.SerializedCauseFrame>): string {\n for (let index = frames.length - 1; index >= 0; index -= 1) {\n const frame = frames[index];\n const message = frame?.message;\n\n if (message !== undefined && message !== \"\" && message !== frame?.valueKind) {\n return message;\n }\n }\n\n return frames[0]?.tag ?? frames[0]?.name ?? \"\";\n}\n\n/**\n * Drops absent keys.\n *\n * A cancellation declares both of its fields whether the failure had them or\n * not, so either can be `undefined`, and the transport's JSON check rejects an\n * `undefined` value rather than dropping it.\n */\nexport function compact(record: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n\n for (const key in record) {\n if (!Object.prototype.hasOwnProperty.call(record, key)) {\n continue;\n }\n\n // Read once: a getter read twice can answer differently the second time.\n const value = record[key];\n\n if (value !== undefined) {\n out[key] = value;\n }\n }\n\n return out;\n}\n",
|
|
7
|
+
"/**\n * The vocabulary both encoders emit where a value did not survive whole.\n *\n * Shared rather than duplicated because the two encoders disagree about almost\n * everything else — `\"shape\"` says as little as it can and `\"full\"` says as much\n * as it can — and the one thing they must agree on is how a reader tells a\n * marker from data.\n */\n\n/**\n * A failure, as its chain of causes rather than as its outermost link.\n *\n * The outermost link is almost never the interesting one. Frond wraps failures\n * as it unwinds — `RefreshFailed` around `ActionFailed` around whatever the app\n * actually threw — and those wrappers are `Data.TaggedError`s, whose `message`\n * is the empty string. Encoding one as `{name, message}` therefore yields\n * `{\"RefreshFailed\", \"\"}`: the shape of an answer with none of the content.\n *\n * Deliberately not a *projection*. Core can also produce one of those, with a\n * headline, a severity guess and a retryability guess, and it is the right thing\n * to put in front of a human or into an error reporter. This feed is read by an\n * agent, which is better served by the frames themselves — every wrapper, in\n * order, with the fields each one carries — than by someone else's summary of\n * them.\n */\nexport type ErrorDescriptor = {\n readonly _: \"error\";\n /**\n * The deepest non-empty message in the chain: what actually went wrong.\n *\n * A selection, not a synthesis — it is one of the messages in `causes`,\n * hoisted because it is the field worth reading first and it is otherwise\n * buried under however many wrappers the unwinding added.\n */\n readonly message: string;\n /** Outermost first. Frame `n + 1` is frame `n`'s `cause`. */\n readonly causes: ReadonlyArray<Record<string, unknown>>;\n};\n\n/**\n * A marker that survived where a value did not.\n *\n * Only ever emitted alongside real data — at `\"full\"`, and at `\"shape\"` for a\n * string long enough to be cut or a number with no JSON form — which is why\n * these stay objects while the `\"shape\"` vocabulary is strings. A reader looking at real values has to be\n * able to tell a marker from one of them, and `{_: …}` is that tell.\n *\n * `_` rather than `_tag` so a descriptor is never mistaken for a domain tagged\n * union by anything reading the feed.\n *\n * Two markers are *keys* rather than arms of this union, because they annotate\n * an encoded object from the inside and have nowhere else to go: `\"full\"` adds\n * `_type` — a string — to a class instance, and `_elided` (whose value is the\n * `\"elided\"` arm below) to an object whose key list was cut. Both are listed\n * here so this type stays the one place the vocabulary is written down.\n */\nexport type ShapeDescriptor =\n | { readonly _: \"opaque\"; readonly type: string }\n | { readonly _: \"string\"; readonly length: number; readonly head: string }\n | ErrorDescriptor\n /** A value already on the path above this one. Emitted instead of recursing. */\n | { readonly _: \"cycle\" }\n /** A bound stopped the walk here. `by` names which one. */\n | { readonly _: \"elided\"; readonly by: \"depth\" | \"budget\" | \"entries\"; readonly length?: number }\n /**\n * Collections, at `\"full\"` only — `\"shape\"` names them `Map(3)` and `Set(3)`.\n * `size` is the collection's real size; `entries` and `values` are what\n * survived the entry bound, and end in an `\"elided\"` marker when it cut them\n * — in a map, as both halves of a last pair.\n */\n | {\n readonly _: \"map\";\n readonly entries: ReadonlyArray<readonly [unknown, unknown]>;\n readonly size: number;\n }\n | { readonly _: \"set\"; readonly values: ReadonlyArray<unknown>; readonly size: number };\n\n/**\n * What `\"none\"` puts where a value was.\n *\n * A word, not a descriptor: `\"none\"` is the policy that has decided the reader\n * learns nothing about this value, and a key list or a type name is something.\n * The same marker for every value, so it cannot be read as a shape either.\n */\nexport const WITHHELD = \"withheld\";\n\n/**\n * Reading a value can run the app's code, so reading it can throw.\n *\n * A getter that throws, a revoked `Proxy` — a finalized immer draft, a torn-down\n * reactive scope — a prototype whose `constructor` is a throwing getter: every\n * one of those turns `Object.keys` or an `instanceof` into an exception, and\n * none of them is exotic in a frontend app.\n *\n * The consequence is what makes this worth guarding rather than letting throw.\n * On the event path the encoder runs inside the app's own observer, and core\n * routes an observer failure to sinks only — so the record would vanish without\n * incrementing `dropped`, which is exactly the \"did not happen\" versus \"was\n * lost\" distinction the protocol exists to preserve. On the snapshot path one\n * unreadable node would fail the whole graph read and leave a reader with\n * nothing instead of with 299 good rows and one marked hole.\n *\n * `{_: \"opaque\"}` is the honest answer: there is something here, and this\n * encoder could not look at it. The thrown error's own message is not carried —\n * it comes from app code, and a `\"shape\"` read that let one through would be a\n * hole in the policy rather than a diagnostic.\n */\nexport const UNREADABLE = { _: \"opaque\", type: \"unreadable\" } satisfies ShapeDescriptor;\n\nconst NOT_A_NUMBER = { _: \"opaque\", type: \"number:NaN\" } satisfies ShapeDescriptor;\nconst POSITIVE_INFINITY = { _: \"opaque\", type: \"number:Infinity\" } satisfies ShapeDescriptor;\nconst NEGATIVE_INFINITY = { _: \"opaque\", type: \"number:-Infinity\" } satisfies ShapeDescriptor;\n\n/**\n * A number JSON cannot carry, said by name.\n *\n * Passing `NaN` or an infinity through as a number fails the transport, not\n * just the reader: the RPC codec validates every value as JSON and rejects the\n * whole event batch or snapshot reply that holds one. And `JSON.stringify`\n * alone would write `null`, which a reader cannot tell from a field that really\n * was `null`. Both encoders emit the same three markers so a value reads the\n * same at either policy.\n *\n * Callers test finiteness themselves and reach this only for the non-finite\n * case, so a finite number pays no call. Shared constants, like\n * {@link UNREADABLE}, so marking one allocates nothing.\n */\nexport function describeNonFiniteNumber(value: number): ShapeDescriptor {\n return value > 0 ? POSITIVE_INFINITY : value < 0 ? NEGATIVE_INFINITY : NOT_A_NUMBER;\n}\n\n/**\n * A class instance's name, or `\"object\"` when it has none it will give up.\n *\n * Guarded on its own, because both encoders read it after deciding what else\n * to send: a `constructor` or `name` getter that throws would otherwise reach\n * the catch around the whole value and trade its readable fields, or its\n * label, for one marker.\n *\n * Checked for being a string, because nothing else makes it one: the name is\n * read off the app's own prototype, and a `name` of `Infinity` there would\n * otherwise fail the transport for the whole batch.\n */\nexport function typeName(value: object): string {\n try {\n const name = (value.constructor as { readonly name?: unknown } | undefined)?.name;\n\n return typeof name === \"string\" ? name : \"object\";\n } catch {\n return \"object\";\n }\n}\n\n/**\n * Writes `key` onto an encoded record as an own data property.\n *\n * Assignment is not that for one key: `out[\"__proto__\"] = x` sets the record's\n * prototype, which drops the field and leaves an object the transport's JSON\n * check rejects, failing the whole batch. `JSON.parse` makes `__proto__` an\n * ordinary own key, so an app holding a parsed payload can hold one. Only that\n * key takes the slow path; every other key is a plain assignment.\n */\nexport function setField(record: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") {\n Object.defineProperty(record, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n } else {\n record[key] = value;\n }\n}\n",
|
|
8
|
+
"import { describeError } from \"./cause.ts\";\nimport {\n describeNonFiniteNumber,\n type ShapeDescriptor,\n setField,\n typeName,\n UNREADABLE,\n} from \"./descriptors.ts\";\n\n/**\n * Bounds for `\"full\"`. Termination guards, not a byte budget.\n *\n * This encoder runs against a loopback socket, so bytes are close to free; what\n * these stop is a cycle the `seen` set cannot catch, a proxy that manufactures\n * keys on demand, or a linked list a few hundred thousand long — cases where the\n * walk would hang the observed app inside its own devtools. Set them where a\n * pathological structure trips them and a large-but-real one does not, and every\n * one of them announces itself in the output. A cap an agent cannot see is worse\n * than a low cap: it turns \"there was more\" into \"that was all\", which is the\n * one thing this feed must never say.\n */\nconst FULL_MAX_DEPTH = 24;\nconst FULL_MAX_STRING_LENGTH = 65536;\nconst FULL_MAX_ENTRIES = 4096;\n/**\n * Total encoded values per record, across the whole tree.\n *\n * Counts values, not characters: one 64k string spends the same allowance as\n * `true`. So this bounds how long the walk runs, and only loosely bounds what it\n * produces — which is the right trade here, where the walk is the expensive half\n * and the wire is a socket to the same machine.\n */\nexport const FULL_MAX_NODES = 50000;\n\nexport type Budget = { remaining: number };\n\n/**\n * Reduces a value to JSON-safe form while keeping its contents.\n *\n * The counterpart to `describeShape`, and the opposite default: where the shape\n * encoder asks \"what can I say without revealing this\", this one asks \"what is\n * the least I can leave out\".\n *\n * Which is also why it does not share that encoder's string vocabulary. Here the\n * values around a marker are real data, so a marker has to stay\n * distinguishable from one — hence `{_: \"elided\"}` rather than a word. There,\n * nothing structured is real, so there is nothing for a word to collide with.\n *\n * `seen` is the ancestor path, not every value visited. A value that appears\n * twice in a result — a shared config object, the same node referenced by two\n * dependents — is legitimately encoded twice; only a value containing *itself*\n * is a cycle. Tracking all visited values instead would silently blank out\n * shared structure and read as data loss.\n */\nexport function describeFull(\n value: unknown,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n if (budget.remaining <= 0) {\n return { _: \"elided\", by: \"budget\" } satisfies ShapeDescriptor;\n }\n\n budget.remaining -= 1;\n\n if (value === null || value === undefined) {\n return value ?? null;\n }\n\n switch (typeof value) {\n case \"boolean\": {\n return value;\n }\n // See `describeShape` for the finiteness test: one subtraction, so a finite\n // number takes the same path it always did.\n case \"number\": {\n return value - value === 0 ? value : describeNonFiniteNumber(value);\n }\n // Not JSON-safe, and no rendering of them is more useful than saying what\n // they were.\n case \"bigint\": {\n return { _: \"opaque\", type: `bigint:${value.toString()}` } satisfies ShapeDescriptor;\n }\n case \"function\": {\n return {\n _: \"opaque\",\n type: `function:${functionName(value)}`,\n } satisfies ShapeDescriptor;\n }\n case \"symbol\": {\n return { _: \"opaque\", type: value.toString() } satisfies ShapeDescriptor;\n }\n case \"string\": {\n return value.length <= FULL_MAX_STRING_LENGTH\n ? value\n : ({\n _: \"string\",\n length: value.length,\n head: value.slice(0, FULL_MAX_STRING_LENGTH),\n } satisfies ShapeDescriptor);\n }\n default: {\n return describeFullStructure(value as object, depth, seen, budget);\n }\n }\n}\n\nfunction describeFullStructure(\n value: object,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n try {\n return describeFullStructureUnguarded(value, depth, seen, budget);\n } catch {\n // See {@link UNREADABLE}. The `seen` set is left as this call found it: the\n // one place that adds to it deletes in a `finally`.\n return UNREADABLE;\n }\n}\n\nfunction describeFullStructureUnguarded(\n value: object,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n if (seen.has(value)) {\n return { _: \"cycle\" } satisfies ShapeDescriptor;\n }\n\n if (value instanceof Error) {\n const described = describeError(value, \"full\", {\n seen,\n encodeValue: (own) => describeFull(own, depth + 1, seen, budget),\n });\n\n // Charged against the record's allowance like any other subtree, so one\n // deeply-wrapped failure cannot spend the whole budget on itself.\n budget.remaining -= described.causes.length;\n\n return described;\n }\n\n if (value instanceof Date) {\n // An invalid date throws here and reaches the guard around this walk as\n // unreadable. An override can instead return anything, and a non-string\n // fails the transport for the whole batch, so it reads the same way.\n const iso: unknown = value.toISOString();\n\n return typeof iso === \"string\" ? iso : UNREADABLE;\n }\n\n if (depth >= FULL_MAX_DEPTH) {\n return { _: \"elided\", by: \"depth\" } satisfies ShapeDescriptor;\n }\n\n seen.add(value);\n\n try {\n if (Array.isArray(value)) {\n const length = arrayLength(value);\n // `length` is read through the array's own getter, which a proxy can\n // answer with anything: a non-number or `NaN` reads as empty, and an\n // infinity as past the bound.\n const count =\n typeof length === \"number\" && length > 0\n ? Math.min(Math.floor(length), FULL_MAX_ENTRIES)\n : 0;\n const encoded: Array<unknown> = [];\n\n // Indexed, with each read guarded on its own: a hole reads as `undefined`\n // and goes out as `null`, where a hole left in place fails the transport\n // for the whole batch, and an entry whose read throws costs that entry\n // rather than every readable one beside it.\n for (let index = 0; index < count; index++) {\n let entry: unknown;\n\n try {\n entry = value[index];\n } catch {\n encoded.push(UNREADABLE);\n continue;\n }\n\n encoded.push(describeFull(entry, depth + 1, seen, budget));\n }\n\n if (typeof length === \"number\" && length > FULL_MAX_ENTRIES) {\n encoded.push(entriesCut(finiteNumber(length)));\n }\n\n return encoded;\n }\n\n // Read through the iterator protocol, as a spread reads them, with every\n // read that can run the app's code guarded on its own: `size`, each step,\n // its `done` and its `value`, and each half of a map's pair. A subclass can\n // override any of them, and a throw in one should not cost what the others\n // read. The walk of what a step held has guards of its own. The iterator is\n // taken outside the guards, because a value that cannot even give one up\n // has nothing readable at all.\n if (value instanceof Map) {\n const walk = readSteps(value.entries());\n const entries: Array<readonly [unknown, unknown]> = [];\n\n for (let index = 0; index < walk.values.length; index++) {\n const pair = walk.values[index];\n\n entries.push([\n describeStepValue(halfOf(pair, 0), depth, seen, budget),\n describeStepValue(halfOf(pair, 1), depth, seen, budget),\n ]);\n }\n\n const reported = collectionSize(value);\n const size = reported ?? entries.length;\n\n // Each marker is a pair, like every other entry, so a reader walking\n // pairs meets it where the entries stopped.\n switch (walk.end) {\n case \"broken\": {\n entries.push([UNREADABLE, UNREADABLE]);\n break;\n }\n case \"cut\": {\n const marker = entriesCut(reported);\n\n entries.push([marker, marker]);\n break;\n }\n case \"done\": {\n break;\n }\n }\n\n return { _: \"map\", entries, size } satisfies ShapeDescriptor;\n }\n\n if (value instanceof Set) {\n const walk = readSteps(value.values());\n const values: Array<unknown> = [];\n\n for (let index = 0; index < walk.values.length; index++) {\n values.push(describeStepValue(walk.values[index], depth, seen, budget));\n }\n\n const reported = collectionSize(value);\n const size = reported ?? values.length;\n\n switch (walk.end) {\n case \"broken\": {\n values.push(UNREADABLE);\n break;\n }\n case \"cut\": {\n values.push(entriesCut(reported));\n break;\n }\n case \"done\": {\n break;\n }\n }\n\n return { _: \"set\", values, size } satisfies ShapeDescriptor;\n }\n\n const out: Record<string, unknown> = {};\n\n // Own enumerable keys only. Walking the prototype chain would drag in\n // methods and framework internals, which is noise rather than visibility.\n const allKeys = Object.keys(value);\n const keys = allKeys.slice(0, FULL_MAX_ENTRIES);\n\n // Guarded per key, around the read as well as the walk below it: the read\n // is where a getter runs, and a throw there would otherwise reach the catch\n // around this whole walk and trade every readable sibling for one marker.\n // The nested walk restores `seen` itself, so nothing needs undoing here.\n for (const key of keys) {\n let encoded: unknown;\n\n try {\n encoded = describeFull((value as Record<string, unknown>)[key], depth + 1, seen, budget);\n } catch {\n encoded = UNREADABLE;\n }\n\n setField(out, key, encoded);\n }\n\n // An array that gets truncated pushes a marker; an object has to carry one\n // as a key, and a silently short key list is the failure this whole encoder\n // is written against — it reads as \"the object had 256 keys\", which is a lie\n // the consumer has no way to detect.\n //\n // A real key named `_elided` loses to the marker. Preferred over a mangled\n // name: the collision is vanishingly rare, and a marker under a name nobody\n // reads is the same as no marker.\n if (allKeys.length > keys.length) {\n out[\"_elided\"] = {\n _: \"elided\",\n by: \"entries\",\n length: allKeys.length,\n } satisfies ShapeDescriptor;\n }\n\n const prototype = Object.getPrototypeOf(value) as unknown;\n\n // Class instances keep their type name alongside their fields: knowing a\n // value is a `HubServerResult` and not a bag of keys is most of what makes\n // a graph result readable.\n if (prototype !== null && prototype !== Object.prototype) {\n out[\"_type\"] = typeName(value);\n }\n\n return out;\n } finally {\n seen.delete(value);\n }\n}\n\n/**\n * Stands in for a step's `value`, or a half of a map's pair, whose read threw.\n * Private to this module, so no app value can be it.\n */\nconst UNREADABLE_STEP: unique symbol = Symbol(\"unreadable step\");\n\nconst NO_ARGUMENTS: ReadonlyArray<never> = [];\n\n/** What one walk of a collection's iterator read, and how it ended. */\ntype CollectionWalk = {\n /** Each step's `value`, read once, or {@link UNREADABLE_STEP}. */\n readonly values: Array<unknown>;\n /**\n * `\"done\"` when the iterator finished, `\"cut\"` when the entry bound stopped\n * the reads, and `\"broken\"` when a step could not be read: `next` threw, its\n * result was not an object, or its `done` threw. Without a readable `done`\n * there is no telling whether the walk is over, so it stops there.\n */\n readonly end: \"done\" | \"cut\" | \"broken\";\n};\n\n/**\n * Reads a collection's steps by the iterator protocol, as a spread does.\n *\n * The iterator comes from the iterable `entries()` or `values()` returned,\n * because an override may hand back any iterable, and a built-in iterator\n * returns itself. One that is not iterable is used as the iterator itself.\n * `next` is read once and `done` is taken by truthiness, both as the protocol\n * has it.\n *\n * Each step's `value` is read once, so a map's key and value come from the same\n * read. A step whose `value` read throws is still a step: the iterator said it\n * was not done, so the walk goes on past it.\n *\n * The bound stops the reads, not just the output: an iterator runs the app's\n * code and need never finish. One step past the bound says whether anything was\n * cut, so a collection exactly at it reads as whole.\n */\nfunction readSteps(source: object): CollectionWalk {\n const method = (source as { readonly [Symbol.iterator]?: unknown })[Symbol.iterator];\n const iterator: unknown =\n typeof method === \"function\" ? Reflect.apply(method, source, NO_ARGUMENTS) : source;\n const next = (iterator as { readonly next?: unknown }).next as (this: unknown) => unknown;\n const values: Array<unknown> = [];\n\n for (;;) {\n let step: unknown;\n let done: unknown;\n\n try {\n step = Reflect.apply(next, iterator, NO_ARGUMENTS);\n\n if (step === null || (typeof step !== \"object\" && typeof step !== \"function\")) {\n return { values, end: \"broken\" };\n }\n\n done = (step as { readonly done?: unknown }).done;\n } catch {\n return { values, end: \"broken\" };\n }\n\n if (done) {\n return { values, end: \"done\" };\n }\n\n if (values.length === FULL_MAX_ENTRIES) {\n return { values, end: \"cut\" };\n }\n\n let entry: unknown;\n\n try {\n entry = (step as { readonly value?: unknown }).value;\n } catch {\n entry = UNREADABLE_STEP;\n }\n\n values.push(entry);\n }\n}\n\n/** One half of a map step's pair, read on its own guard. */\nfunction halfOf(pair: unknown, index: 0 | 1): unknown {\n if (pair === UNREADABLE_STEP) {\n return UNREADABLE_STEP;\n }\n\n try {\n return (pair as { readonly [index: number]: unknown })[index];\n } catch {\n return UNREADABLE_STEP;\n }\n}\n\n/** A read from {@link readSteps} or {@link halfOf}, walked unless it threw. */\nfunction describeStepValue(\n read: unknown,\n depth: number,\n seen: Set<object>,\n budget: Budget\n): unknown {\n return read === UNREADABLE_STEP ? UNREADABLE : describeFull(read, depth + 1, seen, budget);\n}\n\n/** The largest array index. `2 ** 32 - 1` is an ordinary key on an array. */\nconst MAX_ARRAY_INDEX = 2 ** 32 - 2;\n\n/**\n * An array's length, read once.\n *\n * A proxy can make the read throw, and its entries may still be readable. Then\n * the length is one past the highest own index key, enumerable or not, so the\n * entries survive and a hole among them still reads as one. The keys are\n * listed by name alone, which asks the proxy for no descriptors. If they\n * cannot be listed either, nothing about the array is readable and the throw\n * reaches the caller's guard.\n */\nfunction arrayLength(value: ReadonlyArray<unknown>): unknown {\n try {\n return value.length;\n } catch {\n const keys = Object.getOwnPropertyNames(value);\n let length = 0;\n\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index] as string;\n const position = Number(key);\n\n // A canonical array index only: `\"01\"` and `\"1.5\"` are ordinary keys,\n // and so is anything past the largest index.\n if (\n position >= length &&\n position <= MAX_ARRAY_INDEX &&\n String(position) === key &&\n Number.isInteger(position)\n ) {\n length = position + 1;\n }\n }\n\n return length;\n }\n}\n\n/**\n * A function's name, or `\"anonymous\"` when it has none it will give up.\n *\n * Guarded and checked for the reason {@link typeName} is: the read can run a\n * getter, and a name that is not a string — a symbol, say — would throw when\n * written into the marker.\n */\nfunction functionName(value: unknown): string {\n try {\n const name = (value as { readonly name?: unknown }).name;\n\n return typeof name === \"string\" && name !== \"\" ? name : \"anonymous\";\n } catch {\n return \"anonymous\";\n }\n}\n\n/**\n * A collection's `size`, when reading it neither throws nor gives a number JSON\n * cannot carry. The caller falls back to the entries it counted.\n */\nfunction collectionSize(\n value: ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>\n): number | undefined {\n try {\n return finiteNumber(value.size);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The marker for a list the entry bound cut, with the full count when the value\n * gave one JSON can carry. Without it the marker still says entries were cut;\n * it just cannot say how many.\n */\nfunction entriesCut(length: number | undefined): ShapeDescriptor {\n return length === undefined\n ? { _: \"elided\", by: \"entries\" }\n : { _: \"elided\", by: \"entries\", length };\n}\n\n/**\n * A length or size as the value reports it, when that is a finite number.\n *\n * Both are read through the app's own getters: a `Map` or `Set` subclass can\n * override `size`, and a proxy over an array can answer anything for `length`.\n * A non-finite number there would fail the transport for the whole batch, so a\n * caller falls back to what it counted, or leaves the count out.\n */\nfunction finiteNumber(reported: unknown): number | undefined {\n return typeof reported === \"number\" && reported - reported === 0 ? reported : undefined;\n}\n",
|
|
9
|
+
"import { describeError } from \"./cause.ts\";\nimport {\n describeNonFiniteNumber,\n type ShapeDescriptor,\n typeName,\n UNREADABLE,\n} from \"./descriptors.ts\";\n\nconst MAX_STRING_LENGTH = 256;\nconst MAX_KEYS = 32;\nconst MAX_DEPTH = 3;\n\n/**\n * Reduces a value to something JSON-safe that cannot carry user data.\n *\n * Small primitives pass through, because in a runtime event they are ids, tags,\n * timestamps, and flags — the entire signal. Anything structured becomes a\n * descriptor: a node result or an action input is exactly the kind of value\n * that must not leave the process, and it is always an object or an array.\n *\n * ## The shape vocabulary\n *\n * One line per value, in a syntax that says what it is without a legend:\n *\n * ```text\n * {} a plain object, no own keys\n * {id,name,total} a plain object with those keys, in order\n * {id,name,…} …and more keys than {@link MAX_KEYS}\n * Wired{_tag,run} the same object, discriminated: its `_tag` is \"Wired\"\n * AccountModel{?} a class instance — the type, and no claim about fields\n * string[42] an array of 42, named by its first element\n * {id,name}[3] the same, where that element is an object\n * unknown[0] an empty array: nothing to name it by\n * unreadable[2] the first element could not be read\n * string[?] the length could not be read\n * Map(3) / Set(3) collections, by size\n * function / symbol / bigint values with no JSON form\n * {…} / […] the depth bound stopped the walk here\n * ```\n *\n * Strings rather than the `{_: \"object\", keys, truncated}` objects this used to\n * emit, and the reason is the reader rather than the wire: this feed is read by\n * an agent through MCP, where each descriptor arrived as several lines of\n * pretty-printed JSON to say one thing about one field. A node result rendered\n * as forty lines that contain no data is worse than one rendered as `{id,name}`.\n *\n * Lossless, which is the part that makes it safe: a shape descriptor is only\n * ever produced once the policy has decided the value itself is not crossing, so\n * there is nothing behind it that a richer encoding could have expanded to.\n *\n * The residual ambiguity is named rather than defended: a short app string that\n * happens to read `\"function\"` crosses verbatim at this policy and is\n * indistinguishable from the descriptor. Structured values are not ambiguous —\n * none of them cross — and paying an object per field to fix a collision with a\n * literal `\"function\"` is the wrong trade.\n */\nexport function describeShape(value: unknown, depth: number): unknown {\n if (value === null || value === undefined) {\n return value ?? null;\n }\n\n switch (typeof value) {\n case \"boolean\": {\n return value;\n }\n case \"number\": {\n // `value - value` is zero for every finite number and `NaN` for the rest:\n // one subtraction, so a finite number stays as cheap as a boolean.\n return value - value === 0 ? value : describeNonFiniteNumber(value);\n }\n case \"bigint\":\n case \"function\":\n case \"symbol\": {\n return typeof value;\n }\n case \"string\": {\n // An object at this policy, like a non-finite number's marker, because it\n // carries content: `head` is app data, and a reader has to be able to\n // tell it from a string that crossed whole.\n return value.length <= MAX_STRING_LENGTH\n ? value\n : ({\n _: \"string\",\n length: value.length,\n head: value.slice(0, MAX_STRING_LENGTH),\n } satisfies ShapeDescriptor);\n }\n default: {\n return describeStructure(value, depth);\n }\n }\n}\n\n/** See {@link UNREADABLE} for why this cannot be allowed to throw. */\nfunction describeStructure(value: object, depth: number): unknown {\n try {\n return describeStructureUnguarded(value, depth);\n } catch {\n return UNREADABLE;\n }\n}\n\nfunction describeStructureUnguarded(value: object, depth: number): unknown {\n // Before the depth check: a failure nested past the limit is still the reason\n // the event exists, and \"an object, elided\" is not worth the bytes it saves.\n if (value instanceof Error) {\n return describeError(value, \"shape\");\n }\n\n if (depth >= MAX_DEPTH) {\n return Array.isArray(value) ? \"[…]\" : \"{…}\";\n }\n\n if (Array.isArray(value)) {\n // Named by its first element rather than by every one of them: a\n // homogeneous array is the common case and the first entry settles it, and\n // a heterogeneous one is not summarizable at any length worth spending.\n return `${firstElementName(value, depth + 1)}[${lengthLabel(value)}]`;\n }\n\n if (value instanceof Map) {\n return `Map(${value.size})`;\n }\n\n if (value instanceof Set) {\n return `Set(${value.size})`;\n }\n\n const prototype = Object.getPrototypeOf(value) as unknown;\n\n // Class instances are app domain objects by construction; the type name is as\n // far as this encoder is willing to go, and `{?}` says the fields exist rather\n // than letting a bare type name read as \"it has none\".\n if (prototype !== null && prototype !== Object.prototype) {\n return `${typeName(value)}{?}`;\n }\n\n // A fresh array, so cut in place rather than copied.\n const keys = Object.keys(value);\n if (keys.length > MAX_KEYS) {\n keys.length = MAX_KEYS;\n keys.push(\"…\");\n }\n // `_tag` is the one nested field that survives verbatim. A discriminant is\n // structure, not data — and a failure feed that says \"an object with these\n // keys\" instead of \"GraphNodeAcquireFailed\" is not worth reading.\n //\n // Read on its own guard: a getter that throws here costs the tag, not the\n // key list already read.\n let tag: unknown;\n\n try {\n tag = (value as { readonly _tag?: unknown })._tag;\n } catch {\n tag = undefined;\n }\n\n return `${typeof tag === \"string\" ? tag : \"\"}{${keys.join(\",\")}}`;\n}\n\n/**\n * What an array's first element is, read on its own guard so a throw costs the\n * name and not the length beside it.\n */\nfunction firstElementName(value: ReadonlyArray<unknown>, depth: number): string {\n let first: unknown;\n\n try {\n first = value[0];\n } catch {\n return \"unreadable\";\n }\n\n return first === undefined ? \"unknown\" : shapeName(first, depth);\n}\n\n/**\n * An array's length as the label writes it, or `?` when it cannot be read or\n * written: a proxy can make the read throw, or answer with a symbol.\n */\nfunction lengthLabel(value: ReadonlyArray<unknown>): string {\n try {\n return `${value.length}`;\n } catch {\n return \"?\";\n }\n}\n\n/**\n * What an array is an array of.\n *\n * Distinct from {@link describeShape} because that answers with the value where\n * it can — a number stays a number — and a position naming a type needs the\n * type. `typeof` supplies every primitive name; structured entries recurse, so\n * an array of objects reads `{id,name}[3]` and inherits the depth bound with it.\n */\nfunction shapeName(value: unknown, depth: number): string {\n if (value === null) {\n return \"null\";\n }\n\n if (typeof value !== \"object\") {\n return typeof value;\n }\n\n const described = describeStructure(value, depth);\n\n // An `Error` element describes as a cause chain, which is an object. Its\n // descriptor names it `error`, so the array says the same. An element that\n // could not be read describes as the unreadable marker, also an object, and\n // is named for that instead: it is not a failure.\n if (typeof described === \"string\") {\n return described;\n }\n\n return described === UNREADABLE ? \"unreadable\" : \"error\";\n}\n",
|
|
10
|
+
"import type { Runtime } from \"@frondruntime/core\";\nimport { describeError } from \"./cause.ts\";\nimport { setField, UNREADABLE, WITHHELD } from \"./descriptors.ts\";\nimport { type Budget, describeFull, FULL_MAX_NODES } from \"./full.ts\";\nimport type { EncodePolicy } from \"./policy.ts\";\nimport type { EncodedEventRecord } from \"./protocol.ts\";\nimport { describeShape } from \"./shape.ts\";\n\n/**\n * Applies a policy to a value.\n *\n * The three encoders this composes are deliberately separate modules: the clamp\n * that decides disclosure (`policy.ts`), the walk that says as little as it can\n * (`shape.ts`), the walk that says as much as it can (`full.ts`), and the one\n * that describes failures the same way at every policy (`cause.ts`). What is\n * left here is the wiring — which walk a policy gets, and how one runtime event\n * is laid out on the wire.\n */\n\n/**\n * A policy, applied to one answer.\n *\n * One of these per snapshot, and one budget per record in `encodeRecord`,\n * because the budget is the thing worth bounding: what a single answer costs\n * the wire. A record with one enormous field should spend its own allowance\n * rather than be judged field by field, and two records should never be able\n * to spend each other's.\n */\nexport type ValueEncoder = {\n /** Ordinary app data, redacted according to the policy. */\n readonly value: (value: unknown) => unknown;\n /**\n * A failure, as a chain of causes.\n *\n * Separate from {@link value} because the runtime already knows which is\n * which, and sniffing would get it wrong: a failure that is not an `Error`\n * instance — an Effect `Cause`, a node status — reaches the value encoder as\n * an anonymous bag of keys.\n */\n readonly failure: (value: unknown) => unknown;\n};\n\nexport function createValueEncoder(policy: EncodePolicy): ValueEncoder {\n // Spelled out rather than folded into the `\"shape\"` branch. Falling through\n // was the bug: `\"none\"` reached the shape encoder and emitted key lists for\n // every node in a graph snapshot, which is a description of app data by an\n // app that had said it would send none.\n if (policy === \"none\") {\n return { value: withheldValue, failure: noneFailure };\n }\n\n if (policy === \"shape\") {\n return { value: shapeValue, failure: shapeFailure };\n }\n\n const budget: Budget = { remaining: FULL_MAX_NODES };\n\n return {\n value: (value) => fullValue(value, budget),\n failure: (value) => fullFailure(value, budget),\n };\n}\n\n// Module-level rather than closures made per encoder: `\"none\"` and `\"shape\"`\n// hold no state, and `encodeRecord` calls the `\"full\"` pair with its own budget.\nfunction withheldValue(): unknown {\n return WITHHELD;\n}\n\n// Still a chain, because \"there is an error here\" is not the value's data.\n// What crosses is what the failure names about itself — its tags, its node,\n// the innermost message — and never its payload or its stack, which\n// `describeError` withholds at anything below `\"full\"`.\nfunction noneFailure(value: unknown): unknown {\n return describeError(value, \"none\");\n}\n\nfunction shapeValue(value: unknown): unknown {\n return describeShape(value, 0);\n}\n\nfunction shapeFailure(value: unknown): unknown {\n return describeError(value, \"shape\");\n}\n\nfunction fullValue(value: unknown, budget: Budget): unknown {\n return describeFull(value, 0, new Set<object>(), budget);\n}\n\n// The `seen` set is per call and shared between the two halves of that call:\n// `describeError` marks each link of the chain as an ancestor, and the payload\n// walk it hands off to has to see those marks or it will descend back into an\n// error it is already standing on. That hand-off is a closure on purpose:\n// `cause.ts` reaches the full walk only through `FullContext`.\nfunction fullFailure(value: unknown, budget: Budget): unknown {\n const seen = new Set<object>();\n\n return describeError(value, \"full\", {\n seen,\n encodeValue: (own) => describeFull(own, 1, seen, budget),\n });\n}\n\nfunction encodeValueAt(policy: EncodePolicy, value: unknown, budget: Budget): unknown {\n switch (policy) {\n case \"none\": {\n return WITHHELD;\n }\n case \"shape\": {\n return describeShape(value, 0);\n }\n case \"full\": {\n return fullValue(value, budget);\n }\n }\n}\n\nfunction encodeFailureAt(policy: EncodePolicy, value: unknown, budget: Budget): unknown {\n switch (policy) {\n case \"none\":\n case \"shape\": {\n return describeError(value, policy);\n }\n case \"full\": {\n return fullFailure(value, budget);\n }\n }\n}\n\n/** The budget below `\"full\"`, where nothing reads it. Frozen, so a spend would throw. */\nconst UNSPENT: Budget = Object.freeze({ remaining: FULL_MAX_NODES });\n\n/** A record with its routing fields written, waiting for `fields` and `failures`. */\ntype RecordDraft = {\n -readonly [K in keyof Omit<EncodedEventRecord, \"fields\" | \"failures\">]: EncodedEventRecord[K];\n} & {\n fields?: EncodedEventRecord[\"fields\"];\n failures?: EncodedEventRecord[\"failures\"];\n};\n\n/**\n * Encodes one runtime event for the wire.\n *\n * Classification, work context, and node ids are metadata the runtime already\n * owns and are copied verbatim — they are ids and enum members, never user\n * data. A signal's channel and name join them, on the reasoning\n * `EncodedEventRecord` gives for the two fields. Only the event body goes\n * through the value encoder.\n *\n * Built field by field rather than through a {@link ValueEncoder}: this runs\n * once per runtime event, and on Hermes the encoder object, its closures, and\n * an identity object spread into the record are a cost per event. One budget\n * per record, as with an encoder.\n */\nexport function encodeRecord(\n record: Runtime.RuntimeEventRecord,\n policy: EncodePolicy\n): EncodedEventRecord {\n const budget = policy === \"full\" ? { remaining: FULL_MAX_NODES } : UNSPENT;\n const event = record.event;\n const encoded: RecordDraft = {\n sequence: record.sequence,\n recordedAt: record.recordedAt,\n tag: event._tag,\n category: record.classification.category,\n severity: record.classification.severity,\n timeline: record.classification.timeline,\n reportable: record.classification.reportable,\n workId: record.work.workId,\n parentWorkId: record.work.parentWorkId,\n source: record.work.source,\n reason: record.work.reason,\n priority: record.work.priority,\n nodeIds: record.nodeIds,\n };\n\n // Unclamped, like every routing field above it. A signal's channel and name\n // are how a reader addresses one — the filters `frond_read_events` exposes —\n // and they are authored as constants next to the code that publishes, the\n // same standing as `tag` and `nodeIds`. What the payload holds is the value,\n // and that is what `fields` withholds a line below.\n writeSignalIdentity(encoded, event);\n encoded.fields = policy === \"none\" ? {} : describeFields(event, policy, budget, record.failures);\n // Failures are causes, not results: their messages are what makes a\n // devtools feed worth reading, so they are described rather than dropped —\n // including under `\"none\"`, whose subject is values, not what broke.\n //\n // Encoded as failures rather than as values, because that is what the\n // runtime says they are — no sniffing required. Which matters for the ones\n // that are not `Error` instances: an Effect `Cause` reaching the value\n // encoder comes out as a bag of key names.\n //\n // With `Array.map`'s semantics, which the wire output was built on: the\n // length is read once, so a failure appended while encoding is not encoded,\n // and a hole stays a hole, which goes over JSON as `null`.\n const source = record.failures;\n const length = source.length;\n const failures: Array<unknown> = new Array(length);\n for (let index = 0; index < length; index++) {\n if (index in source) {\n failures[index] = encodeFailureAt(policy, source[index], budget);\n }\n }\n encoded.failures = failures;\n\n // Every field is written: the literal holds all but two, assigned above.\n return encoded as EncodedEventRecord;\n}\n\n/**\n * Names the signal an event is about, where it is about one.\n *\n * Two tags, written out, rather than a rule the field walk could apply to any\n * event: a general \"promote a field called `channel`\" would promote whatever an\n * app happened to name that way, which is app data crossing the policy that was\n * meant to clamp it. Only these two events have a channel the runtime itself put\n * there, and `RuntimeSignalSubscriberFailureObserved` is here for the same\n * reason as the publication — a subscriber failure that cannot say which signal\n * it was handling is a failure with no subject.\n *\n * Absent rather than empty on everything else. `channel: \"\"` is a record\n * claiming a channel it does not have, and a reader filtering on the field would\n * have to know to treat one string as meaning \"no\".\n *\n * Each read on its own guard, like the field walk's: these run outside it, so\n * its guards never see them, and a getter that throws here would otherwise take\n * the whole record with it. A read that throws, or a value that is not a string,\n * costs that field — the transport takes `channel` and `name` as strings or not\n * at all.\n */\nfunction writeSignalIdentity(encoded: RecordDraft, event: Runtime.RuntimeEvent): void {\n switch (event._tag) {\n case \"RuntimeSignalPublished\": {\n writeIdentityOf(encoded, readGuarded(readGuarded(event, \"record\"), \"signal\"));\n return;\n }\n case \"RuntimeSignalSubscriberFailureObserved\": {\n writeIdentityOf(encoded, readGuarded(readGuarded(event, \"signal\"), \"signal\"));\n return;\n }\n default: {\n return;\n }\n }\n}\n\nfunction writeIdentityOf(encoded: RecordDraft, signal: unknown): void {\n const channel = readGuarded(signal, \"channel\");\n const name = readGuarded(signal, \"name\");\n\n if (typeof channel === \"string\") {\n encoded.channel = channel;\n }\n\n if (typeof name === \"string\") {\n encoded.name = name;\n }\n}\n\n/** `target[key]`, or `undefined` when `target` is not an object or the read throws. */\nfunction readGuarded(target: unknown, key: string): unknown {\n if (typeof target !== \"object\" || target === null) {\n return undefined;\n }\n\n try {\n return (target as Record<string, unknown>)[key];\n } catch {\n return undefined;\n }\n}\n\n/**\n * The event body, each field through the value walk.\n *\n * The runtime pulls `failures` straight off the event's own fields, so the\n * same object arrives twice — once as `fields.error`, once as `failures[0]`.\n * Matched by identity so both come out as the same thing; a record that\n * described one failure two different ways would read as two.\n */\nfunction describeFields(\n event: Runtime.RuntimeEvent,\n policy: EncodePolicy,\n budget: Budget,\n failures: ReadonlyArray<unknown>\n): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n const keys = Object.keys(event);\n\n // Each read guarded on its own. The read runs before the value walk, so the\n // walk's guards never see a getter that throws here, and the throw would\n // otherwise take the whole record with it.\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index] as string;\n\n if (key === \"_tag\") {\n continue;\n }\n\n let value: unknown;\n\n try {\n value = (event as unknown as Record<string, unknown>)[key];\n } catch {\n setField(fields, key, UNREADABLE);\n continue;\n }\n\n setField(\n fields,\n key,\n typeof value === \"object\" && value !== null && failures.includes(value)\n ? encodeFailureAt(policy, value, budget)\n : encodeValueAt(policy, value, budget)\n );\n }\n\n return fields;\n}\n",
|
|
11
11
|
"import type { ValuePolicy } from \"./protocol.ts\";\n\n/**\n * What this encoder can produce. All three policies are implemented.\n *\n * `\"full\"` is a stub in the sense that it has no per-field allowlist and no\n * redaction — it sends what it finds. It is not a stub in its bounds: cycles,\n * depth, and breadth are enforced, because those three are not polish. A cyclic\n * or unboundedly deep graph result would hang the observed app inside its own\n * devtools, on its own event loop.\n *\n * What those bounds are not is a size budget. This socket is loopback and the\n * eventual reader is an agent's context window, so the scarce resource is the\n * reader's attention rather than the wire — which is why `\"shape\"` spends real\n * effort being terse and `\"full\"` spends none.\n */\nexport type EncodePolicy = ValuePolicy;\n\n/** Increasing disclosure. The only ordering the clamp below depends on. */\nconst POLICY_RANK: Record<ValuePolicy, number> = { none: 0, shape: 1, full: 2 };\n\n/**\n * Clamps what the hub asked for to what this app is willing to send.\n *\n * The whole negotiation lives here, in one expression, rather than as a policy\n * check threaded through the encoder: a sender may always answer with less than\n * it was asked for and may never answer with more, and that rule is only\n * trustworthy if there is exactly one place it can be got wrong.\n *\n * Its own module for the same reason. This is the one function in the package\n * whose failure mode is disclosure rather than a bad rendering, and it should be\n * readable — and testable — without the several hundred lines of walking that\n * depend on it.\n */\nexport function resolvePolicy(requested: ValuePolicy, ceiling: ValuePolicy): EncodePolicy {\n return POLICY_RANK[requested] <= POLICY_RANK[ceiling] ? requested : ceiling;\n}\n",
|
|
12
12
|
"import type { Graph, Runtime } from \"@frondruntime/core\";\nimport { createValueEncoder, type ValueEncoder } from \"./encode.ts\";\nimport type { EncodePolicy } from \"./policy.ts\";\nimport type { EncodedGraphEdge, EncodedNodeSnapshot, GraphSnapshot } from \"./protocol.ts\";\n\n/**\n * Derived from the snapshot rather than imported by name.\n *\n * `NodeOperationFailure` is exported from core and `NodeLiveFailure` is not,\n * even though both appear on the public `NodeSnapshot`. Reading them off the\n * field keeps this file working either way, and means neither can drift from\n * the shape actually being encoded.\n */\ntype OperationFailure = NonNullable<Graph.NodeSnapshot[\"operationFailure\"]>;\ntype LiveFailure = NonNullable<Graph.NodeSnapshot[\"liveFailure\"]>;\n\nexport type SnapshotRequest = {\n readonly policy: EncodePolicy;\n readonly capturedAt: number;\n /**\n * Narrow to one node and include its result.\n *\n * The whole difference between the two queries. A graph read answers a\n * topology question and a few hundred results would drown it; a node read is\n * someone asking what one value currently is, which is the only question a\n * result answers.\n */\n readonly nodeId?: string | undefined;\n};\n\n/**\n * The graph as the app sees it right now, reduced to something sendable.\n *\n * The counterpart to {@link encodeRecord}, and deliberately built from the same\n * {@link ValueEncoder}: a node that is failing in a snapshot and the event that\n * failed it should read identically, and the way to guarantee that is for one\n * piece of code to describe both.\n *\n * Two things in a `NodeSnapshot` cannot cross and are dropped rather than\n * approximated. `Pending.attempt` is a `Promise<NodeRead>` — nothing about it\n * survives serialization, and `state: \"Pending\"` already says the only thing it\n * would have told a reader. And `Ready.node` is the node facade object, which is\n * mostly methods; `result` is the value someone actually meant to ask about.\n *\n * Two more are dropped for costing a line each in every row of a graph read\n * while saying something the row already said: `label` is core's presentation\n * formatting of `tag`, and `key` is the second half of `nodeId`. `kind` stays —\n * `\"node\"` against `\"resource\"` is nowhere in the other fields, and it is what\n * tells a reader whether release semantics apply to this row.\n */\nexport function encodeGraphSnapshot(\n snapshot: Runtime.RuntimeSnapshot,\n request: SnapshotRequest\n): GraphSnapshot {\n const encoder = createValueEncoder(request.policy);\n\n const nodes =\n request.nodeId === undefined\n ? snapshot.graph.nodes\n : snapshot.graph.nodes.filter((node) => node.nodeId === request.nodeId);\n\n // Every edge touching the node, in either direction: \"what does this depend\n // on\" and \"what breaks if this does\" are the same question asked twice, and a\n // single-node read that answered only the first would be half a diagnosis.\n const edges =\n request.nodeId === undefined\n ? snapshot.graph.edges\n : snapshot.graph.edges.filter(\n (edge) => edge.from === request.nodeId || edge.to === request.nodeId\n );\n\n return {\n capturedAt: request.capturedAt,\n // Absent rather than zero on a runtime that has not emitted: zero is a real\n // position in a log, and claiming one this snapshot does not have would let\n // a reader line it up against events that had not happened yet. Through\n // `absent` for the same reason everything else optional here is — see below.\n ...absent(\"sequence\", snapshot.events.at(-1)?.sequence, identity),\n runtimeId: snapshot.runtimeId,\n runtimeStatus: snapshot.status,\n graphStatus: snapshot.graph.status,\n observedInputs: snapshot.graph.observedInputs,\n values: request.policy,\n nodes: nodes.map((node) => encodeNode(node, encoder, request.nodeId !== undefined)),\n edges: edges.map(encodeEdge),\n };\n}\n\nfunction encodeEdge(edge: Graph.EdgeSnapshot): EncodedGraphEdge {\n return { from: edge.from, to: edge.to, dependency: edge.dependency };\n}\n\n/**\n * One node's worth of failure stays one node's worth.\n *\n * The value encoder guards its own walks, so reaching here should take something\n * it does not model at all. But a graph read is the answer to \"what is the app\n * doing\", and answering it with a single `Failed` because one row of three\n * hundred could not be encoded trades a complete diagnosis for none. The\n * identity fields are the runtime's own struct rather than app data, so a row\n * that keeps them and drops everything else is still a row a reader can act on —\n * and `status` naming the hole is what stops it reading as a healthy node.\n */\nfunction encodeNode(\n node: Graph.NodeSnapshot,\n encoder: ValueEncoder,\n includeResult: boolean\n): EncodedNodeSnapshot {\n try {\n return encodeNodeUnguarded(node, encoder, includeResult);\n } catch {\n return {\n nodeId: node.nodeId,\n tag: node.tag,\n kind: node.kind,\n state: node._tag,\n revision: node.revision,\n status: { _: \"opaque\", type: \"unreadable\" },\n liveDemand: { _: \"opaque\", type: \"unreadable\" },\n operation: { _: \"opaque\", type: \"unreadable\" },\n };\n }\n}\n\nfunction encodeNodeUnguarded(\n node: Graph.NodeSnapshot,\n encoder: ValueEncoder,\n includeResult: boolean\n): EncodedNodeSnapshot {\n const failure = nodeFailure(node);\n\n return {\n nodeId: node.nodeId,\n tag: node.tag,\n kind: node.kind,\n state: node._tag,\n revision: node.revision,\n // `status` can carry an error of its own — `Invalid.error`, or a `Wired` run\n // state that is `Error`. Those reach the value encoder, which routes an\n // `Error` to the same cause-chain description at either policy, so they are\n // not lost the way a hand-rolled struct walk would lose them.\n status: encoder.value(node.status),\n liveDemand: encoder.value(node.liveDemand),\n operation: encoder.value(node.operation),\n ...absent(\"resultValidity\", node.resultValidity, encoder.value),\n ...absent(\"failure\", failure, encoder.failure),\n ...absent(\"operationFailure\", encodeOperationFailure(node.operationFailure, encoder), identity),\n ...absent(\"liveFailure\", encodeLiveFailure(node.liveFailure, encoder), identity),\n // Read off the `Ready` arm rather than from a general field walk, because\n // that is the only arm that has one — an unresolved node has no result, and\n // an absent field here means exactly that.\n ...absent(\n \"result\",\n includeResult && node._tag === \"Ready\" ? { value: node.result } : undefined,\n (held) => encoder.value(held.value)\n ),\n };\n}\n\nconst identity = <A>(value: A): A => value;\n\n/**\n * Omits the key rather than setting it to `undefined`.\n *\n * Load-bearing, not tidiness. These fields cross as `Schema.optional`, and an\n * explicit `undefined` in that position does not survive the trip — it arrives\n * as `null`, so a healthy node would report `failure: null` and a topology read\n * would report a `result` on every node it deliberately withheld one from. An\n * absent key is the only encoding that still reads as \"there is nothing here\".\n *\n * The `result` case goes through a wrapper because `undefined` is a legitimate\n * value for a `Ready` node to hold, and unwrapping it here would make \"the node\n * resolved to undefined\" indistinguishable from \"no result was asked for\".\n */\nfunction absent<K extends string, A, B>(\n key: K,\n value: A | undefined,\n encode: (value: A) => B\n): { [P in K]?: B } {\n return value === undefined ? {} : ({ [key]: encode(value) } as { [P in K]?: B });\n}\n\n/**\n * The failure that explains this node's state, if it has one.\n *\n * The arm-specific error wins over the general `failure` field: on a node that\n * is `ReadinessError` or `Invalid`, that error *is* why the node is in that arm,\n * whereas `failure` is whatever was last recorded and can be older.\n */\nfunction nodeFailure(node: Graph.NodeSnapshot): unknown {\n if (node._tag === \"ReadinessError\" || node._tag === \"Invalid\") {\n return node.error;\n }\n\n return node.failure;\n}\n\n/**\n * Unwrapped rather than handed to the value encoder whole.\n *\n * `NodeOperationFailure` is a struct with an error inside it, and passing the\n * struct as a value would reduce the whole thing to `{operationId,kind,at,error}`\n * at `\"shape\"` — a key list, with the error behind the last key never described\n * at all. That is the exact loss the failure path exists to prevent. Naming the\n * field explicitly is what keeps the chain crossing at every policy.\n */\nfunction encodeOperationFailure(\n failure: OperationFailure | undefined,\n encoder: ValueEncoder\n): unknown | undefined {\n return failure === undefined\n ? undefined\n : {\n operationId: failure.operationId,\n kind: failure.kind,\n at: failure.at,\n error: encoder.failure(failure.error),\n };\n}\n\n/** Same reasoning as {@link encodeOperationFailure}, over a list. */\nfunction encodeLiveFailure(\n failure: LiveFailure | undefined,\n encoder: ValueEncoder\n): unknown | undefined {\n return failure === undefined\n ? undefined\n : { at: failure.at, failures: failure.failures.map(encoder.failure) };\n}\n",
|
|
13
13
|
"import type { Runtime } from \"@frondruntime/core\";\nimport { Cause, Data, Effect, Fiber } from \"effect\";\nimport { attachLayer, attachRuntime, newInstanceId } from \"./attach.ts\";\nimport { HUB_DEFAULT_ATTACH_URL, HubRejection, type ValuePolicy } from \"./protocol.ts\";\n\n/**\n * How long to wait before dialing again.\n *\n * Fixed rather than backing off: the hub is a process on the same machine that\n * a developer starts and stops by hand, and an app that had backed off to\n * thirty seconds would spend most of a debugging session not yet reconnected.\n * Two seconds of an idle loopback socket costs nothing worth measuring.\n */\nconst RETRY_DELAY = \"2 seconds\";\n\n/**\n * Ends the retry loop.\n *\n * A second error rather than reusing `HubRejection`, because the two travel in\n * opposite directions through the same code: `HubRejection` arrives from the\n * hub into an attempt that swallows everything, and this one has to get back\n * *out* of that swallowing. Keeping them distinct is what lets the loop stop for\n * exactly one thing.\n */\nclass AttachRefused extends Data.TaggedError(\"AttachRefused\")<{\n readonly reason: string;\n}> {}\n\n/**\n * The hub's refusal, picked out of whatever else an attempt failed with.\n *\n * Matched on the error value's own identity, not on message text: a refusal is\n * the one outcome that stops the loop forever, and \"the message looked like a\n * rejection\" is not a property worth betting that on.\n *\n * The refusal is a typed failure here rather than a defect or a closed stream\n * because the RPC roles are inverted from who dials — the app is the *client*,\n * so the hub's `Attach` error channel is this side's error channel, and the\n * decoded `HubRejection` lands as an ordinary `Fail` on the cause.\n */\nfunction refusal(cause: Cause.Cause<unknown>): HubRejection | undefined {\n for (const reason of cause.reasons) {\n if (Cause.isFailReason(reason) && reason.error instanceof HubRejection) {\n return reason.error;\n }\n }\n\n return undefined;\n}\n\nexport type DevtoolsOptions = {\n readonly runtime: Runtime.Runtime;\n /** Human label for the hub's list, e.g. the host app's package name. */\n readonly name: string;\n /**\n * Where to dial. Defaults to the hub's own default port on loopback.\n *\n * Worth setting for a non-default port, and required for anything that is not\n * on the same host as the hub — a real iOS device or an Android emulator\n * cannot reach `127.0.0.1`, and needs the developer machine's LAN address.\n */\n readonly url?: string | undefined;\n /** Free-form origin hint. Guessed from the environment when omitted. */\n readonly platform?: string | undefined;\n /** See {@link import(\"./attach.ts\").AttachOptions.values}. Defaults to `\"shape\"`. */\n readonly values?: ValuePolicy | undefined;\n /**\n * Stable identity for this app across reconnects. Generated when omitted.\n *\n * Worth setting to something recognisable when several apps attach at once,\n * since this is what tells one from another after a hub restart. Any string\n * does, so long as it is stable for the life of the process and distinct per\n * running app.\n */\n readonly instanceId?: string | undefined;\n /** Return false to leave a record out of the stream entirely. */\n readonly include?: ((record: Runtime.RuntimeEventRecord) => boolean) | undefined;\n /**\n * Called instead of failing, on every attempt that ends badly.\n *\n * Silent by default, and that is the right default: not being able to reach\n * the hub is the *normal* state of an app whose developer has not started one\n * yet, and a devtools client that logged about it once every two seconds\n * would be a worse citizen of the console than one that says nothing.\n *\n * The one exception is a hub that *refuses* the attachment, which is terminal\n * rather than normal. Supplying this takes ownership of reporting it: the\n * console fallback below fires only when this is absent.\n */\n readonly onError?: ((cause: unknown) => void) | undefined;\n};\n\n/**\n * Streams a runtime's events to a local hub for as long as the app lives.\n *\n * The plain-function front door, as opposed to {@link attachRuntime}: a host\n * app's entry file is not an Effect program, and making one the price of\n * admission would put this behind a rewrite nobody is going to do.\n *\n * Three properties make it safe to leave in an entry file behind nothing but a\n * dev check. It never throws and never rejects, so a devtools client cannot\n * take down the app it is observing. It retries forever, so the hub can be\n * started, stopped and restarted underneath a running app. And it returns\n * before it connects, so it costs the startup path nothing.\n *\n * \"Forever\" has one deliberate exception. A hub that *refuses* the attachment —\n * today, only a protocol version mismatch — is answering a question about this\n * build, and every retry would ask it again and get the same answer. So a\n * refusal stops the loop and says so out loud, because the alternative is what\n * this used to do: reconnect every two seconds, silently, for the whole life of\n * a process that was never going to attach.\n *\n * @example\n * ```ts\n * if (import.meta.env.DEV) {\n * attachDevtools({ runtime, name: \"checkout-web\" });\n * }\n * ```\n *\n * @returns A function that detaches. Idempotent, and safe to ignore.\n */\nexport function attachDevtools(options: DevtoolsOptions): () => void {\n const url = options.url ?? HUB_DEFAULT_ATTACH_URL;\n\n // Minted here rather than per attempt, so a hub restart underneath a running\n // app brings back the same runtime instead of an apparent stranger. Paired\n // with `generation` below, which is what says how many times that happened.\n const instanceId = options.instanceId ?? newInstanceId();\n\n let generation = 0;\n\n // Deferred so each attempt reads the counter as it stands, and bumped only\n // when the hub accepted — a hub that is simply not running yet must not\n // inflate this every two seconds.\n const session = Effect.suspend(() =>\n attachRuntime({\n runtime: options.runtime,\n attachUrl: url,\n name: options.name,\n platform: options.platform ?? detectPlatform(),\n instanceId,\n generation,\n onAttached: () => {\n generation += 1;\n },\n ...(options.values === undefined ? {} : { values: options.values }),\n ...(options.include === undefined ? {} : { include: options.include }),\n })\n ).pipe(\n Effect.scoped,\n Effect.provide(attachLayer(url)),\n // `catchCause`, not `catch`: a defect in the transport is exactly as much\n // the host app's problem as a failure is, which is to say none.\n Effect.catchCause((cause) => {\n options.onError?.(cause);\n\n const refused = refusal(cause);\n\n // Every other ending is worth another attempt — a hub not started yet, a\n // socket dropped, a port moved — and retrying them is the behavior this\n // whole loop exists for. A refusal is not one of those: the next attempt\n // sends the same version and earns the same answer, so it leaves as a\n // failure, which is the one thing `forever` below does not swallow.\n return refused === undefined ? Effect.void : new AttachRefused({ reason: refused.reason });\n })\n );\n\n // `forever` over a *caught* attempt rather than `retry` over a failing one,\n // so the loop is reached by both outcomes. A hub that closes the stream\n // cleanly on shutdown is a success, and a success that stopped reconnecting\n // would leave the app permanently detached from the next hub.\n const fiber = Effect.runFork(\n Effect.forever(Effect.andThen(session, Effect.sleep(RETRY_DELAY))).pipe(\n Effect.catchTag(\"AttachRefused\", (refused) =>\n Effect.sync(() => {\n // Reached at most once per call, and that is structural rather than\n // guarded by a flag: getting here at all means the loop has stopped.\n //\n // Written to the console only when nobody asked for the causes. An\n // app that passed `onError` has already been told, in the handler it\n // supplied, and owns what it does with it; an app that did not would\n // otherwise be left with devtools that will never connect and nothing\n // anywhere saying so — which is the exact failure this whole change\n // is about, and a silent default would only move it one layer down.\n if (options.onError === undefined) {\n console.error(`[frond] devtools attach refused: ${refused.reason}`);\n }\n })\n )\n )\n );\n\n return () => {\n Effect.runFork(Fiber.interrupt(fiber));\n };\n}\n\n/** What `detectPlatform` reads. Everything on it is assumed absent. */\ntype PlatformGlobals = {\n readonly document?: unknown;\n readonly navigator?: { readonly product?: string };\n readonly process?: { readonly versions?: { readonly bun?: string } };\n};\n\n/**\n * A best-effort origin hint for the hub's list.\n *\n * Read off `globalThis` rather than referenced directly, for two reasons: a\n * bare `process` in a browser is a ReferenceError rather than `undefined`, and\n * naming it directly would drag `@types/node` into an entry point whose whole\n * claim is that it does not depend on Node.\n */\nfunction detectPlatform(): string {\n const globals = globalThis as PlatformGlobals;\n\n if (globals.document !== undefined) {\n return \"web\";\n }\n\n if (globals.navigator?.product === \"ReactNative\") {\n return \"react-native\";\n }\n\n if (globals.process !== undefined) {\n return globals.process.versions?.bun === undefined ? \"node\" : \"bun\";\n }\n\n return \"unknown\";\n}\n"
|
|
14
14
|
],
|
|
15
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AACA;AACA;;;ACHA;AAoBA,IAAM,kBAAkB;AACxB,IAAM,4BAA4B;AAClC,IAAM,2BAA2B;AAQjC,IAAM,4BAA4B;AAQlC,IAAM,oBA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AAAA,IAC3B,QAAQ,UAAU,KAAK;AAAA,IAEvB,MAAM,UAAU,QAAQ,KAAK;AAAA,IAO7B,OAAO,YAAY,YAAY,QAAO,OAAO,IAAI,cAAc,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAAA,GAC1F,CACH;AAAA,EAMA,MAAM,QAAQ,QAAO,QACnB,QAAO,QAAQ,QAAO,QAAQ,SAAS,QAAO,MAAM,WAAW,CAAC,CAAC,EAAE,KACjE,QAAO,SAAS,iBAAiB,CAAC,YAChC,QAAO,KAAK,MAAM;AAAA,IAUhB,IAAI,QAAQ,YAAY,WAAW;AAAA,MACjC,QAAQ,MAAM,oCAAoC,QAAQ,QAAQ;AAAA,IACpE;AAAA,GACD,CACH,CACF,CACF;AAAA,EAEA,OAAO,MAAM;AAAA,IACX,QAAO,QAAQ,MAAM,UAAU,KAAK,CAAC;AAAA;AAAA;AAmBzC,SAAS,cAAc,GAAW;AAAA,EAChC,MAAM,UAAU;AAAA,EAEhB,IAAI,QAAQ,aAAa,WAAW;AAAA,IAClC,OAAO;AAAA,EACT;AAAA,EAEA,IAAI,QAAQ,WAAW,YAAY,eAAe;AAAA,IAChD,OAAO;AAAA,EACT;AAAA,EAEA,IAAI,QAAQ,YAAY,WAAW;AAAA,IACjC,OAAO,QAAQ,QAAQ,UAAU,QAAQ,YAAY,SAAS;AAAA,EAChE;AAAA,EAEA,OAAO;AAAA;",
|
|
16
|
+
"debugId": "A1F31E6F36A07D0A64756E2164756E21",
|
|
17
17
|
"names": []
|
|
18
18
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frondruntime/devtools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0-rc.0",
|
|
4
4
|
"description": "Attach a Frond runtime to the local devtools hub.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"private": false,
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"test": "bun --conditions=source test"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
|
-
"@frondruntime/core": "0.
|
|
60
|
+
"@frondruntime/core": "0.6.0-rc.0",
|
|
61
61
|
"effect": "^4.0.0"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
package/src/attach.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { Runtime } from "@frondruntime/core";
|
|
2
|
-
import { Clock, Effect, Layer, Stream } from "effect";
|
|
2
|
+
import { Clock, Effect, Layer, Option, Schema, Stream } from "effect";
|
|
3
3
|
import { RpcClient, RpcSerialization } from "effect/rpc";
|
|
4
4
|
import { Socket } from "effect/socket";
|
|
5
5
|
import { encodeRecord } from "./encode.ts";
|
|
6
6
|
import { type EncodePolicy, resolvePolicy } from "./policy.ts";
|
|
7
7
|
import {
|
|
8
8
|
type AttachmentInfo,
|
|
9
|
-
|
|
9
|
+
EncodedEventRecord,
|
|
10
10
|
FrondHubRpcs,
|
|
11
11
|
HUB_PROTOCOL_VERSION,
|
|
12
12
|
type HubCommand,
|
|
@@ -129,6 +129,12 @@ export function attachLayer(attachUrl: string): Layer.Layer<RpcClient.Protocol>
|
|
|
129
129
|
*/
|
|
130
130
|
export const attachRuntime = Effect.fnUntraced(function* (options: AttachOptions) {
|
|
131
131
|
const client = yield* RpcClient.make(FrondHubRpcs);
|
|
132
|
+
// The transport's own codec, so the check below rejects exactly what a send
|
|
133
|
+
// would. Built once; it runs only after a batch has already failed.
|
|
134
|
+
const { codecFor } = yield* RpcClient.Protocol;
|
|
135
|
+
const encodeForWire = Schema.encodeUnknownOption(codecFor(EncodedEventRecord));
|
|
136
|
+
const crossesTheWire = (record: EncodedEventRecord): boolean =>
|
|
137
|
+
Option.isSome(encodeForWire(record));
|
|
132
138
|
|
|
133
139
|
const ceiling: ValuePolicy = options.values ?? "shape";
|
|
134
140
|
|
|
@@ -192,10 +198,29 @@ export const attachRuntime = Effect.fnUntraced(function* (options: AttachOptions
|
|
|
192
198
|
buffer = [];
|
|
193
199
|
dropped = 0;
|
|
194
200
|
|
|
195
|
-
|
|
196
|
-
|
|
201
|
+
// One record the codec rejects fails the send of the whole batch, and a
|
|
202
|
+
// failure here ends the attachment (see below), which would make every
|
|
203
|
+
// such record cost a reconnect and the batch around it. So a failed batch
|
|
204
|
+
// is checked record by record, against the transport's own codec, and sent
|
|
205
|
+
// again without the records that cannot cross; those are counted as
|
|
206
|
+
// dropped, because to the hub they are the same gap. A batch in which every
|
|
207
|
+
// record crosses failed for some other reason, and that failure goes on to
|
|
208
|
+
// end the attachment.
|
|
209
|
+
yield* Effect.catchCause(
|
|
210
|
+
client["Frond.Ingest"]({ attachmentId: id, records, droppedSince }),
|
|
211
|
+
(cause) => {
|
|
212
|
+
const sendable = records.filter(crossesTheWire);
|
|
197
213
|
|
|
198
|
-
|
|
214
|
+
return sendable.length === records.length
|
|
215
|
+
? Effect.failCause(cause)
|
|
216
|
+
: client["Frond.Ingest"]({
|
|
217
|
+
attachmentId: id,
|
|
218
|
+
records: sendable,
|
|
219
|
+
droppedSince: droppedSince + records.length - sendable.length,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
);
|
|
223
|
+
});
|
|
199
224
|
|
|
200
225
|
/**
|
|
201
226
|
* Answers one query, on its own fiber.
|
|
@@ -246,7 +271,7 @@ export const attachRuntime = Effect.fnUntraced(function* (options: AttachOptions
|
|
|
246
271
|
);
|
|
247
272
|
});
|
|
248
273
|
|
|
249
|
-
|
|
274
|
+
const commands = Stream.runForEach(client["Frond.Attach"]({ info }), (command) => {
|
|
250
275
|
if (command._tag === "Attached") {
|
|
251
276
|
return Effect.sync(() => {
|
|
252
277
|
attachmentId = command.attachmentId;
|
|
@@ -261,6 +286,15 @@ export const attachRuntime = Effect.fnUntraced(function* (options: AttachOptions
|
|
|
261
286
|
|
|
262
287
|
return Effect.void;
|
|
263
288
|
});
|
|
289
|
+
|
|
290
|
+
// The flusher and the command stream are one attachment, and whichever ends
|
|
291
|
+
// first ends it. A send that fails, on a socket whose write side broke while
|
|
292
|
+
// its read side still answers, ends neither the stream nor its heartbeat,
|
|
293
|
+
// and a flusher left to die on its own would leave the app attached and
|
|
294
|
+
// sending nothing for good. Ending the attachment hands the failure to
|
|
295
|
+
// whoever runs it, which for `attachDevtools` is a reconnect. The flusher
|
|
296
|
+
// never succeeds, so a stream the hub closes still ends it the way it did.
|
|
297
|
+
yield* Effect.raceFirst(commands, Effect.forever(flushOnce));
|
|
264
298
|
});
|
|
265
299
|
|
|
266
300
|
/**
|