statewire 0.20.0 → 0.22.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 (143) hide show
  1. package/dist/client/changes.d.ts +3 -6
  2. package/dist/client/changes.d.ts.map +1 -1
  3. package/dist/client/changes.js +1 -2
  4. package/dist/client/connection.d.ts +80 -83
  5. package/dist/client/connection.d.ts.map +1 -1
  6. package/dist/client/connection.js +20 -7
  7. package/dist/client/connection.js.map +1 -1
  8. package/dist/client/core.d.ts +39 -41
  9. package/dist/client/core.d.ts.map +1 -1
  10. package/dist/client/core.js +2 -3
  11. package/dist/client/session.d.ts +93 -93
  12. package/dist/client/session.d.ts.map +1 -1
  13. package/dist/client/session.js +47 -23
  14. package/dist/client/session.js.map +1 -1
  15. package/dist/client/sessionStore.d.ts +11 -14
  16. package/dist/client/sessionStore.d.ts.map +1 -1
  17. package/dist/client/sessionStore.js +1 -2
  18. package/dist/client/storageError.d.ts +2 -5
  19. package/dist/client/storageError.d.ts.map +1 -1
  20. package/dist/client/storageError.js +1 -2
  21. package/dist/client/timing.d.ts +11 -14
  22. package/dist/client/timing.d.ts.map +1 -1
  23. package/dist/client/timing.js +1 -2
  24. package/dist/document.d.ts +17 -20
  25. package/dist/document.d.ts.map +1 -1
  26. package/dist/document.js +1 -2
  27. package/dist/host/adapter.d.ts +4 -7
  28. package/dist/host/adapter.d.ts.map +1 -1
  29. package/dist/host/adapter.js +1 -2
  30. package/dist/host/draft.d.ts +13 -16
  31. package/dist/host/draft.d.ts.map +1 -1
  32. package/dist/host/draft.js +1 -2
  33. package/dist/host/engine.d.ts +7 -10
  34. package/dist/host/engine.d.ts.map +1 -1
  35. package/dist/host/engine.js +1 -2
  36. package/dist/host/host.d.ts +42 -45
  37. package/dist/host/host.d.ts.map +1 -1
  38. package/dist/host/host.js +15 -13
  39. package/dist/host/host.js.map +1 -1
  40. package/dist/host/http.d.ts +4 -7
  41. package/dist/host/http.d.ts.map +1 -1
  42. package/dist/host/http.js +15 -11
  43. package/dist/host/http.js.map +1 -1
  44. package/dist/host/socket.d.ts +145 -140
  45. package/dist/host/socket.d.ts.map +1 -1
  46. package/dist/host/socket.js +99 -17
  47. package/dist/host/socket.js.map +1 -1
  48. package/dist/host/synced.d.ts +3 -6
  49. package/dist/host/synced.d.ts.map +1 -1
  50. package/dist/host/synced.js +1 -2
  51. package/dist/host/work.d.ts +2 -5
  52. package/dist/host/work.d.ts.map +1 -1
  53. package/dist/host/work.js +1 -2
  54. package/dist/host-internal.d.ts +99 -90
  55. package/dist/host-internal.d.ts.map +1 -1
  56. package/dist/host.d.ts +90 -91
  57. package/dist/host.d.ts.map +1 -1
  58. package/dist/index.d.ts +11 -8
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +1 -1
  61. package/dist/statewire.d.ts +265 -268
  62. package/dist/statewire.d.ts.map +1 -1
  63. package/dist/statewire.js +7 -7
  64. package/dist/statewire.js.map +1 -1
  65. package/dist/storage.d.ts +23 -26
  66. package/dist/storage.d.ts.map +1 -1
  67. package/dist/storage.js +1 -2
  68. package/dist/transports/fake-sse.d.ts +7 -10
  69. package/dist/transports/fake-sse.d.ts.map +1 -1
  70. package/dist/transports/fake-sse.js +1 -2
  71. package/dist/transports/fixtures.d.ts +19 -25
  72. package/dist/transports/fixtures.d.ts.map +1 -1
  73. package/dist/transports/fixtures.js +1 -2
  74. package/dist/transports/remote.d.ts +8 -11
  75. package/dist/transports/remote.d.ts.map +1 -1
  76. package/dist/transports/remote.js +1 -2
  77. package/dist/transports/sse-parser.d.ts +1 -4
  78. package/dist/transports/sse-parser.d.ts.map +1 -1
  79. package/dist/transports/sse-parser.js +1 -2
  80. package/dist/transports/sse.d.ts +50 -52
  81. package/dist/transports/sse.d.ts.map +1 -1
  82. package/dist/transports/sse.js +9 -3
  83. package/dist/transports/sse.js.map +1 -1
  84. package/dist/transports/testing.d.ts +31 -34
  85. package/dist/transports/testing.d.ts.map +1 -1
  86. package/dist/transports/testing.js +1 -2
  87. package/dist/transports/ws.d.ts +5 -7
  88. package/dist/transports/ws.d.ts.map +1 -1
  89. package/dist/transports/ws.js +3 -4
  90. package/dist/transports/ws.js.map +1 -1
  91. package/dist/types.d.ts +81 -78
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/types.js +1 -2
  94. package/dist/util/draftTraps.d.ts +2 -4
  95. package/dist/util/draftTraps.d.ts.map +1 -1
  96. package/dist/util/draftTraps.js +1 -2
  97. package/dist/util/macrotask.d.ts +1 -4
  98. package/dist/util/macrotask.d.ts.map +1 -1
  99. package/dist/util/macrotask.js +1 -2
  100. package/dist/util/methodProxy.d.ts +1 -4
  101. package/dist/util/methodProxy.d.ts.map +1 -1
  102. package/dist/util/methodProxy.js +1 -2
  103. package/dist/util/randomId.d.ts +1 -4
  104. package/dist/util/randomId.d.ts.map +1 -1
  105. package/dist/util/randomId.js +1 -2
  106. package/dist/util/recordMutations.d.ts +5 -7
  107. package/dist/util/recordMutations.d.ts.map +1 -1
  108. package/dist/util/recordMutations.js +1 -2
  109. package/dist/util/statePath.d.ts +9 -12
  110. package/dist/util/statePath.d.ts.map +1 -1
  111. package/dist/util/statePath.js +1 -2
  112. package/dist/wire/context.d.ts +7 -12
  113. package/dist/wire/context.d.ts.map +1 -1
  114. package/dist/wire/context.js +2 -3
  115. package/dist/wire/documents.d.ts +36 -39
  116. package/dist/wire/documents.d.ts.map +1 -1
  117. package/dist/wire/documents.js +2 -3
  118. package/dist/wire/documents.js.map +1 -1
  119. package/dist/wire/limits.d.ts +7 -10
  120. package/dist/wire/limits.d.ts.map +1 -1
  121. package/dist/wire/limits.js +1 -2
  122. package/dist/wire/meta.d.ts +9 -11
  123. package/dist/wire/meta.d.ts.map +1 -1
  124. package/dist/wire/meta.js +1 -2
  125. package/dist/wire/meta.js.map +1 -1
  126. package/dist/wire/ops.d.ts +9 -12
  127. package/dist/wire/ops.d.ts.map +1 -1
  128. package/dist/wire/ops.js +1 -2
  129. package/dist/wire/protocol.d.ts +53 -56
  130. package/dist/wire/protocol.d.ts.map +1 -1
  131. package/dist/wire/protocol.js +1 -2
  132. package/dist/wire/version.d.ts +1 -4
  133. package/dist/wire/version.d.ts.map +1 -1
  134. package/dist/wire/version.js +1 -2
  135. package/package.json +6 -6
  136. package/src/client/connection.ts +25 -15
  137. package/src/client/session.ts +54 -15
  138. package/src/host/host.ts +9 -3
  139. package/src/host/http.ts +37 -5
  140. package/src/host/socket.ts +158 -9
  141. package/src/host-internal.ts +14 -0
  142. package/src/statewire.ts +11 -6
  143. package/src/transports/sse.ts +12 -0
@@ -1 +1 @@
1
- {"version":3,"file":"statewire.js","names":["StatewireDocuments","StatewireProtocol","StatewireHost","useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","createTapRoot","flushTapSync","resource","useContextProvider","useResource","useResources","withKey","ResourceElement","CONNECTED_CONNECTION","useStatewireCore","Statewire","TERMINAL","DocumentStorageContext","LinkContext","ProtocolContext","SessionStorageContext","useSessionTransport","transport","session","documents","protocol","link","StatewireClient","SessionStorage","Storage","Options","isNew","context","Readonly","Record","Context","SessionTransport","useStatewire","Commands","options","TState","TCommands","Helpers","latest","current","storage","undefined","wireVersion","applicationProtocols","keyPrefixes","value","localContext","connection","setContext","Object","entries","core","rematerialize","materializeKey","subscribe","listener","state","getState","isBusy","getBusy","failed","getFailed","source","selection","invoke","transportInvoke","transportSetContext","failures","transportFailures","method","params","Error","NonNullable","commands","CommandsProxy","retryFailed","entry","FailedCommand","retry","discardFailed","discard","StatewireResource","root","disposed","constructor","ClientRoot","getValue","Connection","Source","Selection","Promise","dispose","unmount","Range","Offer","initialState","optimistic","Optimistic","materialize","Materialize","onStateChange","ctx","changes","Changes","onCommandChange","update","CommandUpdate","onConnectionChange","onError","error","ConnectionError","failureCovered","ConnectionState","status","reason","degraded","attempt","cause","code","nextRetryAt","lastError","message","payload","reconnect","ConnectionStatus","draft","command","Command","OptimisticContext","ts","seq","clientId","SendFailure","fate","predecessorLost","OnSessionLost","pending","ReadonlyArray","produced","SessionCommand","meta","failure","wire","protocols","SessionLane","nextSeq","verdicts","SessionVerdict","SessionRecord","lanes","type","ready","flush","load","save","record","migrate","lock","fn","T","fin","Fin","HeadersOption","HeadersInit","staleAuth","HttpOptions","sessionStore","url","headers","fetch","globalThis","onSessionLost","onChange","onDone","WebsocketOptions","query","webSocket","WebSocket"],"sources":["../src/statewire.ts"],"sourcesContent":["import type { StatewireDocuments } from \"./wire/documents\";\nimport type { StatewireProtocol } from \"./wire/protocol\";\nimport type { StatewireHost } from \"./host\";\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n createTapRoot,\n flushTapSync,\n resource,\n useContextProvider,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { CONNECTED_CONNECTION, useStatewireCore } from \"./client/core\";\nimport type { Statewire } from \"./types\";\nimport type { TERMINAL } from \"./client/connection\";\nimport {\n DocumentStorageContext,\n LinkContext,\n ProtocolContext,\n SessionStorageContext,\n} from \"./client/sessionStore\";\n\nconst useSessionTransport = ({\n transport,\n session,\n documents,\n protocol,\n link,\n}: {\n transport: ResourceElement<Statewire<any, any>>;\n session: StatewireClient.SessionStorage | undefined;\n documents: StatewireDocuments.Storage | undefined;\n protocol: StatewireProtocol.Options;\n link: {\n isNew?: boolean | undefined;\n context?: Readonly<Record<string, Statewire.Context>> | undefined;\n };\n}): Statewire<unknown> =>\n useContextProvider(SessionStorageContext, session, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useContextProvider(DocumentStorageContext, documents, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useContextProvider(ProtocolContext, protocol, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useContextProvider(LinkContext, link, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useResource(transport),\n ),\n ),\n ),\n );\n\n// The transport owns the session; it reads the storage off the context this\n// wrapper's own fiber provides, so plain-React callers get a provider too.\nconst SessionTransport = resource(useSessionTransport);\n\nexport const useStatewire = <\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireClient.Options<TState, TCommands>,\n): StatewireClient.Helpers<TState, TCommands> => {\n const latest = useRef(options);\n latest.current = options;\n\n const session = useResources(\n options.storage?.session !== undefined\n ? [withKey(\"session\", options.storage.session)]\n : [],\n )[0];\n const documents = useResources(\n options.storage?.documents === undefined\n ? []\n : [withKey(\"documents\", options.storage.documents)],\n )[0];\n const protocol: StatewireProtocol.Options = {\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n ...(options.wireVersion !== undefined && {\n wireVersion: options.wireVersion,\n }),\n ...(options.applicationProtocols !== undefined && {\n applicationProtocols: options.applicationProtocols,\n }),\n ...(options.keyPrefixes !== undefined && {\n keyPrefixes: options.keyPrefixes,\n }),\n };\n const link = useMemo(\n () => ({\n ...(options.isNew === undefined ? {} : { isNew: options.isNew }),\n ...(options.context === undefined ? {} : { context: options.context }),\n }),\n [options.isNew, options.context],\n );\n const value = useResource(\n SessionTransport({\n transport: options.transport,\n session,\n documents,\n protocol,\n link,\n }),\n );\n const localContext =\n value.connection === undefined ? value.setContext : undefined;\n useEffect(() => {\n const current = latest.current;\n if (localContext === undefined || current.context === undefined) return;\n for (const [protocol, context] of Object.entries(current.context))\n localContext(protocol, context);\n }, [options.context, localContext]);\n const core = useStatewireCore(() => latest.current, value);\n useEffect(() => core.rematerialize(), [core, options.materializeKey]);\n const [subscribe] = useState(\n () => (listener: () => void) =>\n core.subscribe(() => flushTapSync(listener)),\n );\n\n const state = useSyncExternalStore(\n subscribe,\n core.getState,\n core.getState,\n ) as TState;\n const isBusy = useSyncExternalStore(subscribe, core.getBusy, core.getBusy);\n const failed = useSyncExternalStore(\n subscribe,\n core.getFailed,\n core.getFailed,\n );\n const connection = value.connection ?? CONNECTED_CONNECTION;\n const {\n documents: source,\n selection,\n invoke: transportInvoke,\n setContext: transportSetContext,\n failures: transportFailures,\n } = value;\n\n const invoke = useCallback(\n (protocol: string, method: string, params: readonly unknown[]) => {\n if (!transportInvoke)\n throw new Error(\n \"statewire: transport does not support protocol commands\",\n );\n return transportInvoke(protocol, method, params);\n },\n [transportInvoke],\n );\n\n return useMemo(() => {\n const failures = (): NonNullable<typeof transportFailures> => {\n if (!transportFailures) {\n throw new Error(\"statewire: this transport has no failed-send lane\");\n }\n return transportFailures;\n };\n return {\n state,\n documents: source,\n selection,\n invoke,\n setContext: (protocol: string, value: Statewire.Context) => {\n if (!transportSetContext)\n throw new Error(\"statewire: transport does not support context\");\n transportSetContext(protocol, value);\n },\n getState: core.getState as () => TState,\n connection,\n commands: core.commands as Statewire.CommandsProxy<TCommands>,\n isBusy,\n failed,\n retryFailed: (entry: StatewireClient.FailedCommand) =>\n failures().retry(entry),\n discardFailed: (entry: StatewireClient.FailedCommand) =>\n failures().discard(entry),\n };\n }, [\n state,\n isBusy,\n failed,\n connection,\n core,\n source,\n selection,\n invoke,\n transportFailures,\n transportSetContext,\n ]);\n};\n\nexport const StatewireResource = <\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireClient.Options<TState, TCommands>,\n): ResourceElement<StatewireClient.Helpers<TState, TCommands>> =>\n resource(useStatewire<TState, TCommands>)(options);\n\nexport class StatewireClient<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n> {\n private readonly root;\n private disposed = false;\n\n constructor(options: StatewireClient.Options<TState, TCommands>) {\n const ClientRoot = () => useStatewire<TState, TCommands>(options);\n this.root = createTapRoot(ClientRoot);\n }\n\n get state(): TState {\n return this.root.getValue().getState();\n }\n\n get connection(): StatewireClient.Connection {\n return this.root.getValue().connection;\n }\n\n get commands(): Statewire.CommandsProxy<TCommands> {\n return this.root.getValue().commands;\n }\n\n get documents(): StatewireDocuments.Source | undefined {\n return this.root.getValue().documents;\n }\n get selection(): StatewireProtocol.Selection | undefined {\n return this.root.getValue().selection;\n }\n invoke(\n protocol: string,\n method: string,\n params: readonly unknown[],\n ): Promise<unknown> {\n return this.root.getValue().invoke(protocol, method, params);\n }\n setContext(protocol: string, value: Statewire.Context): void {\n this.root.getValue().setContext(protocol, value);\n }\n get isBusy(): boolean {\n return this.root.getValue().isBusy;\n }\n\n get failed(): readonly StatewireClient.FailedCommand[] {\n return this.root.getValue().failed;\n }\n\n retryFailed(entry: StatewireClient.FailedCommand): Promise<unknown> {\n return this.root.getValue().retryFailed(entry);\n }\n\n discardFailed(entry: StatewireClient.FailedCommand): void {\n this.root.getValue().discardFailed(entry);\n }\n\n subscribe(listener: () => void): () => void {\n return this.root.subscribe(listener);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.root.unmount();\n }\n}\n\nexport namespace StatewireClient {\n export type Options<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n > = {\n protocol?: string;\n context?: Readonly<Record<string, Statewire.Context>>;\n keyPrefixes?: Readonly<Record<string, readonly string[]>>;\n wireVersion?: StatewireProtocol.Range;\n applicationProtocols?: readonly StatewireProtocol.Offer[] | \"*\";\n transport: ResourceElement<Statewire<TState, TCommands>>;\n /** The session does not exist on the server yet: the transport's first attach waits for the first command send; the transport's own `isNew` wins. */\n isNew?: boolean;\n /** Durable session: the mounted storage holds this client's lane identity and its un-durable commands, which resend on the next attach. */\n storage?:\n | {\n session?: ResourceElement<SessionStorage> | undefined;\n documents?: ResourceElement<StatewireDocuments.Storage> | undefined;\n }\n | undefined;\n /** Served as the canonical state until the attach snapshot; own commands fold over it. */\n initialState?: TState;\n optimistic?: Optimistic<NonNullable<TState>, TCommands>;\n materialize?: Materialize<NonNullable<TState>>;\n /** Republishes through `materialize` when it changes (`Object.is`); `materialize` itself is read fresh on every publish. */\n materializeKey?: unknown;\n onStateChange?: (\n state: NonNullable<TState>,\n ctx: { changes: Statewire.Changes },\n ) => void;\n onCommandChange?: (\n update: Statewire.CommandUpdate<TCommands>,\n ctx: { state: NonNullable<TState> },\n ) => void;\n onConnectionChange?: (connection: Connection) => void;\n onError?: (error: ConnectionError) => void;\n /** Drops a retained failed entry once a canonical snapshot shows its effect landed; checked against each new snapshot. */\n failureCovered?: (\n state: NonNullable<TState>,\n entry: FailedCommand,\n ) => boolean;\n };\n\n export type Helpers<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n > = {\n /** The statewire's state type — remote statewires include `undefined` until the first attach snapshot applies. */\n state: TState;\n documents: StatewireDocuments.Source | undefined;\n selection: StatewireProtocol.Selection | undefined;\n setContext: (protocol: string, value: Statewire.Context) => void;\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n /** Identity-stable across renders; reads the current canonical state without subscribing the caller. */\n getState: () => TState;\n connection: Connection;\n commands: Statewire.CommandsProxy<TCommands>;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n /** Non-accepted sends retained in the session record; reload with it. */\n failed: readonly FailedCommand[];\n /** Re-enqueues the entry's command on fresh clocks and removes the entry. */\n retryFailed: (entry: FailedCommand) => Promise<unknown>;\n /** Removes the entry. */\n discardFailed: (entry: FailedCommand) => void;\n };\n\n /** Connection lifecycle and whether its current state warrants a problem indicator. */\n export type ConnectionState =\n | { status: \"standby\"; reason: \"deferred\" | \"idle\"; degraded: false }\n | { status: \"connecting\"; degraded: false }\n | { status: \"connected\"; degraded: false }\n | {\n status: \"retrying\";\n degraded: true;\n attempt: number;\n /** Backoff details are absent while the retry dial is in flight. */\n cause?: \"dropped\" | \"reconnect\" | \"error\" | \"unauthorized\";\n code?: string;\n nextRetryAt?: number;\n lastError?: string;\n message?: string;\n }\n | {\n status: \"stopped\";\n degraded: true;\n reason:\n | \"gone\"\n | \"forbidden\"\n | \"protocol-error\"\n | \"unauthorized\"\n | \"storage-error\";\n message?: string;\n payload?: unknown;\n };\n export type Connection = ConnectionState & {\n error?: ConnectionError;\n reconnect: () => void;\n };\n export type ConnectionStatus = Connection[\"status\"];\n\n /**\n * Mutate the draft in place; the client records the next state plus the exact\n * changed paths. Re-run against the new base on every rebase.\n */\n export type Optimistic<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n > = (\n draft: TState,\n command: Statewire.Command<TCommands>,\n ctx: OptimisticContext,\n ) => void;\n\n export type OptimisticContext = {\n ts: number;\n seq: number;\n clientId?: string;\n };\n\n /**\n * Mutate the draft to fold client-known facts into the state: server-accepted,\n * still-uncommitted intents (e.g. dispatch records into messages) or the live\n * state of a sibling statewire. Runs after the optimistic folds on every\n * published state; `materializeKey` republishes when the facts change.\n */\n export type Materialize<TState> = (draft: TState) => void;\n\n /**\n * fate: \"aborted\" = never sent, \"rejected\" = the server refused it\n * (`code` \"unknown-command\" | \"invalid-params\" for the static rejects,\n * code-less for handler rejects), \"lost\" = sent but no verdict will ever\n * arrive — the record is gone (a proven seq gap) or the channel died: it\n * may or may not have run, \"failed\" = the handler ran and threw,\n * \"crashed\" = the handler died involuntarily, \"expired\" = settled —\n * result, rejected, failed, or crashed — but the verdict outlived the\n * server's retention.\n * cause is which channel settled it: \"server\" = the server's answer;\n * the rest are channel deaths the client settled locally.\n */\n export type SendFailure =\n | {\n fate: \"rejected\";\n cause: \"server\";\n code?: string;\n message?: string;\n payload?: unknown;\n }\n | { fate: \"failed\"; cause: \"server\"; message?: string }\n | { fate: \"crashed\"; cause: \"server\" }\n | { fate: \"expired\"; cause: \"server\" }\n | {\n fate: \"aborted\";\n cause: \"unmount\" | \"stream-gone\" | \"session-lost\";\n predecessorLost?: true;\n }\n | {\n fate: \"lost\";\n cause: \"unmount\" | \"stream-gone\" | \"session-lost\";\n };\n\n /** Held commands a proven record gap settled `{fate: \"lost\", cause: \"session-lost\"}`; return \"requeue\" to re-enqueue them on the reset clocks. */\n export type OnSessionLost = (\n pending: ReadonlyArray<{\n method: string;\n params: readonly unknown[];\n ts: number;\n seq: number;\n clientId?: string;\n }>,\n ) => \"requeue\" | \"drop\";\n\n /** A non-accepted send retained for the user: the wire statement, its failure, and its original clocks. */\n export type FailedCommand = {\n readonly protocol: string;\n readonly produced?: SessionCommand[\"produced\"];\n readonly command: string;\n readonly params: readonly unknown[];\n readonly meta?: unknown;\n readonly failure: SendFailure;\n readonly ts: number;\n readonly seq: number;\n };\n\n /** A command as persisted while un-durable: its lane seq plus the wire statement. */\n export type SessionCommand = {\n seq: number;\n produced?: {\n wire: StatewireProtocol.Range;\n protocols: readonly StatewireProtocol.Offer[] | \"*\";\n };\n method: string;\n params: unknown[];\n meta?: unknown;\n };\n\n /** A durable lane: its cmd clock and the commands the server has not marked durable. */\n export type SessionLane = {\n nextSeq: number;\n commands: readonly SessionCommand[];\n /** Terminal verdicts parked for the sharer that minted the seq (shared storage only). */\n verdicts?: readonly SessionVerdict[];\n /** Non-accepted sends retained for the user; survive record rebases and resets. */\n failed?: readonly FailedCommand[];\n };\n\n /** The persisted session: the client identity plus one lane per durable protocol. */\n export type SessionRecord = {\n clientId: string;\n lanes: Readonly<Record<string, SessionLane>>;\n };\n\n /** A terminal verdict one sharer's connection carried, parked for the sharer awaiting the seq. */\n export type SessionVerdict = {\n seq: number;\n type: (typeof TERMINAL)[number];\n code?: string;\n message?: string;\n payload?: unknown;\n meta?: unknown;\n };\n\n /** Session storage seam with optional asynchronous hydration and persistence. */\n export type SessionStorage = {\n /** Resolves when a synchronous load can return the hydrated record. */\n ready?: Promise<void>;\n /** Resolves after all queued saves are persisted; awaited before sending statements. */\n flush?: () => void | Promise<void>;\n load: () => SessionRecord | null;\n save: (record: SessionRecord) => void;\n /** Upgrade incompatible stored commands; null discards the old record and starts a new client identity. */\n migrate?: (\n record: SessionRecord,\n current: NonNullable<SessionCommand[\"produced\"]>,\n ) => SessionRecord | null;\n /** Serializes record mutations across sharers; presence marks the storage shared. */\n lock?: <T>(fn: () => T | Promise<T>) => Promise<T>;\n /** Notifies of record saves by other sharers; returns unsubscribe. Required alongside `lock`. */\n subscribe?: (listener: () => void) => () => void;\n };\n\n /** Static headers, or a resolver invoked per request/attach; `staleAuth` is true right after an auth rejection. */\n export type ConnectionError = Error & { fin?: StatewireHost.Fin };\n\n export type HeadersOption =\n | HeadersInit\n | ((ctx: { staleAuth: boolean }) => HeadersInit | Promise<HeadersInit>);\n\n export type HttpOptions = StatewireProtocol.Options & {\n sessionStore?: SessionStorage | undefined;\n url: string;\n /** The session does not exist on the server yet: the first attach waits for the first command send (or an explicit `reconnect()`). */\n isNew?: boolean;\n headers?: HeadersOption;\n fetch?: typeof globalThis.fetch;\n onSessionLost?: OnSessionLost;\n onChange?: (connection: Connection) => void;\n onError?: (error: ConnectionError) => void;\n /** The broadcast idle flag's rising edge: the instance went quiet. */\n onDone?: () => void;\n };\n\n export type WebsocketOptions = StatewireProtocol.Options & {\n sessionStore?: SessionStorage | undefined;\n url: string;\n /** The session does not exist on the server yet: the first attach waits for the first command send (or an explicit `reconnect()`). */\n isNew?: boolean;\n headers?: HeadersOption;\n protocols?: string | string[];\n query?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n webSocket?: new (url: string, protocols?: string | string[]) => WebSocket;\n onSessionLost?: OnSessionLost;\n onChange?: (connection: Connection) => void;\n onError?: (error: ConnectionError) => void;\n /** The broadcast idle flag's rising edge: the instance went quiet. */\n onDone?: () => void;\n };\n}\n"],"mappings":";;;;;AA+BA,MAAMyB,uBAAuB,EAC3BC,WACAC,SACAC,WACAC,UACAC,WAWAlB,mBAAmBY,uBAAuBG,eAExCf,mBAAmBS,wBAAwBO,iBAEzChB,mBAAmBW,iBAAiBM,gBAElCjB,mBAAmBU,aAAaQ,YAE9BjB,YAAYa,SAAS,CACvB,CACF,CACF,CACF;AAIF,MAAMc,mBAAmB7B,SAASc,mBAAmB;AAErD,MAAagB,gBAIXE,YAC+C;CAC/C,MAAMI,SAASzC,OAAOqC,OAAO;CAC7BI,OAAOC,UAAUL;CAEjB,MAAMhB,UAAUb,aACd6B,QAAQM,SAAStB,YAAYuB,KAAAA,IACzB,CAACnC,QAAQ,WAAW4B,QAAQM,QAAQtB,OAA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KU,QAAQ;CACpB;AACF"}
1
+ {"version":3,"file":"statewire.js","names":["StatewireDocuments","StatewireProtocol","StatewireHost","useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","createTapRoot","flushTapSync","resource","useContextProvider","useResource","useResources","withKey","ResourceElement","CONNECTED_CONNECTION","useStatewireCore","Statewire","TERMINAL","DocumentStorageContext","LinkContext","ProtocolContext","SessionStorageContext","useSessionTransport","transport","session","documents","protocol","link","StatewireClient","SessionStorage","Storage","Options","isNew","context","Readonly","Record","Context","SessionTransport","useStatewire","Commands","options","TState","TCommands","Helpers","latest","current","storage","undefined","wireVersion","applicationProtocols","keyPrefixes","value","localContext","connection","setContext","Object","entries","core","rematerialize","materializeKey","subscribe","listener","state","getState","isBusy","getBusy","failed","getFailed","source","selection","invoke","transportInvoke","transportSetContext","failures","transportFailures","method","params","Error","NonNullable","commands","CommandsProxy","retryFailed","entry","FailedCommand","retry","discardFailed","discard","StatewireResource","root","disposed","constructor","ClientRoot","getValue","Connection","Source","Selection","Promise","dispose","unmount","Range","Offer","initialState","optimistic","Optimistic","materialize","Materialize","onStateChange","ctx","changes","Changes","onCommandChange","update","CommandUpdate","onConnectionChange","onError","error","ConnectionError","failureCovered","ConnectionState","status","reason","degraded","attempt","cause","code","nextRetryAt","lastError","message","payload","reconnect","ConnectionStatus","draft","command","Command","OptimisticContext","ts","seq","clientId","SendFailure","fate","predecessorLost","OnSessionLost","pending","ReadonlyArray","produced","SessionCommand","meta","failure","wire","protocols","SessionLane","nextSeq","verdicts","SessionVerdict","SessionRecord","lanes","type","ready","flush","load","save","record","migrate","lock","fn","T","fin","Fin","HeadersOption","HeadersInit","staleAuth","HttpOptions","sessionStore","url","headers","fetch","globalThis","onSessionLost","onChange","onDone","WebsocketOptions","query","webSocket","WebSocket"],"sources":["../src/statewire.ts"],"sourcesContent":["import type { StatewireDocuments } from \"./wire/documents\";\nimport type { StatewireProtocol } from \"./wire/protocol\";\nimport type { StatewireHost } from \"./host\";\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n createTapRoot,\n flushTapSync,\n resource,\n useContextProvider,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { CONNECTED_CONNECTION, useStatewireCore } from \"./client/core\";\nimport type { Statewire } from \"./types\";\nimport type { TERMINAL } from \"./client/connection\";\nimport {\n DocumentStorageContext,\n LinkContext,\n ProtocolContext,\n SessionStorageContext,\n} from \"./client/sessionStore\";\n\nconst useSessionTransport = ({\n transport,\n session,\n documents,\n protocol,\n link,\n}: {\n transport: ResourceElement<Statewire<any, any>>;\n session: StatewireClient.SessionStorage | undefined;\n documents: StatewireDocuments.Storage | undefined;\n protocol: StatewireProtocol.Options;\n link: {\n isNew?: boolean | undefined;\n context?: Readonly<Record<string, Statewire.Context>> | undefined;\n };\n}): Statewire<unknown> =>\n useContextProvider(SessionStorageContext, session, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useContextProvider(DocumentStorageContext, documents, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useContextProvider(ProtocolContext, protocol, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useContextProvider(LinkContext, link, () =>\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useResource(transport),\n ),\n ),\n ),\n );\n\n// The transport owns the session; it reads the storage off the context this\n// wrapper's own fiber provides, so plain-React callers get a provider too.\nconst SessionTransport = resource(useSessionTransport);\n\nexport const useStatewire = <\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireClient.Options<TState, TCommands>,\n): StatewireClient.Helpers<TState, TCommands> => {\n const latest = useRef(options);\n latest.current = options;\n\n const session = useResources(\n options.storage?.session !== undefined\n ? [withKey(\"session\", options.storage.session)]\n : [],\n )[0];\n const documents = useResources(\n options.storage?.documents === undefined\n ? []\n : [withKey(\"documents\", options.storage.documents)],\n )[0];\n const protocol: StatewireProtocol.Options = {\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n ...(options.wireVersion !== undefined && {\n wireVersion: options.wireVersion,\n }),\n ...(options.applicationProtocols !== undefined && {\n applicationProtocols: options.applicationProtocols,\n }),\n ...(options.keyPrefixes !== undefined && {\n keyPrefixes: options.keyPrefixes,\n }),\n };\n const link = useMemo(\n () => ({\n ...(options.isNew === undefined ? {} : { isNew: options.isNew }),\n ...(options.context === undefined ? {} : { context: options.context }),\n }),\n [options.isNew, options.context],\n );\n const value = useResource(\n SessionTransport({\n transport: options.transport,\n session,\n documents,\n protocol,\n link,\n }),\n );\n const localContext =\n value.connection === undefined ? value.setContext : undefined;\n useEffect(() => {\n const current = latest.current;\n if (localContext === undefined || current.context === undefined) return;\n for (const [protocol, context] of Object.entries(current.context))\n localContext(protocol, context);\n }, [options.context, localContext]);\n const core = useStatewireCore(() => latest.current, value);\n useEffect(() => core.rematerialize(), [core, options.materializeKey]);\n const [subscribe] = useState(\n () => (listener: () => void) =>\n core.subscribe(() => flushTapSync(listener)),\n );\n\n const state = useSyncExternalStore(\n subscribe,\n core.getState,\n core.getState,\n ) as TState;\n const isBusy = useSyncExternalStore(subscribe, core.getBusy, core.getBusy);\n const failed = useSyncExternalStore(\n subscribe,\n core.getFailed,\n core.getFailed,\n );\n const connection = value.connection ?? CONNECTED_CONNECTION;\n const {\n documents: source,\n selection,\n invoke: transportInvoke,\n setContext: transportSetContext,\n failures: transportFailures,\n } = value;\n\n const invoke = useCallback(\n (protocol: string, method: string, params: readonly unknown[]) => {\n if (!transportInvoke)\n throw new Error(\n \"statewire: transport does not support protocol commands\",\n );\n return transportInvoke(protocol, method, params);\n },\n [transportInvoke],\n );\n\n const setContext = useCallback(\n (protocol: string, value: Statewire.Context) => {\n if (!transportSetContext)\n throw new Error(\"statewire: transport does not support context\");\n transportSetContext(protocol, value);\n },\n [transportSetContext],\n );\n\n return useMemo(() => {\n const failures = (): NonNullable<typeof transportFailures> => {\n if (!transportFailures) {\n throw new Error(\"statewire: this transport has no failed-send lane\");\n }\n return transportFailures;\n };\n return {\n state,\n documents: source,\n selection,\n invoke,\n setContext,\n getState: core.getState as () => TState,\n connection,\n commands: core.commands as Statewire.CommandsProxy<TCommands>,\n isBusy,\n failed,\n retryFailed: (entry: StatewireClient.FailedCommand) =>\n failures().retry(entry),\n discardFailed: (entry: StatewireClient.FailedCommand) =>\n failures().discard(entry),\n };\n }, [\n state,\n isBusy,\n failed,\n connection,\n core,\n source,\n selection,\n invoke,\n transportFailures,\n setContext,\n ]);\n};\n\nexport const StatewireResource = <\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireClient.Options<TState, TCommands>,\n): ResourceElement<StatewireClient.Helpers<TState, TCommands>> =>\n resource(useStatewire<TState, TCommands>)(options);\n\nexport class StatewireClient<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n> {\n private readonly root;\n private disposed = false;\n\n constructor(options: StatewireClient.Options<TState, TCommands>) {\n const ClientRoot = () => useStatewire<TState, TCommands>(options);\n this.root = createTapRoot(ClientRoot);\n }\n\n get state(): TState {\n return this.root.getValue().getState();\n }\n\n get connection(): StatewireClient.Connection {\n return this.root.getValue().connection;\n }\n\n get commands(): Statewire.CommandsProxy<TCommands> {\n return this.root.getValue().commands;\n }\n\n get documents(): StatewireDocuments.Source | undefined {\n return this.root.getValue().documents;\n }\n get selection(): StatewireProtocol.Selection | undefined {\n return this.root.getValue().selection;\n }\n invoke(\n protocol: string,\n method: string,\n params: readonly unknown[],\n ): Promise<unknown> {\n return this.root.getValue().invoke(protocol, method, params);\n }\n setContext(protocol: string, value: Statewire.Context): void {\n this.root.getValue().setContext(protocol, value);\n }\n get isBusy(): boolean {\n return this.root.getValue().isBusy;\n }\n\n get failed(): readonly StatewireClient.FailedCommand[] {\n return this.root.getValue().failed;\n }\n\n retryFailed(entry: StatewireClient.FailedCommand): Promise<unknown> {\n return this.root.getValue().retryFailed(entry);\n }\n\n discardFailed(entry: StatewireClient.FailedCommand): void {\n this.root.getValue().discardFailed(entry);\n }\n\n subscribe(listener: () => void): () => void {\n return this.root.subscribe(listener);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.root.unmount();\n }\n}\n\nexport namespace StatewireClient {\n export type Options<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n > = {\n protocol?: string;\n context?: Readonly<Record<string, Statewire.Context>>;\n keyPrefixes?: Readonly<Record<string, readonly string[]>>;\n wireVersion?: StatewireProtocol.Range;\n applicationProtocols?: readonly StatewireProtocol.Offer[] | \"*\";\n transport: ResourceElement<Statewire<TState, TCommands>>;\n /** The session does not exist on the server yet: the transport's first attach waits for the first command send; the transport's own `isNew` wins. */\n isNew?: boolean;\n /** Durable session: the mounted storage holds this client's lane identity and its un-durable commands, which resend on the next attach. */\n storage?:\n | {\n session?: ResourceElement<SessionStorage> | undefined;\n documents?: ResourceElement<StatewireDocuments.Storage> | undefined;\n }\n | undefined;\n /** Served as the canonical state until the attach snapshot; own commands fold over it. */\n initialState?: TState;\n optimistic?: Optimistic<NonNullable<TState>, TCommands>;\n materialize?: Materialize<NonNullable<TState>>;\n /** Republishes through `materialize` when it changes (`Object.is`); `materialize` itself is read fresh on every publish. */\n materializeKey?: unknown;\n onStateChange?: (\n state: NonNullable<TState>,\n ctx: { changes: Statewire.Changes },\n ) => void;\n onCommandChange?: (\n update: Statewire.CommandUpdate<TCommands>,\n ctx: { state: NonNullable<TState> },\n ) => void;\n onConnectionChange?: (connection: Connection) => void;\n onError?: (error: ConnectionError) => void;\n /** Drops a retained failed entry once a canonical snapshot shows its effect landed; checked against each new snapshot. */\n failureCovered?: (\n state: NonNullable<TState>,\n entry: FailedCommand,\n ) => boolean;\n };\n\n export type Helpers<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n > = {\n /** The statewire's state type — remote statewires include `undefined` until the first attach snapshot applies. */\n state: TState;\n documents: StatewireDocuments.Source | undefined;\n selection: StatewireProtocol.Selection | undefined;\n setContext: (protocol: string, value: Statewire.Context) => void;\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n /** Identity-stable across renders; reads the current canonical state without subscribing the caller. */\n getState: () => TState;\n connection: Connection;\n commands: Statewire.CommandsProxy<TCommands>;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n /** Non-accepted sends retained in the session record; reload with it. */\n failed: readonly FailedCommand[];\n /** Re-enqueues the entry's command on fresh clocks and removes the entry. */\n retryFailed: (entry: FailedCommand) => Promise<unknown>;\n /** Removes the entry. */\n discardFailed: (entry: FailedCommand) => void;\n };\n\n /** Connection lifecycle and whether its current state warrants a problem indicator. */\n export type ConnectionState =\n | { status: \"standby\"; reason: \"deferred\" | \"idle\"; degraded: false }\n | { status: \"connecting\"; degraded: false }\n | { status: \"connected\"; degraded: false }\n | {\n status: \"retrying\";\n degraded: true;\n attempt: number;\n /** Backoff details are absent while the retry dial is in flight. */\n cause?: \"dropped\" | \"reconnect\" | \"error\" | \"unauthorized\";\n code?: string;\n nextRetryAt?: number;\n lastError?: string;\n message?: string;\n }\n | {\n status: \"stopped\";\n degraded: true;\n reason:\n | \"gone\"\n | \"forbidden\"\n | \"protocol-error\"\n | \"unauthorized\"\n | \"storage-error\";\n message?: string;\n payload?: unknown;\n };\n export type Connection = ConnectionState & {\n error?: ConnectionError;\n reconnect: () => void;\n };\n export type ConnectionStatus = Connection[\"status\"];\n\n /**\n * Mutate the draft in place; the client records the next state plus the exact\n * changed paths. Re-run against the new base on every rebase.\n */\n export type Optimistic<\n TState,\n TCommands extends Statewire.Commands = Statewire.Commands,\n > = (\n draft: TState,\n command: Statewire.Command<TCommands>,\n ctx: OptimisticContext,\n ) => void;\n\n export type OptimisticContext = {\n ts: number;\n seq: number;\n clientId?: string;\n };\n\n /**\n * Mutate the draft to fold client-known facts into the state: server-accepted,\n * still-uncommitted intents (e.g. dispatch records into messages) or the live\n * state of a sibling statewire. Runs after the optimistic folds on every\n * published state; `materializeKey` republishes when the facts change.\n */\n export type Materialize<TState> = (draft: TState) => void;\n\n /**\n * fate: \"aborted\" = never sent, \"rejected\" = the server refused it\n * (`code` \"unknown-command\" | \"invalid-params\" for the static rejects,\n * code-less for handler rejects), \"lost\" = sent but no verdict will ever\n * arrive — the record is gone (a proven seq gap) or the channel died: it\n * may or may not have run, \"failed\" = the handler ran and threw,\n * \"crashed\" = the handler died involuntarily, \"expired\" = settled —\n * result, rejected, failed, or crashed — but the verdict outlived the\n * server's retention.\n * cause is which channel settled it: \"server\" = the server's answer;\n * the rest are channel deaths the client settled locally.\n */\n export type SendFailure =\n | {\n fate: \"rejected\";\n cause: \"server\";\n code?: string;\n message?: string;\n payload?: unknown;\n }\n | { fate: \"failed\"; cause: \"server\"; message?: string }\n | { fate: \"crashed\"; cause: \"server\" }\n | { fate: \"expired\"; cause: \"server\" }\n | {\n fate: \"aborted\";\n cause: \"unmount\" | \"stream-gone\" | \"session-lost\";\n predecessorLost?: true;\n }\n | {\n fate: \"lost\";\n cause: \"unmount\" | \"stream-gone\" | \"session-lost\";\n };\n\n /** Held commands a proven record gap settled `{fate: \"lost\", cause: \"session-lost\"}`; return \"requeue\" to re-enqueue them on the reset clocks. */\n export type OnSessionLost = (\n pending: ReadonlyArray<{\n method: string;\n params: readonly unknown[];\n ts: number;\n seq: number;\n clientId?: string;\n }>,\n ) => \"requeue\" | \"drop\";\n\n /** A non-accepted send retained for the user: the wire statement, its failure, and its original clocks. */\n export type FailedCommand = {\n readonly protocol: string;\n readonly produced?: SessionCommand[\"produced\"];\n readonly command: string;\n readonly params: readonly unknown[];\n readonly meta?: unknown;\n readonly failure: SendFailure;\n readonly ts: number;\n readonly seq: number;\n };\n\n /** A command as persisted while un-durable: its lane seq plus the wire statement. */\n export type SessionCommand = {\n seq: number;\n produced?: {\n wire: StatewireProtocol.Range;\n protocols: readonly StatewireProtocol.Offer[] | \"*\";\n };\n method: string;\n params: unknown[];\n meta?: unknown;\n };\n\n /** A durable lane: its cmd clock and the commands the server has not marked durable. */\n export type SessionLane = {\n nextSeq: number;\n commands: readonly SessionCommand[];\n /** Terminal verdicts parked for the sharer that minted the seq (shared storage only). */\n verdicts?: readonly SessionVerdict[];\n /** Non-accepted sends retained for the user; survive record rebases and resets. */\n failed?: readonly FailedCommand[];\n };\n\n /** The persisted session: the client identity plus one lane per durable protocol. */\n export type SessionRecord = {\n clientId: string;\n lanes: Readonly<Record<string, SessionLane>>;\n };\n\n /** A terminal verdict one sharer's connection carried, parked for the sharer awaiting the seq. */\n export type SessionVerdict = {\n seq: number;\n type: (typeof TERMINAL)[number];\n code?: string;\n message?: string;\n payload?: unknown;\n meta?: unknown;\n };\n\n /** Session storage seam with optional asynchronous hydration and persistence. */\n export type SessionStorage = {\n /** Resolves when a synchronous load can return the hydrated record. */\n ready?: Promise<void>;\n /** Resolves after all queued saves are persisted; awaited before sending statements. */\n flush?: () => void | Promise<void>;\n load: () => SessionRecord | null;\n save: (record: SessionRecord) => void;\n /** Upgrade incompatible stored commands; null discards the old record and starts a new client identity. */\n migrate?: (\n record: SessionRecord,\n current: NonNullable<SessionCommand[\"produced\"]>,\n ) => SessionRecord | null;\n /** Serializes record mutations across sharers; presence marks the storage shared. */\n lock?: <T>(fn: () => T | Promise<T>) => Promise<T>;\n /** Notifies of record saves by other sharers; returns unsubscribe. Required alongside `lock`. */\n subscribe?: (listener: () => void) => () => void;\n };\n\n /** Static headers, or a resolver invoked per request/attach; `staleAuth` is true right after an auth rejection. */\n export type ConnectionError = Error & { fin?: StatewireHost.Fin };\n\n export type HeadersOption =\n | HeadersInit\n | ((ctx: { staleAuth: boolean }) => HeadersInit | Promise<HeadersInit>);\n\n export type HttpOptions = StatewireProtocol.Options & {\n sessionStore?: SessionStorage | undefined;\n url: string;\n /** The session does not exist on the server yet: the first attach waits for the first command send (or an explicit `reconnect()`). */\n isNew?: boolean;\n headers?: HeadersOption;\n fetch?: typeof globalThis.fetch;\n onSessionLost?: OnSessionLost;\n onChange?: (connection: Connection) => void;\n onError?: (error: ConnectionError) => void;\n /** The broadcast idle flag's rising edge: the instance went quiet. */\n onDone?: () => void;\n };\n\n export type WebsocketOptions = StatewireProtocol.Options & {\n sessionStore?: SessionStorage | undefined;\n url: string;\n /** The session does not exist on the server yet: the first attach waits for the first command send (or an explicit `reconnect()`). */\n isNew?: boolean;\n headers?: HeadersOption;\n protocols?: string | string[];\n query?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n webSocket?: new (url: string, protocols?: string | string[]) => WebSocket;\n onSessionLost?: OnSessionLost;\n onChange?: (connection: Connection) => void;\n onError?: (error: ConnectionError) => void;\n /** The broadcast idle flag's rising edge: the instance went quiet. */\n onDone?: () => void;\n };\n}\n"],"mappings":";;;;;AA+BA,MAAMyB,uBAAuB,EAC3BC,WACAC,SACAC,WACAC,UACAC,WAWAlB,mBAAmBY,uBAAuBG,eAExCf,mBAAmBS,wBAAwBO,iBAEzChB,mBAAmBW,iBAAiBM,gBAElCjB,mBAAmBU,aAAaQ,YAE9BjB,YAAYa,SAAS,CACvB,CACF,CACF,CACF;AAIF,MAAMc,mBAAmB7B,SAASc,mBAAmB;AAErD,MAAagB,gBAIXE,YAC+C;CAC/C,MAAMI,SAASzC,OAAOqC,OAAO;CAC7BI,OAAOC,UAAUL;CAEjB,MAAMhB,UAAUb,aACd6B,QAAQM,SAAStB,YAAYuB,KAAAA,IACzB,CAACnC,QAAQ,WAAW4B,QAAQM,QAAQtB,OAAO,CAAC,IAC5C,CAAA,CACN,CAAC,CAAC;CACF,MAAMC,YAAYd,aAChB6B,QAAQM,SAASrB,cAAcsB,KAAAA,IAC3B,CAAA,IACA,CAACnC,QAAQ,aAAa4B,QAAQM,QAAQrB,SAAS,CAAC,CACtD,CAAC,CAAC;CACF,MAAMC,WAAsC;EAC1C,GAAIc,QAAQd,aAAaqB,KAAAA,KAAa,EAAErB,UAAUc,QAAQd,SAAS;EACnE,GAAIc,QAAQQ,gBAAgBD,KAAAA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aAAyC;EAC3C,OAAO,KAAKmC,KAAKI,SAAS,CAAC,CAACvC;CAC9B;CAEA,IAAI0B,WAA+C;EACjD,OAAO,KAAKS,KAAKI,SAAS,CAAC,CAACb;CAC9B;CAEA,IAAItD,YAAmD;EACrD,OAAO,KAAK+D,KAAKI,SAAS,CAAC,CAACnE;CAC9B;CACA,IAAI4C,YAAqD;EACvD,OAAO,KAAKmB,KAAKI,SAAS,CAAC,CAACvB;CAC9B;CACAC,OACE5C,UACAiD,QACAC,QACkB;EAClB,OAAO,KAAKY,KAAKI,SAAS,CAAC,CAACtB,OAAO5C,UAAUiD,QAAQC,MAAM;CAC7D;CACAtB,WAAW5B,UAAkByB,OAAgC;EAC3D,KAAKqC,KAAKI,SAAS,CAAC,CAACtC,WAAW5B,UAAUyB,KAAK;CACjD;CACA,IAAIa,SAAkB;EACpB,OAAO,KAAKwB,KAAKI,SAAS,CAAC,CAAC5B;CAC9B;CAEA,IAAIE,SAAmD;EACrD,OAAO,KAAKsB,KAAKI,SAAS,CAAC,CAAC1B;CAC9B;CAEAe,YAAYC,OAAwD;EAClE,OAAO,KAAKM,KAAKI,SAAS,CAAC,CAACX,YAAYC,KAAK;CAC/C;CAEAG,cAAcH,OAA4C;EACxD,KAAKM,KAAKI,SAAS,CAAC,CAACP,cAAcH,KAAK;CAC1C;CAEAtB,UAAUC,UAAkC;EAC1C,OAAO,KAAK2B,KAAK5B,UAAUC,QAAQ;CACrC;CAEAoC,UAAgB;EACd,IAAI,KAAKR,UAAU;EACnB,KAAKA,WAAW;EAChB,KAAKD,KAAKU,QAAQ;CACpB;AACF"}
package/dist/storage.d.ts CHANGED
@@ -1,30 +1,27 @@
1
- import { StatewireClient } from "./statewire.js";
2
- //#region src/storage.d.ts
1
+ import type { StatewireClient } from "./statewire.js";
3
2
  /** Persist sessions through a synchronous or asynchronous string storage backend. */
4
- declare const KeyValueSessionStorage: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [options: KeyValueSessionStorage.Options]>;
5
- declare namespace KeyValueSessionStorage {
6
- type Backend = {
7
- getItem: (key: string) => string | null | Promise<string | null>;
8
- setItem: (key: string, value: string) => void | Promise<void>;
9
- removeItem: (key: string) => void | Promise<void>;
10
- getAllKeys?: () => readonly string[] | Promise<readonly string[]>;
11
- /** Runs cleanup under exclusive access, skipping keys in use by another runtime. */
12
- withUnused?: (key: string, action: () => Promise<void>) => Promise<void>;
13
- };
14
- type Options = {
15
- backend: Backend;
16
- key: string;
17
- namespace?: string;
18
- /** The lane that sessions saved in a single-lane format lift into; defaults to the client's default protocol. */
19
- protocol?: string;
20
- migrate?: StatewireClient.SessionStorage["migrate"];
21
- retention?: {
22
- maxAgeMs?: number;
23
- maxEntries?: number;
3
+ export declare const KeyValueSessionStorage: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [options: KeyValueSessionStorage.Options]>;
4
+ export declare namespace KeyValueSessionStorage {
5
+ type Backend = {
6
+ getItem: (key: string) => string | null | Promise<string | null>;
7
+ setItem: (key: string, value: string) => void | Promise<void>;
8
+ removeItem: (key: string) => void | Promise<void>;
9
+ getAllKeys?: () => readonly string[] | Promise<readonly string[]>;
10
+ /** Runs cleanup under exclusive access, skipping keys in use by another runtime. */
11
+ withUnused?: (key: string, action: () => Promise<void>) => Promise<void>;
12
+ };
13
+ type Options = {
14
+ backend: Backend;
15
+ key: string;
16
+ namespace?: string;
17
+ /** The lane that sessions saved in a single-lane format lift into; defaults to the client's default protocol. */
18
+ protocol?: string;
19
+ migrate?: StatewireClient.SessionStorage["migrate"];
20
+ retention?: {
21
+ maxAgeMs?: number;
22
+ maxEntries?: number;
23
+ };
24
+ onError?: (error: unknown) => void;
24
25
  };
25
- onError?: (error: unknown) => void;
26
- };
27
26
  }
28
- //#endregion
29
- export { KeyValueSessionStorage };
30
27
  //# sourceMappingURL=storage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.ts","names":[],"sources":["../src/storage.ts"],"mappings":";;;cAggBa,oDAAsB,SAAA,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AAC,EAAE,eAAe,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;QACpD,SAAS,CAAC,EAAE;YAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;YAAC,UAAU,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;QACvD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;KACpC,CAAC;CACH"}
package/dist/storage.js CHANGED
@@ -2,7 +2,7 @@ import { DEFAULT_PROTOCOL, negotiationHeaders, protocolToken } from "./wire/prot
2
2
  import { wrapStorageError } from "./client/storageError.js";
3
3
  import { useEffect, useMemo, useRef } from "@assistant-ui/tap/react-shim";
4
4
  import { resource } from "@assistant-ui/tap";
5
- //#region src/storage.ts
5
+ // src/storage.ts
6
6
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
7
  const isOptionalString = (value) => value === void 0 || typeof value === "string";
8
8
  const isPositiveSafeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
@@ -330,7 +330,6 @@ const useKeyValueSessionStorage = (options) => {
330
330
  };
331
331
  /** Persist sessions through a synchronous or asynchronous string storage backend. */
332
332
  const KeyValueSessionStorage = resource(useKeyValueSessionStorage);
333
- //#endregion
334
333
  export { KeyValueSessionStorage };
335
334
 
336
335
  //# sourceMappingURL=storage.js.map
@@ -1,12 +1,9 @@
1
- import { StatewireEnvelope } from "../client/connection.js";
2
- //#region src/transports/fake-sse.d.ts
3
- type FakeStreamHandle = {
4
- clientId: string;
5
- send: (text: string) => void;
6
- close: () => void;
1
+ import type { StatewireEnvelope } from "../client/connection.js";
2
+ export type FakeStreamHandle = {
3
+ clientId: string;
4
+ send: (text: string) => void;
5
+ close: () => void;
7
6
  };
8
- declare const sseFrame: (envelope: StatewireEnvelope) => string;
9
- declare const openSSEStream: (streams: Set<FakeStreamHandle>, clientId: string, onOpen: (handle: FakeStreamHandle) => void, signal?: AbortSignal, headers?: Record<string, string>) => Response;
10
- //#endregion
11
- export { FakeStreamHandle, openSSEStream, sseFrame };
7
+ export declare const sseFrame: (envelope: StatewireEnvelope) => string;
8
+ export declare const openSSEStream: (streams: Set<FakeStreamHandle>, clientId: string, onOpen: (handle: FakeStreamHandle) => void, signal?: AbortSignal, headers?: Record<string, string>) => Response;
12
9
  //# sourceMappingURL=fake-sse.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fake-sse.d.ts","names":[],"sources":["../../src/transports/fake-sse.ts"],"mappings":";;KAEY;EACV;EACA,OAAO;EACP;;cAGW,WAAY,UAAU;cAGtB,gBACX,SAAS,IAAI,mBACb,kBACA,SAAS,QAAQ,2BACjB,SAAS,aACT,UAAU,2BACT"}
1
+ {"version":3,"file":"fake-sse.d.ts","sourceRoot":"","sources":["../../src/transports/fake-sse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gCAA6B;AAE9D,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AAEF,eAAO,MAAM,QAAQ,GAAI,UAAU,iBAAiB,WACX,CAAC;AAE1C,eAAO,MAAM,aAAa,GACxB,SAAS,GAAG,CAAC,gBAAgB,CAAC,EAC9B,UAAU,MAAM,EAChB,QAAQ,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,EAC1C,SAAS,WAAW,EACpB,UAAU,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAC/B,QAkCF,CAAC"}
@@ -1,4 +1,4 @@
1
- //#region src/transports/fake-sse.ts
1
+ // src/transports/fake-sse.ts
2
2
  const sseFrame = (envelope) => `data: ${JSON.stringify(envelope)}\n\n`;
3
3
  const openSSEStream = (streams, clientId, onOpen, signal, headers) => {
4
4
  const encoder = new TextEncoder();
@@ -36,7 +36,6 @@ const openSSEStream = (streams, clientId, onOpen, signal, headers) => {
36
36
  }
37
37
  });
38
38
  };
39
- //#endregion
40
39
  export { openSSEStream, sseFrame };
41
40
 
42
41
  //# sourceMappingURL=fake-sse.js.map
@@ -1,32 +1,26 @@
1
- import { StatewireHost } from "../host.js";
2
- import { Statewire } from "../types.js";
3
- import "../index.js";
4
- //#region src/transports/fixtures.d.ts
5
1
  /** Let several rounds of queued microtasks and op batches drain. */
6
- declare const settle: () => Promise<void>;
2
+ export declare const settle: () => Promise<void>;
7
3
  /** A minimal statewire host element: `{ count }` state with an `increment` command. */
8
- declare const createCounterElement: () => import("@assistant-ui/tap").ResourceElement<{
9
- state: {
10
- count: number;
11
- };
12
- commands: Statewire.CommandsProxy<StatewireHost.HandledCommands<{
13
- increment: () => void;
14
- }>>;
4
+ export declare const createCounterElement: () => import("@assistant-ui/tap").ResourceElement<{
5
+ state: {
6
+ count: number;
7
+ };
8
+ commands: import("../index.js").Statewire.CommandsProxy<import("../host.js").StatewireHost.HandledCommands<{
9
+ increment: () => void;
10
+ }>>;
15
11
  }>;
16
12
  /** Serialize a one-statement cmd-lane frame as a client would send it. */
17
- declare const commandFrame: (method: string, seq: number, params?: unknown[]) => string;
18
- type SocketRecorder = {
19
- sent: string[];
20
- closes: {
21
- code?: number;
22
- reason?: string;
23
- }[];
24
- last: () => any;
25
- send: (data: string) => void;
26
- close: (code?: number, reason?: string) => void;
13
+ export declare const commandFrame: (method: string, seq: number, params?: unknown[]) => string;
14
+ export type SocketRecorder = {
15
+ sent: string[];
16
+ closes: {
17
+ code?: number;
18
+ reason?: string;
19
+ }[];
20
+ last: () => any;
21
+ send: (data: string) => void;
22
+ close: (code?: number, reason?: string) => void;
27
23
  };
28
24
  /** Record sent frames and close calls; `last()` parses the latest frame. */
29
- declare const createSocketRecorder: () => SocketRecorder;
30
- //#endregion
31
- export { SocketRecorder, commandFrame, createCounterElement, createSocketRecorder, settle };
25
+ export declare const createSocketRecorder: () => SocketRecorder;
32
26
  //# sourceMappingURL=fixtures.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fixtures.d.ts","names":[],"sources":["../../src/transports/fixtures.ts"],"mappings":";;;;;cAKa,cAAM;;cAKN,wDAAoB;;;;YAApB,UAAA,cAAA,cAAA;;;;;cAYA,eACX,gBACA,aACA;KAGU;EACV;EACA;IAAU;IAAe;;EACzB;EACA,OAAO;EACP,QAAQ,eAAe;;;cAIZ,4BAA2B"}
1
+ {"version":3,"file":"fixtures.d.ts","sourceRoot":"","sources":["../../src/transports/fixtures.ts"],"names":[],"mappings":"AAIA,oEAAoE;AACpE,eAAO,MAAM,MAAM,qBAElB,CAAC;AAEF,uFAAuF;AACvF,eAAO,MAAM,oBAAoB;;;;;;;EAS3B,CAAC;AAEP,0EAA0E;AAC1E,eAAO,MAAM,YAAY,GACvB,QAAQ,MAAM,EACd,KAAK,MAAM,EACX,SAAQ,OAAO,EAAO,WACoD,CAAC;AAE7E,MAAM,MAAM,cAAc,GAAG;IAC3B,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,MAAM,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC7C,IAAI,EAAE,MAAM,GAAG,CAAC;IAChB,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;CACjD,CAAC;AAEF,4EAA4E;AAC5E,eAAO,MAAM,oBAAoB,QAAO,cAiBvC,CAAC"}
@@ -2,7 +2,7 @@ import { useStatewireCommands, useStatewireState } from "../host/host.js";
2
2
  import "../host.js";
3
3
  import { tick } from "./testing.js";
4
4
  import { resource } from "@assistant-ui/tap";
5
- //#region src/transports/fixtures.ts
5
+ // src/transports/fixtures.ts
6
6
  /** Let several rounds of queued microtasks and op batches drain. */
7
7
  const settle = async () => {
8
8
  for (let i = 0; i < 3; i++) await tick();
@@ -43,7 +43,6 @@ const createSocketRecorder = () => {
43
43
  }
44
44
  };
45
45
  };
46
- //#endregion
47
46
  export { commandFrame, createCounterElement, createSocketRecorder, settle };
48
47
 
49
48
  //# sourceMappingURL=fixtures.js.map
@@ -1,13 +1,10 @@
1
- import { RemoteLink, StatewireRemoteProps } from "./sse.js";
2
- import { StatewireClient } from "../statewire.js";
3
- import { Statewire } from "../types.js";
4
- import { StatewireSessionOptions } from "../client/session.js";
5
- //#region src/transports/remote.d.ts
6
- declare const useStatewireRemote: <TOptions extends {
7
- url: string;
8
- onChange?: (connection: StatewireClient.Connection) => void;
9
- onDone?: () => void;
1
+ import type { Statewire } from "../types.js";
2
+ import type { StatewireSessionOptions } from "../client/session.js";
3
+ import type { StatewireClient } from "../statewire.js";
4
+ import type { RemoteLink, StatewireRemoteProps } from "./sse.js";
5
+ export declare const useStatewireRemote: <TOptions extends {
6
+ url: string;
7
+ onChange?: (connection: StatewireClient.Connection) => void;
8
+ onDone?: () => void;
10
9
  } & StatewireSessionOptions>(options: TOptions, useLink: (options: TOptions, ctx: StatewireRemoteProps) => RemoteLink) => Statewire<any, any>;
11
- //#endregion
12
- export { useStatewireRemote };
13
10
  //# sourceMappingURL=remote.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote.d.ts","names":[],"sources":["../../src/transports/remote.ts"],"mappings":";;;;;cAiBa,qBACX;EACE;EACA,YAAY,YAAY,gBAAgB;EACxC;IACE,yBAEJ,SAAS,UACT,UAAU,SAAS,UAAU,KAAK,yBAAyB,eAC1D"}
1
+ {"version":3,"file":"remote.d.ts","sourceRoot":"","sources":["../../src/transports/remote.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAiB;AAW1C,OAAO,KAAK,EAAE,uBAAuB,EAAE,6BAA0B;AACjE,OAAO,KAAK,EAAE,eAAe,EAAE,wBAAqB;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,oBAAoB,EAAE,iBAAc;AAE9D,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,SAAS;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,CAAC,UAAU,KAAK,IAAI,CAAC;IAC5D,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC;CACrB,GAAG,uBAAuB,EAE3B,SAAS,QAAQ,EACjB,SAAS,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,oBAAoB,KAAK,UAAU,KACpE,SAAS,CAAC,GAAG,EAAE,GAAG,CAuCpB,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { LinkContext, ProtocolContext } from "../client/sessionStore.js";
2
2
  import { discardFailed, documentSource, failedCommands, invokeProtocol, retryFailed, setContext, setTransport, useStatewireSession } from "../client/session.js";
3
3
  import { useContext, useEffect, useMemo } from "@assistant-ui/tap/react-shim";
4
- //#region src/transports/remote.ts
4
+ // src/transports/remote.ts
5
5
  const useStatewireRemote = (options, useLink) => {
6
6
  const configured = {
7
7
  ...useContext(ProtocolContext),
@@ -35,7 +35,6 @@ const useStatewireRemote = (options, useLink) => {
35
35
  }
36
36
  };
37
37
  };
38
- //#endregion
39
38
  export { useStatewireRemote };
40
39
 
41
40
  //# sourceMappingURL=remote.js.map
@@ -1,5 +1,2 @@
1
- //#region src/transports/sse-parser.d.ts
2
- declare const createSseParser: () => ((chunk: string) => string[]);
3
- //#endregion
4
- export { createSseParser };
1
+ export declare const createSseParser: () => ((chunk: string) => string[]);
5
2
  //# sourceMappingURL=sse-parser.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sse-parser.d.ts","names":[],"sources":["../../src/transports/sse-parser.ts"],"mappings":";cAAa,yBAAwB"}
1
+ {"version":3,"file":"sse-parser.d.ts","sourceRoot":"","sources":["../../src/transports/sse-parser.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,QAAO,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,EAAE,CAuB9D,CAAC"}
@@ -1,4 +1,4 @@
1
- //#region src/transports/sse-parser.ts
1
+ // src/transports/sse-parser.ts
2
2
  const createSseParser = () => {
3
3
  let buffer = "";
4
4
  let dataLines = [];
@@ -20,7 +20,6 @@ const createSseParser = () => {
20
20
  return events;
21
21
  };
22
22
  };
23
- //#endregion
24
23
  export { createSseParser };
25
24
 
26
25
  //# sourceMappingURL=sse-parser.js.map
@@ -1,62 +1,60 @@
1
- import { StatewireHost } from "../host.js";
2
- import { StatewireDocument } from "../document.js";
3
- import { StatewireCmd, StatewireSyn } from "../client/connection.js";
4
- import { StatewireClient } from "../statewire.js";
5
- import { Statewire } from "../types.js";
6
- import { ResourceElement } from "@assistant-ui/tap";
7
- //#region src/transports/sse.d.ts
1
+ import type { StatewireDocument } from "../document.js";
2
+ import type { ResourceElement } from "@assistant-ui/tap";
3
+ import type { StatewireCmd, StatewireSyn } from "../client/connection.js";
4
+ import type { Statewire } from "../types.js";
5
+ import type { StatewireClient } from "../statewire.js";
6
+ import type { StatewireHost } from "../host.js";
8
7
  /** A client frame's lanes: stamped statements, strictly consecutive per lane. */
9
- type StatewireFrame = {
10
- ctx?: ({
11
- protocol: string;
12
- } & StatewireDocument.Encoded)[];
13
- cmd?: {
14
- protocol: string;
15
- method: string;
16
- params: unknown[];
17
- meta?: unknown;
18
- seq: number;
19
- }[];
8
+ export type StatewireFrame = {
9
+ ctx?: ({
10
+ protocol: string;
11
+ } & StatewireDocument.Encoded)[];
12
+ cmd?: {
13
+ protocol: string;
14
+ method: string;
15
+ params: unknown[];
16
+ meta?: unknown;
17
+ seq: number;
18
+ }[];
20
19
  };
21
- type StatewireRemoteProps = {
22
- beforeAttach?: () => void | Promise<void>;
23
- clientId: string;
24
- /** Lanes to ride the attach frame: ephemeral-lane statements, plus durable cmds on no-lease supersession; records the included entries. */
25
- takeAttachLanes: () => StatewireFrame | null;
26
- onHello: (args: {
27
- ops: unknown[];
28
- syn: StatewireSyn;
29
- }) => void;
30
- onOps: (args: {
31
- ops: unknown[];
32
- cmds: StatewireCmd[];
33
- }) => void;
34
- onCmds: (cmds: StatewireCmd[]) => void;
35
- onRefusal: (syn: StatewireSyn) => void;
36
- onIdle: (level: boolean) => void;
37
- onDetach: () => void;
38
- onFinish: (args: StatewireHost.Fin) => void;
20
+ export type StatewireRemoteProps = {
21
+ beforeAttach?: () => void | Promise<void>;
22
+ clientId: string;
23
+ /** Lanes to ride the attach frame: ephemeral-lane statements, plus durable cmds on no-lease supersession; records the included entries. */
24
+ takeAttachLanes: () => StatewireFrame | null;
25
+ onHello: (args: {
26
+ ops: unknown[];
27
+ syn: StatewireSyn;
28
+ }) => void;
29
+ onOps: (args: {
30
+ ops: unknown[];
31
+ cmds: StatewireCmd[];
32
+ }) => void;
33
+ onCmds: (cmds: StatewireCmd[]) => void;
34
+ onRefusal: (syn: StatewireSyn) => void;
35
+ onIdle: (level: boolean) => void;
36
+ onDetach: () => void;
37
+ onFinish: (args: StatewireHost.Fin) => void;
39
38
  };
40
- type StatewireSubmitResult = {
41
- type: "ok";
39
+ export type StatewireSubmitResult = {
40
+ type: "ok";
42
41
  } | {
43
- type: "refusal";
44
- syn: StatewireSyn;
42
+ type: "refusal";
43
+ syn: StatewireSyn;
45
44
  } | {
46
- type: "stale-lease";
45
+ type: "stale-lease";
47
46
  } | {
48
- type: "no-lease";
47
+ type: "no-lease";
49
48
  };
50
- type ConnectionState = StatewireClient.ConnectionState;
49
+ export type ConnectionState = StatewireClient.ConnectionState;
51
50
  /** The live wire a remote session drives: connection status plus frame submission. */
52
- type RemoteLink = {
53
- storageFailed: (error: Error) => void;
54
- connection: StatewireClient.Connection;
55
- /** A deferred first attach still waiting; `reconnect()` releases it. */
56
- parked: boolean;
57
- send: (frame: StatewireFrame) => Promise<StatewireSubmitResult>;
51
+ export type RemoteLink = {
52
+ storageFailed: (error: Error) => void;
53
+ protocolFailed: (error: Error) => void;
54
+ connection: StatewireClient.Connection;
55
+ /** A deferred first attach still waiting; `reconnect()` releases it. */
56
+ parked: boolean;
57
+ send: (frame: StatewireFrame) => Promise<StatewireSubmitResult>;
58
58
  };
59
- declare const StatewireHttp: <TState = any, TCommands extends Statewire.Commands = Statewire.Commands>(options: StatewireClient.HttpOptions) => ResourceElement<Statewire<TState | undefined, TCommands>>;
60
- //#endregion
61
- export { ConnectionState, RemoteLink, StatewireFrame, StatewireHttp, StatewireRemoteProps, StatewireSubmitResult };
59
+ export declare const StatewireHttp: <TState = any, TCommands extends Statewire.Commands = Statewire.Commands>(options: StatewireClient.HttpOptions) => ResourceElement<Statewire<TState | undefined, TCommands>>;
62
60
  //# sourceMappingURL=sse.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sse.d.ts","names":[],"sources":["../../src/transports/sse.ts"],"mappings":";;;;;;;;KA2BY;EACV;IAAS;MAAqB,kBAAkB;EAChD;IACE;IACA;IACA;IACA;IACA;;;KAIQ;EACV,4BAA4B;EAC5B;;EAEA,uBAAuB;EACvB,UAAU;IAAQ;IAAgB,KAAK;;EACvC,QAAQ;IAAQ;IAAgB,MAAM;;EACtC,SAAS,MAAM;EACf,YAAY,KAAK;EACjB,SAAS;EACT;EACA,WAAW,MAAM,cAAc;;KAGrB;EACN;;EACA;EAAiB,KAAK;;EACtB;;EACA;;KAEM,kBAAkB,gBAAgB;;KAGlC;EACV,gBAAgB,OAAO;EACvB,YAAY,gBAAgB;;EAE5B;EACA,OAAO,OAAO,mBAAmB,QAAQ;;cAyP9B,gBACX,cACA,kBAAkB,UAAU,WAAW,UAAU,UAEjD,SAAS,gBAAgB,gBACtB,gBAAgB,UAAU,oBAAoB"}
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/transports/sse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,uBAAoB;AAErD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAWzD,OAAO,KAAK,EAGV,YAAY,EAEZ,YAAY,EACb,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I,EAAE,aAAa,CAAC,GAAG,KAAK,IAAI,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAC7B;IAAE,IAAI,EAAE,IAAI,CAAA;CAAE,GACd;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,GAAG,EAAE,YAAY,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC;AAEzB,MAAM,MAAM,eAAe,GAAG,eAAe,CAAC,eAAe,CAAC;AAE9D,sFAAsF;AACtF,MAAM,MAAM,UAAU,GAAG;IACvB,aAAa,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACtC,cAAc,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACvC,UAAU,EAAE,eAAe,CAAC,UAAU,CAAC;IACvC,wEAAwE;IACxE,MAAM,EAAE,OAAO,CAAC;IAChB,IAAI,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,OAAO,CAAC,qBAAqB,CAAC,CAAC;CACjE,CAAC;AAmQF,eAAO,MAAM,aAAa,EAAiC,CACzD,MAAM,GAAG,GAAG,EACZ,SAAS,SAAS,SAAS,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,EAEzD,OAAO,EAAE,eAAe,CAAC,WAAW,KACjC,eAAe,CAAC,SAAS,CAAC,MAAM,GAAG,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC"}
@@ -1,11 +1,17 @@
1
1
  import { negotiationHeaders, parseNegotiation } from "../wire/protocol.js";
2
- import { createSseParser } from "./sse-parser.js";
3
2
  import { timing } from "../client/timing.js";
4
3
  import { classify, handleEnvelope, resolveHeaders, settleFin, useLink, validateRefusalSyn } from "../client/connection.js";
4
+ import { createSseParser } from "./sse-parser.js";
5
5
  import { useStatewireRemote } from "./remote.js";
6
6
  import { flushTapSync, resource } from "@assistant-ui/tap";
7
- //#region src/transports/sse.ts
7
+ // src/transports/sse.ts
8
8
  const LEASE_HEADER = "Statewire-Lease";
9
+ let warnedNoLease = false;
10
+ const warnNoLease = () => {
11
+ if (warnedNoLease) return;
12
+ warnedNoLease = true;
13
+ console.warn("statewire: SSE attach returned no readable Statewire-Lease header; commands will re-attach the stream. Cross-origin hosts must expose it (Access-Control-Expose-Headers: Statewire-Lease).");
14
+ };
9
15
  const baseUrl = (options) => options.url.replace(/\/$/, "");
10
16
  const withExtra = (headers, extra) => {
11
17
  const merged = new Headers(headers);
@@ -76,6 +82,7 @@ const attemptStream = async (c, options, abort) => {
76
82
  }
77
83
  if (!res.body) throw new Error("statewire: protocol error: stream response has no body");
78
84
  c.lease = res.headers.get(LEASE_HEADER);
85
+ if (c.lease === null) warnNoLease();
79
86
  const reader = res.body.getReader();
80
87
  const cancel = () => {
81
88
  reader.cancel().catch(() => {});
@@ -159,7 +166,6 @@ const useSseLink = (options, ctx) => useLink({
159
166
  });
160
167
  const useStatewireHttp = (options) => useStatewireRemote(options, useSseLink);
161
168
  const StatewireHttp = resource(useStatewireHttp);
162
- //#endregion
163
169
  export { StatewireHttp };
164
170
 
165
171
  //# sourceMappingURL=sse.js.map