experimental-a2 0.5.0 → 0.6.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/{ai-CFNeCrRl.d.ts → ai-D_PGS-JR.d.ts} +2 -2
  3. package/dist/{ai-CFNeCrRl.d.ts.map → ai-D_PGS-JR.d.ts.map} +1 -1
  4. package/dist/ai-server.d.ts +2 -2
  5. package/dist/ai-server.js +1 -1
  6. package/dist/ai.d.ts +1 -1
  7. package/dist/{client-D7mvIXrF.d.ts → client-CdMqi7mC.d.ts} +23 -12
  8. package/dist/client-CdMqi7mC.d.ts.map +1 -0
  9. package/dist/{client-BKlyLiOU.js → client-Dj5d3SP_.js} +37 -19
  10. package/dist/client-Dj5d3SP_.js.map +1 -0
  11. package/dist/client.d.ts +1 -1
  12. package/dist/client.js +1 -1
  13. package/dist/http.d.ts +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/otel.d.ts +1 -1
  16. package/dist/react.d.ts +41 -7
  17. package/dist/react.d.ts.map +1 -1
  18. package/dist/react.js +74 -35
  19. package/dist/react.js.map +1 -1
  20. package/dist/scheduler-qstash.d.ts +1 -1
  21. package/dist/scheduler-qstash.js +1 -1
  22. package/dist/scheduler-vercel.d.ts +1 -1
  23. package/dist/scheduler-vercel.js +1 -1
  24. package/dist/{server-DUF9pjsx.d.ts → server-DpvjhdoE.d.ts} +2 -2
  25. package/dist/{server-DUF9pjsx.d.ts.map → server-DpvjhdoE.d.ts.map} +1 -1
  26. package/dist/{server-C72KOw51.js → server-Duw6MVlB.js} +13 -7
  27. package/dist/server-Duw6MVlB.js.map +1 -0
  28. package/dist/server.d.ts +1 -1
  29. package/dist/server.js +1 -1
  30. package/dist/{telemetry-BjYHTfh2.d.ts → telemetry-CpeclqB2.d.ts} +3 -3
  31. package/dist/{telemetry-BjYHTfh2.d.ts.map → telemetry-CpeclqB2.d.ts.map} +1 -1
  32. package/docs/guides/03-react.mdx +98 -1
  33. package/docs/guides/09-presence.mdx +5 -2
  34. package/docs/reference/01-api.mdx +45 -4
  35. package/package.json +1 -1
  36. package/src/client.ts +69 -33
  37. package/src/react.ts +118 -44
  38. package/src/server.ts +2 -2
  39. package/src/telemetry.ts +17 -10
  40. package/dist/client-BKlyLiOU.js.map +0 -1
  41. package/dist/client-D7mvIXrF.d.ts.map +0 -1
  42. package/dist/server-C72KOw51.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 850e287: Standalone `useSession(client, sessionId, options?)` in
8
+ `experimental-a2/react`: mount any session from any component, no
9
+ provider required. The handle is identity-mapped (every hook and
10
+ provider mounting the same session shares one runtime) and the stream
11
+ is refcounted across all of them — first mount connects, last unmount
12
+ closes, StrictMode-safe.
13
+
14
+ Hydration is app-owned through one atomic option: `hydrate` takes the
15
+ `{ state, index }` pair `session.state(reducer)` returns, fetched by
16
+ the app through its own route, so the fold and its frontier travel
17
+ together or not at all. While `hydrate` is `undefined` the hook holds
18
+ the stream (connecting without a fold would replay the whole log — the
19
+ library never picks the expensive path silently); when the value
20
+ lands, the session hydrates under the usual never-move-backward rule
21
+ and the stream connects at that frontier. A deliberate full replay
22
+ needs no special vocabulary:
23
+ `hydrate: { state: reducer.initialState, index: 0 }` — state at index
24
+ 0 is the reducer's seed by definition. The result carries no pending
25
+ flag: whether the fold has been handed over is the caller's own input,
26
+ so the app's data-layer loading state is the pending state.
27
+
28
+ `connect()` now takes a lease on the live stream and returns its
29
+ release: leases refcount per handle (the first connects, releasing the
30
+ last closes, releasing twice is a no-op), so independent consumers of
31
+ one identity-mapped handle — hooks, providers, vanilla code — never
32
+ fight over the stream. `close()` stays as the hard stop: it drops
33
+ every outstanding lease and closes now. Returning a disposer from the
34
+ previously void `connect()` is additive.
35
+
36
+ `createClient` gains `participant` — identity is a client-level fact,
37
+ stated once as the default for every session handle. The per-session
38
+ `participant` (session options, `SessionProvider`, `useSession`)
39
+ remains as the override for apps whose identity is only known at mount
40
+ time.
41
+
42
+ Deliberately not included: a library-served state read. Reducer names
43
+ are the snapshot-invalidation knob and are designed to churn, so
44
+ putting them on the wire would open a version-skew window on every
45
+ rename; the app route calls `session.state(reducer)` with the reducer
46
+ by reference instead, and no name crosses the wire.
47
+
48
+ ## 0.5.1
49
+
50
+ ### Patch Changes
51
+
52
+ - 185b79b: Swallowed errors now print by default. Errors a2 absorbs by design — a
53
+ caught handler failure entering the retry machinery, a lost scheduler
54
+ arm — never travel up the stack, and with no `telemetry` configured they
55
+ previously vanished into a no-op sink: in dev, a failing handler blocked
56
+ its lane with zero terminal output. The default telemetry is now a
57
+ console reporter whose `recordError` logs the error with its span
58
+ context (contract, session, event type, index, attempt) via
59
+ `console.error`. Spans remain free and passing `telemetry` (e.g.
60
+ `otel()`) replaces the sink wholesale, so instrumented deployments are
61
+ unchanged.
62
+
3
63
  ## 0.5.0
4
64
 
5
65
  ### Minor Changes
@@ -1,5 +1,5 @@
1
1
  import { a as EventDefs, h as StandardSchemaV1, n as Contract, p as Reducer, t as AppendInput } from "./contract-jIfaR085.js";
2
- import { s as HandlerContext } from "./server-DUF9pjsx.js";
2
+ import { s as HandlerContext } from "./server-DpvjhdoE.js";
3
3
  import { FinishReason, JSONValue, LanguageModelUsage, UIMessage as UIMessage$1, UIMessageChunk as UIMessageChunk$1 } from "ai";
4
4
  //#region src/ai.d.ts
5
5
  type AgentStatus = "idle" | "generating" | "waiting" | "failed" | "closed";
@@ -331,4 +331,4 @@ declare function handlerContext<D extends AgentToolEventDefs>(agentOrContract: C
331
331
  declare function agent<M extends UIMessage$1 = UIMessage$1, E extends EventDefs = Record<never, never>>(options: AgentOptions<M, E>): AgentDefinition<M, AIEventDefs<M> & E>;
332
332
  //#endregion
333
333
  export { MessageInterruptedPayload as A, UIMessage$1 as B, GenerationUsage as C, LanguageModelUsage as D, JSONValue as E, SessionClosedPayload as F, deriveUIMessages as G, agent as H, SessionCreatedPayload as I, inputs as J, events as K, ToolActivity as L, PendingInput as M, RetryGenerationOptions as N, MessageCompletedPayload as O, RetryRequestedPayload as P, ToolCalledPayload as R, GenerationStartedPayload as S, InputRespondedPayload as T, createEvents as U, UIMessageChunk$1 as V, createReducer as W, reduceAIState as Y, GenerationCompletedPayload as _, ActiveGenerationProjection as a, GenerationReason as b, AgentStatus as c, ApprovalRequestedPayload as d, ApprovalRespondedPayload as f, FinishReason as g, CompactionState as h, ActiveGeneration as i, PendingApproval as j, MessageCreatedPayload as k, AgentToolContext as l, CompactionRequestedPayload as m, AIInputs as n, AgentDefinition as o, CompactionCompletedPayload as p, handlerContext as q, AIState as r, AgentOptions as s, AIEventDefs as t, AgentToolEventDefs as u, GenerationFailedPayload as v, InputRequestedPayload as w, GenerationRequestedPayload as x, GenerationProgressPayload as y, ToolResultPayload as z };
334
- //# sourceMappingURL=ai-CFNeCrRl.d.ts.map
334
+ //# sourceMappingURL=ai-D_PGS-JR.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ai-CFNeCrRl.d.ts","names":[],"sources":["../src/ai.ts"],"mappings":";;;;KAwBY;KAGA;KAEA;EAA0B,WAAW;;KACrC;EAAyB;;KACzB,sBAAsB,UAAU;EAC1C,SAAS;;EAET;;KAEU;EAA4B;;KACnC;EACH;EACA;;EAEA;;KAEU,4BAA4B;EAEhC;EAAsB;;EACtB;EAAmB;;KAEf;EACV;EACA,QAAQ;EACR;;KAEU;EACV;EACA;EACA;;KAEU,wBAAwB;KACxB;EACV;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA,QAAQ;;KAEE;EACV;EACA;EACA;EACA;EACA,eAAe;EACf,QAAQ;;KAEE;EACV;EACA;EACA;EACA;EACA;;EAEA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;E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,cAAc;;;cAkBN,QAAQ;;;;;;;;;iBA8DL,eAAe,UAAU,oBACvC,iBAAiB,SAAS;WAAgB,UAAU,SAAS;IAC5D,iBAAiB;;;;;iBAqBJ,MACd,UAAU,cAAY,aACtB,UAAU,YAAY,sBACtB,SAAS,aAAa,GAAG,KAAK,gBAAgB,GAAG,YAAY,KAAK"}
1
+ {"version":3,"file":"ai-D_PGS-JR.d.ts","names":[],"sources":["../src/ai.ts"],"mappings":";;;;KAwBY;KAGA;KAEA;EAA0B,WAAW;;KACrC;EAAyB;;KACzB,sBAAsB,UAAU;EAC1C,SAAS;;EAET;;KAEU;EAA4B;;KACnC;EACH;EACA;;EAEA;;KAEU,4BAA4B;EAEhC;EAAsB;;EACtB;EAAmB;;KAEf;EACV;EACA,QAAQ;EACR;;KAEU;EACV;EACA;EACA;;KAEU,wBAAwB;KACxB;EACV;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA,QAAQ;;KAEE;EACV;EACA;EACA;EACA;EACA,eAAe;EACf,QAAQ;;KAEE;EACV;EACA;EACA;EACA;EACA;;EAEA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA;;KAEU;EACV;EACA;EACA;EACA;EACA,WAAW;;KAED;EACV;EACA;EACA;EACA;EACA,OAAO;;KAEG;EACV;EACA;;KAEU,2BAA2B,UAAU;EAC/C;EACA;EACA,UAAU;EACV;;KAGU,YAAY,UAAU,cAAY;EAC5C,sBAAsB,iBAAiB;EACvC,qBAAqB,iBAAiB;EACtC,sBAAsB,iBAAiB,sBAAsB;EAC7D,wBAAwB,iBAAiB;EACzC,0BAA0B,iBAAiB;EAC3C,2BAA2B,iBAAiB;EA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A,SAAS;;EAET,gBAAgB,iBAAiB;;EAEjC;;KAGG,cAAc,UAAU,aAC3B,UAAU,mCAAmC,UAAU,oBACnD,iBAAiB,YAAY,WAAW,4BAChC,UAAU,eAEhB,IACA,cACF;iBA2LU,aAAa,UAAU,cAAY,aAAW;EAC5D,gBAAgB,iBAAiB;IAC/B,YAAY;cA0JH,QAAQ,YAAY;;iBA8ajB,cAAc,UAAU,aACtC,OAAO,QAAQ,IACf;EAAS;EAAc;EAAkB;EAAe;IACvD,QAAQ;;iBAu2BK,iBAAiB,UAAU,cAAY,aACrD;EAAoB;EAAc;EAAkB;MACnD;;iBAOa,cAAc,UAAU,WAAW;EACjD,UAAU,SAAS;EACnB;IACE,QAAQ,GAAG,QAAQ,cAAc;KAUhC,cACH,UAAU,aACV,gBAAgB,YAAY,eAC1B,YAAY,KAAK,YAAY,IAAI;KAEzB;;EAEV,QAAQ,UAAU,aAChB,SAAS,GACT;IAAY;MACX,cAAc;;EAEjB,KAAK,UAAU,aACb,SAAS,IACR,cAAc;;EAEjB,SACE,UAAU,2BACT,cAAc;;EAEjB,MACE,UAAU,wBACT,cAAc;;EAEjB,aACE,SAAS,wBACR,cAAc;;EAEjB,MACE,SAAS,yBACR,cAAc;;EAEjB,UACE,cAAc,4BACb,cAAc;;;cAkBN,QAAQ;;;;;;;;;iBA8DL,eAAe,UAAU,oBACvC,iBAAiB,SAAS;WAAgB,UAAU,SAAS;IAC5D,iBAAiB;;;;;iBAqBJ,MACd,UAAU,cAAY,aACtB,UAAU,YAAY,sBACtB,SAAS,aAAa,GAAG,KAAK,gBAAgB,GAAG,YAAY,KAAK"}
@@ -1,6 +1,6 @@
1
1
  import { a as EventDefs, r as ContractEvent } from "./contract-jIfaR085.js";
2
- import { d as PushValidationContext, g as ServerOptions, n as A2Server } from "./server-DUF9pjsx.js";
3
- import { l as AgentToolContext, o as AgentDefinition, r as AIState, t as AIEventDefs, u as AgentToolEventDefs } from "./ai-CFNeCrRl.js";
2
+ import { d as PushValidationContext, g as ServerOptions, n as A2Server } from "./server-DpvjhdoE.js";
3
+ import { l as AgentToolContext, o as AgentDefinition, r as AIState, t as AIEventDefs, u as AgentToolEventDefs } from "./ai-D_PGS-JR.js";
4
4
  import { Instructions, LanguageModel, TextStreamPart, ToolSet, ToolSet as ToolSet$1, UIMessage, UIMessageChunk, streamText } from "ai";
5
5
  //#region src/ai-sdk-step.d.ts
6
6
  type StreamTextOptions<T extends ToolSet$1> = Parameters<typeof streamText<T>>[0];
package/dist/ai-server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as A2Error } from "./errors-BQuJpe82.js";
2
2
  import { m as installAmbientToolScopeStorage, p as consumeSchedulerSendFailure } from "./internal-DstsI6Re.js";
3
- import { t as createServer } from "./server-C72KOw51.js";
3
+ import { t as createServer } from "./server-Duw6MVlB.js";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { convertToModelMessages, stepCountIs, streamText, toUIMessageStream } from "ai";
6
6
  //#region src/ai-sdk-step.ts
package/dist/ai.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as MessageInterruptedPayload, B as UIMessage, C as GenerationUsage, D as LanguageModelUsage, E as JSONValue, F as SessionClosedPayload, G as deriveUIMessages, H as agent, I as SessionCreatedPayload, J as inputs, K as events, L as ToolActivity, M as PendingInput, N as RetryGenerationOptions, O as MessageCompletedPayload, P as RetryRequestedPayload, R as ToolCalledPayload, S as GenerationStartedPayload, T as InputRespondedPayload, U as createEvents, V as UIMessageChunk, W as createReducer, Y as reduceAIState, _ as GenerationCompletedPayload, a as ActiveGenerationProjection, b as GenerationReason, c as AgentStatus, d as ApprovalRequestedPayload, f as ApprovalRespondedPayload, g as FinishReason, h as CompactionState, i as ActiveGeneration, j as PendingApproval, k as MessageCreatedPayload, l as AgentToolContext, m as CompactionRequestedPayload, n as AIInputs, o as AgentDefinition, p as CompactionCompletedPayload, q as handlerContext, r as AIState, s as AgentOptions, t as AIEventDefs, u as AgentToolEventDefs, v as GenerationFailedPayload, w as InputRequestedPayload, x as GenerationRequestedPayload, y as GenerationProgressPayload, z as ToolResultPayload } from "./ai-CFNeCrRl.js";
1
+ import { A as MessageInterruptedPayload, B as UIMessage, C as GenerationUsage, D as LanguageModelUsage, E as JSONValue, F as SessionClosedPayload, G as deriveUIMessages, H as agent, I as SessionCreatedPayload, J as inputs, K as events, L as ToolActivity, M as PendingInput, N as RetryGenerationOptions, O as MessageCompletedPayload, P as RetryRequestedPayload, R as ToolCalledPayload, S as GenerationStartedPayload, T as InputRespondedPayload, U as createEvents, V as UIMessageChunk, W as createReducer, Y as reduceAIState, _ as GenerationCompletedPayload, a as ActiveGenerationProjection, b as GenerationReason, c as AgentStatus, d as ApprovalRequestedPayload, f as ApprovalRespondedPayload, g as FinishReason, h as CompactionState, i as ActiveGeneration, j as PendingApproval, k as MessageCreatedPayload, l as AgentToolContext, m as CompactionRequestedPayload, n as AIInputs, o as AgentDefinition, p as CompactionCompletedPayload, q as handlerContext, r as AIState, s as AgentOptions, t as AIEventDefs, u as AgentToolEventDefs, v as GenerationFailedPayload, w as InputRequestedPayload, x as GenerationRequestedPayload, y as GenerationProgressPayload, z as ToolResultPayload } from "./ai-D_PGS-JR.js";
2
2
  export { AIEventDefs, AIInputs, AIState, ActiveGeneration, ActiveGenerationProjection, AgentDefinition, AgentOptions, AgentStatus, AgentToolContext, AgentToolEventDefs, ApprovalRequestedPayload, ApprovalRespondedPayload, CompactionCompletedPayload, CompactionRequestedPayload, CompactionState, type FinishReason, GenerationCompletedPayload, GenerationFailedPayload, GenerationProgressPayload, GenerationReason, GenerationRequestedPayload, GenerationStartedPayload, GenerationUsage, InputRequestedPayload, InputRespondedPayload, type JSONValue, type LanguageModelUsage, MessageCompletedPayload, MessageCreatedPayload, MessageInterruptedPayload, PendingApproval, PendingInput, RetryGenerationOptions, RetryRequestedPayload, SessionClosedPayload, SessionCreatedPayload, ToolActivity, ToolCalledPayload, ToolResultPayload, type UIMessage, type UIMessageChunk, agent, createEvents, createReducer, deriveUIMessages, events, handlerContext, inputs, reduceAIState };
@@ -112,13 +112,19 @@ type SessionClient<D extends EventDefs, S, P extends PresenceDefs = Record<never
112
112
  * this throws a TypeError there.
113
113
  */
114
114
  loadHistory(options?: LoadHistoryOptions): Promise<ContractEvent<D>[]>;
115
- /** Open the live stream (idempotent while open). Reconnects with
116
- * backoff and resumes from the frontier until `close()`. */
117
- connect(): void;
118
115
  /**
119
- * Stop the live stream. Not terminal: `connect()` starts it again
120
- * from the current frontier which is what makes the React
121
- * StrictMode mount dance (setup cleanup setup) work.
116
+ * Take a lease on the live stream and return its release. Leases
117
+ * refcount per handlethe first connects, releasing the last
118
+ * closes so independent consumers of one identity-mapped handle
119
+ * (two hooks, a hook plus vanilla code) never fight over the
120
+ * stream. Releasing twice is a no-op. While any lease is held the
121
+ * stream reconnects with backoff and resumes from the frontier.
122
+ */
123
+ connect(): () => void;
124
+ /**
125
+ * The hard stop: drops every outstanding lease and closes the
126
+ * stream now. Not terminal — a later `connect()` starts fresh from
127
+ * the current frontier.
122
128
  */
123
129
  close(): void;
124
130
  };
@@ -127,11 +133,8 @@ type SessionOptions<D extends EventDefs, S> = {
127
133
  initialIndex?: number;
128
134
  /** Server-rendered history through `initialIndex`. Seeds the event feed. */
129
135
  initialEvents?: ContractEvent<D>[];
130
- /**
131
- * This client's presence identity — required to call `setPresence`.
132
- * Caller-supplied (a user id, a tab nonce, a guest name): A2 does
133
- * not invent an identity story. Bound once per session handle.
134
- */
136
+ /** Overrides the client's `participant` for this session handle.
137
+ * Bound once per handle. */
135
138
  participant?: string;
136
139
  };
137
140
  type A2Client<D extends EventDefs, S, P extends PresenceDefs = Record<never, never>> = {
@@ -184,8 +187,16 @@ type CreateClientOptions<D extends EventDefs, S, P extends PresenceDefs = Record
184
187
  /** How long an idle session keeps its in-memory identity, in
185
188
  * milliseconds. Defaults to five minutes; `Infinity` disables GC. */
186
189
  gcTime?: number;
190
+ /**
191
+ * This client's presence identity — required to call `setPresence`.
192
+ * Caller-supplied (a user id, a tab nonce, a guest name): A2 does
193
+ * not invent an identity story; the app states it once here. The
194
+ * default for every session handle this client creates;
195
+ * `session(id, { participant })` overrides it per handle.
196
+ */
197
+ participant?: string;
187
198
  };
188
199
  declare function createClient<D extends EventDefs, S, P extends PresenceDefs = Record<never, never>>(options: CreateClientOptions<D, S, P>): A2Client<D, S, P>;
189
200
  //#endregion
190
201
  export { Connection as a, HistoryState as c, SessionClient as d, SessionClientPresence as f, createClient as h, ClientWebSocketConstructor as i, LoadHistoryOptions as l, SessionSnapshot as m, ClientApi as n, ConnectionStatus as o, SessionOptions as p, ClientWebSocket as r, CreateClientOptions as s, A2Client as t, PushResult as u };
191
- //# sourceMappingURL=client-D7mvIXrF.d.ts.map
202
+ //# sourceMappingURL=client-CdMqi7mC.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-CdMqi7mC.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;KAoDY;;;;;;;KAQA;EACN;;EAEA;;EAEA;;EAEA,OAAO;;EAEP;EAAgB;;EAChB;;;;;;;;;;KAUM,WAAW,UAAU,aAAa,QAAQ,cAAc;WACzD,WAAW,QAAQ,cAAc;;KAGhC;;;;;;EAMV;;EAEA;;;KAIU;;EAEV;;EAEA;;EAEA;;;KAIU,gBACV,UAAU,WACV,GACA,UAAU,eAAe,wBACvB,aACF;;EAGE,UAAU,YAAY;;;EAIxB,OAAO;;;;;EAKP,QAAQ,cAAc;;;EAGtB;;EAEA,SAAS;EACT,YAAY;;;;;;;KAQF,sBAAsB,UAAU;;;;;;;;;;EAU1C,YAAY,QAAQ,cAAc;;KAGxB,cACV,UAAU,WACV,GACA,UAAU,eAAe,wBACvB,aAAa,GAAG,sBAAsB;WAC/B;EACT,UAAU;EACV,eAAe,gBAAgB,GAAG,GAAG;;;;;;;;;;EAUrC,QAAQ,QAAQ,YAAY,OAAO,WAAW;;;;;;;;;;;EAW9C,YAAY,UAAU,qBAAqB,QAAQ,cAAc;;;;;;;;;EASjE;;;;;;EAMA;;KAGU,eAAe,UAAU,WAAW;EAC9C,eAAe;EACf;;EAEA,gBAAgB,cAAc;;;EAG9B;;KAGU,SACV,UAAU,WACV,GACA,UAAU,eAAe;EAEzB,QACE,mBACA,UAAU,eAAe,GAAG,KAC3B,cAAc,GAAG,GAAG;;;;;;;;;KAUb;EAEN;EAAc;EAAc;;EAC5B;EAAY;;;;;;;KAON;WACD;EACT,KAAK;EACL,MAAM,eAAe;EACrB,iBAAiB,cAAc;EAC/B,iBACE,iBACA,WAAW;IAAS;;EAEtB,iBACE,eACA,WAAW;IAAS;IAAc;;EAEpC,iBAAiB,eAAe;;KAGtB,kCAAkC,gBAAgB;KAElD,oBACV,UAAU,WACV,GACA,UAAU,eAAe;EAEzB,SAAS,QAAQ,GAAG,GAAG;;EAEvB,KAAK;;EAEL,eAAe,WAAW;;;EAG1B,YAAY;;;EAGZ;;;;;;;;EAQA;;iBAirBc,aACd,UAAU,WACV,GACA,UAAU,eAAe,sBACzB,SAAS,oBAAoB,GAAG,GAAG,KAAK,SAAS,GAAG,GAAG"}
@@ -454,7 +454,7 @@ function createClient(options) {
454
454
  let foldedState = sessionOptions?.initialState !== void 0 ? sessionOptions.initialState : reducer.initialState;
455
455
  const serverEvents = (sessionOptions?.initialEvents ?? []).filter((event) => event.index <= frontier).toSorted((a, b) => a.index - b.index);
456
456
  let pending = [];
457
- let participant = sessionOptions?.participant;
457
+ let participant = sessionOptions?.participant ?? options.participant;
458
458
  let presenceState = nullProtoRecord();
459
459
  let presenceLastSentAt = 0;
460
460
  /** The last LWW stamp issued — see `nextPresenceAt`. */
@@ -655,7 +655,7 @@ function createClient(options) {
655
655
  presenceTimer.unref?.();
656
656
  };
657
657
  const setPresence = (values) => {
658
- if (participant === void 0) throw new TypeError("setPresence requires a participant — pass one in the session options (the SessionProvider participant prop)");
658
+ if (participant === void 0) throw new TypeError("setPresence requires a participant — pass one to createClient({ participant }) or in the session options (the SessionProvider/useSession participant prop)");
659
659
  const validated = nullProtoRecord();
660
660
  for (const [field, value] of Object.entries(values)) {
661
661
  if (value === void 0) continue;
@@ -854,6 +854,21 @@ function createClient(options) {
854
854
  let generation = 0;
855
855
  let active = false;
856
856
  let abort = null;
857
+ let leases = 0;
858
+ let leaseEpoch = 0;
859
+ const stopStream = () => {
860
+ touch(sessionId);
861
+ if (!active) return;
862
+ active = false;
863
+ generation += 1;
864
+ abort?.abort();
865
+ abort = null;
866
+ clearTimeout(presenceTimer);
867
+ presenceTimer = void 0;
868
+ presenceBuffer = null;
869
+ status = "closed";
870
+ notify();
871
+ };
857
872
  const runStream = async (run) => {
858
873
  let backoff = STREAM_TIMINGS.reconnectBaseMs;
859
874
  while (generation === run) {
@@ -939,24 +954,27 @@ function createClient(options) {
939
954
  loadHistory,
940
955
  connect() {
941
956
  touch(sessionId);
942
- if (active) return;
943
- active = true;
944
- status = "connecting";
945
- notify();
946
- runStream(generation);
957
+ leases += 1;
958
+ const epoch = leaseEpoch;
959
+ if (!active) {
960
+ active = true;
961
+ status = "connecting";
962
+ notify();
963
+ runStream(generation);
964
+ }
965
+ let released = false;
966
+ return () => {
967
+ if (released || leaseEpoch !== epoch) return;
968
+ released = true;
969
+ touch(sessionId);
970
+ leases -= 1;
971
+ if (leases === 0) stopStream();
972
+ };
947
973
  },
948
974
  close() {
949
- touch(sessionId);
950
- if (!active) return;
951
- active = false;
952
- generation += 1;
953
- abort?.abort();
954
- abort = null;
955
- clearTimeout(presenceTimer);
956
- presenceTimer = void 0;
957
- presenceBuffer = null;
958
- status = "closed";
959
- notify();
975
+ leases = 0;
976
+ leaseEpoch += 1;
977
+ stopStream();
960
978
  },
961
979
  hydrate(next) {
962
980
  touch(sessionId);
@@ -1005,4 +1023,4 @@ function createClient(options) {
1005
1023
  //#endregion
1006
1024
  export { createClient as t };
1007
1025
 
1008
- //# sourceMappingURL=client-BKlyLiOU.js.map
1026
+ //# sourceMappingURL=client-Dj5d3SP_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-Dj5d3SP_.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\n * experimental-a2/client — the framework-agnostic session client.\n *\n * Everything the browser needs to read a session live and push\n * optimistically, with no framework attached: the SSE subscription with\n * frontier resume and reconnection, the optimistic push queue with\n * ack/rollback, and the local fold through the same reducer the server\n * uses. `experimental-a2/react`'s `createReact` is a thin binding over it, and the\n * store contract (`subscribe`/`getSnapshot`) is exactly what\n * `useSyncExternalStore` wants.\n *\n * The client is a replica, never an access path — the routes it talks\n * to authorize every read and write.\n */\n\n// oxlint-disable no-await-in-loop -- retry/backoff/stream loops are sequential by nature\nimport { A2Error } from './errors.ts'\nimport {\n PRESENCE_TIMINGS,\n STREAM_TIMINGS,\n nullProtoRecord,\n} from './internal.ts'\nimport type {\n AppendInput,\n ContractEvent,\n EventDefs,\n PresenceDefs,\n PresenceMap,\n PresencePatch,\n WithPresence,\n} from './contract.ts'\nimport type { Reducer } from './reducer.ts'\nimport { validateSync } from './validate.ts'\nimport {\n errorFromWire,\n eventFromWire,\n isWireEvent,\n isWirePresencePatch,\n isWirePresenceSnapshot,\n parseSocketFrame,\n presencePatchFromWire,\n presenceSnapshotFromWire,\n type SocketDownFrame,\n type SocketPresenceFrame,\n type SocketPushFrame,\n type SocketSubscribeFrame,\n type SocketUnsubscribeFrame,\n type WireEvent,\n type WirePresencePatch,\n type WirePresenceSnapshot,\n} from './wire.ts'\n\nexport type ConnectionStatus = 'idle' | 'connecting' | 'live' | 'closed'\n\n/**\n * The connection, as a discriminated union — impossible states are\n * unrepresentable: an error only exists while disconnected,\n * `reconnects` only once a connection has been attempted.\n * \"Reconnecting…\" is `status === 'connecting' && reconnects > 0`.\n */\nexport type Connection =\n | { status: 'idle' }\n | {\n status: 'connecting'\n /** Drops of an established stream so far. `0` = first connect. */\n reconnects: number\n /** Why the last connection ended; `null` on the first connect. */\n error: Error | null\n }\n | { status: 'live'; reconnects: number }\n | { status: 'closed' }\n\n/**\n * What `push` returns: resolves at the server ack (exactly like a\n * plain promise — `await push(...)` gives the acked events), and\n * carries `confirmed` for the later moment when the live stream has\n * delivered the whole batch back and the optimistic overlay entry\n * retired — the view now shows server truth. `confirmed` is lazy:\n * never accessed, never created. A rejected push rejects both.\n */\nexport type PushResult<D extends EventDefs> = Promise<ContractEvent<D>[]> & {\n readonly confirmed: Promise<ContractEvent<D>[]>\n}\n\nexport type LoadHistoryOptions = {\n /**\n * Exclusive upper bound for the fetch. Defaults to the oldest\n * already-loaded index — successive calls page backward — or one\n * past the hydration frontier while nothing is loaded yet.\n */\n before?: number\n /** Page size; defaults to 50. */\n limit?: number\n}\n\n/** Backscroll progress, derived from the raw event feed. */\nexport type HistoryState = {\n /** A `loadHistory` fetch is in flight. */\n loading: boolean\n /** The feed reaches index 1 — nothing older remains to fetch. */\n complete: boolean\n /** The oldest loaded index; `null` while nothing is loaded. */\n oldestLoaded: number | null\n}\n\n/** One immutable view of the session — stable identity between changes. */\nexport type SessionSnapshot<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = WithPresence<\n P,\n {\n /** The replicated presence map, this client included (local echo). */\n presence: PresenceMap<P>\n }\n> & {\n /** The live view: server events folded, optimistic pushes applied. */\n state: S\n /** The raw event feed: server truth — observed, seeded, or\n * backscrolled via `loadHistory` — plus pending optimistic events\n * (provisional indexes past the frontier). `state` never folds\n * backscrolled events; they are display data below the frontier. */\n events: ContractEvent<D>[]\n /** The stream frontier: the last server-confirmed index. This is the\n * `lastSeenIndex` cancellation wants. */\n index: number\n /** Backscroll progress — `loadHistory` moves it. */\n history: HistoryState\n connection: Connection\n}\n\n/**\n * The presence member of a client session — intersected in via\n * `WithPresence`, so it exists exactly when the contract declares\n * presence fields.\n */\nexport type SessionClientPresence<P extends PresenceDefs> = {\n /**\n * Fire-and-forget presence: validates locally against the reducer's\n * presence schemas, merges into the local map immediately (the\n * echo), and coalesces on the wire to a fixed cadence — a leading\n * send immediately, then at most one merged send per interval,\n * later values winning field-wise. `null` clears a field. No ack,\n * no retry, no rollback: a lost patch is repainted by the next one.\n * Requires the session's `participant`.\n */\n setPresence(values: PresencePatch<P>['values']): void\n}\n\nexport type SessionClient<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = WithPresence<P, SessionClientPresence<P>> & {\n readonly sessionId: string\n subscribe(listener: () => void): () => void\n getSnapshot(): SessionSnapshot<D, S, P>\n /**\n * Optimistic append: validates locally against the reducer's event\n * schemas (instant `INVALID_PAYLOAD`, no flicker), applies to the\n * local fold, POSTs, swaps in the ack, rolls back on rejection.\n * Auto-retries only `STORE_UNAVAILABLE`. Resolves with the appended\n * events as the server recorded them. Overlapping calls on this\n * handle enter the transport in invocation order without delaying\n * their optimistic folds.\n */\n push(...events: AppendInput<D>[]): PushResult<D>\n /**\n * Backscroll: fetch a bounded slice of events from below the\n * frontier and merge it into `events` — deduped, ordered, shared by\n * every handle of this session. Folded state and the optimistic\n * overlay are never touched. Calls serialize per session and skip\n * already-loaded ranges, so overlapping backscrolls never fetch the\n * same range twice. Resolves with the events in the requested range.\n * Requires an http api; the `ws` transport has no history lane and\n * this throws a TypeError there.\n */\n loadHistory(options?: LoadHistoryOptions): Promise<ContractEvent<D>[]>\n /**\n * Take a lease on the live stream and return its release. Leases\n * refcount per handle — the first connects, releasing the last\n * closes — so independent consumers of one identity-mapped handle\n * (two hooks, a hook plus vanilla code) never fight over the\n * stream. Releasing twice is a no-op. While any lease is held the\n * stream reconnects with backoff and resumes from the frontier.\n */\n connect(): () => void\n /**\n * The hard stop: drops every outstanding lease and closes the\n * stream now. Not terminal — a later `connect()` starts fresh from\n * the current frontier.\n */\n close(): void\n}\n\nexport type SessionOptions<D extends EventDefs, S> = {\n initialState?: S\n initialIndex?: number\n /** Server-rendered history through `initialIndex`. Seeds the event feed. */\n initialEvents?: ContractEvent<D>[]\n /** Overrides the client's `participant` for this session handle.\n * Bound once per handle. */\n participant?: string\n}\n\nexport type A2Client<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = {\n session(\n sessionId: string,\n options?: SessionOptions<D, S>,\n ): SessionClient<D, S, P>\n}\n\n/**\n * The wire the client rides. The string form is one route serving GET\n * (SSE stream) + POST (push). `http` splits the verbs across two\n * routes, for when platform duration limits differ per verb. `ws`\n * rides everything — every session of this client — over one\n * multiplexed WebSocket, served by `sessionsSocket`.\n */\nexport type ClientApi =\n | string // one route: GET SSE stream + POST push\n | { type: 'http'; push: string; stream: string } // split routes\n | { type: 'ws'; url: string } // one socket, all sessions, both directions\n\n/**\n * The socket surface the `ws` transport drives — satisfied structurally\n * by the DOM `WebSocket` and Node's alike, and small enough to fake in\n * tests.\n */\nexport type ClientWebSocket = {\n readonly readyState: number\n send(data: string): void\n close(code?: number, reason?: string): void\n addEventListener(type: 'open', listener: () => void): void\n addEventListener(\n type: 'message',\n listener: (event: { data: unknown }) => void,\n ): void\n addEventListener(\n type: 'close',\n listener: (event: { code: number; reason: string }) => void,\n ): void\n addEventListener(type: 'error', listener: () => void): void\n}\n\nexport type ClientWebSocketConstructor = new (url: string) => ClientWebSocket\n\nexport type CreateClientOptions<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n> = {\n reducer: Reducer<D, S, P>\n /** The route (or routes) the client speaks — see `ClientApi`. */\n api: ClientApi\n /** Injectable fetch — defaults to the global. */\n fetch?: typeof globalThis.fetch\n /** Injectable WebSocket constructor for the `ws` api — defaults to\n * the global. The http transports never touch it. */\n webSocket?: ClientWebSocketConstructor\n /** How long an idle session keeps its in-memory identity, in\n * milliseconds. Defaults to five minutes; `Infinity` disables GC. */\n gcTime?: number\n /**\n * This client's presence identity — required to call `setPresence`.\n * Caller-supplied (a user id, a tab nonce, a guest name): A2 does\n * not invent an identity story; the app states it once here. The\n * default for every session handle this client creates;\n * `session(id, { participant })` overrides it per handle.\n */\n participant?: string\n}\n\nconst PUSH_ATTEMPTS = 3\nconst DEFAULT_GC_TIME_MS = 5 * 60 * 1_000\nconst DEFAULT_HISTORY_LIMIT = 50\n\n// ── the transport seam ───────────────────────────────────────────────\n// Everything above it — optimistic queue, retry loop, presence\n// throttle, reconnect/backoff, stall watchdog — is transport-agnostic.\n\n/** The parsed frame lanes every transport yields: the SSE frame\n * discrimination today, the ws `kind` discriminant tomorrow. `ping`\n * carries no data — it exists so the watchdog sees liveness. */\ntype TransportFrame =\n | { kind: 'event'; event: WireEvent }\n | { kind: 'presence'; patch: WirePresencePatch }\n | { kind: 'presence-snapshot'; snapshot: WirePresenceSnapshot }\n | { kind: 'ping' }\n\ntype TransportPushBody = {\n sessionId: string\n events: Array<{ id: string; type: string; payload: unknown }>\n}\n\ntype TransportPresenceEnvelope = {\n sessionId: string\n presence: {\n participant: string\n values: Record<string, unknown>\n seen: number\n at: number\n }\n}\n\ntype Transport = {\n /**\n * One live read: the first frame means the stream is established\n * (any kind — a bare `ping` when no data is pending), the iterable\n * ending or throwing is the disconnect. The caller owns\n * reconnect/backoff and counts every frame as liveness.\n */\n connect(opts: {\n sessionId: string\n startAfter: number\n signal: AbortSignal\n }): AsyncIterable<TransportFrame>\n /** One attempt (the retry loop lives above the seam): resolves with\n * the acked wire events, throws the wire-deserialized A2Error. */\n push(body: TransportPushBody): Promise<WireEvent[]>\n /** One bounded cold read of the log, oldest first — the lane\n * `loadHistory` rides. Absent on transports without a\n * request/response wire (ws), where `loadHistory` fails fast. */\n history?(opts: {\n sessionId: string\n gte: number\n lte: number\n }): Promise<WireEvent[]>\n /** Fire-and-forget; failures are dropped (presence repaints). */\n sendPresence(envelope: TransportPresenceEnvelope): void\n /**\n * Resolve when the session's wire can carry a push again, or after\n * `maxWaitMs` — whichever comes first; never rejects. Transports\n * whose pushes are connection-bound (ws) implement it so the retry\n * loop waits for the wire instead of a fixed clock; HTTP pushes are\n * stream-independent and omit it.\n */\n awaitReady?(sessionId: string, maxWaitMs: number): Promise<void>\n}\n\nconst httpTransport = (\n routes: { push: string; stream: string },\n fetchImpl: typeof globalThis.fetch,\n // Contracts that declare no presence skip presence frames unparsed,\n // exactly like unknown named frames.\n presence: boolean,\n): Transport => ({\n async *connect({ sessionId, startAfter, signal }) {\n const sep = routes.stream.includes('?') ? '&' : '?'\n const res = await fetchImpl(\n `${routes.stream}${sep}sessionId=${encodeURIComponent(sessionId)}&index=${startAfter}`,\n { headers: { accept: 'text/event-stream' }, signal },\n )\n if (!res.ok || !res.body) {\n throw new Error(`stream failed with ${res.status}`)\n }\n yield { kind: 'ping' } // connected — headers in hand, before any bytes\n const decoder = new TextDecoder()\n const reader = res.body.getReader()\n let buffer = ''\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- stream read loop\n const { done, value } = await reader.read()\n if (done) return\n // Any bytes count — heartbeat comments included. Liveness is\n // about the connection, not about events.\n yield { kind: 'ping' }\n buffer += decoder.decode(value, { stream: true })\n for (;;) {\n const boundary = buffer.indexOf('\\n\\n')\n if (boundary === -1) break\n const frame = buffer.slice(0, boundary)\n buffer = buffer.slice(boundary + 2)\n let eventName: string | undefined\n const dataLines: string[] = []\n for (const line of frame.split('\\n')) {\n if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart())\n } else if (line.startsWith('event:')) {\n eventName = line.slice(6).trim()\n }\n }\n const data = dataLines.join('\\n')\n if (!data) continue\n if (eventName === undefined) {\n const parsed: unknown = JSON.parse(data)\n if (isWireEvent(parsed)) yield { kind: 'event', event: parsed }\n } else if (presence && eventName === 'presence-snapshot') {\n const parsed: unknown = JSON.parse(data)\n if (isWirePresenceSnapshot(parsed)) {\n yield { kind: 'presence-snapshot', snapshot: parsed }\n }\n } else if (presence && eventName === 'presence') {\n const parsed: unknown = JSON.parse(data)\n if (isWirePresencePatch(parsed)) {\n yield { kind: 'presence', patch: parsed }\n }\n }\n // Other named frames: skipped — old clients stay compatible\n // with future lanes the same way.\n }\n }\n } finally {\n reader.cancel().catch(() => {})\n }\n },\n\n async push(body) {\n const res = await fetchImpl(routes.push, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (res.ok) {\n const rows = (await res.json()) as unknown\n if (!Array.isArray(rows) || !rows.every(isWireEvent)) {\n throw new A2Error(\n 'STORE_UNAVAILABLE',\n 'push ack was not a list of events',\n )\n }\n return rows\n }\n throw (\n errorFromWire(await res.json().catch(() => null)) ??\n new A2Error('STORE_UNAVAILABLE', `push failed with ${res.status}`)\n )\n },\n\n async history({ sessionId, gte, lte }) {\n const sep = routes.stream.includes('?') ? '&' : '?'\n const res = await fetchImpl(\n `${routes.stream}${sep}sessionId=${encodeURIComponent(sessionId)}&gte=${gte}&lte=${lte}`,\n { headers: { accept: 'application/json' } },\n )\n if (!res.ok) {\n throw (\n errorFromWire(await res.json().catch(() => null)) ??\n new A2Error('STORE_UNAVAILABLE', `history failed with ${res.status}`)\n )\n }\n const rows = (await res.json()) as unknown\n if (!Array.isArray(rows) || !rows.every(isWireEvent)) {\n throw new A2Error(\n 'STORE_UNAVAILABLE',\n 'history response was not a list of events',\n )\n }\n return rows\n },\n\n sendPresence(envelope) {\n void (async () => {\n try {\n const res = await fetchImpl(routes.push, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(envelope),\n })\n await res.arrayBuffer()\n } catch {\n // Dropped by design — nothing was ever true.\n }\n })()\n },\n})\n\n/** `WebSocket.OPEN` — fixed by the spec, identical in every runtime. */\nconst WS_OPEN = 1\n\n/** One session's lane on the shared ws socket — created per `connect`\n * attempt, so `startAfter` is that attempt's resume frontier. */\ntype WsChannel = {\n sessionId: string\n startAfter: number\n queue: TransportFrame[]\n /** The server confirmed the subscribe — pushes and presence ride. */\n live: boolean\n /** The server already dropped it — no unsubscribe frame owed. */\n dropped: boolean\n ended: boolean\n failure: Error | null\n wake: (() => void) | null\n}\n\nconst wakeChannel = (channel: WsChannel): void => {\n channel.wake?.()\n channel.wake = null\n}\n\nconst subscribeFrame = (\n sessions: Array<{ id: string; index: number }>,\n): string => {\n const frame: SocketSubscribeFrame = { kind: 'subscribe', sessions }\n return JSON.stringify(frame)\n}\n\nconst wsTransport = (\n url: string,\n webSocketImpl: ClientWebSocketConstructor | undefined,\n presence: boolean,\n): Transport => {\n type PendingAck = {\n resolve: (events: WireEvent[]) => void\n reject: (error: A2Error) => void\n }\n // ONE socket serves every session of this client (specs §13's\n // multiplexed superset): channels subscribe on it at their own\n // frontiers, down frames route back by sessionId, acks by req.\n const channels = new Map<string, WsChannel>()\n const pending = new Map<number, PendingAck>()\n /** Push retries parked in `awaitReady`, flushed per session on its\n * subscribe confirmation. */\n const readyWaiters = new Map<string, Set<() => void>>()\n let socket: ClientWebSocket | null = null\n let socketOpen = false\n let watchdog: ReturnType<typeof setTimeout> | undefined\n let nextReq = 1\n\n const flushReadyWaiters = (sessionId: string): void => {\n const waiters = readyWaiters.get(sessionId)\n if (!waiters) return\n readyWaiters.delete(sessionId)\n for (const waiter of waiters) waiter()\n }\n\n const socketUrl = (): string => {\n let resolved: URL\n if (/^(https?|wss?):\\/\\//i.test(url)) {\n resolved = new URL(url)\n } else {\n // A relative url resolves against the page, exactly like fetch.\n // Outside a browser (SSR, tests) there is nothing to resolve\n // against — demand an absolute url there.\n const base = (globalThis as { location?: { href: string } }).location\n ?.href\n if (base === undefined) {\n throw new TypeError(\n `cannot resolve the relative ws url '${url}' without a browser location — pass an absolute ws:// or wss:// url`,\n )\n }\n resolved = new URL(url, base)\n }\n if (resolved.protocol === 'http:') resolved.protocol = 'ws:'\n else if (resolved.protocol === 'https:') resolved.protocol = 'wss:'\n return resolved.href\n }\n\n const trySend = (data: string): void => {\n if (socket === null || !socketOpen) return\n try {\n socket.send(data)\n } catch {\n // Dropped — the socket is going down and its close event settles\n // everything that depended on this frame.\n }\n }\n\n const deliver = (channel: WsChannel, frame: TransportFrame): void => {\n channel.queue.push(frame)\n wakeChannel(channel)\n }\n\n const settleChannel = (channel: WsChannel, failure: Error | null): void => {\n if (channel.ended) return\n channel.ended = true\n channel.failure = failure\n wakeChannel(channel)\n }\n\n // Unhook the socket from the transport state and reject every\n // outstanding ack — nothing was acked, and the client-generated ids\n // make the retries idempotent (§13).\n const releaseSocket = (): ClientWebSocket | null => {\n const current = socket\n socket = null\n socketOpen = false\n clearTimeout(watchdog)\n watchdog = undefined\n if (pending.size > 0) {\n const rejection = new A2Error(\n 'STORE_UNAVAILABLE',\n 'socket closed with the ack outstanding',\n )\n for (const waiter of pending.values()) waiter.reject(rejection)\n pending.clear()\n }\n return current\n }\n\n // Idempotent from every direction (close event, error event, stall):\n // every channel ends — each session's reconnect loop re-subscribes at\n // its own current frontier.\n const failSocket = (failure: Error | null): void => {\n const current = releaseSocket()\n for (const channel of channels.values()) settleChannel(channel, failure)\n try {\n current?.close(1000)\n } catch {\n // Already closed — it is down either way.\n }\n }\n\n const detach = (channel: WsChannel): void => {\n if (channels.get(channel.sessionId) !== channel) return\n channels.delete(channel.sessionId)\n if (!channel.dropped) {\n const frame: SocketUnsubscribeFrame = {\n kind: 'unsubscribe',\n sessions: [channel.sessionId],\n }\n trySend(JSON.stringify(frame))\n }\n if (channels.size === 0) {\n // The last session left — the shared socket has no reason to live.\n const current = releaseSocket()\n try {\n current?.close(1000)\n } catch {\n // Already closed — it is down either way.\n }\n }\n }\n\n // One heartbeat watchdog per socket: any frame is liveness, and\n // silence past the stall timeout means the connection is dead in a\n // way the socket won't report.\n const armWatchdog = (created: ClientWebSocket): void => {\n clearTimeout(watchdog)\n watchdog = setTimeout(() => {\n if (socket !== created) return\n failSocket(\n new Error(\n `socket stalled: no data for ${STREAM_TIMINGS.stallTimeoutMs}ms`,\n ),\n )\n }, STREAM_TIMINGS.stallTimeoutMs)\n ;(watchdog as { unref?: () => void }).unref?.()\n }\n\n const route = (frame: SocketDownFrame): void => {\n switch (frame.kind) {\n case 'ping': {\n // Global liveness — every live channel's stall watchdog feeds\n // on it, the way each SSE stream feeds on its own heartbeat.\n for (const channel of channels.values()) {\n if (channel.live && !channel.ended) {\n deliver(channel, { kind: 'ping' })\n }\n }\n return\n }\n case 'subscribed': {\n const channel = channels.get(frame.sessionId)\n if (channel === undefined || channel.ended || channel.live) return\n channel.live = true\n deliver(channel, { kind: 'ping' }) // the connected signal\n flushReadyWaiters(frame.sessionId)\n return\n }\n case 'unsubscribed': {\n const channel = channels.get(frame.sessionId)\n if (channel === undefined) return\n channel.dropped = true\n settleChannel(\n channel,\n frame.reason === undefined ? null : new Error(frame.reason),\n )\n return\n }\n case 'ack': {\n const waiter = pending.get(frame.req)\n if (waiter === undefined) return\n pending.delete(frame.req)\n if ('events' in frame) waiter.resolve(frame.events)\n else waiter.reject(frame.error)\n return\n }\n case 'event': {\n // Pre-confirmation frames are safe to drop: the subscription\n // being confirmed replays from this channel's own frontier.\n const channel = channels.get(frame.event.sessionId)\n if (channel !== undefined && channel.live && !channel.ended) {\n deliver(channel, { kind: 'event', event: frame.event })\n }\n return\n }\n case 'presence': {\n // Contracts that declare no presence skip presence frames,\n // exactly like the http transport.\n if (!presence || frame.sessionId === undefined) return\n const channel = channels.get(frame.sessionId)\n if (channel !== undefined && channel.live && !channel.ended) {\n deliver(channel, { kind: 'presence', patch: frame.patch })\n }\n return\n }\n case 'presence-snapshot': {\n if (!presence || frame.sessionId === undefined) return\n const channel = channels.get(frame.sessionId)\n if (channel !== undefined && channel.live && !channel.ended) {\n deliver(channel, {\n kind: 'presence-snapshot',\n snapshot: frame.snapshot,\n })\n }\n return\n }\n }\n }\n\n const ensureSocket = (): void => {\n if (socket !== null) return\n if (webSocketImpl === undefined) {\n throw new TypeError(\n 'no WebSocket implementation available — pass one via createClient({ webSocket }) where the global is missing',\n )\n }\n const created = new webSocketImpl(socketUrl())\n socket = created\n socketOpen = false\n armWatchdog(created)\n created.addEventListener('open', () => {\n if (socket !== created) return\n socketOpen = true\n armWatchdog(created)\n const sessions = [...channels.values()]\n .filter((channel) => !channel.ended)\n .map((channel) => ({\n id: channel.sessionId,\n index: channel.startAfter,\n }))\n if (sessions.length > 0) trySend(subscribeFrame(sessions))\n })\n created.addEventListener('message', (event) => {\n if (socket !== created) return\n if (typeof event.data !== 'string') return\n armWatchdog(created)\n const frame = parseSocketFrame(event.data)\n if (frame === null) return\n route(frame)\n })\n created.addEventListener('close', (event) => {\n if (socket !== created) return\n failSocket(\n event.code === 1000\n ? null // deliberate server close — reconnect, but not an error\n : new Error(\n `socket closed (${event.code}${event.reason ? `: ${event.reason}` : ''})`,\n ),\n )\n })\n created.addEventListener('error', () => {\n if (socket !== created) return\n failSocket(new Error('socket error'))\n })\n }\n\n return {\n async *connect({ sessionId, startAfter, signal }) {\n const channel: WsChannel = {\n sessionId,\n startAfter,\n queue: [],\n live: false,\n dropped: false,\n ended: false,\n failure: null,\n wake: null,\n }\n channels.set(sessionId, channel)\n try {\n ensureSocket()\n if (socketOpen) {\n trySend(subscribeFrame([{ id: sessionId, index: startAfter }]))\n }\n } catch (error) {\n if (channels.get(sessionId) === channel) channels.delete(sessionId)\n throw error\n }\n\n const onAbort = (): void => {\n settleChannel(\n channel,\n signal.reason instanceof Error\n ? signal.reason\n : new Error('stream aborted'),\n )\n // Synchronously, not from the pump's finally: the watchdog and\n // close() must not leave a dead subscription behind.\n detach(channel)\n }\n if (signal.aborted) onAbort()\n else signal.addEventListener('abort', onAbort, { once: true })\n\n // An unconfirmed subscribe receives no frames at all (global\n // pings only feed live channels), so a server that never answers\n // — a single-session route, say — would hang this session\n // silently. Fail it loudly instead; the reconnect loop retries.\n const pendingSubscribe = setTimeout(() => {\n if (channel.live) return\n settleChannel(\n channel,\n new Error(\n 'subscribe not confirmed: is the ws route serving the multiplexed socket (handle with options.upgrade)?',\n ),\n )\n }, STREAM_TIMINGS.stallTimeoutMs)\n ;(pendingSubscribe as { unref?: () => void }).unref?.()\n\n try {\n for (;;) {\n while (channel.queue.length > 0) yield channel.queue.shift()!\n if (channel.ended) {\n if (channel.failure) throw channel.failure\n return\n }\n // oxlint-disable-next-line no-await-in-loop -- frame pump\n await new Promise<void>((resolve) => {\n channel.wake = resolve\n })\n }\n } finally {\n clearTimeout(pendingSubscribe)\n signal.removeEventListener('abort', onAbort)\n settleChannel(channel, null)\n detach(channel)\n }\n },\n\n async push(body) {\n const channel = channels.get(body.sessionId)\n const target = socket\n if (\n channel === undefined ||\n !channel.live ||\n channel.ended ||\n target === null ||\n !socketOpen ||\n target.readyState !== WS_OPEN\n ) {\n // Retryable by contract: the reconnect loop restores the\n // socket and the retry rides the same event ids.\n throw new A2Error('STORE_UNAVAILABLE', 'no open socket for the session')\n }\n const req = nextReq\n nextReq += 1\n return await new Promise<WireEvent[]>((resolve, reject) => {\n pending.set(req, { resolve, reject })\n const frame: SocketPushFrame = {\n kind: 'push',\n req,\n sessionId: body.sessionId,\n events: body.events,\n }\n try {\n target.send(JSON.stringify(frame))\n } catch (cause) {\n pending.delete(req)\n reject(\n new A2Error('STORE_UNAVAILABLE', 'socket send failed', { cause }),\n )\n }\n })\n },\n\n awaitReady(sessionId, maxWaitMs) {\n const channel = channels.get(sessionId)\n if (\n channel !== undefined &&\n channel.live &&\n !channel.ended &&\n socketOpen\n ) {\n return Promise.resolve()\n }\n return new Promise((resolve) => {\n let waiters = readyWaiters.get(sessionId)\n if (!waiters) {\n waiters = new Set()\n readyWaiters.set(sessionId, waiters)\n }\n let settled = false\n const done = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n waiters.delete(done)\n if (waiters.size === 0) readyWaiters.delete(sessionId)\n // oxlint-disable-next-line promise/no-multiple-resolved -- `settled` guards the two callers (timer, open flush); the rule cannot see through the flag\n resolve()\n }\n // The cap keeps a session nobody reconnects (write-only usage,\n // an unreachable server) from parking a push forever — the\n // attempt then fails fast and the loop moves on.\n const timer = setTimeout(done, maxWaitMs)\n ;(timer as { unref?: () => void }).unref?.()\n waiters.add(done)\n })\n },\n sendPresence(envelope) {\n const channel = channels.get(envelope.sessionId)\n if (channel === undefined || !channel.live || channel.ended) {\n return // dropped by design — the reconnect re-send covers the gap\n }\n const frame: SocketPresenceFrame = {\n kind: 'presence',\n sessionId: envelope.sessionId,\n ...envelope.presence,\n }\n trySend(JSON.stringify(frame))\n },\n }\n}\n\nconst transportFor = (\n api: ClientApi,\n fetchImpl: typeof globalThis.fetch,\n webSocketImpl: ClientWebSocketConstructor | undefined,\n presence: boolean,\n): Transport => {\n if (typeof api === 'string') {\n return httpTransport({ push: api, stream: api }, fetchImpl, presence)\n }\n if (api.type === 'http') {\n return httpTransport(\n { push: api.push, stream: api.stream },\n fetchImpl,\n presence,\n )\n }\n return wsTransport(api.url, webSocketImpl, presence)\n}\n\ntype Pending<D extends EventDefs> = {\n id: string\n type: string\n payload: unknown\n createdAt: Date\n /** Set once the POST ack returns; the entry leaves the overlay when\n * the stream delivers its index. */\n acked?: ContractEvent<D>\n}\n\ntype SessionRuntime<\n D extends EventDefs,\n S,\n P extends PresenceDefs,\n> = SessionClient<D, S, P> & {\n hydrate(options?: SessionOptions<D, S>): void\n canEvict(): boolean\n}\n\ntype CachedSession<D extends EventDefs, S, P extends PresenceDefs> = {\n runtime: SessionRuntime<D, S, P>\n timer?: ReturnType<typeof setTimeout>\n}\n\nexport function createClient<\n D extends EventDefs,\n S,\n P extends PresenceDefs = Record<never, never>,\n>(options: CreateClientOptions<D, S, P>): A2Client<D, S, P> {\n const { reducer, api } = options\n const presenceDefs: Readonly<PresenceDefs> = reducer.presence\n const declaresPresence = Object.keys(presenceDefs).length > 0\n const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis)\n const webSocketImpl =\n options.webSocket ??\n (globalThis as { WebSocket?: ClientWebSocketConstructor }).WebSocket\n const transport = transportFor(\n api,\n fetchImpl,\n webSocketImpl,\n declaresPresence,\n )\n const gcTime = options.gcTime ?? DEFAULT_GC_TIME_MS\n if (Number.isNaN(gcTime) || gcTime < 0) {\n throw new RangeError('gcTime must be a non-negative number or Infinity')\n }\n const sessions = new Map<string, CachedSession<D, S, P>>()\n\n const scheduleGc = (sessionId: string, delay = gcTime): void => {\n const entry = sessions.get(sessionId)\n if (!entry) return\n clearTimeout(entry.timer)\n if (gcTime === Infinity) return\n entry.timer = setTimeout(() => {\n const current = sessions.get(sessionId)\n if (current !== entry) return\n if (entry.runtime.canEvict()) {\n sessions.delete(sessionId)\n return\n }\n // `gcTime: 0` is useful for tests and explicit no-cache clients,\n // but must not spin while a session is mounted or a push is in flight.\n scheduleGc(sessionId, Math.max(gcTime, 1_000))\n }, delay)\n ;(entry.timer as { unref?: () => void }).unref?.()\n }\n\n const touch = (sessionId: string): void => {\n scheduleGc(sessionId)\n }\n\n const makeSession = (\n sessionId: string,\n sessionOptions?: SessionOptions<D, S>,\n ): SessionRuntime<D, S, P> => {\n // ── server truth ─────────────────────────────────────────────\n let frontier = sessionOptions?.initialIndex ?? 0\n let foldedState: S =\n sessionOptions?.initialState !== undefined\n ? sessionOptions.initialState\n : reducer.initialState\n const serverEvents: ContractEvent<D>[] = (\n sessionOptions?.initialEvents ?? []\n )\n .filter((event) => event.index <= frontier)\n .toSorted((a, b) => a.index - b.index)\n\n // ── optimistic overlay ───────────────────────────────────────\n let pending: Pending<D>[] = []\n\n // ── the presence plane ───────────────────────────────────────\n // Never cached, never folded. Foreign entries replicate from the\n // stream; the own entry is the local echo — server copies of self\n // are ignored (the echo is at least as new, and comparing it to\n // server stamps would put two clocks in one order).\n let participant = sessionOptions?.participant ?? options.participant\n // Participant and field keys arrive off the wire, so the map and\n // every entry are built null-prototype — see `nullProtoRecord`.\n let presenceState: PresenceMap = nullProtoRecord()\n let presenceLastSentAt = 0\n /** The last LWW stamp issued — see `nextPresenceAt`. */\n let presenceLastAt = 0\n /** Values awaiting the trailing send — non-null exactly while\n * `presenceTimer` is armed. */\n let presenceBuffer: Record<string, unknown> | null = null\n let presenceTimer: ReturnType<typeof setTimeout> | undefined\n /** Own fields set while the stream was down — re-sent once on\n * reconnect (their POSTs may have been lost with the network). */\n let presenceResend: Record<string, unknown> | null = null\n\n // ── store plumbing ───────────────────────────────────────────\n const listeners = new Set<() => void>()\n let snapshot: SessionSnapshot<D, S> | null = null\n let status: ConnectionStatus = 'idle'\n let reconnects = 0\n let lastError: Error | null = null\n let inFlightPushes = 0\n let pushWireTail: Promise<void> = Promise.resolve()\n let deferredHydration: SessionOptions<D, S> | undefined\n let hydrationNotification: ReturnType<typeof setTimeout> | undefined\n\n const emit = (): void => {\n // copy: a listener may unsubscribe (or subscribe) mid-notify\n // oxlint-disable-next-line no-useless-spread\n for (const listener of [...listeners]) listener()\n }\n\n const notify = (): void => {\n snapshot = null\n emit()\n }\n\n const notifyHydrated = (): void => {\n // `session(id, serverFold)` is also called while a destination\n // provider renders. Its own snapshot must advance synchronously,\n // but notifying an outgoing provider during that render would be a\n // React setState-in-render violation.\n snapshot = null\n clearTimeout(hydrationNotification)\n hydrationNotification = setTimeout(emit, 0)\n ;(hydrationNotification as { unref?: () => void }).unref?.()\n }\n\n const mergeServerEvents = (\n events: ContractEvent<D>[] | undefined,\n throughIndex: number,\n ): boolean => {\n if (!events || events.length === 0) return false\n const byIndex = new Map(serverEvents.map((event) => [event.index, event]))\n let changed = false\n for (const event of events) {\n if (event.index > throughIndex) continue\n const existing = byIndex.get(event.index)\n if (existing?.id === event.id) continue\n byIndex.set(event.index, event)\n changed = true\n }\n if (!changed) return false\n serverEvents.splice(\n 0,\n serverEvents.length,\n ...[...byIndex.values()].toSorted((a, b) => a.index - b.index),\n )\n return true\n }\n\n const overlayEvents = (): ContractEvent<D>[] => {\n // Acked entries first (they have a server-assigned order), then\n // unacked in push order with provisional indexes.\n const acked = pending\n .filter((p) => p.acked)\n .map((p) => p.acked!)\n .toSorted((a, b) => a.index - b.index)\n const maxKnown = acked.at(-1)?.index ?? frontier\n const unacked = pending\n .filter((p) => !p.acked)\n .map(\n (p, i) =>\n ({\n id: p.id,\n type: p.type,\n payload: p.payload,\n index: maxKnown + 1 + i, // provisional\n sessionId,\n createdAt: p.createdAt,\n }) as ContractEvent<D>,\n )\n return [...acked, ...unacked]\n }\n\n const connection = (): Connection => {\n switch (status) {\n case 'idle':\n return { status: 'idle' }\n case 'closed':\n return { status: 'closed' }\n case 'live':\n return { status: 'live', reconnects }\n case 'connecting':\n return { status: 'connecting', reconnects, error: lastError }\n }\n }\n\n const historyState = (): HistoryState => {\n const oldestLoaded = serverEvents[0]?.index ?? null\n return {\n loading: historyLoads > 0,\n // Index 1 loaded — or a frontier of 0, an empty log as far as\n // this client knows — means nothing older is left to fetch.\n complete: oldestLoaded === 1 || frontier === 0,\n oldestLoaded,\n }\n }\n\n const buildSnapshot = (): SessionSnapshot<D, S, P> => {\n const overlay = overlayEvents()\n let state = foldedState\n for (const event of overlay) state = reducer.fold(state, event)\n return {\n state,\n events: [...serverEvents, ...overlay],\n index: frontier,\n history: historyState(),\n connection: connection(),\n ...(declaresPresence\n ? { presence: presenceState as PresenceMap<P> }\n : {}),\n } as SessionSnapshot<D, S, P>\n }\n\n // ── presence ─────────────────────────────────────────────────\n /**\n * The per-session monotonic LWW stamp: wall-seeded, guarded\n * `max(now, last + 1)`, so overlapping sends can never invert —\n * the wall clock seeds it because it is the only monotonic state\n * that survives a reload without A2 owning persistence.\n */\n const nextPresenceAt = (): number => {\n presenceLastAt = Math.max(Date.now(), presenceLastAt + 1)\n return presenceLastAt\n }\n\n // Copy-on-write throughout: snapshots alias `presenceState`, so\n // every change replaces the map and the touched entry instead of\n // mutating them.\n const applyPresencePatch = (patch: PresencePatch): void => {\n if (patch.participant === participant) return // the echo is self truth\n const entry: PresenceMap[string] = Object.assign(\n nullProtoRecord<PresenceMap[string]>(),\n presenceState[patch.participant],\n )\n let changed = false\n for (const [field, value] of Object.entries(patch.values)) {\n if (value === undefined) continue\n const existing = entry[field]\n // Field-wise LWW: an older stamp loses, a tie goes to the wire.\n if (existing && existing.at.getTime() > patch.at.getTime()) continue\n if (value === null) {\n if (existing) {\n delete entry[field]\n changed = true\n }\n } else {\n entry[field] = { value, seen: patch.seen, at: patch.at }\n changed = true\n }\n }\n if (!changed) return\n const next = Object.assign(nullProtoRecord<PresenceMap>(), presenceState)\n if (Object.keys(entry).length === 0) delete next[patch.participant]\n else next[patch.participant] = entry\n presenceState = next\n notify()\n }\n\n const applyPresenceSnapshot = (incoming: PresenceMap): void => {\n const next: PresenceMap = nullProtoRecord()\n for (const [id, fields] of Object.entries(incoming)) {\n if (id === participant) continue\n next[id] = fields\n }\n // Foreign entries replaced wholesale; the own echo survives.\n const own =\n participant === undefined ? undefined : presenceState[participant]\n if (participant !== undefined && own !== undefined)\n next[participant] = own\n presenceState = next\n notify()\n }\n\n const echoPresence = (\n id: string,\n values: Record<string, unknown>,\n atMs: number,\n ): void => {\n const entry: PresenceMap[string] = Object.assign(\n nullProtoRecord<PresenceMap[string]>(),\n presenceState[id],\n )\n const at = new Date(atMs)\n for (const [field, value] of Object.entries(values)) {\n if (value === null) delete entry[field]\n else entry[field] = { value, seen: frontier, at }\n }\n const next = Object.assign(nullProtoRecord<PresenceMap>(), presenceState)\n if (Object.keys(entry).length === 0) delete next[id]\n else next[id] = entry\n presenceState = next\n notify()\n }\n\n // One send, fire-and-forget: no retry, no rollback, failures\n // dropped silently — the next send repaints. Sends are NOT\n // serialized on the ack and may overlap in flight: safe, because\n // merges are LWW by `at` per (participant, field) and one\n // sender's stamps are monotonic. `seen` is the frontier at send\n // time, not at set time; `at` is the sender's monotonic stamp.\n const sendPresence = (\n values: Record<string, unknown>,\n at: number,\n ): void => {\n presenceLastSentAt = Date.now()\n transport.sendPresence({\n sessionId,\n // Every path here starts at setPresence, which requires the\n // participant.\n presence: { participant: participant!, values, seen: frontier, at },\n })\n touch(sessionId)\n }\n\n // The fixed-cadence throttle: a set outside the interval sends on\n // the leading edge; within it, values merge field-wise into one\n // trailing send at the boundary. The cadence never couples to RTT\n // — waiting on the ack served no purpose on this plane and\n // stretched remote motion on slow links.\n const queuePresenceSend = (\n values: Record<string, unknown>,\n at?: number,\n ): void => {\n if (presenceTimer !== undefined) {\n presenceBuffer = { ...presenceBuffer, ...values }\n return\n }\n const wait =\n presenceLastSentAt + PRESENCE_TIMINGS.sendIntervalMs - Date.now()\n if (wait <= 0) {\n sendPresence(values, at ?? nextPresenceAt())\n return\n }\n presenceBuffer = { ...presenceBuffer, ...values }\n presenceTimer = setTimeout(() => {\n presenceTimer = undefined\n const buffered = presenceBuffer\n presenceBuffer = null\n // The trailing send stamps at fire time — always past every\n // stamp its merged values echoed with.\n if (buffered) sendPresence(buffered, nextPresenceAt())\n }, wait)\n ;(presenceTimer as { unref?: () => void }).unref?.()\n }\n\n const setPresence = (values: PresencePatch<P>['values']): void => {\n if (participant === undefined) {\n throw new TypeError(\n 'setPresence requires a participant — pass one to createClient({ participant }) or in the session options (the SessionProvider/useSession participant prop)',\n )\n }\n const validated: Record<string, unknown> = nullProtoRecord()\n for (const [field, value] of Object.entries(values)) {\n if (value === undefined) continue\n const schema = Object.hasOwn(presenceDefs, field)\n ? presenceDefs[field]\n : undefined\n if (!schema) {\n throw new A2Error(\n 'UNKNOWN_PRESENCE_FIELD',\n `no presence field '${field}' in the reducer's vocabulary`,\n )\n }\n if (value === null) {\n validated[field] = null\n continue\n }\n const result = validateSync(schema, value, `presence field '${field}'`)\n if (result.issues) {\n throw new A2Error(\n 'INVALID_PAYLOAD',\n `invalid value for presence field '${field}'`,\n { details: result.issues },\n )\n }\n validated[field] = result.value\n }\n if (Object.keys(validated).length === 0) return\n // One stamp per set: the echo and a leading send share it, so\n // the local map and the wire agree on this write's LWW position.\n const at = nextPresenceAt()\n echoPresence(participant, validated, at)\n if (status !== 'live') {\n presenceResend = { ...presenceResend, ...validated }\n }\n queuePresenceSend(validated, at)\n touch(sessionId)\n }\n\n /** Pushes awaiting stream confirmation — resolved by `ingest` the\n * moment the frontier passes their batch. */\n let confirmWatchers: Array<{ index: number; resolve: () => void }> = []\n\n /** The single ingest point: every server-confirmed event, in log\n * order, from the stream. */\n const ingest = (event: ContractEvent<D>): void => {\n if (event.index <= frontier) return\n frontier = event.index\n serverEvents.push(event)\n foldedState = reducer.fold(foldedState, event)\n pending = pending.filter((p) => p.id !== event.id)\n if (confirmWatchers.some((w) => w.index <= frontier)) {\n const due = confirmWatchers.filter((w) => w.index <= frontier)\n confirmWatchers = confirmWatchers.filter((w) => w.index > frontier)\n for (const watcher of due) watcher.resolve()\n }\n notify()\n touch(sessionId)\n }\n\n // ── push ─────────────────────────────────────────────────────\n const validated = (\n events: AppendInput<D>[],\n ): Array<{ id: string; type: string; payload: unknown }> =>\n events.map((event) => {\n const schema = Object.hasOwn(reducer.events, event.type)\n ? reducer.events[event.type]\n : undefined\n if (!schema) {\n throw new A2Error(\n 'UNKNOWN_EVENT_TYPE',\n `no event type '${String(event.type)}' in the reducer's vocabulary`,\n )\n }\n const result = validateSync(\n schema,\n event.payload,\n `event '${String(event.type)}'`,\n )\n if (result.issues) {\n throw new A2Error(\n 'INVALID_PAYLOAD',\n `invalid payload for event '${String(event.type)}'`,\n { details: result.issues },\n )\n }\n return {\n id: event.id ?? crypto.randomUUID(),\n type: event.type,\n payload: result.value,\n }\n })\n\n const post = async (\n body: TransportPushBody,\n ): Promise<ContractEvent<D>[]> => {\n let lastPushError: A2Error = new A2Error(\n 'STORE_UNAVAILABLE',\n 'push failed',\n )\n for (let attempt = 1; attempt <= PUSH_ATTEMPTS; attempt += 1) {\n try {\n const rows = await transport.push(body)\n return rows.map((row) => eventFromWire(row) as ContractEvent<D>)\n } catch (err) {\n lastPushError =\n err instanceof A2Error\n ? err\n : new A2Error('STORE_UNAVAILABLE', 'push request failed', {\n cause: err,\n })\n }\n // Only the documented retryable code retries; identical ids\n // make the retry idempotent on the server.\n if (lastPushError.code !== 'STORE_UNAVAILABLE') throw lastPushError\n if (attempt < PUSH_ATTEMPTS) {\n const sleepMs = 250 * attempt\n // Wait for the clock AND, when the transport can tell us,\n // the wire. The pacing sleep is a floor: a failure acked\n // over a healthy socket (a shedding store) must not re-fire\n // at wire speed. A push caught in a routine reconnect blip\n // additionally parks until the subscription is confirmed;\n // that cap scales with the reconnect backoff so an\n // unreachable server still exhausts attempts promptly.\n await Promise.all([\n new Promise((resolve) => setTimeout(resolve, sleepMs)),\n transport.awaitReady?.(\n sessionId,\n sleepMs + STREAM_TIMINGS.reconnectBaseMs * attempt,\n ),\n ])\n }\n }\n throw lastPushError\n }\n\n /**\n * Decorate the ack promise into a PushResult. `confirmed` is a\n * lazy getter — materialized on first access, so callers that\n * ignore it can't leak an unhandled rejection.\n */\n const withConfirmed = (ack: Promise<ContractEvent<D>[]>): PushResult<D> => {\n let confirmed: Promise<ContractEvent<D>[]> | undefined\n return Object.defineProperty(ack as PushResult<D>, 'confirmed', {\n get(): Promise<ContractEvent<D>[]> {\n confirmed ??= ack.then(\n (acked) =>\n new Promise<ContractEvent<D>[]>((resolve) => {\n const last = acked.at(-1)?.index ?? 0\n if (frontier >= last) {\n resolve(acked)\n return\n }\n confirmWatchers.push({\n index: last,\n resolve: () => resolve(acked),\n })\n }),\n )\n return confirmed\n },\n })\n }\n\n const push = (...events: AppendInput<D>[]): PushResult<D> => {\n touch(sessionId)\n return withConfirmed(\n (async () => {\n if (events.length === 0) {\n throw new TypeError('push requires at least one event')\n }\n const entries: Pending<D>[] = validated(events).map((e) => ({\n id: e.id,\n type: e.type,\n payload: e.payload,\n createdAt: new Date(),\n }))\n // Reserve before notifying: a subscriber may reenter push(),\n // and that work must follow the call whose state it observed.\n const waitForPriorPush = pushWireTail\n let releasePush!: () => void\n pushWireTail = new Promise<void>((resolve) => {\n releasePush = resolve\n })\n pending.push(...entries)\n inFlightPushes += 1\n\n try {\n notify() // optimistic — the view updates before the network moves\n await waitForPriorPush\n const acked = await post({\n sessionId,\n events: entries.map(({ id, type, payload }) => ({\n id,\n type,\n payload,\n })),\n })\n for (const event of acked) {\n const entry = pending.find((p) => p.id === event.id)\n if (entry) entry.acked = event // stream retires it at its index\n }\n notify()\n return acked\n } catch (err) {\n // Rollback: refold without the rejected events.\n const ids = new Set(entries.map((e) => e.id))\n pending = pending.filter((p) => !ids.has(p.id))\n notify()\n throw err\n } finally {\n releasePush()\n inFlightPushes -= 1\n if (inFlightPushes === 0 && deferredHydration) {\n const next = deferredHydration\n deferredHydration = undefined\n runtime.hydrate(next)\n }\n touch(sessionId)\n }\n })(),\n )\n }\n\n // ── backscroll ───────────────────────────────────────────────\n // Cold reads of the log below the frontier. Fetched events merge\n // into `serverEvents` only — never the fold, never the overlay.\n let historyLoads = 0\n /** Calls chain per session: each resolves its bounds after the\n * prior call's merge, so overlapping backscrolls page backward\n * instead of re-fetching the same range. */\n let historyTail: Promise<unknown> = Promise.resolve()\n\n const eventsBetween = (gte: number, lte: number): ContractEvent<D>[] =>\n serverEvents.filter((event) => event.index >= gte && event.index <= lte)\n\n /** The narrowest sub-range of [gte, lte] missing from the feed, or\n * null when the range is fully loaded (nothing to fetch). */\n const missingBetween = (\n gte: number,\n lte: number,\n ): { gte: number; lte: number } | null => {\n const present = new Set(eventsBetween(gte, lte).map((e) => e.index))\n let lo = gte\n while (lo <= lte && present.has(lo)) lo += 1\n if (lo > lte) return null\n let hi = lte\n while (hi > lo && present.has(hi)) hi -= 1\n return { gte: lo, lte: hi }\n }\n\n const loadHistory = (\n loadOptions?: LoadHistoryOptions,\n ): Promise<ContractEvent<D>[]> => {\n const readHistory = transport.history\n if (readHistory === undefined) {\n throw new TypeError(\n 'loadHistory requires an http api — the ws transport has no history lane; serve the session over handle() and pass its route url as the string or { type: \"http\" } api',\n )\n }\n const before = loadOptions?.before\n const limit = loadOptions?.limit\n if (\n before !== undefined &&\n (!Number.isSafeInteger(before) || before < 1)\n ) {\n throw new TypeError(\n 'loadHistory before must be a positive safe integer',\n )\n }\n if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) {\n throw new TypeError('loadHistory limit must be a positive safe integer')\n }\n touch(sessionId)\n const run = historyTail.then(async () => {\n const upper = before ?? serverEvents[0]?.index ?? frontier + 1\n // Strictly at or below the frontier: the live stream owns\n // everything above it, and the optimistic overlay must never\n // collide with a backscrolled row.\n const lte = Math.min(upper - 1, frontier)\n const gte = Math.max(1, upper - (limit ?? DEFAULT_HISTORY_LIMIT))\n if (gte > lte) return []\n const missing = missingBetween(gte, lte)\n if (missing === null) return eventsBetween(gte, lte)\n historyLoads += 1\n notify()\n try {\n const rows = await readHistory({ sessionId, ...missing })\n mergeServerEvents(\n rows.map((row) => eventFromWire(row) as ContractEvent<D>),\n frontier,\n )\n return eventsBetween(gte, lte)\n } finally {\n historyLoads -= 1\n notify()\n touch(sessionId)\n }\n })\n // Failures reject the caller, never the chain.\n historyTail = run.catch(() => {})\n return run\n }\n\n // ── the live stream ──────────────────────────────────────────\n // A run-generation model instead of a terminal `closed` flag:\n // stopping bumps the generation (the running loop notices and\n // exits), connect() starts a fresh one. Reentrant by design.\n // Consumers hold leases: connect() counts one and returns its\n // release, the last release stops the stream, and close() is the\n // hard stop — it drops every lease and stops now (bumping\n // `leaseEpoch` makes the outstanding releases inert).\n let generation = 0\n let active = false\n let abort: AbortController | null = null\n let leases = 0\n let leaseEpoch = 0\n\n const stopStream = (): void => {\n touch(sessionId)\n if (!active) return\n active = false\n generation += 1 // the running loop notices and exits\n abort?.abort()\n abort = null\n // A pending trailing send dies with the stream — losing one is\n // fine by definition; sets made while closed accumulate in\n // `presenceResend` and repaint after the next connect.\n clearTimeout(presenceTimer)\n presenceTimer = undefined\n presenceBuffer = null\n status = 'closed'\n notify()\n }\n\n const runStream = async (run: number): Promise<void> => {\n let backoff = STREAM_TIMINGS.reconnectBaseMs\n // oxlint-disable no-await-in-loop -- sequential reconnect loop\n // oxlint-disable-next-line no-unmodified-loop-condition -- close() bumps `generation`\n while (generation === run) {\n const controller = new AbortController()\n abort = controller\n // The stall watchdog: the server heartbeats the stream, so a\n // healthy connection is never silent for long. Silence past the\n // timeout means the connection is dead in a way the socket\n // won't report (an offline browser's established SSE socket\n // neither errors nor receives) — abort it and let the normal\n // reconnect path run. This is what keeps `status: 'live'`\n // honest.\n let stall: ReturnType<typeof setTimeout> | undefined\n let stalled = false\n const armStall = (): void => {\n clearTimeout(stall)\n stall = setTimeout(() => {\n stalled = true\n controller.abort()\n }, STREAM_TIMINGS.stallTimeoutMs)\n ;(stall as { unref?: () => void }).unref?.()\n }\n let wasLive = false\n try {\n const frames = transport.connect({\n sessionId,\n startAfter: frontier,\n signal: controller.signal,\n })\n for await (const frame of frames) {\n if (generation !== run) break\n // Every frame counts — heartbeats included. Liveness is\n // about the connection, not about events.\n armStall()\n if (!wasLive) {\n // The first frame is the connection signal: the transport\n // yields it the moment the stream is established.\n backoff = STREAM_TIMINGS.reconnectBaseMs\n wasLive = true\n status = 'live'\n lastError = null\n notify()\n if (presenceResend) {\n const values = presenceResend\n presenceResend = null\n queuePresenceSend(values)\n }\n }\n if (frame.kind === 'event') {\n ingest(eventFromWire(frame.event) as ContractEvent<D>)\n } else if (frame.kind === 'presence') {\n applyPresencePatch(presencePatchFromWire(frame.patch))\n } else if (frame.kind === 'presence-snapshot') {\n applyPresenceSnapshot(\n presenceSnapshotFromWire(frame.snapshot).snapshot,\n )\n }\n }\n // The transport ended the stream cleanly — reconnect, but it\n // isn't an error.\n if (generation === run) {\n lastError = null\n }\n } catch (err) {\n if (generation === run) {\n lastError = stalled\n ? new Error(\n `stream stalled: no data for ${STREAM_TIMINGS.stallTimeoutMs}ms`,\n )\n : err instanceof Error\n ? err\n : new Error(String(err))\n }\n } finally {\n clearTimeout(stall)\n }\n if (generation !== run) break\n if (wasLive) reconnects += 1\n status = 'connecting'\n notify()\n await new Promise<void>((resolve) => {\n let settled = false\n const finish = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n // oxlint-disable-next-line no-multiple-resolved -- guarded above\n resolve()\n }\n const timer = setTimeout(finish, backoff)\n ;(timer as { unref?: () => void }).unref?.()\n abort?.signal.addEventListener('abort', finish)\n })\n backoff = Math.min(backoff * 2, STREAM_TIMINGS.reconnectMaxMs)\n }\n // oxlint-enable no-await-in-loop\n }\n\n const runtime: SessionRuntime<D, S, P> = {\n sessionId,\n // Only on presence-declaring contracts — the type surface\n // promises no runtime-inert members (a2-api.md §12).\n ...(declaresPresence ? { setPresence } : {}),\n subscribe(listener) {\n touch(sessionId)\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n touch(sessionId)\n }\n },\n getSnapshot() {\n snapshot ??= buildSnapshot()\n return snapshot\n },\n push,\n loadHistory,\n connect() {\n touch(sessionId)\n leases += 1\n const epoch = leaseEpoch\n if (!active) {\n active = true\n status = 'connecting'\n notify()\n void runStream(generation)\n }\n let released = false\n return () => {\n // Idempotent, and inert after a hard close() — a stale\n // release must not touch leases taken since.\n if (released || leaseEpoch !== epoch) return\n released = true\n touch(sessionId)\n leases -= 1\n if (leases === 0) stopStream()\n }\n },\n close() {\n leases = 0\n leaseEpoch += 1\n stopStream()\n },\n hydrate(next) {\n touch(sessionId)\n if (!next) return\n participant ??= next.participant\n const nextIndex = next.initialIndex ?? 0\n if (nextIndex > frontier && inFlightPushes > 0) {\n if (\n !deferredHydration ||\n nextIndex > (deferredHydration.initialIndex ?? 0)\n ) {\n deferredHydration = next\n }\n return\n }\n\n const historyChanged = mergeServerEvents(\n next.initialEvents,\n Math.min(nextIndex, frontier),\n )\n if (next.initialState === undefined || nextIndex <= frontier) {\n if (historyChanged) notifyHydrated()\n return\n }\n\n // The server fold subsumes everything observed through the old\n // frontier. Keep later optimistic work overlaid, retiring acked\n // entries the new frontier proves are already durable.\n frontier = nextIndex\n foldedState = next.initialState\n mergeServerEvents(next.initialEvents, frontier)\n pending = pending.filter(\n (entry) => !entry.acked || entry.acked.index > frontier,\n )\n if (confirmWatchers.some((watcher) => watcher.index <= frontier)) {\n const due = confirmWatchers.filter(\n (watcher) => watcher.index <= frontier,\n )\n confirmWatchers = confirmWatchers.filter(\n (watcher) => watcher.index > frontier,\n )\n for (const watcher of due) watcher.resolve()\n }\n notifyHydrated()\n },\n canEvict() {\n return (\n listeners.size === 0 &&\n !active &&\n inFlightPushes === 0 &&\n historyLoads === 0 &&\n confirmWatchers.length === 0 &&\n presenceTimer === undefined\n )\n },\n } as SessionRuntime<D, S, P>\n\n return runtime\n }\n\n return {\n session(sessionId, sessionOptions) {\n const existing = sessions.get(sessionId)\n if (existing) {\n existing.runtime.hydrate(sessionOptions)\n touch(sessionId)\n return existing.runtime\n }\n\n const runtime = makeSession(sessionId, sessionOptions)\n sessions.set(sessionId, { runtime })\n touch(sessionId)\n return runtime\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsRA,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAiE9B,MAAM,iBACJ,QACA,WAGA,cACe;CACf,OAAO,QAAQ,EAAE,WAAW,YAAY,UAAU;EAChD,MAAM,MAAM,OAAO,OAAO,SAAS,GAAG,IAAI,MAAM;EAChD,MAAM,MAAM,MAAM,UAChB,GAAG,OAAO,SAAS,IAAI,YAAY,mBAAmB,SAAS,EAAE,SAAS,cAC1E;GAAE,SAAS,EAAE,QAAQ,oBAAoB;GAAG;EAAO,CACrD;EACA,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,MAClB,MAAM,IAAI,MAAM,sBAAsB,IAAI,QAAQ;EAEpD,MAAM,EAAE,MAAM,OAAO;EACrB,MAAM,UAAU,IAAI,YAAY;EAChC,MAAM,SAAS,IAAI,KAAK,UAAU;EAClC,IAAI,SAAS;EACb,IAAI;GACF,SAAS;IAEP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;IAC1C,IAAI,MAAM;IAGV,MAAM,EAAE,MAAM,OAAO;IACrB,UAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;IAChD,SAAS;KACP,MAAM,WAAW,OAAO,QAAQ,MAAM;KACtC,IAAI,aAAa,IAAI;KACrB,MAAM,QAAQ,OAAO,MAAM,GAAG,QAAQ;KACtC,SAAS,OAAO,MAAM,WAAW,CAAC;KAClC,IAAI;KACJ,MAAM,YAAsB,CAAC;KAC7B,KAAK,MAAM,QAAQ,MAAM,MAAM,IAAI,GACjC,IAAI,KAAK,WAAW,OAAO,GACzB,UAAU,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC;UACnC,IAAI,KAAK,WA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S,KACnB,CAAC,UACD,mBAAmB,KACnB,iBAAiB,KACjB,gBAAgB,WAAW,KAC3B,kBAAkB,KAAA;GAEtB;EACF;EAEA,OAAO;CACT;CAEA,OAAO,EACL,QAAQ,WAAW,gBAAgB;EACjC,MAAM,WAAW,SAAS,IAAI,SAAS;EACvC,IAAI,UAAU;GACZ,SAAS,QAAQ,QAAQ,cAAc;GACvC,MAAM,SAAS;GACf,OAAO,SAAS;EAClB;EAEA,MAAM,UAAU,YAAY,WAAW,cAAc;EACrD,SAAS,IAAI,WAAW,EAAE,QAAQ,CAAC;EACnC,MAAM,SAAS;EACf,OAAO;CACT,EACF;AACF"}
package/dist/client.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as Connection, c as HistoryState, d as SessionClient, f as SessionClientPresence, h as createClient, i as ClientWebSocketConstructor, l as LoadHistoryOptions, m as SessionSnapshot, n as ClientApi, o as ConnectionStatus, p as SessionOptions, r as ClientWebSocket, s as CreateClientOptions, t as A2Client, u as PushResult } from "./client-D7mvIXrF.js";
1
+ import { a as Connection, c as HistoryState, d as SessionClient, f as SessionClientPresence, h as createClient, i as ClientWebSocketConstructor, l as LoadHistoryOptions, m as SessionSnapshot, n as ClientApi, o as ConnectionStatus, p as SessionOptions, r as ClientWebSocket, s as CreateClientOptions, t as A2Client, u as PushResult } from "./client-CdMqi7mC.js";
2
2
  export { A2Client, ClientApi, ClientWebSocket, ClientWebSocketConstructor, Connection, ConnectionStatus, CreateClientOptions, HistoryState, LoadHistoryOptions, PushResult, SessionClient, SessionClientPresence, SessionOptions, SessionSnapshot, createClient };
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createClient } from "./client-BKlyLiOU.js";
1
+ import { t as createClient } from "./client-Dj5d3SP_.js";
2
2
  export { createClient };
package/dist/http.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as EventDefs, o as PresenceDefs, r as ContractEvent } from "./contract-jIfaR085.js";
2
- import { f as PushedEvent, i as DrainableServer, n as A2Server, p as PushedPresence } from "./server-DUF9pjsx.js";
2
+ import { f as PushedEvent, i as DrainableServer, n as A2Server, p as PushedPresence } from "./server-DpvjhdoE.js";
3
3
  import { t as A2Error } from "./errors-W6nwJ-fm.js";
4
4
  //#region src/session-socket.d.ts
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as EventDefs, c as PresencePatch, f as contract, h as StandardSchemaV1, i as EventBatchFactory, l as PresenceSnapshot, m as ReducerBuilder, n as Contract, o as PresenceDefs, p as Reducer, r as ContractEvent, s as PresenceMap, t as AppendInput, u as ReducerOptions } from "./contract-jIfaR085.js";
2
2
  import { a as Event } from "./store-DysUkTH3.js";
3
- import { i as A2Telemetry, n as A2SpanHandle, r as A2SpanName, t as A2AttributeValue } from "./telemetry-BjYHTfh2.js";
3
+ import { i as A2Telemetry, n as A2SpanHandle, r as A2SpanName, t as A2AttributeValue } from "./telemetry-CpeclqB2.js";
4
4
  import { n as A2ErrorCode, t as A2Error } from "./errors-W6nwJ-fm.js";
5
5
  export { type A2AttributeValue, A2Error, type A2ErrorCode, type A2SpanHandle, type A2SpanName, type A2Telemetry, type AppendInput, type Contract, type ContractEvent, type Event, type EventBatchFactory, type EventDefs, type PresenceDefs, type PresenceMap, type PresencePatch, type PresenceSnapshot, type Reducer, type ReducerBuilder, type ReducerOptions, type StandardSchemaV1, contract };
package/dist/otel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as A2Telemetry } from "./telemetry-BjYHTfh2.js";
1
+ import { i as A2Telemetry } from "./telemetry-CpeclqB2.js";
2
2
  import { Tracer } from "@opentelemetry/api";
3
3
  //#region src/otel.d.ts
4
4
  type OtelOptions = {
package/dist/react.d.ts CHANGED
@@ -1,7 +1,33 @@
1
1
  import { a as EventDefs, c as PresencePatch, d as WithPresence, o as PresenceDefs, p as Reducer, r as ContractEvent, s as PresenceMap, t as AppendInput } from "./contract-jIfaR085.js";
2
- import { a as Connection, c as HistoryState, l as LoadHistoryOptions, t as A2Client, u as PushResult } from "./client-D7mvIXrF.js";
2
+ import { a as Connection, c as HistoryState, l as LoadHistoryOptions, t as A2Client, u as PushResult } from "./client-CdMqi7mC.js";
3
3
  import { ReactElement, ReactNode } from "react";
4
4
  //#region src/react.d.ts
5
+ type UseSessionOptions<S> = {
6
+ /** Overrides the client's `participant` for this session — for apps
7
+ * whose identity is only known at mount time. Bound once per
8
+ * session handle. */
9
+ participant?: string;
10
+ /**
11
+ * The server fold this session mounts from: the `{ state, index }`
12
+ * pair `session.state(reducer)` returns, fetched by the app through
13
+ * its own route. Atomic on purpose — the fold and its frontier
14
+ * travel together or not at all. While `undefined` (the app's fetch
15
+ * has not landed), the hook holds the stream; when the value
16
+ * arrives, the session hydrates through the ordinary re-hydration
17
+ * seam and the stream connects at that frontier. To fold from the log's start
18
+ * deliberately, hand the fold's true starting point:
19
+ * `{ state: reducer.initialState, index: 0 }` — state at index 0 is
20
+ * the reducer's seed by definition, so the explicit replay needs no
21
+ * special vocabulary. There is no pending/ready echo on the result:
22
+ * whether the fold has been handed over is this option — the
23
+ * caller's own input — so the data layer's loading state IS the
24
+ * pending state.
25
+ */
26
+ hydrate?: {
27
+ state: S;
28
+ index: number;
29
+ } | undefined;
30
+ };
5
31
  type SessionProviderProps<D extends EventDefs, S> = {
6
32
  /** Which session to subscribe to. */
7
33
  sessionId: string;
@@ -13,11 +39,8 @@ type SessionProviderProps<D extends EventDefs, S> = {
13
39
  initialIndex: number;
14
40
  /** Server-rendered event history through `initialIndex`. */
15
41
  initialEvents?: ContractEvent<D>[];
16
- /**
17
- * This client's presence identity required to call `setPresence`.
18
- * Caller-supplied (a user id, a tab nonce, a guest name): A2 does
19
- * not invent an identity story.
20
- */
42
+ /** Overrides the client's `participant` for this session — for apps
43
+ * whose identity is only known at mount time. */
21
44
  participant?: string;
22
45
  children?: ReactNode;
23
46
  };
@@ -81,6 +104,17 @@ declare function createReact<D extends EventDefs, S, P extends PresenceDefs = Re
81
104
  declare function createReact<D extends EventDefs, S, P extends PresenceDefs = Record<never, never>>(options: {
82
105
  reducer: Reducer<D, S, P>;
83
106
  }): A2React<D, S, P>;
107
+ /**
108
+ * The standalone, provider-less hook — for apps whose components reach
109
+ * sessions ad hoc (a sidebar of channel sessions, a user session read
110
+ * from a menu). Takes the shared client and a session id; the handle
111
+ * is identity-mapped, so every hook and provider mounting the same
112
+ * session shares one runtime and one leased stream. Hydration is
113
+ * app-owned: pass `hydrate` when your fetch lands; until then the
114
+ * stream is held, and your data layer's loading state is the pending
115
+ * state.
116
+ */
117
+ declare function useSession<D extends EventDefs, S, P extends PresenceDefs = Record<never, never>>(client: A2Client<D, S, P>, sessionId: string, options?: UseSessionOptions<S>): UseSessionResult<D, S, P>;
84
118
  //#endregion
85
- export { A2React, BoundA2React, BoundSessionProviderProps, SessionProviderProps, UseSessionPresence, UseSessionResult, createReact };
119
+ export { A2React, BoundA2React, BoundSessionProviderProps, SessionProviderProps, UseSessionOptions, UseSessionPresence, UseSessionResult, createReact, useSession };
86
120
  //# sourceMappingURL=react.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.ts","names":[],"sources":["../src/react.ts"],"mappings":";;;;KA8CY,qBAAqB,UAAU,WAAW;;EAEpD;;EAEA;;EAEA,cAAc;;EAEd;;EAEA,gBAAgB,cAAc;;;;;;EAM9B;EACA,WAAW;;KAGD,0BAA0B,UAAU,WAAW,KAAK,KAC9D,qBAAqB,GAAG;;;;;;KASd,mBAAmB,UAAU;;EAEvC,UAAU,YAAY;;;;;;;;EAQtB,cAAc,QAAQ,cAAc;;KAG1B,iBACV,UAAU,WACV,GACA,UAAU,eAAe,wBACvB,aAAa,GAAG,mBAAmB;;EAErC,OAAO;;EAEP,QAAQ,cAAc;;EAEtB;;;;;;EAMA,YAAY;;;;;;EAMZ,UAAU,QAAQ,YAAY,SAAS,WAAW;;;;;;EAMlD,cAAc,UAAU,uBAAuB,QAAQ,cAAc;;EAErE,SAAS;;KAGC,QACV,UAAU,WAC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