@nice-code/action 0.8.0 → 0.9.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 (145) hide show
  1. package/build/ActionDevtoolsCore-B4s6aGvI.d.ts +79 -0
  2. package/build/ActionDevtoolsCore-BLeY_N-3.js +159 -0
  3. package/build/ActionDevtoolsCore-BLeY_N-3.js.map +1 -0
  4. package/build/ActionDevtoolsCore-Pg7ERO3L.d.ts +79 -0
  5. package/build/ActionDevtoolsCore-yfJ9tkvl.js +154 -0
  6. package/build/ActionDevtoolsCore-yfJ9tkvl.js.map +1 -0
  7. package/build/ActionPayload.types-BN-rXFBK.d.ts +2328 -0
  8. package/build/ActionPayload.types-D28ELKXC.d.ts +2328 -0
  9. package/build/RunningAction.types-C176rqHG.js +22 -0
  10. package/build/RunningAction.types-C176rqHG.js.map +1 -0
  11. package/build/RunningAction.types-DjCX1xp5.js +39 -0
  12. package/build/RunningAction.types-DjCX1xp5.js.map +1 -0
  13. package/build/devtools/browser/index.d.ts +17 -0
  14. package/build/devtools/browser/index.js +3762 -5145
  15. package/build/devtools/browser/index.js.map +1 -0
  16. package/build/devtools/server/index.d.ts +35 -0
  17. package/build/devtools/server/index.js +97 -261
  18. package/build/devtools/server/index.js.map +1 -0
  19. package/build/index.d.ts +2 -0
  20. package/build/index.js +3872 -3870
  21. package/build/index.js.map +1 -0
  22. package/build/react-query/index.d.ts +17 -0
  23. package/build/react-query/index.js +60 -60
  24. package/build/react-query/index.js.map +1 -0
  25. package/package.json +11 -10
  26. package/build/types/ActionDefinition/Action/Action.combined.types.d.ts +0 -37
  27. package/build/types/ActionDefinition/Action/ActionBase.d.ts +0 -14
  28. package/build/types/ActionDefinition/Action/ActionBase.types.d.ts +0 -24
  29. package/build/types/ActionDefinition/Action/Context/ActionContext.d.ts +0 -25
  30. package/build/types/ActionDefinition/Action/Context/ActionContext.types.d.ts +0 -35
  31. package/build/types/ActionDefinition/Action/Core/ActionCore.d.ts +0 -19
  32. package/build/types/ActionDefinition/Action/Core/ActionCore.types.d.ts +0 -10
  33. package/build/types/ActionDefinition/Action/Payload/ActionPayload.d.ts +0 -14
  34. package/build/types/ActionDefinition/Action/Payload/ActionPayload.types.d.ts +0 -110
  35. package/build/types/ActionDefinition/Action/Payload/ActionPayload_Progress.d.ts +0 -15
  36. package/build/types/ActionDefinition/Action/Payload/ActionPayload_Request.d.ts +0 -26
  37. package/build/types/ActionDefinition/Action/Payload/ActionPayload_Result.d.ts +0 -19
  38. package/build/types/ActionDefinition/Action/RunningAction.d.ts +0 -36
  39. package/build/types/ActionDefinition/Action/RunningAction.types.d.ts +0 -73
  40. package/build/types/ActionDefinition/Domain/ActionDomain.d.ts +0 -42
  41. package/build/types/ActionDefinition/Domain/ActionDomain.types.d.ts +0 -43
  42. package/build/types/ActionDefinition/Domain/ActionDomainBase.d.ts +0 -14
  43. package/build/types/ActionDefinition/Domain/ActionRootDomain.d.ts +0 -24
  44. package/build/types/ActionDefinition/Domain/helpers/createRootActionDomain.d.ts +0 -5
  45. package/build/types/ActionDefinition/Schema/ActionSchema.d.ts +0 -68
  46. package/build/types/ActionDefinition/Schema/ActionSchema.types.d.ts +0 -28
  47. package/build/types/ActionRuntime/ActionDomainManager.d.ts +0 -13
  48. package/build/types/ActionRuntime/ActionRuntime.d.ts +0 -78
  49. package/build/types/ActionRuntime/ActionRuntime.types.d.ts +0 -22
  50. package/build/types/ActionRuntime/ActionRuntimeManager.d.ts +0 -20
  51. package/build/types/ActionRuntime/Handler/ActionHandler.d.ts +0 -16
  52. package/build/types/ActionRuntime/Handler/ActionHandler.types.d.ts +0 -65
  53. package/build/types/ActionRuntime/Handler/ExternalClient/ActionExternalClientHandler.d.ts +0 -45
  54. package/build/types/ActionRuntime/Handler/ExternalClient/ActionExternalClientHandler.types.d.ts +0 -7
  55. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/ConnectionTransportManager.d.ts +0 -16
  56. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Custom/CustomConnection.d.ts +0 -7
  57. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Custom/CustomTransport.d.ts +0 -43
  58. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Custom/TransportCustom.types.d.ts +0 -11
  59. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Http/HttpConnection.d.ts +0 -8
  60. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Http/HttpTransport.d.ts +0 -26
  61. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Http/TransportHttp.types.d.ts +0 -16
  62. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Transport.d.ts +0 -27
  63. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/Transport.types.d.ts +0 -131
  64. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/TransportConnection.d.ts +0 -27
  65. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/TransportWebSocket.types.d.ts +0 -41
  66. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/WebSocketConnection.d.ts +0 -34
  67. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/WebSocketTransport.d.ts +0 -60
  68. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/actionFrameCrypto.d.ts +0 -31
  69. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/actionWireCodec.d.ts +0 -41
  70. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/actionWsHandshake.d.ts +0 -187
  71. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/createBinaryWsAdapter.d.ts +0 -20
  72. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/createBinaryWsSessionFactory.d.ts +0 -31
  73. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/secureWsChannel.d.ts +0 -63
  74. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/WebSocket/ws_util.d.ts +0 -11
  75. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/err_nice_transport.d.ts +0 -36
  76. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/err_nice_transport_ws.d.ts +0 -18
  77. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/helpers/addTransportStatusMetadata.d.ts +0 -2
  78. package/build/types/ActionRuntime/Handler/ExternalClient/Transport/helpers/createUnsetTransportResolvers.d.ts +0 -2
  79. package/build/types/ActionRuntime/Handler/ExternalClient/err_nice_external_client.d.ts +0 -5
  80. package/build/types/ActionRuntime/Handler/Local/ActionLocalHandler.d.ts +0 -55
  81. package/build/types/ActionRuntime/Handler/Local/ActionLocalHandler.types.d.ts +0 -7
  82. package/build/types/ActionRuntime/Handler/Server/ActionServerHandler.d.ts +0 -254
  83. package/build/types/ActionRuntime/Handler/Server/WsConnectionStateStore.d.ts +0 -61
  84. package/build/types/ActionRuntime/Handler/Server/createActionFetchHandler.d.ts +0 -40
  85. package/build/types/ActionRuntime/Handler/Server/createSecureActionServer.d.ts +0 -71
  86. package/build/types/ActionRuntime/HandlerCallStack.d.ts +0 -3
  87. package/build/types/ActionRuntime/Routing/ActionRouter.d.ts +0 -55
  88. package/build/types/ActionRuntime/Routing/ActionRouter.types.d.ts +0 -20
  89. package/build/types/ActionRuntime/RuntimeCoordinate.d.ts +0 -58
  90. package/build/types/ActionRuntime/test/helpers/new_action_test_data.d.ts +0 -207
  91. package/build/types/ActionRuntime/utils/runtimeCoordinateToStringIds.d.ts +0 -2
  92. package/build/types/devtools/browser/NiceActionDevtools.d.ts +0 -14
  93. package/build/types/devtools/browser/components/ActionErrorDisplay.d.ts +0 -5
  94. package/build/types/devtools/browser/components/CallStackSection.d.ts +0 -8
  95. package/build/types/devtools/browser/components/ChildDispatchChips.d.ts +0 -6
  96. package/build/types/devtools/browser/components/Chip.d.ts +0 -22
  97. package/build/types/devtools/browser/components/DetailSection.d.ts +0 -5
  98. package/build/types/devtools/browser/components/DomainChip.d.ts +0 -8
  99. package/build/types/devtools/browser/components/HandlerChips.d.ts +0 -21
  100. package/build/types/devtools/browser/components/Icon.d.ts +0 -16
  101. package/build/types/devtools/browser/components/MetaSection.d.ts +0 -4
  102. package/build/types/devtools/browser/components/NiceErrorDisplay.d.ts +0 -19
  103. package/build/types/devtools/browser/components/OriginChip.d.ts +0 -15
  104. package/build/types/devtools/browser/components/RoutingSection.d.ts +0 -5
  105. package/build/types/devtools/browser/components/RunningTimer.d.ts +0 -7
  106. package/build/types/devtools/browser/components/SectionLabel.d.ts +0 -1
  107. package/build/types/devtools/browser/components/StackTraceSection.d.ts +0 -9
  108. package/build/types/devtools/browser/components/Tooltip.d.ts +0 -1
  109. package/build/types/devtools/browser/components/action_detail/ActionDetailPanel.d.ts +0 -7
  110. package/build/types/devtools/browser/components/action_list/ActionEntryRow.d.ts +0 -14
  111. package/build/types/devtools/browser/components/action_list/ActionInputAndOutputChip.d.ts +0 -11
  112. package/build/types/devtools/browser/components/action_list/ActionList.d.ts +0 -10
  113. package/build/types/devtools/browser/components/action_list/IoTooltipContent.d.ts +0 -3
  114. package/build/types/devtools/browser/components/action_list/action_list.types.d.ts +0 -4
  115. package/build/types/devtools/browser/components/sourceMapResolver.d.ts +0 -6
  116. package/build/types/devtools/browser/components/utils.d.ts +0 -20
  117. package/build/types/devtools/browser/devtools_storage.d.ts +0 -6
  118. package/build/types/devtools/browser/index.d.ts +0 -3
  119. package/build/types/devtools/browser/ui_util/size.d.ts +0 -6
  120. package/build/types/devtools/core/ActionDevtools.types.d.ts +0 -55
  121. package/build/types/devtools/core/ActionDevtoolsCore.d.ts +0 -17
  122. package/build/types/devtools/core/devtools_colors.d.ts +0 -38
  123. package/build/types/devtools/server/NiceActionServerDevtools.d.ts +0 -30
  124. package/build/types/devtools/server/index.d.ts +0 -3
  125. package/build/types/errors/err_nice_action.d.ts +0 -96
  126. package/build/types/index.d.ts +0 -43
  127. package/build/types/nice_action.static.d.ts +0 -3
  128. package/build/types/react-query/hooks/useActionMutation.d.ts +0 -10
  129. package/build/types/react-query/hooks/useActionQuery.d.ts +0 -17
  130. package/build/types/react-query/index.d.ts +0 -2
  131. package/build/types/utils/assertIsActionJson.d.ts +0 -2
  132. package/build/types/utils/decodeActionFrame.d.ts +0 -17
  133. package/build/types/utils/getAssumedRuntimeEnvironment.d.ts +0 -2
  134. package/build/types/utils/hashPayloadData.d.ts +0 -5
  135. package/build/types/utils/isActionPayload_Any_JsonObject.d.ts +0 -2
  136. package/build/types/utils/isActionPayload_Progress_JsonObject.d.ts +0 -2
  137. package/build/types/utils/isActionPayload_Request_JsonObject.d.ts +0 -2
  138. package/build/types/utils/isActionPayload_Result_JsonObject.d.ts +0 -2
  139. package/build/types/utils/isAction_Any_Instance.d.ts +0 -3
  140. package/build/types/utils/isAction_Any_JsonObject.d.ts +0 -2
  141. package/build/types/utils/isAction_Base_JsonObject.d.ts +0 -2
  142. package/build/types/utils/isAction_Context_JsonObject.d.ts +0 -2
  143. package/build/types/utils/isAction_Core_JsonObject.d.ts +0 -2
  144. package/build/types/utils/typescript/MaybePromise.d.ts +0 -1
  145. package/build/types/utils/wait.utils.d.ts +0 -13
@@ -1,254 +0,0 @@
1
- import type { ClientCryptoKeyLink, TTypeAndId } from "@nice-code/util";
2
- import type { TDistributeActionPayload_Request } from "../../../ActionDefinition/Action/Action.combined.types";
3
- import type { IActionRouteItemHandler } from "../../../ActionDefinition/Action/Payload/ActionPayload.types";
4
- import { type TActionPayload_Any_Instance, type TActionPayload_Any_JsonObject } from "../../../ActionDefinition/Action/Payload/ActionPayload.types";
5
- import type { ActionPayload_Request } from "../../../ActionDefinition/Action/Payload/ActionPayload_Request";
6
- import { RunningAction } from "../../../ActionDefinition/Action/RunningAction";
7
- import type { ActionDomain } from "../../../ActionDefinition/Domain/ActionDomain";
8
- import type { IActionDomain } from "../../../ActionDefinition/Domain/ActionDomain.types";
9
- import { ActionRuntime } from "../../ActionRuntime";
10
- import { type IRuntimeCoordinate, RuntimeCoordinate } from "../../RuntimeCoordinate";
11
- import type { IHandleActionOptions } from "../ActionHandler.types";
12
- import { ActionExternalClientHandler } from "../ExternalClient/ActionExternalClientHandler";
13
- import { ESecurityLevel, type IClientVerifyKeyResolver, type IHandshakeEncryptionKeyMaterial } from "../ExternalClient/Transport/WebSocket/actionWsHandshake";
14
- import type { IActionTransportReadyData_Ws } from "../ExternalClient/Transport/WebSocket/TransportWebSocket.types";
15
- import { ActionLocalHandler } from "../Local/ActionLocalHandler";
16
- import type { THandleActionExecutionFn } from "../Local/ActionLocalHandler.types";
17
- import { type IWsConnectionStateStoreOptions, WsConnectionStateStore } from "./WsConnectionStateStore";
18
- /** The codec shape `ActionServerHandler` uses to pack/unpack frames — same as the WS transport's. */
19
- export type TActionChannelFormatMessage = NonNullable<IActionTransportReadyData_Ws["formatMessage"]>;
20
- /** How a connection encodes its frames, remembered so we answer each client in its own dialect. */
21
- export type TActionConnectionEncoding = "json" | "binary";
22
- /** A connection's restorable identity — what to persist so a binding survives transport eviction. */
23
- export interface IActionServerConnectionBinding {
24
- /** Full client coordinate, so `originClient` can be re-injected into frames that omit it. */
25
- client: IRuntimeCoordinate;
26
- encoding: TActionConnectionEncoding;
27
- /**
28
- * Secure-session state (set once a connection's handshake completes). Persist it alongside the
29
- * binding so an authenticated/encrypted connection resumes after eviction without re-handshaking —
30
- * the `keyMaterial` lets the server re-derive the shared key from its own persisted identity.
31
- */
32
- secure?: {
33
- securityLevel: ESecurityLevel;
34
- linkedClientId: TTypeAndId;
35
- keyMaterial?: IHandshakeEncryptionKeyMaterial;
36
- };
37
- }
38
- /**
39
- * Server-side secure-channel config. When set, each connection negotiates a level from
40
- * {@link securityLevel}: an `authenticated`/`encrypted` client must complete the handshake (and is then
41
- * bound to its *authenticated* coordinate) before any action frame is accepted. A `none` client (only
42
- * when `none` is in the allowed set) is accepted as-is with a self-asserted identity. For the
43
- * `encrypted` level the codec source should be a session factory (`createFormatMessage`).
44
- */
45
- export interface IActionServerSecurity {
46
- /**
47
- * Accepted level(s). A single level is strict; an array is a negotiable allowed set — the server
48
- * adopts whichever level each client requests (e.g. `[none, authenticated, encrypted]` serves all
49
- * three over one endpoint).
50
- */
51
- securityLevel: ESecurityLevel | readonly ESecurityLevel[];
52
- /** This server's crypto identity (verify + exchange key pairs, optionally persisted). */
53
- link: ClientCryptoKeyLink;
54
- /** This server's coordinate — its identity to clients during the handshake. */
55
- localCoordinate: IRuntimeCoordinate;
56
- /** Wire dictionary version; the handshake rejects a client on a mismatch. */
57
- dictionaryVersion: string;
58
- /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */
59
- verifyKeyResolver?: IClientVerifyKeyResolver;
60
- }
61
- interface IActionServerHandlerBaseOptions<TConn> {
62
- /**
63
- * Coordinate of the *connecting clients* (typically env-only, e.g. `RuntimeCoordinate.env("web_app")`).
64
- * The runtime's return-path dispatch scores incoming actions' `originClient` against this to pick
65
- * this handler for sending results/pushes back over the right channel.
66
- */
67
- clientEnv: RuntimeCoordinate;
68
- /** Write an encoded frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */
69
- send: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;
70
- /**
71
- * The runtime this handler belongs to. When set, {@link ActionServerHandler.broadcast} can be called
72
- * without threading a runtime through each call. Optional — `pushToClient` still takes one explicitly.
73
- */
74
- runtime?: ActionRuntime;
75
- /** Timeout (ms) applied to server-initiated actions awaiting a client response. */
76
- defaultTimeout?: number;
77
- /**
78
- * Called once when a connection is first bound to a client identity. Use it to persist the binding
79
- * for transports that can resume after eviction — e.g. a Durable Object's hibernatable WebSocket:
80
- * `(ws, binding) => ws.serializeAttachment(binding)` — then replay it via {@link ActionServerHandler.rehydrateConnection}
81
- * when the channel comes back.
82
- */
83
- onConnectionBound?: (connection: TConn, binding: IActionServerConnectionBinding) => void;
84
- /**
85
- * Enable the authenticated (optionally encrypted) handshake. When omitted, connections are trusted
86
- * as-is (identity self-asserted) — fine for dev / trusted networks.
87
- */
88
- security?: IActionServerSecurity;
89
- }
90
- /**
91
- * Provide exactly one codec source:
92
- * - `formatMessage` — a single shared codec for every connection (stateless, e.g. `createBinaryWsAdapter`).
93
- * - `createFormatMessage` — a per-connection factory for stateful codecs (e.g.
94
- * `createBinaryWsSessionFactory`, whose sessions hold correlation + identity state). Required for the
95
- * leanest binary wire; the handler creates and caches one codec per connection.
96
- */
97
- export type IActionServerHandlerOptions<TConn> = IActionServerHandlerBaseOptions<TConn> & ({
98
- formatMessage: TActionChannelFormatMessage;
99
- createFormatMessage?: never;
100
- } | {
101
- createFormatMessage: () => TActionChannelFormatMessage;
102
- formatMessage?: never;
103
- });
104
- /**
105
- * A connection-aware execution case (see {@link ActionServerHandler.forConnectionDomainCases}). It
106
- * receives the primed request plus the originating client's live connection (already resolved from the
107
- * request's `originClient`, `undefined` if the socket is gone), and may return the action's raw output,
108
- * a result payload, or nothing (auto-wrapped as an empty success) — exactly like a local handler case.
109
- */
110
- export type TServerConnectionCaseFn<DOM extends IActionDomain, ID extends keyof DOM["actionSchema"] & string, TConn> = (action: TDistributeActionPayload_Request<DOM, ID>, connection: TConn | undefined) => ReturnType<THandleActionExecutionFn<DOM, ID>> | void;
111
- /**
112
- * Server-side handler for backends that accept many client connections over a single open channel
113
- * (WebSockets, Durable Objects, …). It is transport-agnostic: you feed it inbound frames with
114
- * {@link receive} and tell it how to write outbound frames via the `send` option.
115
- *
116
- * Add it alongside your local execution handler:
117
- * ```ts
118
- * const serverHandler = createServerHandler({ clientEnv, formatMessage, send: (ws, f) => ws.send(f) });
119
- * runtime.addHandlers([localHandler, serverHandler]);
120
- * // per inbound message (e.g. a Durable Object's webSocketMessage):
121
- * serverHandler.receive(ws, message);
122
- * ```
123
- *
124
- * Inbound requests route to your local handler; the runtime's return dispatch then calls this
125
- * handler back (it is an external handler keyed to `clientEnv`) to send the result to the originating
126
- * connection. The handler keeps a per-connection identity registry so each result lands on the right
127
- * socket, and remembers each connection's encoding so binary and JSON clients can share the channel.
128
- *
129
- * It registers an empty action router, so it is never chosen to *execute* an inbound request — only
130
- * to ferry results/pushes back out.
131
- */
132
- export declare class ActionServerHandler<TConn = unknown> extends ActionExternalClientHandler {
133
- private readonly _formatMessage?;
134
- private readonly _createFormatMessage?;
135
- private readonly _send;
136
- private readonly _runtime?;
137
- private readonly _serverTimeout;
138
- private _onConnectionBound?;
139
- /** Incoming-data listeners installed by the runtime (`resolveIncomingActionPayload`). */
140
- private readonly _incomingListeners;
141
- private readonly _security?;
142
- /** Normalized accepted levels; whether `none` (plain) is allowed; whether any level needs a handshake. */
143
- private readonly _allowedLevels;
144
- private readonly _noneAllowed;
145
- private readonly _handshakeMode;
146
- private readonly _connByClient;
147
- private readonly _clientByConn;
148
- private readonly _connEncoding;
149
- private readonly _codecByConn;
150
- private readonly _handshakeByConn;
151
- private readonly _cryptoByConn;
152
- private readonly _authedConns;
153
- private readonly _plainConns;
154
- private readonly _inboundChainByConn;
155
- private readonly _outboundChainByConn;
156
- constructor(options: IActionServerHandlerOptions<TConn>);
157
- /**
158
- * The codec for a connection: a per-connection session (cached) when a factory was provided, else
159
- * the single shared `formatMessage`.
160
- */
161
- private _codecFor;
162
- _setIncomingActionDataListener(listener: (json: TActionPayload_Any_JsonObject<any>) => void): void;
163
- /**
164
- * Register (or replace) the connection-bound persistence callback after construction. Used by
165
- * lifecycle helpers like {@link createHibernatableWsServerAdapter} so persistence and replay are
166
- * owned by one place instead of being split across the constructor options.
167
- */
168
- setOnConnectionBound(onConnectionBound: (connection: TConn, binding: IActionServerConnectionBinding) => void): void;
169
- /**
170
- * Create a typed per-connection state store that co-owns the consumer's app state and this handler's
171
- * routing binding in one attachment. It registers itself as the connection-bound persistence callback
172
- * (so bindings are written without overwriting app state) and immediately replays every live
173
- * connection's stored binding via {@link rehydrateConnection} — so on a transport that resumes after
174
- * eviction (e.g. a Durable Object waking from hibernation) both the app identity and the action
175
- * routing come back from a single attachment, with no storage reads and no hand-rolled merge.
176
- *
177
- * This supersedes {@link createHibernatableWsServerAdapter} for app code that also pins its own state
178
- * to the connection. Construct it once when the handler is built, then `get`/`set` app state directly.
179
- */
180
- createConnectionState<TApp>(options: IWsConnectionStateStoreOptions<TConn, TApp>): WsConnectionStateStore<TConn, TApp>;
181
- /**
182
- * Feed one inbound frame from a connection into the runtime. Decodes text or binary, binds the
183
- * connection to the requesting client's identity, then routes it (requests execute locally;
184
- * results/progress resolve pending server-initiated actions).
185
- */
186
- receive(connection: TConn, frame: string | ArrayBuffer | Uint8Array): void;
187
- private _receivePlain;
188
- private _receiveSecure;
189
- private _completeServerHandshake;
190
- /**
191
- * Ensure an inbound request carries the client's identity and that this connection is bound to it,
192
- * so its result can be routed back. A session codec omits `originClient` after the first request, so
193
- * when it's missing we restore it from the (possibly rehydrated) binding instead. (Plain mode only;
194
- * secure mode binds the authenticated coordinate at handshake time.)
195
- */
196
- private _resolveRequestIdentity;
197
- /**
198
- * Restore a connection→client binding without an inbound frame — for transports that resume after
199
- * eviction. Pair it with the {@link IActionServerHandlerOptions.onConnectionBound} hook: persist
200
- * the binding there, then replay each live connection here when the channel comes back (e.g. a
201
- * Durable Object iterating `ctx.getWebSockets()` as it wakes from hibernation).
202
- */
203
- rehydrateConnection(connection: TConn, binding: IActionServerConnectionBinding): void;
204
- toHandlerRouteItem(): IActionRouteItemHandler;
205
- /** Forget a connection (call on socket close) so stale entries don't misroute later results. */
206
- dropConnection(connection: TConn): void;
207
- /** Live connection for a client coordinate, if currently registered. */
208
- getConnectionForClient(client: RuntimeCoordinate): TConn | undefined;
209
- /**
210
- * Send (and optionally await) a server-initiated action to a specific connected client. Pass the
211
- * connection token directly (e.g. the `ws`) or a client `RuntimeCoordinate` to look one up.
212
- */
213
- pushToClient<DOM extends IActionDomain, ID extends keyof DOM["actionSchema"] & string>(runtime: ActionRuntime, target: TConn | RuntimeCoordinate, request: ActionPayload_Request<DOM, ID>, options?: {
214
- timeout?: number;
215
- }): RunningAction<DOM, ID>;
216
- /**
217
- * Build a local handler whose cases are connection-aware: each case receives the primed request and
218
- * the originating client's live connection (resolved from `originClient`), so handlers don't repeat
219
- * the `getConnectionForClient(action.context.originClient)` lookup. Cases may return raw output or
220
- * nothing, just like {@link ActionLocalHandler.forDomainActionCases}. Add the returned handler to the
221
- * runtime alongside this server handler:
222
- * ```ts
223
- * runtime.addHandlers([serverHandler.forConnectionDomainCases(domain, { … }), serverHandler]);
224
- * ```
225
- */
226
- forConnectionDomainCases<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, cases: {
227
- [ID in keyof FOR_DOM["actionSchema"] & string]?: TServerConnectionCaseFn<FOR_DOM, ID, TConn>;
228
- }): ActionLocalHandler;
229
- /**
230
- * Fan a server-initiated request out to every currently-bound connection. A fresh request is built
231
- * per connection (each push mutates its own action context) and dispatched fire-and-forget. Pass
232
- * `except` to skip the originating socket and `where` to filter by connection (e.g. read its
233
- * attachment for a role). Iterating bound connections (rather than every accepted socket) skips
234
- * sockets that are still mid-handshake and so can't yet receive a frame.
235
- */
236
- broadcast<DOM extends IActionDomain, ID extends keyof DOM["actionSchema"] & string>(makeRequest: () => ActionPayload_Request<DOM, ID>, options?: {
237
- runtime?: ActionRuntime;
238
- except?: TConn | null;
239
- where?: (connection: TConn) => boolean;
240
- timeout?: number;
241
- onError?: (error: unknown, connection: TConn) => void;
242
- }): void;
243
- sendReturnPayload(payload: TActionPayload_Any_Instance<any, any>, config: {
244
- targetLocalRuntime: ActionRuntime;
245
- }): Promise<boolean>;
246
- handleActionRequest<DOM extends IActionDomain, ID extends keyof DOM["actionSchema"] & string>(action: ActionPayload_Request<DOM, ID>, config?: IHandleActionOptions): Promise<RunningAction<DOM, ID>>;
247
- private _dispatch;
248
- private _sendPayload;
249
- private _bindConnection;
250
- private _resolveConnection;
251
- private _resolveSingleConnection;
252
- }
253
- export declare const createServerHandler: <TConn = unknown>(options: IActionServerHandlerOptions<TConn>) => ActionServerHandler<TConn>;
254
- export {};
@@ -1,61 +0,0 @@
1
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2
- import type { IActionServerConnectionBinding } from "./ActionServerHandler";
3
- /**
4
- * The composite value persisted to a connection's attachment: the consumer's own app state plus the
5
- * {@link ActionServerHandler} routing binding. Co-storing them in one slot means a transport whose
6
- * sockets outlive process eviction (e.g. a Durable Object's hibernatable WebSocket) recovers both the
7
- * application identity *and* the action routing from a single attachment after a wake — no storage reads.
8
- */
9
- export interface IConnectionAttachment<TApp> {
10
- app?: TApp;
11
- binding?: IActionServerConnectionBinding;
12
- }
13
- export interface IWsConnectionStateStoreOptions<TConn, TApp> {
14
- /** Read a connection's raw attachment (e.g. `(ws) => ws.deserializeAttachment()`). */
15
- read: (connection: TConn) => unknown;
16
- /** Persist a connection's attachment (e.g. `(ws, value) => ws.serializeAttachment(value)`). */
17
- write: (connection: TConn, value: IConnectionAttachment<TApp>) => void;
18
- /**
19
- * All currently-live connections (e.g. `() => ctx.getWebSockets()`). Used to replay routing bindings
20
- * after a wake (via {@link ActionServerHandler.createConnectionState}) and to enumerate app state in
21
- * {@link WsConnectionStateStore.entries}.
22
- */
23
- getConnections: () => TConn[];
24
- /**
25
- * Optional Standard Schema (valibot, zod, …) validating the *app* portion on read. A value that
26
- * fails validation reads back as `null` — the same lenient behavior as a hand-written safeParse
27
- * helper. The binding is the library's own shape and is never validated.
28
- */
29
- schema?: StandardSchemaV1<unknown, TApp>;
30
- }
31
- /**
32
- * A typed per-connection state store that co-owns the app state and the server handler's routing
33
- * binding in one attachment, so neither the consumer nor the handler has to hand-merge the two. Create
34
- * it through {@link ActionServerHandler.createConnectionState} (which also wires binding persistence and
35
- * replays surviving connections after a wake), then `get`/`set`/`clearApp` the app state directly.
36
- *
37
- * ```ts
38
- * const players = serverHandler.createConnectionState({
39
- * schema: vs_player,
40
- * read: (ws) => ws.deserializeAttachment(),
41
- * write: (ws, v) => ws.serializeAttachment(v),
42
- * getConnections: () => ctx.getWebSockets(),
43
- * });
44
- * players.set(ws, player); // binding is preserved automatically
45
- * const player = players.get(ws);
46
- * ```
47
- */
48
- export declare class WsConnectionStateStore<TConn, TApp> {
49
- private readonly options;
50
- constructor(options: IWsConnectionStateStoreOptions<TConn, TApp>);
51
- /** The validated app state for a connection, or `null` if unset / invalid. */
52
- get(connection: TConn): TApp | null;
53
- /** Set the app state, preserving the runtime binding already pinned to the connection. */
54
- set(connection: TConn, app: TApp): void;
55
- /** Clear the app state but keep the binding (e.g. a spectator that stopped watching). */
56
- clearApp(connection: TConn): void;
57
- /** Every live connection paired with its (validated) app state — for rebuilding in-memory state after a wake. */
58
- entries(): [TConn, TApp | null][];
59
- private _readAttachment;
60
- private _validateApp;
61
- }
@@ -1,40 +0,0 @@
1
- import type { ActionRuntime } from "../../ActionRuntime";
2
- export interface IActionFetchHandlerOptions {
3
- /**
4
- * CORS headers merged onto every response (a preflight `OPTIONS` is answered `204` with them).
5
- * Defaults to permissive `*`; pass `false` to attach no CORS headers at all.
6
- */
7
- cors?: Record<string, string> | false;
8
- /** Which requests carry an action wire on `POST`. Default: pathname ends with `/action`. */
9
- isActionPath?: (url: URL) => boolean;
10
- /** Which requests are WebSocket upgrades. Default: pathname ends with `/ws`. */
11
- isWebSocketPath?: (url: URL) => boolean;
12
- /**
13
- * Perform the transport-specific WebSocket upgrade (e.g. a Durable Object's
14
- * `new WebSocketPair()` + `ctx.acceptWebSocket()` returning a `101`). Omit for HTTP-only endpoints.
15
- * Its response is returned as-is — a `101` upgrade carries no CORS headers.
16
- */
17
- onWebSocketUpgrade?: (request: Request, url: URL) => Response | Promise<Response>;
18
- /** Forwarded to `ActionPayload_Result.toHttpResponse` — use the error's HTTP status (default true). */
19
- useErrorStatus?: boolean;
20
- }
21
- /**
22
- * Build the `fetch` handler a server/Durable-Object exposes for action traffic, folding in the
23
- * boilerplate every endpoint repeats: CORS (incl. the `OPTIONS` preflight), routing the `/action`
24
- * `POST` body through the runtime (`handleActionPayloadWire` → `waitForResultPayload` →
25
- * `toHttpResponse`), an optional WebSocket-upgrade hook, and a `404` fallback.
26
- *
27
- * It only touches web-standard `Request`/`Response`, so it stays transport-agnostic — the one
28
- * environment-specific bit (the WS upgrade) is injected via {@link IActionFetchHandlerOptions.onWebSocketUpgrade}:
29
- * ```ts
30
- * this.fetchHandler = createActionFetchHandler(this.runtime, {
31
- * onWebSocketUpgrade: () => {
32
- * const pair = new WebSocketPair();
33
- * this.ctx.acceptWebSocket(pair[1]);
34
- * return new Response(null, { status: 101, webSocket: pair[0] });
35
- * },
36
- * });
37
- * // async fetch(request) { return this.fetchHandler(request); }
38
- * ```
39
- */
40
- export declare function createActionFetchHandler(runtime: ActionRuntime, options?: IActionFetchHandlerOptions): (request: Request) => Promise<Response>;
@@ -1,71 +0,0 @@
1
- import { type StorageAdapter } from "@nice-code/util";
2
- import type { ActionRuntime } from "../../ActionRuntime";
3
- import type { RuntimeCoordinate } from "../../RuntimeCoordinate";
4
- import { ESecurityLevel, type IClientVerifyKeyResolver } from "../ExternalClient/Transport/WebSocket/actionWsHandshake";
5
- import type { ISecureWsChannel } from "../ExternalClient/Transport/WebSocket/secureWsChannel";
6
- import { ActionServerHandler, type IActionServerConnectionBinding } from "./ActionServerHandler";
7
- export interface ISecureActionServerHandlerOptions<TConn> {
8
- /** The shared channel identity (codec + dictionary version) — same one the clients use. */
9
- channel: ISecureWsChannel;
10
- /**
11
- * Coordinate of the *connecting clients* (typically env-only, e.g. `RuntimeCoordinate.env("web_app")`),
12
- * used to route results/pushes back over this handler.
13
- */
14
- clientEnv: RuntimeCoordinate;
15
- /** This server's runtime — its coordinate is the server identity presented in the handshake. */
16
- runtime: ActionRuntime;
17
- /**
18
- * One backing store for the server's crypto identity *and* its trust-on-first-use verify-key pins.
19
- * Their keys don't collide, so a single adapter is enough; back it with persistent storage (e.g. a
20
- * Durable Object's storage) so identity and pins survive eviction.
21
- */
22
- storageAdapter: StorageAdapter;
23
- /** Write an encoded frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */
24
- send: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;
25
- /** Accepted level(s); defaults to negotiating any of none/authenticated/encrypted. */
26
- securityLevel?: ESecurityLevel | readonly ESecurityLevel[];
27
- /** Trust decision for a client's verify key; defaults to storage-backed TOFU over `storageAdapter`. */
28
- verifyKeyResolver?: IClientVerifyKeyResolver;
29
- /** Timeout (ms) applied to server-initiated actions awaiting a client response. */
30
- defaultTimeout?: number;
31
- }
32
- /**
33
- * Build an {@link ActionServerHandler} for the secure binary channel with the boilerplate folded in:
34
- * it creates the {@link ClientCryptoKeyLink} and the storage-backed TOFU resolver from a single
35
- * `storageAdapter`, installs the channel's per-connection codec, and assembles the `security` block
36
- * from the runtime coordinate + channel version (accepting all three levels by default).
37
- *
38
- * For a hibernatable transport (e.g. a Durable Object), pair it with
39
- * {@link createHibernatableWsServerAdapter} to wire persistence + replay.
40
- */
41
- export declare function createSecureActionServerHandler<TConn = unknown>(options: ISecureActionServerHandlerOptions<TConn>): ActionServerHandler<TConn>;
42
- export interface IHibernatableWsServerAdapterOptions<TConn> {
43
- /** The handler to drive (from {@link createSecureActionServerHandler} or `createServerHandler`). */
44
- handler: ActionServerHandler<TConn>;
45
- /** All currently-live connections — replayed on construction to rebuild bindings after a wake. */
46
- getWebSockets: () => TConn[];
47
- /** Read a connection's persisted binding (e.g. `(ws) => ws.deserializeAttachment()`). */
48
- getAttachment: (connection: TConn) => IActionServerConnectionBinding | undefined;
49
- /** Persist a connection's binding when it is bound (e.g. `(ws, b) => ws.serializeAttachment(b)`). */
50
- setAttachment: (connection: TConn, binding: IActionServerConnectionBinding) => void;
51
- }
52
- export interface IHibernatableWsServerAdapter<TConn> {
53
- /** Feed one inbound frame from a connection into the handler. */
54
- receive: (connection: TConn, frame: string | ArrayBuffer | Uint8Array) => void;
55
- /** Forget a connection (call on socket close/error). */
56
- drop: (connection: TConn) => void;
57
- }
58
- /**
59
- * Wire the hibernation lifecycle for a server handler on a transport whose sockets outlive process
60
- * eviction (e.g. a Durable Object's hibernatable WebSockets). It owns persistence end to end:
61
- * registers `setAttachment` as the handler's connection-bound callback and immediately replays every
62
- * live connection's stored binding via `getAttachment`, so results/pushes still route after a wake.
63
- *
64
- * Construct it once when the handler is built, then forward socket events:
65
- * ```ts
66
- * const wsServer = createHibernatableWsServerAdapter({ handler, getWebSockets, getAttachment, setAttachment });
67
- * // webSocketMessage(ws, msg) => wsServer.receive(ws, msg);
68
- * // webSocketClose/Error(ws) => wsServer.drop(ws);
69
- * ```
70
- */
71
- export declare function createHibernatableWsServerAdapter<TConn>(options: IHibernatableWsServerAdapterOptions<TConn>): IHibernatableWsServerAdapter<TConn>;
@@ -1,3 +0,0 @@
1
- export declare function pushHandlerCuid(cuid: string): void;
2
- export declare function popHandlerCuid(): void;
3
- export declare function peekHandlerCuid(): string | undefined;
@@ -1,55 +0,0 @@
1
- import type { INiceActionIdAndDomain } from "../../ActionDefinition/Action/ActionBase.types";
2
- import type { ActionCore } from "../../ActionDefinition/Action/Core/ActionCore";
3
- import type { ActionDomain } from "../../ActionDefinition/Domain/ActionDomain";
4
- import type { IActionDomain } from "../../ActionDefinition/Domain/ActionDomain.types";
5
- import { ActionDomainManager } from "../ActionDomainManager";
6
- import type { IHandleActionOptions } from "../Handler/ActionHandler.types";
7
- import { type IActionRouterContext, type TMatchHandlerKey } from "./ActionRouter.types";
8
- export declare class ActionRouter<DATA> {
9
- readonly domainManager: ActionDomainManager;
10
- private actionRouteData;
11
- private _context;
12
- constructor(context: IActionRouterContext);
13
- /** Copy all routes from another router into this one, replacing any overlapping keys. */
14
- mergeRouter(actionRouter: ActionRouter<DATA>): void;
15
- addDomainsFromOther(actionRouter: ActionRouter<DATA>): void;
16
- /** All FNs registered for an action, ID-specific entries first then domain wildcard. */
17
- getRouteDataEntriesForAction(action: {
18
- domain: string;
19
- id: string;
20
- }): DATA[];
21
- /** First FN registered for an action (ID-specific beats domain wildcard). */
22
- getRouteDataForAction(action: INiceActionIdAndDomain): DATA | undefined;
23
- private throwNoHandlerForAction;
24
- getRouteDataEntriesForActionOrThrow(action: INiceActionIdAndDomain, context: IHandleActionOptions): DATA[];
25
- getRouteDataForActionOrThrow(action: INiceActionIdAndDomain, context: IHandleActionOptions): DATA;
26
- /** All FNs stored under an exact match key. */
27
- getForKey(key: TMatchHandlerKey): readonly DATA[];
28
- /** Every match key that has at least one registered FN. */
29
- getRegisteredKeys(): TMatchHandlerKey[];
30
- getDomains(): ActionDomain[];
31
- /** Register a handler for all actions in a domain, replacing any existing one. */
32
- forDomain<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, routeData: DATA): this;
33
- forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM["actionSchema"] & string>(action: ActionCore<ACT_DOM, ID>, routeData: DATA): this;
34
- /** Register a handler for a specific action, replacing any existing one. */
35
- forActionId<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM["actionSchema"] & string>(domain: ActionDomain<ACT_DOM>, id: ID, routeData: DATA): this;
36
- /** Register one handler for several action IDs, replacing any existing ones. */
37
- forActionIds<ACT_DOM extends IActionDomain, IDS extends ReadonlyArray<keyof ACT_DOM["actionSchema"] & string>>(domain: ActionDomain<ACT_DOM>, ids: IDS, routeData: DATA): this;
38
- /** Register per-action handlers from a cases map, replacing any existing ones. */
39
- forDomainActionCases<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, cases: {
40
- [ID in keyof FOR_DOM["actionSchema"] & string]?: DATA;
41
- }): this;
42
- /** Append a handler for all actions in a domain (accumulates alongside existing). */
43
- addForDomain<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, routeData: DATA): this;
44
- /** Append a handler for a specific action (accumulates alongside existing). */
45
- addForAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM["actionSchema"] & string>(domain: ActionDomain<ACT_DOM>, id: ID, routeData: DATA): this;
46
- /** Append one handler for several action IDs (accumulates alongside existing). */
47
- addForActionIds<ACT_DOM extends IActionDomain, IDS extends ReadonlyArray<keyof ACT_DOM["actionSchema"] & string>>(domain: ActionDomain<ACT_DOM>, ids: IDS, routeData: DATA): this;
48
- /** Append per-action handlers from a cases map (accumulates alongside existing). */
49
- addForDomainActionCases<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, cases: {
50
- [ID in keyof FOR_DOM["actionSchema"] & string]?: DATA;
51
- }): this;
52
- /** Append a handler directly by its raw match key (used when the key is known ahead of time). */
53
- addForKey(key: TMatchHandlerKey, routeData: DATA): this;
54
- private _push;
55
- }
@@ -1,20 +0,0 @@
1
- import type { ActionRuntime } from "../ActionRuntime";
2
- import type { TActionHandler } from "../Handler/ActionHandler.types";
3
- /**
4
- * Format: `dom[${domainName}]id[${actionId | "_"}]`
5
- * The wildcard `_` matches any action ID within a domain.
6
- */
7
- export type TMatchHandlerKey = `${"dom"}[${string}]id[${string | "_"}]`;
8
- export declare enum EActionRouterContextType {
9
- runtime_to_handler = "runtime_to_handler",
10
- handler_route = "handler_route"
11
- }
12
- export interface IActionRouterContext_HandlerRoute {
13
- contextType: EActionRouterContextType.handler_route;
14
- handler: TActionHandler;
15
- }
16
- export interface IActionRouterContext_RuntimeToHandler {
17
- contextType: EActionRouterContextType.runtime_to_handler;
18
- runtime: ActionRuntime;
19
- }
20
- export type IActionRouterContext = IActionRouterContext_HandlerRoute | IActionRouterContext_RuntimeToHandler;
@@ -1,58 +0,0 @@
1
- export interface IRuntimeCoordinateSpecifics {
2
- /**
3
- * A unique and persistent client ID (should stay the same between runtime instance reloads)
4
- */
5
- perId?: string;
6
- /**
7
- * A unique instance (or "memory-only") ID (unique for each instance of an action runtime, which should generally
8
- * not persist between reloads, depending on the architecture)
9
- */
10
- insId?: string;
11
- }
12
- export interface IRuntimeCoordinate extends IRuntimeCoordinateSpecifics {
13
- /**
14
- * A static runtime environment identifier (e.g. "web_app_v1", "backend_analytics")
15
- */
16
- envId: string;
17
- }
18
- export type TRuntimeCoordinateEnvId = `envId[${string}]`;
19
- export type TRuntimeCoordinateStringId = `${TRuntimeCoordinateEnvId}perId[${string | "_"}]:insId[${string | "_"}]`;
20
- export interface IRuntimeFullCoordinates extends Required<IRuntimeCoordinate> {
21
- }
22
- export declare class RuntimeCoordinate implements IRuntimeCoordinate {
23
- readonly envId: string;
24
- readonly perId?: string;
25
- readonly insId?: string;
26
- static get unknown(): RuntimeCoordinate;
27
- static env(envId: string): RuntimeCoordinate;
28
- withPersistentId(perId: string): RuntimeCoordinate;
29
- constructor({ envId, perId, insId }: IRuntimeCoordinate);
30
- specify(specifics: IRuntimeCoordinateSpecifics): RuntimeCoordinate;
31
- specifyIfUnset(specifics: IRuntimeCoordinateSpecifics): RuntimeCoordinate;
32
- toJsonObject(): IRuntimeCoordinate;
33
- isExactlySame(other: IRuntimeCoordinate): boolean;
34
- isSameFor(other: IRuntimeCoordinate): {
35
- id: boolean;
36
- perId: boolean;
37
- insId: boolean;
38
- };
39
- similarityLevel(other: IRuntimeCoordinate): number;
40
- get stringId(): TRuntimeCoordinateStringId;
41
- /**
42
- * Takes the "Runtime Coordinate" and generates a list of full coordinate IDs representing the runtime
43
- * with decreasing levels of specificity.
44
- *
45
- * The first full coordinate ID is the most specific (including instance ID), while the last ID is
46
- * the least specific (only environment ID).
47
- *
48
- * Example output for a RuntimeCoordinate with envId "web_app", perId "user123", and insId "instance456":
49
- * [
50
- * "envId[web_app]perId[user123]:insId[instance456]",
51
- * "envId[web_app]perId[user123]:insId[_]",
52
- * "envId[web_app]perId[_]:insId[_]"
53
- * ]
54
- *
55
- * @returns a list of "full" runtime coordinate IDs with decreasing accuracy for targeting a runtime.
56
- */
57
- toStringIds(): TRuntimeCoordinateStringId[];
58
- }