statewire 0.24.0 → 0.24.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/connection.d.ts +4 -0
- package/dist/client/connection.d.ts.map +1 -1
- package/dist/client/connection.js +9 -2
- package/dist/client/connection.js.map +1 -1
- package/dist/client/session.d.ts +9 -0
- package/dist/client/session.d.ts.map +1 -1
- package/dist/client/session.js +100 -17
- package/dist/client/session.js.map +1 -1
- package/dist/host/host.d.ts +1 -0
- package/dist/host/host.d.ts.map +1 -1
- package/dist/host/host.js +8 -0
- package/dist/host/host.js.map +1 -1
- package/dist/host/socket.d.ts.map +1 -1
- package/dist/host/socket.js +3 -2
- package/dist/host/socket.js.map +1 -1
- package/dist/host.d.ts +13 -7
- package/dist/host.d.ts.map +1 -1
- package/dist/storage.js +1 -1
- package/dist/transports/sse.d.ts.map +1 -1
- package/dist/transports/sse.js +2 -1
- package/dist/transports/sse.js.map +1 -1
- package/dist/wire/protocol.d.ts +6 -1
- package/dist/wire/protocol.d.ts.map +1 -1
- package/dist/wire/protocol.js +12 -4
- package/dist/wire/protocol.js.map +1 -1
- package/package.json +1 -1
- package/src/client/connection.ts +11 -0
- package/src/client/session.ts +166 -18
- package/src/host/host.ts +13 -0
- package/src/host/socket.ts +5 -2
- package/src/host.ts +14 -6
- package/src/transports/sse.ts +2 -0
- package/src/wire/protocol.ts +11 -3
|
@@ -50,6 +50,8 @@ export type Conn = {
|
|
|
50
50
|
connection: StatewireClient.Connection;
|
|
51
51
|
parked: boolean;
|
|
52
52
|
lease: string | null;
|
|
53
|
+
/** Names every attach of this connection, so a host retires the earlier ones (2026-11-02). */
|
|
54
|
+
attacher: string;
|
|
53
55
|
attempt: number;
|
|
54
56
|
authDenials: number;
|
|
55
57
|
authStale: boolean;
|
|
@@ -74,6 +76,8 @@ export declare const settleFin: (c: Conn, fin: StatewireHost.Fin) => AttemptOutc
|
|
|
74
76
|
export declare const handleEnvelope: (c: Conn, value: unknown) => AttemptOutcome | null;
|
|
75
77
|
export declare const unsupportedVersion: (c: Conn, version: string) => AttemptOutcome;
|
|
76
78
|
export declare const resolveHeaders: (headers: StatewireClient.HeadersOption | undefined, staleAuth: boolean) => Promise<Headers>;
|
|
79
|
+
/** Names this connection, so a host retires its earlier attaches before the hello. */
|
|
80
|
+
export declare const replacing: (c: Conn, headers: Headers) => void;
|
|
77
81
|
export declare const attachFrame: (c: Conn, headers: StatewireClient.HeadersOption | undefined) => Promise<{
|
|
78
82
|
headers: Headers;
|
|
79
83
|
body: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/client/connection.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/client/connection.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,iBAAiB,EAAE,4BAAyB;AAO1D,OAAO,KAAK,EAEV,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,qBAAqB,EACtB,6BAA0B;AAC3B,OAAO,KAAK,EAAE,eAAe,EAAE,wBAAqB;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,mBAAgB;AAE7C,MAAM,MAAM,OAAO,GAAG;IACpB,KAAK,EAAE,SAAS,GAAG,WAAW,GAAG,OAAO,GAAG,cAAc,CAAC;IAC1D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,+EAA+E;AAC/E,eAAO,MAAM,QAAQ,iEAMX,CAAC;AAEX,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,SAAS,GAAG,CAAC,OAAO,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC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AW,OAAO,KACjB,OAAO,CAAC,OAAO,CAGf,CAAC;AAGJ,sFAAsF;AACtF,eAAO,MAAM,SAAS,GAAI,GAAG,IAAI,EAAE,SAAS,OAAO,SAElD,CAAC;AAEF,eAAO,MAAM,WAAW,GACtB,GAAG,IAAI,EACP,SAAS,eAAe,CAAC,aAAa,GAAG,SAAS;;;EAuBnD,CAAC;AAEF,eAAO,MAAM,OAAO,GAClB,OAAO,iBAAiB,CAAC,OAAO,GAAG;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC5B,QAAQ,CAAC,EAAE,CAAC,CAAC,UAAU,EAAE,eAAe,CAAC,UAAU,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAC1E,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,eAAe,CAAC,eAAe,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACzE,GAAG,EAAE,oBAAoB,CAAC;IAC1B,WAAW,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,eAAe,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAC1E,IAAI,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,cAAc,KAAK,OAAO,CAAC,qBAAqB,CAAC,CAAC;CAC1E,KACA,UAuFF,CAAC;AAEF,eAAO,MAAM,QAAQ,GAAI,SAAS,WAAW,UACO,CAAC"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { negotiationHeaders, parseNegotiation, validateSelection } from "../wire/protocol.js";
|
|
1
|
+
import { ATTACHER_HEADER, negotiationHeaders, parseNegotiation, validateSelection } from "../wire/protocol.js";
|
|
2
2
|
import { reviveDocumentValue } from "../document.js";
|
|
3
3
|
import { reviveOps } from "../wire/meta.js";
|
|
4
4
|
import { backoff, retryHint, timing } from "./timing.js";
|
|
5
5
|
import { isStorageError } from "./storageError.js";
|
|
6
|
+
import { randomId } from "../util/randomId.js";
|
|
6
7
|
import { useEffect, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
7
8
|
import { flushTapSync } from "@assistant-ui/tap";
|
|
8
9
|
// src/client/connection.ts
|
|
@@ -385,11 +386,16 @@ const unsupportedVersion = (c, version) => flushTapSync(() => handleEnvelope(c,
|
|
|
385
386
|
message: `unsupported protocol version: ${version || "\"\""}`
|
|
386
387
|
} })) ?? "stop";
|
|
387
388
|
const resolveHeaders = async (headers, staleAuth) => new Headers(typeof headers === "function" ? await headers({ staleAuth }) : headers);
|
|
389
|
+
/** Names this connection, so a host retires its earlier attaches before the hello. */
|
|
390
|
+
const replacing = (c, headers) => {
|
|
391
|
+
headers.set(ATTACHER_HEADER, c.attacher);
|
|
392
|
+
};
|
|
388
393
|
const attachFrame = async (c, headers) => {
|
|
389
394
|
const pending = c.ctx.beforeAttach?.();
|
|
390
395
|
if (pending) await pending;
|
|
391
396
|
const resolved = await resolveHeaders(headers, c.authStale);
|
|
392
397
|
for (const [name, value] of Object.entries(negotiationHeaders(c.negotiation ?? {}))) if (!resolved.has(name)) resolved.set(name, value);
|
|
398
|
+
replacing(c, resolved);
|
|
393
399
|
c.negotiation = parseNegotiation(resolved);
|
|
394
400
|
c.authStale = false;
|
|
395
401
|
const persistence = c.ctx.beforeAttach?.();
|
|
@@ -411,6 +417,7 @@ const useLink = (props) => {
|
|
|
411
417
|
const conn = {
|
|
412
418
|
parked: props.isNew ?? false,
|
|
413
419
|
lease: null,
|
|
420
|
+
attacher: randomId(),
|
|
414
421
|
attempt: 0,
|
|
415
422
|
authDenials: 0,
|
|
416
423
|
authStale: false,
|
|
@@ -506,6 +513,6 @@ const useLink = (props) => {
|
|
|
506
513
|
return link;
|
|
507
514
|
};
|
|
508
515
|
const classify = (timeout) => /* @__PURE__ */ new Error(timeout.aborted ? "timeout" : "network");
|
|
509
|
-
export { TERMINAL, attachFrame, classify, handleEnvelope, resolveHeaders, settleFin, unsupportedVersion, useLink, validateRefusalSyn };
|
|
516
|
+
export { TERMINAL, attachFrame, classify, handleEnvelope, replacing, resolveHeaders, settleFin, unsupportedVersion, useLink, validateRefusalSyn };
|
|
510
517
|
|
|
511
518
|
//# sourceMappingURL=connection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connection.js","names":["negotiationHeaders","validateSelection","parseNegotiation","StatewireProtocol","useEffect","useRef","useState","flushTapSync","reviveOps","reviveValue","backoff","retryHint","timing","isStorageError","ConnectionState","RemoteLink","StatewireFrame","StatewireRemoteProps","StatewireSubmitResult","StatewireClient","StatewireHost","Episode","cause","message","code","TERMINAL","const","StatewireCmd","protocol","seq","type","payload","meta","dur","StatewireSyn","version","protocols","name","record","id","idle","retry","StatewireEnvelope","ops","cmd","next","syn","fin","Fin","Gate","latched","wake","newGate","undefined","takeGate","g","was","waitGate","timeoutMs","Promise","resolve","timer","setTimeout","clearTimeout","openGate","AttemptOutcome","Conn","negotiation","Options","connection","Connection","parked","lease","attempt","authDenials","authStale","liveAt","retryAt","error","ConnectionError","episode","awaitingHello","held","gate","abort","AbortController","lifetime","ctx","onError","onChange","attemptOnce","notify","reconnect","sameState","a","b","status","nextRetryAt","lastError","reason","setStatus","c","stopForError","Error","degraded","protocolError","isObject","value","Record","Array","isArray","isNonnegativeSafeInteger","Number","isSafeInteger","isPositiveSafeInteger","validateOptionalString","field","validateSynProtocols","hello","entry","validateSynScalars","validateRefusalSyn","validateCmd","validateFin","validateEnvelope","releaseHeld","length","onCmds","cmdsOf","env","snapshotOf","helloSynOf","isWakeHello","handleHello","onHello","onIdle","Date","now","warnedUnknownSynFact","warnUnknownSynFact","console","warn","deliverSyn","onRefusal","Object","keys","deliverEnvelope","onOps","cmds","push","settleFin","finish","denial","terminal","report","assign","onFinish","handleEnvelope","dialing","scheduleRetry","failure","immediate","backoffResetMs","delay","Math","max","reconnectConn","run","alive","outcome","pending","beforeAttach","signal","aborted","SyntaxError","test","onDetach","unsupportedVersion","resolveHeaders","headers","HeadersOption","staleAuth","Headers","attachFrame","resolved","entries","has","set","persistence","lanes","takeAttachLanes","body","JSON","stringify","fromEntries","useLink","props","url","isNew","send","frame","latest","current","setConnection","conn","link","storageFailed","protocolFailed","wireVersion","applicationProtocols","classify","timeout","AbortSignal","reviveValue"],"sources":["../../src/client/connection.ts"],"sourcesContent":["import {\n negotiationHeaders,\n validateSelection,\n parseNegotiation,\n} from \"../wire/protocol\";\nimport type { StatewireProtocol } from \"../wire/protocol\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { flushTapSync } from \"@assistant-ui/tap\";\nimport { reviveOps, reviveValue } from \"../wire/meta\";\nimport { backoff, retryHint, timing } from \"./timing\";\nimport { isStorageError } from \"./storageError\";\nimport type {\n ConnectionState,\n RemoteLink,\n StatewireFrame,\n StatewireRemoteProps,\n StatewireSubmitResult,\n} from \"../transports/sse\";\nimport type { StatewireClient } from \"../statewire\";\nimport type { StatewireHost } from \"../host\";\n\nexport type Episode = {\n cause: \"dropped\" | \"reconnect\" | \"error\" | \"unauthorized\";\n message?: string;\n code?: string;\n};\n\n/** The terminal cmd verdict types; \"applied\" is the sole non-terminal type. */\nexport const TERMINAL = [\n \"result\",\n \"rejected\",\n \"failed\",\n \"crashed\",\n \"expired\",\n] as const;\n\nexport type StatewireCmd = {\n protocol: string;\n seq: number;\n type?: \"applied\" | (typeof TERMINAL)[number];\n code?: string;\n message?: string;\n payload?: unknown;\n meta?: unknown;\n /** Cumulative: resending through this seq will never be needed. */\n dur?: boolean;\n};\n\nexport type StatewireSyn = {\n version?: string;\n protocols?: {\n name: string;\n version?: string;\n record?: \"ephemeral\";\n seq?: number;\n }[];\n id?: string;\n idle?: boolean;\n retry?: number;\n};\n\nexport type StatewireEnvelope = {\n ops?: unknown[];\n cmd?: StatewireCmd[];\n next?: true;\n idle?: boolean;\n syn?: StatewireSyn;\n fin?: StatewireHost.Fin;\n};\n\nexport type Gate = { latched: boolean; wake: (() => void) | undefined };\n\nconst newGate = (): Gate => ({ latched: false, wake: undefined });\n\nconst takeGate = (g: Gate) => {\n const was = g.latched;\n g.latched = false;\n return was;\n};\n\nconst waitGate = (g: Gate, timeoutMs?: number) => {\n if (g.latched) {\n g.latched = false;\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n g.wake = undefined;\n resolve();\n }, timeoutMs);\n g.wake = () => {\n clearTimeout(timer);\n g.wake = undefined;\n resolve();\n };\n });\n};\n\nconst openGate = (g: Gate) => {\n if (g.wake) g.wake();\n else g.latched = true;\n};\n\nexport type AttemptOutcome = \"stop\" | \"reattach\" | \"ended\" | \"idle\";\n\nexport type Conn = {\n negotiation?: StatewireProtocol.Options;\n connection: StatewireClient.Connection;\n parked: boolean;\n lease: string | null;\n attempt: number;\n authDenials: number;\n authStale: boolean;\n liveAt: number | null;\n retryAt: number;\n error: StatewireClient.ConnectionError | undefined;\n episode: Episode | null;\n awaitingHello: boolean;\n held: StatewireCmd[];\n gate: Gate;\n abort: AbortController | null;\n lifetime: AbortController | null;\n ctx: StatewireRemoteProps;\n onError: (error: StatewireClient.ConnectionError) => void;\n onChange: (connection: StatewireClient.Connection) => void;\n attemptOnce: (abort: AbortController) => Promise<AttemptOutcome>;\n notify: (connection: StatewireClient.Connection) => void;\n reconnect: () => void;\n};\n\nconst sameState = (a: ConnectionState, b: ConnectionState): boolean => {\n if (a.status !== b.status) return false;\n if (a.status === \"retrying\" && b.status === \"retrying\") {\n return (\n a.attempt === b.attempt &&\n a.cause === b.cause &&\n a.code === b.code &&\n a.nextRetryAt === b.nextRetryAt &&\n a.lastError === b.lastError &&\n a.message === b.message\n );\n }\n if (a.status === \"standby\" && b.status === \"standby\") {\n return a.reason === b.reason;\n }\n if (a.status === \"stopped\" && b.status === \"stopped\") {\n return (\n a.reason === b.reason &&\n a.message === b.message &&\n a.payload === b.payload\n );\n }\n return true;\n};\n\nconst setStatus = (c: Conn, next: ConnectionState) => {\n if (sameState(next, c.connection) && c.connection.error === c.error) return;\n c.connection = {\n ...next,\n ...(c.error === undefined ? {} : { error: c.error }),\n reconnect: c.reconnect,\n };\n c.notify(c.connection);\n c.onChange(c.connection);\n};\n\nconst stopForError = ({\n connection: c,\n error,\n reason,\n}: {\n connection: Conn;\n error: Error;\n reason: \"storage-error\" | \"protocol-error\";\n}) => {\n c.error = error;\n c.onError(error);\n flushTapSync(() =>\n setStatus(c, {\n status: \"stopped\",\n reason,\n degraded: true,\n message: error.message,\n }),\n );\n c.abort?.abort();\n};\n\nconst protocolError = (message: string): never => {\n throw new Error(`statewire: protocol error: ${message}`);\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isNonnegativeSafeInteger = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) >= 0;\n\nconst isPositiveSafeInteger = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) > 0;\n\nconst validateOptionalString = (value: unknown, field: string): void => {\n if (value !== undefined && typeof value !== \"string\") {\n protocolError(`${field} must be a string`);\n }\n};\n\nconst validateSynProtocols = (value: unknown, hello: boolean): void => {\n if (value === undefined) return;\n if (!Array.isArray(value))\n return protocolError(\"syn.protocols must be an array\");\n for (const entry of value) {\n if (!isObject(entry))\n return protocolError(\"syn.protocols entry must be an object\");\n if (typeof entry[\"name\"] !== \"string\")\n protocolError(\"syn.protocols[].name must be a string\");\n if (\n !hello &&\n (entry[\"version\"] !== undefined || entry[\"record\"] !== undefined)\n )\n protocolError(\"invalid mid-stream syn\");\n if (\n hello\n ? !isNonnegativeSafeInteger(entry[\"seq\"])\n : entry[\"seq\"] !== undefined && !isNonnegativeSafeInteger(entry[\"seq\"])\n )\n protocolError(\"syn.protocols[].seq must be a nonnegative safe integer\");\n if (hello && entry[\"record\"] === \"ephemeral\" && entry[\"seq\"] !== 0)\n protocolError(\"ephemeral lane hello seq must be 0\");\n }\n};\n\nconst validateSynScalars = (syn: Record<string, unknown>, hello: boolean) => {\n validateSynProtocols(syn[\"protocols\"], hello);\n if (syn[\"retry\"] !== undefined && !isNonnegativeSafeInteger(syn[\"retry\"])) {\n protocolError(\"syn.retry must be a nonnegative safe integer\");\n }\n validateOptionalString(syn[\"id\"], \"syn.id\");\n if (syn[\"idle\"] !== undefined && typeof syn[\"idle\"] !== \"boolean\") {\n protocolError(\"syn.idle must be a boolean\");\n }\n};\n\nexport const validateRefusalSyn = (value: unknown): StatewireSyn => {\n if (!isObject(value)) return protocolError(\"syn must be an object\");\n validateSynScalars(value, false);\n if (\n value[\"id\"] !== undefined ||\n value[\"idle\"] !== undefined ||\n value[\"version\"] !== undefined\n ) {\n protocolError(\"invalid refusal syn\");\n }\n if (value[\"protocols\"] === undefined && value[\"retry\"] === undefined) {\n protocolError(\"refusal syn has no watermarks or retry\");\n }\n return value as StatewireSyn;\n};\n\nconst validateCmd = (value: unknown): value is StatewireCmd => {\n if (!isObject(value)) return protocolError(\"cmd entry must be an object\");\n if (typeof value[\"protocol\"] !== \"string\") {\n protocolError(\"cmd.protocol must be a string\");\n }\n if (!isPositiveSafeInteger(value[\"seq\"])) {\n protocolError(\"cmd.seq must be a positive safe integer\");\n }\n validateOptionalString(value[\"type\"], \"cmd.type\");\n validateOptionalString(value[\"code\"], \"cmd.code\");\n validateOptionalString(value[\"message\"], \"cmd.message\");\n if (value[\"dur\"] !== undefined && value[\"dur\"] !== true) {\n protocolError(\"cmd.dur must be true\");\n }\n return true;\n};\n\nconst validateFin = (value: unknown): value is StatewireHost.Fin => {\n if (!isObject(value)) return protocolError(\"fin must be an object\");\n if (typeof value[\"reason\"] !== \"string\") {\n protocolError(\"fin.reason must be a string\");\n }\n validateOptionalString(value[\"message\"], \"fin.message\");\n validateOptionalString(value[\"code\"], \"fin.code\");\n if (\n value[\"status\"] !== undefined &&\n !isNonnegativeSafeInteger(value[\"status\"])\n )\n protocolError(\"fin.status must be a nonnegative safe integer\");\n if (value[\"retry\"] !== undefined && !isNonnegativeSafeInteger(value[\"retry\"]))\n protocolError(\"fin.retry must be a nonnegative safe integer\");\n return true;\n};\n\nconst validateEnvelope = (value: unknown): StatewireEnvelope => {\n if (!isObject(value)) return protocolError(\"packet must be an object\");\n if (value[\"ops\"] !== undefined && !Array.isArray(value[\"ops\"])) {\n protocolError(\"ops must be an array\");\n }\n if (value[\"cmd\"] !== undefined) {\n const cmd = value[\"cmd\"];\n if (!Array.isArray(cmd)) return protocolError(\"cmd must be an array\");\n for (const entry of cmd) validateCmd(entry);\n }\n if (value[\"idle\"] !== undefined && typeof value[\"idle\"] !== \"boolean\") {\n protocolError(\"idle must be a boolean\");\n }\n if (value[\"next\"] !== undefined) {\n if (value[\"next\"] !== true) protocolError(\"next must be true\");\n if (\n value[\"cmd\"] === undefined ||\n value[\"ops\"] !== undefined ||\n value[\"fin\"] !== undefined\n ) {\n protocolError(\"next must ride a cmd-only packet\");\n }\n }\n if (value[\"fin\"] !== undefined) validateFin(value[\"fin\"]);\n return value as StatewireEnvelope;\n};\n\n// A hold's release delivers, never settles: fin and bare close both drain it.\nconst releaseHeld = (c: Conn) => {\n if (c.held.length === 0) return;\n const held = c.held;\n c.held = [];\n c.ctx.onCmds(held);\n};\n\nconst cmdsOf = (env: StatewireEnvelope): StatewireCmd[] => {\n if (env.cmd === undefined) return [];\n return env.cmd;\n};\n\nconst snapshotOf = (env: StatewireEnvelope): unknown[] => {\n const ops = env.ops;\n if (ops === undefined) return protocolError(\"hello missing snapshot\");\n return reviveOps(ops);\n};\n\nconst helloSynOf = (env: StatewireEnvelope): StatewireSyn => {\n if (!isObject(env.syn)) return protocolError(\"expected hello\");\n validateSynScalars(env.syn, true);\n if (env.syn[\"retry\"] !== undefined) {\n protocolError(\"hello syn cannot carry retry\");\n }\n return env.syn as StatewireSyn;\n};\n\n// A host that woke on a retained socket re-sends its hello; the snapshot\n// replaces the session the way a fresh attach would.\nconst isWakeHello = (env: StatewireEnvelope) =>\n isObject(env.syn) && env.syn[\"version\"] !== undefined;\n\nconst handleHello = (c: Conn, env: StatewireEnvelope) => {\n const syn = helloSynOf(env);\n if (c.negotiation !== undefined) validateSelection(syn, c.negotiation);\n const ops = snapshotOf(env);\n c.ctx.onHello({\n ops,\n syn,\n });\n if (env.cmd !== undefined) c.ctx.onCmds(env.cmd);\n c.ctx.onIdle(syn.idle ?? false);\n c.awaitingHello = false;\n c.error = undefined;\n c.liveAt = Date.now();\n c.authDenials = 0;\n c.episode = null;\n setStatus(c, { status: \"connected\", degraded: false });\n};\n\nlet warnedUnknownSynFact = false;\n\nconst warnUnknownSynFact = () => {\n if (warnedUnknownSynFact) return;\n warnedUnknownSynFact = true;\n console.warn(\"statewire: ignoring unknown syn fact\");\n};\n\nconst deliverSyn = (c: Conn, value: unknown) => {\n if (!isObject(value)) return protocolError(\"syn must be an object\");\n validateSynScalars(value, false);\n if (value[\"version\"] !== undefined || value[\"idle\"] !== undefined) {\n protocolError(\"invalid mid-stream syn\");\n }\n if (value[\"protocols\"] !== undefined || value[\"retry\"] !== undefined) {\n c.ctx.onRefusal(validateRefusalSyn(value));\n return;\n }\n if (value[\"id\"] !== undefined) return;\n if (Object.keys(value).length === 0) {\n protocolError(\"invalid mid-stream syn\");\n }\n warnUnknownSynFact();\n};\n\nconst deliverEnvelope = (c: Conn, env: StatewireEnvelope) => {\n if (env.syn !== undefined) deliverSyn(c, env.syn);\n if (env.ops !== undefined) {\n const held = c.held;\n c.held = [];\n c.ctx.onOps({\n ops: reviveOps(env.ops),\n cmds: [...held, ...cmdsOf(env)],\n });\n } else if (env.cmd !== undefined) {\n const cmds = cmdsOf(env);\n if (env.next === true) c.held.push(...cmds);\n else c.ctx.onCmds(cmds);\n }\n if (typeof env.idle === \"boolean\") c.ctx.onIdle(env.idle);\n};\n\nexport const settleFin = (c: Conn, fin: StatewireHost.Fin): AttemptOutcome => {\n const finish =\n fin.meta === undefined\n ? fin\n : { ...fin, payload: reviveValue(fin.payload, fin.meta) };\n releaseHeld(c);\n c.retryAt = Date.now() + retryHint(finish.retry ?? 0);\n if (finish.reason === \"idle\") {\n c.ctx.onIdle(true);\n c.attempt = 0;\n c.episode = null;\n c.error = undefined;\n setStatus(c, { status: \"standby\", reason: \"idle\", degraded: false });\n return \"idle\";\n }\n const denial = finish.reason === \"unauthorized\";\n const terminal =\n finish.reason === \"gone\" ||\n finish.reason === \"forbidden\" ||\n finish.reason === \"protocol-error\" ||\n (denial && c.authDenials > 0);\n if (denial) {\n c.authDenials += 1;\n c.authStale = true;\n }\n const report =\n finish.reason !== \"reconnect\" &&\n finish.reason !== \"gone\" &&\n (!denial || terminal);\n c.error = report\n ? Object.assign(new Error(finish.message ?? finish.reason), { fin: finish })\n : undefined;\n if (c.error) c.onError(c.error);\n if (!terminal) {\n c.episode = {\n cause:\n finish.reason === \"reconnect\"\n ? \"reconnect\"\n : denial\n ? \"unauthorized\"\n : \"error\",\n ...(finish.message !== undefined && { message: finish.message }),\n ...(finish.code !== undefined && { code: finish.code }),\n };\n if (denial) openGate(c.gate);\n return \"reattach\";\n }\n c.ctx.onFinish(finish);\n setStatus(c, {\n status: \"stopped\",\n degraded: true,\n reason: denial\n ? \"unauthorized\"\n : finish.reason === \"forbidden\"\n ? \"forbidden\"\n : finish.reason === \"protocol-error\"\n ? \"protocol-error\"\n : \"gone\",\n ...(finish.message !== undefined && { message: finish.message }),\n ...(finish.payload !== undefined && { payload: finish.payload }),\n });\n return \"stop\";\n};\n\nexport const handleEnvelope = (\n c: Conn,\n value: unknown,\n): AttemptOutcome | null => {\n const env = validateEnvelope(value);\n if (c.awaitingHello || isWakeHello(env)) {\n if (env.fin !== undefined) return settleFin(c, env.fin);\n handleHello(c, env);\n return null;\n }\n deliverEnvelope(c, env);\n if (c.connection.status === \"stopped\") return \"stop\";\n if (env.fin !== undefined) return settleFin(c, env.fin);\n if (c.connection.status !== \"connected\") {\n c.attempt = 0;\n c.episode = null;\n setStatus(c, { status: \"connected\", degraded: false });\n }\n return null;\n};\n\n// A dial that no wait preceded is part of the current connect: only a\n// scheduled delay surfaces `retrying`, and the dial after it keeps that status.\nconst dialing = (c: Conn) =>\n setStatus(\n c,\n c.connection.status === \"retrying\"\n ? { status: \"retrying\", attempt: c.attempt, degraded: true }\n : { status: \"connecting\", degraded: false },\n );\n\nconst scheduleRetry = (\n c: Conn,\n failure: string | undefined,\n immediate: boolean,\n) => {\n if (c.liveAt !== null && Date.now() - c.liveAt >= timing.backoffResetMs) {\n c.attempt = 0;\n }\n c.liveAt = null;\n c.attempt += 1;\n c.episode ??= { cause: \"dropped\" };\n const delay = Math.max(\n immediate ? 0 : backoff(c.attempt),\n c.retryAt - Date.now(),\n );\n if (delay === 0) return delay;\n setStatus(c, {\n status: \"retrying\",\n degraded: true,\n attempt: c.attempt,\n ...c.episode,\n nextRetryAt: Date.now() + delay,\n ...(failure !== undefined && { lastError: failure }),\n });\n return delay;\n};\n\nconst reconnectConn = (c: Conn) => {\n if (!c.lifetime) return;\n if (c.connection.status === \"standby\" || c.connection.status === \"stopped\") {\n // A reconnect out of a park starts a fresh episode: first dial, attempt 0.\n c.attempt = 0;\n c.authDenials = 0;\n c.episode = null;\n flushTapSync(() => dialing(c));\n }\n openGate(c.gate);\n c.abort?.abort();\n};\n\nconst run = async (c: Conn, lifetime: AbortController, gate: Gate) => {\n const alive = () => c.lifetime === lifetime;\n if (c.parked) {\n await waitGate(gate);\n if (!alive()) return;\n c.parked = false;\n }\n while (alive()) {\n if (c.retryAt > Date.now()) {\n await waitGate(gate, c.retryAt - Date.now());\n continue;\n }\n // The dial is in flight: attempt alone, no backoff fields.\n flushTapSync(() => dialing(c));\n const abort = new AbortController();\n c.abort = abort;\n c.awaitingHello = true;\n c.held = [];\n let outcome: AttemptOutcome | undefined;\n let failure: string | undefined;\n try {\n const pending = c.ctx.beforeAttach?.();\n if (pending) await pending;\n if (!alive()) return;\n outcome = await c.attemptOnce(abort);\n } catch (error) {\n if (!abort.signal.aborted) {\n if (isStorageError(error)) {\n stopForError({ connection: c, error, reason: \"storage-error\" });\n outcome = \"stop\";\n } else if (\n error instanceof SyntaxError ||\n (error instanceof Error &&\n /^(statewire: protocol error:|Statewire cannot apply)/.test(\n error.message,\n ))\n ) {\n outcome = flushTapSync(() =>\n settleFin(c, { reason: \"protocol-error\", message: error.message }),\n );\n } else if (c.authStale) {\n outcome = flushTapSync(() =>\n settleFin(c, {\n reason: \"unauthorized\",\n message:\n error instanceof Error\n ? error.message\n : \"credential refresh failed\",\n }),\n );\n }\n failure =\n error instanceof Error && error.message ? error.message : \"network\";\n }\n }\n abort.abort();\n if (!alive()) return;\n flushTapSync(() => {\n releaseHeld(c);\n c.ctx.onDetach();\n });\n if (!alive()) return;\n if (c.connection.status === \"stopped\") outcome = \"stop\";\n if (outcome === \"stop\" || outcome === \"idle\") {\n await waitGate(gate);\n continue;\n }\n const immediate = takeGate(gate);\n const delay = flushTapSync(() => scheduleRetry(c, failure, immediate));\n if (delay === 0) continue;\n await waitGate(gate, delay);\n }\n};\n\nexport const unsupportedVersion = (c: Conn, version: string): AttemptOutcome =>\n flushTapSync(() =>\n handleEnvelope(c, {\n fin: {\n reason: \"protocol-error\",\n message: `unsupported protocol version: ${version || '\"\"'}`,\n },\n }),\n ) ?? \"stop\";\n\nexport const resolveHeaders = async (\n headers: StatewireClient.HeadersOption | undefined,\n staleAuth: boolean,\n): Promise<Headers> =>\n new Headers(\n typeof headers === \"function\" ? await headers({ staleAuth }) : headers,\n );\n\n// The stale flag clears only once the resolver returns: a throwing refresh keeps it for the next attempt.\nexport const attachFrame = async (\n c: Conn,\n headers: StatewireClient.HeadersOption | undefined,\n) => {\n const pending = c.ctx.beforeAttach?.();\n if (pending) await pending;\n const resolved = await resolveHeaders(headers, c.authStale);\n for (const [name, value] of Object.entries(\n negotiationHeaders(c.negotiation ?? {}),\n )) {\n if (!resolved.has(name)) resolved.set(name, value);\n }\n c.negotiation = parseNegotiation(resolved);\n c.authStale = false;\n const persistence = c.ctx.beforeAttach?.();\n if (persistence) await persistence;\n const lanes = flushTapSync(() => c.ctx.takeAttachLanes());\n return {\n headers: resolved,\n body: JSON.stringify({\n headers: Object.fromEntries(resolved),\n ...(lanes ?? {}),\n }),\n };\n};\n\nexport const useLink = (\n props: StatewireProtocol.Options & {\n url: string;\n isNew?: boolean | undefined;\n onChange?: ((connection: StatewireClient.Connection) => void) | undefined;\n onError?: ((error: StatewireClient.ConnectionError) => void) | undefined;\n ctx: StatewireRemoteProps;\n attemptOnce: (c: Conn, abort: AbortController) => Promise<AttemptOutcome>;\n send: (c: Conn, frame: StatewireFrame) => Promise<StatewireSubmitResult>;\n },\n): RemoteLink => {\n const latest = useRef(props);\n latest.current = props;\n const [, setConnection] = useState<StatewireClient.Connection | null>(null);\n const [c] = useState((): Conn => {\n const conn: Conn = {\n parked: props.isNew ?? false,\n lease: null,\n attempt: 0,\n authDenials: 0,\n authStale: false,\n liveAt: null,\n retryAt: 0,\n error: undefined,\n episode: null,\n awaitingHello: true,\n held: [],\n abort: null,\n gate: newGate(),\n lifetime: null,\n get ctx() {\n return latest.current.ctx;\n },\n onError: (error) => latest.current.onError?.(error),\n onChange: (connection) => latest.current.onChange?.(connection),\n attemptOnce: (abort) => {\n conn.negotiation = latest.current;\n return latest.current.attemptOnce(conn, abort);\n },\n notify: setConnection,\n reconnect: () => reconnectConn(conn),\n connection: {\n ...((props.isNew ?? false)\n ? { status: \"standby\", reason: \"deferred\", degraded: false }\n : { status: \"connecting\", degraded: false }),\n reconnect: () => conn.reconnect(),\n },\n };\n return conn;\n });\n const [link] = useState((): RemoteLink => ({\n get connection() {\n return c.connection;\n },\n get parked() {\n return c.parked;\n },\n send: (frame) => latest.current.send(c, frame),\n storageFailed: (error) =>\n stopForError({ connection: c, error, reason: \"storage-error\" }),\n protocolFailed: (error) =>\n stopForError({ connection: c, error, reason: \"protocol-error\" }),\n }));\n\n const negotiation = JSON.stringify([\n props.protocol,\n props.wireVersion,\n props.applicationProtocols,\n ]);\n useEffect(() => {\n c.lease = null;\n c.attempt = 0;\n c.authDenials = 0;\n c.authStale = false;\n c.liveAt = null;\n c.retryAt = 0;\n c.episode = null;\n setStatus(\n c,\n c.parked\n ? { status: \"standby\", reason: \"deferred\", degraded: false }\n : { status: \"connecting\", degraded: false },\n );\n const lifetime = new AbortController();\n c.lifetime = lifetime;\n c.gate = newGate();\n void run(c, lifetime, c.gate);\n return () => {\n c.abort?.abort();\n lifetime.abort();\n if (c.lifetime === lifetime) c.lifetime = null;\n openGate(c.gate);\n };\n }, [c, props.url, negotiation]);\n\n return link;\n};\n\nexport const classify = (timeout: AbortSignal) =>\n new Error(timeout.aborted ? \"timeout\" : \"network\");\n"],"mappings":";;;;;;;;;AA4BA,MAAayB,WAAW;CACtB;CACA;CACA;CACA;CACA;AAAS;AAuCX,MAAM2B,iBAAuB;CAAEF,SAAS;CAAOC,MAAME,KAAAA;AAAU;AAE/D,MAAMC,YAAYC,MAAY;CAC5B,MAAMC,MAAMD,EAAEL;CACdK,EAAEL,UAAU;CACZ,OAAOM;AACT;AAEA,MAAMC,YAAYF,GAASG,cAAuB;CAChD,IAAIH,EAAEL,SAAS;EACbK,EAAEL,UAAU;EACZ,OAAOS,QAAQC,QAAQ;CACzB;CACA,OAAO,IAAID,SAAeC,YAAY;EACpC,MAAMC,QACJH,cAAcL,KAAAA,IACVA,KAAAA,IACAS,iBAAiB;GACfP,EAAEJ,OAAOE,KAAAA;GACTO,QAAQ;EACV,GAAGF,SAAS;EAClBH,EAAEJ,aAAa;GACbY,aAAaF,KAAK;GAClBN,EAAEJ,OAAOE,KAAAA;GACTO,QAAQ;EACV;CACF,CAAC;AACH;AAEA,MAAMI,YAAYT,MAAY;CAC5B,IAAIA,EAAEJ,MAAMI,EAAEJ,KAAK;MACdI,EAAEL,UAAU;AACnB;AA6BA,MAAM2C,aAAaC,GAAoBC,MAAgC;CACrE,IAAID,EAAEE,WAAWD,EAAEC,QAAQ,OAAO;CAClC,IAAIF,EAAEE,WAAW,cAAcD,EAAEC,WAAW,YAC1C,OACEF,EAAErB,YAAYsB,EAAEtB,WAChBqB,EAAExE,UAAU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CtB,SAASqC,EAAElB,IAAI;EACjB;CACF,GAAG;EAACkB;EAAG+F,MAAMC;EAAKlI;CAAW,CAAC;CAE9B,OAAO0I;AACT;AAEA,MAAaK,YAAYC,4BACvB,IAAI5G,MAAM4G,QAAQtC,UAAU,YAAY,SAAS"}
|
|
1
|
+
{"version":3,"file":"connection.js","names":["ATTACHER_HEADER","negotiationHeaders","validateSelection","parseNegotiation","StatewireProtocol","useEffect","useRef","useState","flushTapSync","reviveOps","reviveValue","backoff","retryHint","timing","isStorageError","randomId","ConnectionState","RemoteLink","StatewireFrame","StatewireRemoteProps","StatewireSubmitResult","StatewireClient","StatewireHost","Episode","cause","message","code","TERMINAL","const","StatewireCmd","protocol","seq","type","payload","meta","dur","StatewireSyn","version","protocols","name","record","id","idle","retry","StatewireEnvelope","ops","cmd","next","syn","fin","Fin","Gate","latched","wake","newGate","undefined","takeGate","g","was","waitGate","timeoutMs","Promise","resolve","timer","setTimeout","clearTimeout","openGate","AttemptOutcome","Conn","negotiation","Options","connection","Connection","parked","lease","attacher","attempt","authDenials","authStale","liveAt","retryAt","error","ConnectionError","episode","awaitingHello","held","gate","abort","AbortController","lifetime","ctx","onError","onChange","attemptOnce","notify","reconnect","sameState","a","b","status","nextRetryAt","lastError","reason","setStatus","c","stopForError","Error","degraded","protocolError","isObject","value","Record","Array","isArray","isNonnegativeSafeInteger","Number","isSafeInteger","isPositiveSafeInteger","validateOptionalString","field","validateSynProtocols","hello","entry","validateSynScalars","validateRefusalSyn","validateCmd","validateFin","validateEnvelope","releaseHeld","length","onCmds","cmdsOf","env","snapshotOf","helloSynOf","isWakeHello","handleHello","onHello","onIdle","Date","now","warnedUnknownSynFact","warnUnknownSynFact","console","warn","deliverSyn","onRefusal","Object","keys","deliverEnvelope","onOps","cmds","push","settleFin","finish","denial","terminal","report","assign","onFinish","handleEnvelope","dialing","scheduleRetry","failure","immediate","backoffResetMs","delay","Math","max","reconnectConn","run","alive","outcome","pending","beforeAttach","signal","aborted","SyntaxError","test","onDetach","unsupportedVersion","resolveHeaders","headers","HeadersOption","staleAuth","Headers","replacing","set","attachFrame","resolved","entries","has","persistence","lanes","takeAttachLanes","body","JSON","stringify","fromEntries","useLink","props","url","isNew","send","frame","latest","current","setConnection","conn","link","storageFailed","protocolFailed","wireVersion","applicationProtocols","classify","timeout","AbortSignal","reviveValue"],"sources":["../../src/client/connection.ts"],"sourcesContent":["import {\n ATTACHER_HEADER,\n negotiationHeaders,\n validateSelection,\n parseNegotiation,\n} from \"../wire/protocol\";\nimport type { StatewireProtocol } from \"../wire/protocol\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { flushTapSync } from \"@assistant-ui/tap\";\nimport { reviveOps, reviveValue } from \"../wire/meta\";\nimport { backoff, retryHint, timing } from \"./timing\";\nimport { isStorageError } from \"./storageError\";\nimport { randomId } from \"../util/randomId\";\nimport type {\n ConnectionState,\n RemoteLink,\n StatewireFrame,\n StatewireRemoteProps,\n StatewireSubmitResult,\n} from \"../transports/sse\";\nimport type { StatewireClient } from \"../statewire\";\nimport type { StatewireHost } from \"../host\";\n\nexport type Episode = {\n cause: \"dropped\" | \"reconnect\" | \"error\" | \"unauthorized\";\n message?: string;\n code?: string;\n};\n\n/** The terminal cmd verdict types; \"applied\" is the sole non-terminal type. */\nexport const TERMINAL = [\n \"result\",\n \"rejected\",\n \"failed\",\n \"crashed\",\n \"expired\",\n] as const;\n\nexport type StatewireCmd = {\n protocol: string;\n seq: number;\n type?: \"applied\" | (typeof TERMINAL)[number];\n code?: string;\n message?: string;\n payload?: unknown;\n meta?: unknown;\n /** Cumulative: resending through this seq will never be needed. */\n dur?: boolean;\n};\n\nexport type StatewireSyn = {\n version?: string;\n protocols?: {\n name: string;\n version?: string;\n record?: \"ephemeral\";\n seq?: number;\n }[];\n id?: string;\n idle?: boolean;\n retry?: number;\n};\n\nexport type StatewireEnvelope = {\n ops?: unknown[];\n cmd?: StatewireCmd[];\n next?: true;\n idle?: boolean;\n syn?: StatewireSyn;\n fin?: StatewireHost.Fin;\n};\n\nexport type Gate = { latched: boolean; wake: (() => void) | undefined };\n\nconst newGate = (): Gate => ({ latched: false, wake: undefined });\n\nconst takeGate = (g: Gate) => {\n const was = g.latched;\n g.latched = false;\n return was;\n};\n\nconst waitGate = (g: Gate, timeoutMs?: number) => {\n if (g.latched) {\n g.latched = false;\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n g.wake = undefined;\n resolve();\n }, timeoutMs);\n g.wake = () => {\n clearTimeout(timer);\n g.wake = undefined;\n resolve();\n };\n });\n};\n\nconst openGate = (g: Gate) => {\n if (g.wake) g.wake();\n else g.latched = true;\n};\n\nexport type AttemptOutcome = \"stop\" | \"reattach\" | \"ended\" | \"idle\";\n\nexport type Conn = {\n negotiation?: StatewireProtocol.Options;\n connection: StatewireClient.Connection;\n parked: boolean;\n lease: string | null;\n /** Names every attach of this connection, so a host retires the earlier ones (2026-11-02). */\n attacher: string;\n attempt: number;\n authDenials: number;\n authStale: boolean;\n liveAt: number | null;\n retryAt: number;\n error: StatewireClient.ConnectionError | undefined;\n episode: Episode | null;\n awaitingHello: boolean;\n held: StatewireCmd[];\n gate: Gate;\n abort: AbortController | null;\n lifetime: AbortController | null;\n ctx: StatewireRemoteProps;\n onError: (error: StatewireClient.ConnectionError) => void;\n onChange: (connection: StatewireClient.Connection) => void;\n attemptOnce: (abort: AbortController) => Promise<AttemptOutcome>;\n notify: (connection: StatewireClient.Connection) => void;\n reconnect: () => void;\n};\n\nconst sameState = (a: ConnectionState, b: ConnectionState): boolean => {\n if (a.status !== b.status) return false;\n if (a.status === \"retrying\" && b.status === \"retrying\") {\n return (\n a.attempt === b.attempt &&\n a.cause === b.cause &&\n a.code === b.code &&\n a.nextRetryAt === b.nextRetryAt &&\n a.lastError === b.lastError &&\n a.message === b.message\n );\n }\n if (a.status === \"standby\" && b.status === \"standby\") {\n return a.reason === b.reason;\n }\n if (a.status === \"stopped\" && b.status === \"stopped\") {\n return (\n a.reason === b.reason &&\n a.message === b.message &&\n a.payload === b.payload\n );\n }\n return true;\n};\n\nconst setStatus = (c: Conn, next: ConnectionState) => {\n if (sameState(next, c.connection) && c.connection.error === c.error) return;\n c.connection = {\n ...next,\n ...(c.error === undefined ? {} : { error: c.error }),\n reconnect: c.reconnect,\n };\n c.notify(c.connection);\n c.onChange(c.connection);\n};\n\nconst stopForError = ({\n connection: c,\n error,\n reason,\n}: {\n connection: Conn;\n error: Error;\n reason: \"storage-error\" | \"protocol-error\";\n}) => {\n c.error = error;\n c.onError(error);\n flushTapSync(() =>\n setStatus(c, {\n status: \"stopped\",\n reason,\n degraded: true,\n message: error.message,\n }),\n );\n c.abort?.abort();\n};\n\nconst protocolError = (message: string): never => {\n throw new Error(`statewire: protocol error: ${message}`);\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isNonnegativeSafeInteger = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) >= 0;\n\nconst isPositiveSafeInteger = (value: unknown): value is number =>\n Number.isSafeInteger(value) && (value as number) > 0;\n\nconst validateOptionalString = (value: unknown, field: string): void => {\n if (value !== undefined && typeof value !== \"string\") {\n protocolError(`${field} must be a string`);\n }\n};\n\nconst validateSynProtocols = (value: unknown, hello: boolean): void => {\n if (value === undefined) return;\n if (!Array.isArray(value))\n return protocolError(\"syn.protocols must be an array\");\n for (const entry of value) {\n if (!isObject(entry))\n return protocolError(\"syn.protocols entry must be an object\");\n if (typeof entry[\"name\"] !== \"string\")\n protocolError(\"syn.protocols[].name must be a string\");\n if (\n !hello &&\n (entry[\"version\"] !== undefined || entry[\"record\"] !== undefined)\n )\n protocolError(\"invalid mid-stream syn\");\n if (\n hello\n ? !isNonnegativeSafeInteger(entry[\"seq\"])\n : entry[\"seq\"] !== undefined && !isNonnegativeSafeInteger(entry[\"seq\"])\n )\n protocolError(\"syn.protocols[].seq must be a nonnegative safe integer\");\n if (hello && entry[\"record\"] === \"ephemeral\" && entry[\"seq\"] !== 0)\n protocolError(\"ephemeral lane hello seq must be 0\");\n }\n};\n\nconst validateSynScalars = (syn: Record<string, unknown>, hello: boolean) => {\n validateSynProtocols(syn[\"protocols\"], hello);\n if (syn[\"retry\"] !== undefined && !isNonnegativeSafeInteger(syn[\"retry\"])) {\n protocolError(\"syn.retry must be a nonnegative safe integer\");\n }\n validateOptionalString(syn[\"id\"], \"syn.id\");\n if (syn[\"idle\"] !== undefined && typeof syn[\"idle\"] !== \"boolean\") {\n protocolError(\"syn.idle must be a boolean\");\n }\n};\n\nexport const validateRefusalSyn = (value: unknown): StatewireSyn => {\n if (!isObject(value)) return protocolError(\"syn must be an object\");\n validateSynScalars(value, false);\n if (\n value[\"id\"] !== undefined ||\n value[\"idle\"] !== undefined ||\n value[\"version\"] !== undefined\n ) {\n protocolError(\"invalid refusal syn\");\n }\n if (value[\"protocols\"] === undefined && value[\"retry\"] === undefined) {\n protocolError(\"refusal syn has no watermarks or retry\");\n }\n return value as StatewireSyn;\n};\n\nconst validateCmd = (value: unknown): value is StatewireCmd => {\n if (!isObject(value)) return protocolError(\"cmd entry must be an object\");\n if (typeof value[\"protocol\"] !== \"string\") {\n protocolError(\"cmd.protocol must be a string\");\n }\n if (!isPositiveSafeInteger(value[\"seq\"])) {\n protocolError(\"cmd.seq must be a positive safe integer\");\n }\n validateOptionalString(value[\"type\"], \"cmd.type\");\n validateOptionalString(value[\"code\"], \"cmd.code\");\n validateOptionalString(value[\"message\"], \"cmd.message\");\n if (value[\"dur\"] !== undefined && value[\"dur\"] !== true) {\n protocolError(\"cmd.dur must be true\");\n }\n return true;\n};\n\nconst validateFin = (value: unknown): value is StatewireHost.Fin => {\n if (!isObject(value)) return protocolError(\"fin must be an object\");\n if (typeof value[\"reason\"] !== \"string\") {\n protocolError(\"fin.reason must be a string\");\n }\n validateOptionalString(value[\"message\"], \"fin.message\");\n validateOptionalString(value[\"code\"], \"fin.code\");\n if (\n value[\"status\"] !== undefined &&\n !isNonnegativeSafeInteger(value[\"status\"])\n )\n protocolError(\"fin.status must be a nonnegative safe integer\");\n if (value[\"retry\"] !== undefined && !isNonnegativeSafeInteger(value[\"retry\"]))\n protocolError(\"fin.retry must be a nonnegative safe integer\");\n return true;\n};\n\nconst validateEnvelope = (value: unknown): StatewireEnvelope => {\n if (!isObject(value)) return protocolError(\"packet must be an object\");\n if (value[\"ops\"] !== undefined && !Array.isArray(value[\"ops\"])) {\n protocolError(\"ops must be an array\");\n }\n if (value[\"cmd\"] !== undefined) {\n const cmd = value[\"cmd\"];\n if (!Array.isArray(cmd)) return protocolError(\"cmd must be an array\");\n for (const entry of cmd) validateCmd(entry);\n }\n if (value[\"idle\"] !== undefined && typeof value[\"idle\"] !== \"boolean\") {\n protocolError(\"idle must be a boolean\");\n }\n if (value[\"next\"] !== undefined) {\n if (value[\"next\"] !== true) protocolError(\"next must be true\");\n if (\n value[\"cmd\"] === undefined ||\n value[\"ops\"] !== undefined ||\n value[\"fin\"] !== undefined\n ) {\n protocolError(\"next must ride a cmd-only packet\");\n }\n }\n if (value[\"fin\"] !== undefined) validateFin(value[\"fin\"]);\n return value as StatewireEnvelope;\n};\n\n// A hold's release delivers, never settles: fin and bare close both drain it.\nconst releaseHeld = (c: Conn) => {\n if (c.held.length === 0) return;\n const held = c.held;\n c.held = [];\n c.ctx.onCmds(held);\n};\n\nconst cmdsOf = (env: StatewireEnvelope): StatewireCmd[] => {\n if (env.cmd === undefined) return [];\n return env.cmd;\n};\n\nconst snapshotOf = (env: StatewireEnvelope): unknown[] => {\n const ops = env.ops;\n if (ops === undefined) return protocolError(\"hello missing snapshot\");\n return reviveOps(ops);\n};\n\nconst helloSynOf = (env: StatewireEnvelope): StatewireSyn => {\n if (!isObject(env.syn)) return protocolError(\"expected hello\");\n validateSynScalars(env.syn, true);\n if (env.syn[\"retry\"] !== undefined) {\n protocolError(\"hello syn cannot carry retry\");\n }\n return env.syn as StatewireSyn;\n};\n\n// A host that woke on a retained socket re-sends its hello; the snapshot\n// replaces the session the way a fresh attach would.\nconst isWakeHello = (env: StatewireEnvelope) =>\n isObject(env.syn) && env.syn[\"version\"] !== undefined;\n\nconst handleHello = (c: Conn, env: StatewireEnvelope) => {\n const syn = helloSynOf(env);\n if (c.negotiation !== undefined) validateSelection(syn, c.negotiation);\n const ops = snapshotOf(env);\n c.ctx.onHello({\n ops,\n syn,\n });\n if (env.cmd !== undefined) c.ctx.onCmds(env.cmd);\n c.ctx.onIdle(syn.idle ?? false);\n c.awaitingHello = false;\n c.error = undefined;\n c.liveAt = Date.now();\n c.authDenials = 0;\n c.episode = null;\n setStatus(c, { status: \"connected\", degraded: false });\n};\n\nlet warnedUnknownSynFact = false;\n\nconst warnUnknownSynFact = () => {\n if (warnedUnknownSynFact) return;\n warnedUnknownSynFact = true;\n console.warn(\"statewire: ignoring unknown syn fact\");\n};\n\nconst deliverSyn = (c: Conn, value: unknown) => {\n if (!isObject(value)) return protocolError(\"syn must be an object\");\n validateSynScalars(value, false);\n if (value[\"version\"] !== undefined || value[\"idle\"] !== undefined) {\n protocolError(\"invalid mid-stream syn\");\n }\n if (value[\"protocols\"] !== undefined || value[\"retry\"] !== undefined) {\n c.ctx.onRefusal(validateRefusalSyn(value));\n return;\n }\n if (value[\"id\"] !== undefined) return;\n if (Object.keys(value).length === 0) {\n protocolError(\"invalid mid-stream syn\");\n }\n warnUnknownSynFact();\n};\n\nconst deliverEnvelope = (c: Conn, env: StatewireEnvelope) => {\n if (env.syn !== undefined) deliverSyn(c, env.syn);\n if (env.ops !== undefined) {\n const held = c.held;\n c.held = [];\n c.ctx.onOps({\n ops: reviveOps(env.ops),\n cmds: [...held, ...cmdsOf(env)],\n });\n } else if (env.cmd !== undefined) {\n const cmds = cmdsOf(env);\n if (env.next === true) c.held.push(...cmds);\n else c.ctx.onCmds(cmds);\n }\n if (typeof env.idle === \"boolean\") c.ctx.onIdle(env.idle);\n};\n\nexport const settleFin = (c: Conn, fin: StatewireHost.Fin): AttemptOutcome => {\n const finish =\n fin.meta === undefined\n ? fin\n : { ...fin, payload: reviveValue(fin.payload, fin.meta) };\n releaseHeld(c);\n c.retryAt = Date.now() + retryHint(finish.retry ?? 0);\n if (finish.reason === \"idle\") {\n c.ctx.onIdle(true);\n c.attempt = 0;\n c.episode = null;\n c.error = undefined;\n setStatus(c, { status: \"standby\", reason: \"idle\", degraded: false });\n return \"idle\";\n }\n const denial = finish.reason === \"unauthorized\";\n const terminal =\n finish.reason === \"gone\" ||\n finish.reason === \"forbidden\" ||\n finish.reason === \"protocol-error\" ||\n (denial && c.authDenials > 0);\n if (denial) {\n c.authDenials += 1;\n c.authStale = true;\n }\n const report =\n finish.reason !== \"reconnect\" &&\n finish.reason !== \"gone\" &&\n (!denial || terminal);\n c.error = report\n ? Object.assign(new Error(finish.message ?? finish.reason), { fin: finish })\n : undefined;\n if (c.error) c.onError(c.error);\n if (!terminal) {\n c.episode = {\n cause:\n finish.reason === \"reconnect\"\n ? \"reconnect\"\n : denial\n ? \"unauthorized\"\n : \"error\",\n ...(finish.message !== undefined && { message: finish.message }),\n ...(finish.code !== undefined && { code: finish.code }),\n };\n if (denial) openGate(c.gate);\n return \"reattach\";\n }\n c.ctx.onFinish(finish);\n setStatus(c, {\n status: \"stopped\",\n degraded: true,\n reason: denial\n ? \"unauthorized\"\n : finish.reason === \"forbidden\"\n ? \"forbidden\"\n : finish.reason === \"protocol-error\"\n ? \"protocol-error\"\n : \"gone\",\n ...(finish.message !== undefined && { message: finish.message }),\n ...(finish.payload !== undefined && { payload: finish.payload }),\n });\n return \"stop\";\n};\n\nexport const handleEnvelope = (\n c: Conn,\n value: unknown,\n): AttemptOutcome | null => {\n const env = validateEnvelope(value);\n if (c.awaitingHello || isWakeHello(env)) {\n if (env.fin !== undefined) return settleFin(c, env.fin);\n handleHello(c, env);\n return null;\n }\n deliverEnvelope(c, env);\n if (c.connection.status === \"stopped\") return \"stop\";\n if (env.fin !== undefined) return settleFin(c, env.fin);\n if (c.connection.status !== \"connected\") {\n c.attempt = 0;\n c.episode = null;\n setStatus(c, { status: \"connected\", degraded: false });\n }\n return null;\n};\n\n// A dial that no wait preceded is part of the current connect: only a\n// scheduled delay surfaces `retrying`, and the dial after it keeps that status.\nconst dialing = (c: Conn) =>\n setStatus(\n c,\n c.connection.status === \"retrying\"\n ? { status: \"retrying\", attempt: c.attempt, degraded: true }\n : { status: \"connecting\", degraded: false },\n );\n\nconst scheduleRetry = (\n c: Conn,\n failure: string | undefined,\n immediate: boolean,\n) => {\n if (c.liveAt !== null && Date.now() - c.liveAt >= timing.backoffResetMs) {\n c.attempt = 0;\n }\n c.liveAt = null;\n c.attempt += 1;\n c.episode ??= { cause: \"dropped\" };\n const delay = Math.max(\n immediate ? 0 : backoff(c.attempt),\n c.retryAt - Date.now(),\n );\n if (delay === 0) return delay;\n setStatus(c, {\n status: \"retrying\",\n degraded: true,\n attempt: c.attempt,\n ...c.episode,\n nextRetryAt: Date.now() + delay,\n ...(failure !== undefined && { lastError: failure }),\n });\n return delay;\n};\n\nconst reconnectConn = (c: Conn) => {\n if (!c.lifetime) return;\n if (c.connection.status === \"standby\" || c.connection.status === \"stopped\") {\n // A reconnect out of a park starts a fresh episode: first dial, attempt 0.\n c.attempt = 0;\n c.authDenials = 0;\n c.episode = null;\n flushTapSync(() => dialing(c));\n }\n openGate(c.gate);\n c.abort?.abort();\n};\n\nconst run = async (c: Conn, lifetime: AbortController, gate: Gate) => {\n const alive = () => c.lifetime === lifetime;\n if (c.parked) {\n await waitGate(gate);\n if (!alive()) return;\n c.parked = false;\n }\n while (alive()) {\n if (c.retryAt > Date.now()) {\n await waitGate(gate, c.retryAt - Date.now());\n continue;\n }\n // The dial is in flight: attempt alone, no backoff fields.\n flushTapSync(() => dialing(c));\n const abort = new AbortController();\n c.abort = abort;\n c.awaitingHello = true;\n c.held = [];\n let outcome: AttemptOutcome | undefined;\n let failure: string | undefined;\n try {\n const pending = c.ctx.beforeAttach?.();\n if (pending) await pending;\n if (!alive()) return;\n outcome = await c.attemptOnce(abort);\n } catch (error) {\n if (!abort.signal.aborted) {\n if (isStorageError(error)) {\n stopForError({ connection: c, error, reason: \"storage-error\" });\n outcome = \"stop\";\n } else if (\n error instanceof SyntaxError ||\n (error instanceof Error &&\n /^(statewire: protocol error:|Statewire cannot apply)/.test(\n error.message,\n ))\n ) {\n outcome = flushTapSync(() =>\n settleFin(c, { reason: \"protocol-error\", message: error.message }),\n );\n } else if (c.authStale) {\n outcome = flushTapSync(() =>\n settleFin(c, {\n reason: \"unauthorized\",\n message:\n error instanceof Error\n ? error.message\n : \"credential refresh failed\",\n }),\n );\n }\n failure =\n error instanceof Error && error.message ? error.message : \"network\";\n }\n }\n abort.abort();\n if (!alive()) return;\n flushTapSync(() => {\n releaseHeld(c);\n c.ctx.onDetach();\n });\n if (!alive()) return;\n if (c.connection.status === \"stopped\") outcome = \"stop\";\n if (outcome === \"stop\" || outcome === \"idle\") {\n await waitGate(gate);\n continue;\n }\n const immediate = takeGate(gate);\n const delay = flushTapSync(() => scheduleRetry(c, failure, immediate));\n if (delay === 0) continue;\n await waitGate(gate, delay);\n }\n};\n\nexport const unsupportedVersion = (c: Conn, version: string): AttemptOutcome =>\n flushTapSync(() =>\n handleEnvelope(c, {\n fin: {\n reason: \"protocol-error\",\n message: `unsupported protocol version: ${version || '\"\"'}`,\n },\n }),\n ) ?? \"stop\";\n\nexport const resolveHeaders = async (\n headers: StatewireClient.HeadersOption | undefined,\n staleAuth: boolean,\n): Promise<Headers> =>\n new Headers(\n typeof headers === \"function\" ? await headers({ staleAuth }) : headers,\n );\n\n// The stale flag clears only once the resolver returns: a throwing refresh keeps it for the next attempt.\n/** Names this connection, so a host retires its earlier attaches before the hello. */\nexport const replacing = (c: Conn, headers: Headers) => {\n headers.set(ATTACHER_HEADER, c.attacher);\n};\n\nexport const attachFrame = async (\n c: Conn,\n headers: StatewireClient.HeadersOption | undefined,\n) => {\n const pending = c.ctx.beforeAttach?.();\n if (pending) await pending;\n const resolved = await resolveHeaders(headers, c.authStale);\n for (const [name, value] of Object.entries(\n negotiationHeaders(c.negotiation ?? {}),\n )) {\n if (!resolved.has(name)) resolved.set(name, value);\n }\n replacing(c, resolved);\n c.negotiation = parseNegotiation(resolved);\n c.authStale = false;\n const persistence = c.ctx.beforeAttach?.();\n if (persistence) await persistence;\n const lanes = flushTapSync(() => c.ctx.takeAttachLanes());\n return {\n headers: resolved,\n body: JSON.stringify({\n headers: Object.fromEntries(resolved),\n ...(lanes ?? {}),\n }),\n };\n};\n\nexport const useLink = (\n props: StatewireProtocol.Options & {\n url: string;\n isNew?: boolean | undefined;\n onChange?: ((connection: StatewireClient.Connection) => void) | undefined;\n onError?: ((error: StatewireClient.ConnectionError) => void) | undefined;\n ctx: StatewireRemoteProps;\n attemptOnce: (c: Conn, abort: AbortController) => Promise<AttemptOutcome>;\n send: (c: Conn, frame: StatewireFrame) => Promise<StatewireSubmitResult>;\n },\n): RemoteLink => {\n const latest = useRef(props);\n latest.current = props;\n const [, setConnection] = useState<StatewireClient.Connection | null>(null);\n const [c] = useState((): Conn => {\n const conn: Conn = {\n parked: props.isNew ?? false,\n lease: null,\n attacher: randomId(),\n attempt: 0,\n authDenials: 0,\n authStale: false,\n liveAt: null,\n retryAt: 0,\n error: undefined,\n episode: null,\n awaitingHello: true,\n held: [],\n abort: null,\n gate: newGate(),\n lifetime: null,\n get ctx() {\n return latest.current.ctx;\n },\n onError: (error) => latest.current.onError?.(error),\n onChange: (connection) => latest.current.onChange?.(connection),\n attemptOnce: (abort) => {\n conn.negotiation = latest.current;\n return latest.current.attemptOnce(conn, abort);\n },\n notify: setConnection,\n reconnect: () => reconnectConn(conn),\n connection: {\n ...((props.isNew ?? false)\n ? { status: \"standby\", reason: \"deferred\", degraded: false }\n : { status: \"connecting\", degraded: false }),\n reconnect: () => conn.reconnect(),\n },\n };\n return conn;\n });\n const [link] = useState((): RemoteLink => ({\n get connection() {\n return c.connection;\n },\n get parked() {\n return c.parked;\n },\n send: (frame) => latest.current.send(c, frame),\n storageFailed: (error) =>\n stopForError({ connection: c, error, reason: \"storage-error\" }),\n protocolFailed: (error) =>\n stopForError({ connection: c, error, reason: \"protocol-error\" }),\n }));\n\n const negotiation = JSON.stringify([\n props.protocol,\n props.wireVersion,\n props.applicationProtocols,\n ]);\n useEffect(() => {\n c.lease = null;\n c.attempt = 0;\n c.authDenials = 0;\n c.authStale = false;\n c.liveAt = null;\n c.retryAt = 0;\n c.episode = null;\n setStatus(\n c,\n c.parked\n ? { status: \"standby\", reason: \"deferred\", degraded: false }\n : { status: \"connecting\", degraded: false },\n );\n const lifetime = new AbortController();\n c.lifetime = lifetime;\n c.gate = newGate();\n void run(c, lifetime, c.gate);\n return () => {\n c.abort?.abort();\n lifetime.abort();\n if (c.lifetime === lifetime) c.lifetime = null;\n openGate(c.gate);\n };\n }, [c, props.url, negotiation]);\n\n return link;\n};\n\nexport const classify = (timeout: AbortSignal) =>\n new Error(timeout.aborted ? \"timeout\" : \"network\");\n"],"mappings":";;;;;;;;;;AA8BA,MAAa2B,WAAW;CACtB;CACA;CACA;CACA;CACA;AAAS;AAuCX,MAAM2B,iBAAuB;CAAEF,SAAS;CAAOC,MAAME,KAAAA;AAAU;AAE/D,MAAMC,YAAYC,MAAY;CAC5B,MAAMC,MAAMD,EAAEL;CACdK,EAAEL,UAAU;CACZ,OAAOM;AACT;AAEA,MAAMC,YAAYF,GAASG,cAAuB;CAChD,IAAIH,EAAEL,SAAS;EACbK,EAAEL,UAAU;EACZ,OAAOS,QAAQC,QAAQ;CACzB;CACA,OAAO,IAAID,SAAeC,YAAY;EACpC,MAAMC,QACJH,cAAcL,KAAAA,IACVA,KAAAA,IACAS,iBAAiB;GACfP,EAAEJ,OAAOE,KAAAA;GACTO,QAAQ;EACV,GAAGF,SAAS;EAClBH,EAAEJ,aAAa;GACbY,aAAaF,KAAK;GAClBN,EAAEJ,OAAOE,KAAAA;GACTO,QAAQ;EACV;CACF,CAAC;AACH;AAEA,MAAMI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AAY;EACd0B,EAAEzB,SAAS;EACXyB,EAAExB,UAAU;EACZwB,EAAErB,UAAU;EACZoB,UACEC,GACAA,EAAE/B,SACE;GAAE0B,QAAQ;GAAWG,QAAQ;GAAYK,UAAU;EAAM,IACzD;GAAER,QAAQ;GAAcQ,UAAU;EAAM,CAC9C;EACA,MAAMlB,WAAW,IAAID,gBAAgB;EACrCgB,EAAEf,WAAWA;EACbe,EAAElB,OAAOhC,QAAQ;EACjB,IAASkD,GAAGf,UAAUe,EAAElB,IAAI;EAC5B,aAAa;GACXkB,EAAEjB,OAAOA,MAAM;GACfE,SAASF,MAAM;GACf,IAAIiB,EAAEf,aAAaA,UAAUe,EAAEf,WAAW;GAC1CvB,SAASsC,EAAElB,IAAI;EACjB;CACF,GAAG;EAACkB;EAAGgG,MAAMC;EAAKpI;CAAW,CAAC;CAE9B,OAAO4I;AACT;AAEA,MAAaK,YAAYC,4BACvB,IAAI7G,MAAM6G,QAAQvC,UAAU,YAAY,SAAS"}
|
package/dist/client/session.d.ts
CHANGED
|
@@ -110,6 +110,8 @@ type Session = {
|
|
|
110
110
|
/** Ephemeral lane clocks: restart at 1 on every attach. */
|
|
111
111
|
ephemeralSeqs: Record<string, number>;
|
|
112
112
|
resumeAt: number;
|
|
113
|
+
/** A refusal named sent durable stamps: a reattach's hello decides them, after `resumeAt`. */
|
|
114
|
+
reattach: boolean;
|
|
113
115
|
idle: boolean;
|
|
114
116
|
onSessionLost: StatewireClient.OnSessionLost | undefined;
|
|
115
117
|
onDeprecatedPath: StatewireClient.OnDeprecatedPath | undefined;
|
|
@@ -130,6 +132,13 @@ type Session = {
|
|
|
130
132
|
lanesOnAttach: boolean;
|
|
131
133
|
attachEntries: ReadonlySet<Pending>;
|
|
132
134
|
frameFailures: number;
|
|
135
|
+
/** A later hello decides stamps this one could not: another live sharer's stamp sat below them. */
|
|
136
|
+
recheck: ReturnType<typeof setTimeout> | undefined;
|
|
137
|
+
/** Hellos in a row that left stamps waiting at the same watermarks: the recheck backs off. */
|
|
138
|
+
rechecks: {
|
|
139
|
+
watermarks: string;
|
|
140
|
+
count: number;
|
|
141
|
+
};
|
|
133
142
|
pending: Pending[];
|
|
134
143
|
canonical: unknown;
|
|
135
144
|
documentListeners: Set<() => void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/client/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,2BAAwB;
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/client/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,2BAAwB;AAShD,OAAO,KAAK,EAAE,iBAAiB,EAAE,4BAAyB;AAO1D,OAAO,KAAK,EAAE,kBAAkB,EAAE,6BAA0B;AAG5D,OAAO,KAAK,EAAE,aAAa,EAAE,uBAAoB;AAMjD,OAAO,KAAK,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,wBAAqB;AACzE,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAiB;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,wBAAqB;AAUpD,OAAO,KAAK,EACV,UAAU,EAEV,oBAAoB,EACrB,6BAA0B;AAE3B,KAAK,WAAW,GAAG;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,WAAW,CAAC,eAAe,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;IACnE,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,OAAO,EAAE,CAAC;IAClB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AAEF,KAAK,UAAU,GAAG;IAChB,CAAC,UAAU,CAAC,IAAI,MAAM,kBAAkB,GAAG,kBAAkB,CAAC,CAAC,CAAC;CACjE,CAAC;AAEF,KAAK,OAAO,GAAG;IACb,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,yEAAyE;IACzE,GAAG,EAAE,MA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AI,CAAC,KAAK,EAAE,eAAe,CAAC,WAAW,KAAK,eAAe,CAAC,WAAW,SAItE,CAAC;AAyBJ,eAAO,MAAM,YAAY,GACvB,GAAG,OAAO,EACV,OAAO,eAAe,CAAC,YAAY,KAClC,MAgGF,CAAC;AAsKF,eAAO,MAAM,cAAc,GAAI,GAAG,OAAO,KAAG,kBAAkB,CAAC,MA6B7D,CAAC;AAEH,eAAO,MAAM,cAAc,GACzB,GAAG,OAAO,EACV,UAAU,MAAM,EAChB,QAAQ,MAAM,EACd,QAAQ,SAAS,OAAO,EAAE,EAC1B,UAAU,eAAe,CAAC,aAAa,qBACa,CAAC;AAkFvD,eAAO,MAAM,UAAU,GACrB,GAAG,OAAO,EACV,UAAU,MAAM,EAChB,OAAO,SAAS,CAAC,OAAO,KACvB,IAWF,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAC9B,SAAS,uBAAuB,KAC/B,OAyLF,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
|
package/dist/client/session.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { inRange, protocolOffers } from "../wire/protocol.js";
|
|
1
|
+
import { CLIENT_WIRE, inRange, protocolOffers } from "../wire/protocol.js";
|
|
2
2
|
import { reviveDocumentValue } from "../document.js";
|
|
3
3
|
import { encodeParams, reviveResponse } from "../wire/meta.js";
|
|
4
4
|
import { backoff, retryHint } from "./timing.js";
|
|
5
5
|
import { wrapStorageError } from "./storageError.js";
|
|
6
|
+
import { randomId } from "../util/randomId.js";
|
|
6
7
|
import { TERMINAL } from "./connection.js";
|
|
7
8
|
import "../wire/limits.js";
|
|
8
9
|
import { encodeContext } from "../wire/context.js";
|
|
@@ -11,7 +12,6 @@ import { StatewireSendError } from "../types.js";
|
|
|
11
12
|
import { bindCommandsHost } from "../host/host.js";
|
|
12
13
|
import { applyDocumentOps, findDocument, mainDocument, resolveDocumentKey } from "../wire/documents.js";
|
|
13
14
|
import { DocumentStorageContext, SessionStorageContext, createMemorySessionStore } from "./sessionStore.js";
|
|
14
|
-
import { randomId } from "../util/randomId.js";
|
|
15
15
|
import { useContext, useEffect, useState } from "@assistant-ui/tap/react-shim";
|
|
16
16
|
// src/client/session.ts
|
|
17
17
|
const protocolError = (message) => {
|
|
@@ -903,10 +903,11 @@ const sessionLostInner = (s, protocol, seqWm) => {
|
|
|
903
903
|
for (const old of held) enqueueInner(s, old.command, old.inv.params, () => {}, () => {}, { ...old.inv.localMeta !== void 0 && { localMeta: old.inv.localMeta } });
|
|
904
904
|
} else {
|
|
905
905
|
const stamps = mergeBacklog(s, protocol);
|
|
906
|
-
const
|
|
907
|
-
const
|
|
906
|
+
const held = outboxOf(lane).filter((c) => c.held);
|
|
907
|
+
const queued = outboxOf(lane).filter((c) => !c.held);
|
|
908
|
+
const keep = new Set(held.map((c) => c.id));
|
|
908
909
|
setRecord(s, withLane(s.record, protocol, {
|
|
909
|
-
...withNotices(
|
|
910
|
+
...withNotices(withOutbox(lane, held), [...stamps.map((c) => lostNotice(c)), ...queued.map((c) => lostNotice(c))]),
|
|
910
911
|
nextSeq: seqWm + 1,
|
|
911
912
|
commands: [],
|
|
912
913
|
...marks(s, lane, [...stamps.map((c) => ({
|
|
@@ -914,7 +915,7 @@ const sessionLostInner = (s, protocol, seqWm) => {
|
|
|
914
915
|
by: c.by ?? c.owner
|
|
915
916
|
})), ...queued], failure)
|
|
916
917
|
}));
|
|
917
|
-
for (const p of s.pending.filter((q) => q.command.protocol === protocol)) {
|
|
918
|
+
for (const p of s.pending.filter((q) => q.command.protocol === protocol && !keep.has(q.id))) {
|
|
918
919
|
s.lifecycle?.onCovered?.(p.inv);
|
|
919
920
|
settleEntry(s, p, {
|
|
920
921
|
ok: false,
|
|
@@ -926,7 +927,7 @@ const sessionLostInner = (s, protocol, seqWm) => {
|
|
|
926
927
|
publish(s);
|
|
927
928
|
wake(s);
|
|
928
929
|
};
|
|
929
|
-
const demote = (s, protocol, watermark, demoted) => {
|
|
930
|
+
const demote = (s, protocol, watermark, demoted, waiting) => {
|
|
930
931
|
const lane = laneOf(s.record, protocol);
|
|
931
932
|
const local = laneEntries(s, protocol).filter((p) => p.seq > watermark);
|
|
932
933
|
const above = new Map(lane.commands.filter((c) => c.seq > watermark).map((c) => [c.id, c]));
|
|
@@ -937,6 +938,12 @@ const demote = (s, protocol, watermark, demoted) => {
|
|
|
937
938
|
sessionLostInner(s, protocol, watermark);
|
|
938
939
|
return;
|
|
939
940
|
}
|
|
941
|
+
const me = s.store.owner?.id;
|
|
942
|
+
const foreign = moved.find((c) => c.owner !== void 0 && c.owner !== me && !local.some((p) => p.id === c.id));
|
|
943
|
+
if (foreign !== void 0) {
|
|
944
|
+
for (const p of local) if (p.seq > foreign.seq) waiting.add(p);
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
940
947
|
setRecord(s, withLane(s.record, protocol, {
|
|
941
948
|
...withOutbox(lane, [...moved.map(({ seq: _seq, owner: _owner, ...command }) => command), ...outboxOf(lane)]),
|
|
942
949
|
nextSeq: watermark + 1,
|
|
@@ -947,6 +954,19 @@ const demote = (s, protocol, watermark, demoted) => {
|
|
|
947
954
|
else unstamp(s, p);
|
|
948
955
|
sortPending(s);
|
|
949
956
|
};
|
|
957
|
+
const recheckLater = (s, watermarks) => {
|
|
958
|
+
if (s.rechecks.watermarks !== watermarks) s.rechecks = {
|
|
959
|
+
watermarks,
|
|
960
|
+
count: 0
|
|
961
|
+
};
|
|
962
|
+
s.rechecks.count += 1;
|
|
963
|
+
if (s.recheck !== void 0) return;
|
|
964
|
+
s.recheck = setTimeout(() => {
|
|
965
|
+
s.recheck = void 0;
|
|
966
|
+
if (s.running && s.attach === "attached") s.transport?.connection.reconnect();
|
|
967
|
+
}, backoff(s.rechecks.count + 1));
|
|
968
|
+
};
|
|
969
|
+
const gapFill = (s) => s.selection !== void 0 && s.selection.version >= "2026-11-01";
|
|
950
970
|
const selectionOf = (syn) => {
|
|
951
971
|
if (syn.version === void 0 || syn.protocols === void 0) return void 0;
|
|
952
972
|
return {
|
|
@@ -961,6 +981,12 @@ const selectionOf = (syn) => {
|
|
|
961
981
|
})
|
|
962
982
|
};
|
|
963
983
|
};
|
|
984
|
+
const carriedThrough = (lane, attached) => {
|
|
985
|
+
const carried = new Set([...attached].filter((p) => p.command.protocol === lane.name).map((p) => p.seq));
|
|
986
|
+
let seq = lane.seq ?? 0;
|
|
987
|
+
while (carried.has(seq + 1)) seq += 1;
|
|
988
|
+
return seq;
|
|
989
|
+
};
|
|
964
990
|
const handleHello = (s, { ops, syn }) => {
|
|
965
991
|
if (s.attach === "attached") {
|
|
966
992
|
s.ephemeralSeqs = {};
|
|
@@ -979,6 +1005,7 @@ const handleHello = (s, { ops, syn }) => {
|
|
|
979
1005
|
s.attachEpoch += 1;
|
|
980
1006
|
s.frameFailures = 0;
|
|
981
1007
|
s.resumeAt = 0;
|
|
1008
|
+
s.reattach = false;
|
|
982
1009
|
const lanes = syn.protocols ?? [];
|
|
983
1010
|
s.ephemeral = lanes.length > 0 && lanes.every((lane) => lane.record === "ephemeral");
|
|
984
1011
|
if (s.ephemeral) s.deactivated = true;
|
|
@@ -986,18 +1013,24 @@ const handleHello = (s, { ops, syn }) => {
|
|
|
986
1013
|
s.attachEntries = /* @__PURE__ */ new Set();
|
|
987
1014
|
const reconcile = () => {
|
|
988
1015
|
const demoted = /* @__PURE__ */ new Set();
|
|
1016
|
+
const waiting = /* @__PURE__ */ new Set();
|
|
989
1017
|
for (const lane of lanes) {
|
|
990
1018
|
if (lane.record === "ephemeral") {
|
|
991
1019
|
s.ephemeralSeqs[lane.name] = Math.max(Object.hasOwn(s.ephemeralSeqs, lane.name) ? s.ephemeralSeqs[lane.name] : 0, ...laneEntries(s, lane.name).map((p) => p.seq));
|
|
992
1020
|
continue;
|
|
993
1021
|
}
|
|
994
|
-
demote(s, lane.name, lane
|
|
1022
|
+
demote(s, lane.name, carriedThrough(lane, attached), demoted, waiting);
|
|
995
1023
|
s.durableSeq[lane.name] = lane.seq ?? 0;
|
|
996
1024
|
}
|
|
997
1025
|
for (const entry of s.pending) {
|
|
998
|
-
entry.posted = attached.has(entry) || isStamped(entry) && entry.seq <= durableSeqOf(s, entry.command.protocol) && !isEphemeral(s, entry.command.protocol);
|
|
1026
|
+
entry.posted = attached.has(entry) || waiting.has(entry) || isStamped(entry) && entry.seq <= durableSeqOf(s, entry.command.protocol) && !isEphemeral(s, entry.command.protocol);
|
|
999
1027
|
entry.stale = false;
|
|
1000
1028
|
}
|
|
1029
|
+
if (waiting.size > 0) recheckLater(s, JSON.stringify(lanes.map((lane) => [lane.name, lane.seq])));
|
|
1030
|
+
else s.rechecks = {
|
|
1031
|
+
watermarks: "",
|
|
1032
|
+
count: 0
|
|
1033
|
+
};
|
|
1001
1034
|
syncBacklogInner(s);
|
|
1002
1035
|
s.sessionKnown = true;
|
|
1003
1036
|
flushInner(s, demoted);
|
|
@@ -1022,7 +1055,15 @@ const handleOps = (s, { ops, cmds }) => {
|
|
|
1022
1055
|
publishIngested(s);
|
|
1023
1056
|
};
|
|
1024
1057
|
const handleRefusal = (s, syn) => {
|
|
1025
|
-
const
|
|
1058
|
+
const stated = (syn.protocols ?? []).filter((lane) => lane.seq !== void 0);
|
|
1059
|
+
const lanes = gapFill(s) ? stated.filter(({ name }) => isEphemeral(s, name)) : stated;
|
|
1060
|
+
if (gapFill(s) && s.pending.some((p) => {
|
|
1061
|
+
if (!isStamped(p) || !p.attempted) return false;
|
|
1062
|
+
const protocol = p.command.protocol;
|
|
1063
|
+
if (isEphemeral(s, protocol)) return false;
|
|
1064
|
+
const seq = stated.find((lane) => lane.name === protocol)?.seq ?? 0;
|
|
1065
|
+
return p.seq > Math.max(seq, durableSeqOf(s, protocol));
|
|
1066
|
+
})) s.reattach = true;
|
|
1026
1067
|
for (const { name, seq } of lanes) {
|
|
1027
1068
|
const watermark = isEphemeral(s, name) ? seq : Math.max(seq, durableSeqOf(s, name));
|
|
1028
1069
|
for (const entry of laneEntries(s, name)) entry.posted = entry.seq <= watermark;
|
|
@@ -1156,13 +1197,30 @@ const pump = async (s) => {
|
|
|
1156
1197
|
while (s.running && !isFinished(s)) {
|
|
1157
1198
|
if (!s.hydrated) await s.ready;
|
|
1158
1199
|
const transport = s.transport;
|
|
1200
|
+
if (s.reattach && s.attach === "attached" && transport) {
|
|
1201
|
+
const delay = s.resumeAt - Date.now();
|
|
1202
|
+
if (delay > 0) {
|
|
1203
|
+
await sleepUntilWake(s, delay);
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
if (s.pending.some((p) => isStamped(p) && p.attempted && isEphemeral(s, p.command.protocol))) {
|
|
1207
|
+
await waitForWake(s);
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
s.reattach = false;
|
|
1211
|
+
const epoch = s.attachEpoch;
|
|
1212
|
+
transport.connection.reconnect();
|
|
1213
|
+
while (s.running && !isFinished(s) && epoch === s.attachEpoch) await waitForWake(s);
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1159
1216
|
const flushable = flushCandidates(s).length > 0;
|
|
1160
|
-
const queued = s.pending.some((p) => isOutboxed(p) && !p.inv.held);
|
|
1217
|
+
const queued = s.pending.some((p) => isOutboxed(p) && !p.inv.held) || queuedInRecord(s);
|
|
1161
1218
|
if (buildLanes(s) === null && !flushable && (!queued || s.attach === "attached")) return;
|
|
1162
|
-
|
|
1219
|
+
const waiting = s.pending.length > 0 || queued;
|
|
1220
|
+
if (transport?.parked && !waiting) return;
|
|
1163
1221
|
if (s.attach !== "attached" || !transport) {
|
|
1164
|
-
if (
|
|
1165
|
-
if (transport?.connection.status === "standby" && transport.connection.reason === "idle" || transport?.parked
|
|
1222
|
+
if (!waiting) return;
|
|
1223
|
+
if (transport?.connection.status === "standby" && transport.connection.reason === "idle" || transport?.parked) transport.connection.reconnect();
|
|
1166
1224
|
await waitForWake(s);
|
|
1167
1225
|
continue;
|
|
1168
1226
|
}
|
|
@@ -1200,6 +1258,14 @@ const pump = async (s) => {
|
|
|
1200
1258
|
}) : send(lanes));
|
|
1201
1259
|
} catch {
|
|
1202
1260
|
if (!s.running || isFinished(s)) return;
|
|
1261
|
+
if (lanes !== null && lanes.entries.length > 0 && gapFill(s)) {
|
|
1262
|
+
if (epoch !== s.attachEpoch) continue;
|
|
1263
|
+
for (const entry of lanes.entries) if (s.pending.includes(entry)) entry.posted = true;
|
|
1264
|
+
s.frameFailures += 1;
|
|
1265
|
+
await sleepUntilWake(s, backoff(s.frameFailures));
|
|
1266
|
+
if (s.running && epoch === s.attachEpoch && s.attach === "attached") transport.connection.reconnect();
|
|
1267
|
+
continue;
|
|
1268
|
+
}
|
|
1203
1269
|
if (lanes?.frame.ctx?.length) {
|
|
1204
1270
|
s.lanesOnAttach = true;
|
|
1205
1271
|
transport.connection.reconnect();
|
|
@@ -1284,6 +1350,8 @@ const start = (s) => {
|
|
|
1284
1350
|
};
|
|
1285
1351
|
const stop = (s) => {
|
|
1286
1352
|
s.running = false;
|
|
1353
|
+
clearTimeout(s.recheck);
|
|
1354
|
+
s.recheck = void 0;
|
|
1287
1355
|
if (s.shared) {
|
|
1288
1356
|
s.shared.unsubscribe?.();
|
|
1289
1357
|
s.shared.unsubscribe = null;
|
|
@@ -1408,6 +1476,7 @@ const flushCandidates = (s) => flushLanes(s).flatMap((protocol) => {
|
|
|
1408
1476
|
stored
|
|
1409
1477
|
}));
|
|
1410
1478
|
});
|
|
1479
|
+
const queuedInRecord = (s) => Object.keys(s.record.lanes).some((protocol) => (s.selection ? negotiated(s, protocol) : offered(s, protocol)) && bubble(s, protocol, laneQueue(s, protocol)).free > 0);
|
|
1411
1480
|
const reasonOf = (s, stored, demoted) => stored.released ? "release" : demoted.has(stored.id) ? "reconnect" : s.mountIds.has(stored.id) ? "reload" : "enqueue";
|
|
1412
1481
|
const NO_IDS = /* @__PURE__ */ new Set();
|
|
1413
1482
|
const patched = (stored, patch) => {
|
|
@@ -1649,7 +1718,7 @@ const updateOutbox = (s, id, fn) => background(outboxOp(s, id, {
|
|
|
1649
1718
|
patch: (entry) => toPatch(fn(entry))
|
|
1650
1719
|
}));
|
|
1651
1720
|
const producedOf = (s) => ({
|
|
1652
|
-
wire: s.options.wireVersion ??
|
|
1721
|
+
wire: s.options.wireVersion ?? CLIENT_WIRE,
|
|
1653
1722
|
protocols: protocolOffers(s.options) === "*" && s.selection ? s.selection.protocols : protocolOffers(s.options)
|
|
1654
1723
|
});
|
|
1655
1724
|
const placed = (queue, entry, { after, before }) => {
|
|
@@ -1699,14 +1768,22 @@ const insertOutbox = (s, entry) => {
|
|
|
1699
1768
|
return;
|
|
1700
1769
|
}
|
|
1701
1770
|
let base = s.record;
|
|
1771
|
+
let entered = stored;
|
|
1702
1772
|
if (entry.from !== void 0) {
|
|
1703
1773
|
const source = Object.entries(base.lanes).find(([, l]) => l.inbox?.some((n) => n.id === entry.from));
|
|
1704
1774
|
if (source === void 0 || locate(s, id) !== void 0) return;
|
|
1775
|
+
const notice = source[1].inbox.find((n) => n.id === entry.from);
|
|
1776
|
+
entered = {
|
|
1777
|
+
...stored,
|
|
1778
|
+
ts: notice.ts
|
|
1779
|
+
};
|
|
1705
1780
|
base = withLane(base, source[0], withoutNotice(source[1], entry.from));
|
|
1706
1781
|
}
|
|
1707
1782
|
const lane = laneOf(base, protocol);
|
|
1783
|
+
const later = outboxOf(lane).find((c) => c.ts >= entered.ts);
|
|
1784
|
+
const position = entry.from !== void 0 && entry.after === void 0 && entry.before === void 0 && later !== void 0 ? { before: later.id } : entry;
|
|
1708
1785
|
try {
|
|
1709
|
-
setRecord(s, withLane(base, protocol, withOutbox(lane, placed(outboxOf(lane),
|
|
1786
|
+
setRecord(s, withLane(base, protocol, withOutbox(lane, placed(outboxOf(lane), entered, position))));
|
|
1710
1787
|
} catch (error) {
|
|
1711
1788
|
if (!isQuota(error)) throw error;
|
|
1712
1789
|
if (entry.from !== void 0) s.skipped.add(entry.from);
|
|
@@ -1888,7 +1965,7 @@ const loadSessionRecord = (store, options) => {
|
|
|
1888
1965
|
let stored = store.load();
|
|
1889
1966
|
if (stored !== null) validateLanes(stored);
|
|
1890
1967
|
const current = {
|
|
1891
|
-
wire: options.wireVersion ??
|
|
1968
|
+
wire: options.wireVersion ?? CLIENT_WIRE,
|
|
1892
1969
|
protocols: protocolOffers(options)
|
|
1893
1970
|
};
|
|
1894
1971
|
const compatible = (record) => Object.entries(record.lanes).every(([protocol, lane]) => [...lane.commands, ...outboxOf(lane)].every((command) => storedCommandCompatible(protocol, command, current)));
|
|
@@ -1974,6 +2051,7 @@ const useStatewireSession = (options) => {
|
|
|
1974
2051
|
durableSeq: {},
|
|
1975
2052
|
ephemeralSeqs: {},
|
|
1976
2053
|
resumeAt: 0,
|
|
2054
|
+
reattach: false,
|
|
1977
2055
|
idle: false,
|
|
1978
2056
|
onSessionLost: void 0,
|
|
1979
2057
|
onDeprecatedPath: void 0,
|
|
@@ -1991,6 +2069,11 @@ const useStatewireSession = (options) => {
|
|
|
1991
2069
|
lanesOnAttach: false,
|
|
1992
2070
|
attachEntries: /* @__PURE__ */ new Set(),
|
|
1993
2071
|
frameFailures: 0,
|
|
2072
|
+
recheck: void 0,
|
|
2073
|
+
rechecks: {
|
|
2074
|
+
watermarks: "",
|
|
2075
|
+
count: 0
|
|
2076
|
+
},
|
|
1994
2077
|
pending: [],
|
|
1995
2078
|
canonical: void 0,
|
|
1996
2079
|
documentListeners: /* @__PURE__ */ new Set(),
|