experimental-a2 0.8.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/dist/actor-client.d.ts +46 -0
- package/dist/actor-client.d.ts.map +1 -0
- package/dist/actor-client.js +54 -0
- package/dist/actor-client.js.map +1 -0
- package/dist/actor-react.d.ts +54 -0
- package/dist/actor-react.d.ts.map +1 -0
- package/dist/actor-react.js +79 -0
- package/dist/actor-react.js.map +1 -0
- package/dist/actor-shared-DI7J5upy.js +127 -0
- package/dist/actor-shared-DI7J5upy.js.map +1 -0
- package/dist/actor-shared-USo5MyuF.d.ts +136 -0
- package/dist/actor-shared-USo5MyuF.d.ts.map +1 -0
- package/dist/actor.browser.d.ts +1 -0
- package/dist/actor.browser.js +13 -0
- package/dist/actor.browser.js.map +1 -0
- package/dist/actor.d.ts +176 -0
- package/dist/actor.d.ts.map +1 -0
- package/dist/actor.js +437 -0
- package/dist/actor.js.map +1 -0
- package/dist/ai-server.d.ts +2 -2
- package/dist/ai-server.js +2 -2
- package/dist/ai.d.ts +2 -2
- package/dist/client.d.ts +14 -8
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +238 -58
- package/dist/client.js.map +1 -1
- package/dist/{errors-BQuJpe82.js → errors-DCk6ch5n.js} +16 -2
- package/dist/{errors-BQuJpe82.js.map → errors-DCk6ch5n.js.map} +1 -1
- package/dist/{idempotent-replay-DuqEkYA7.js → idempotent-replay-DVOlyYbx.js} +2 -2
- package/dist/{idempotent-replay-DuqEkYA7.js.map → idempotent-replay-DVOlyYbx.js.map} +1 -1
- package/dist/index.d.ts +16 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/react.d.ts +1 -1
- package/dist/{contract-jIfaR085.d.ts → reducer-DJKWm3cp.d.ts} +39 -39
- package/dist/reducer-DJKWm3cp.d.ts.map +1 -0
- package/dist/scheduler-qstash.d.ts +2 -2
- package/dist/scheduler-qstash.js +2 -2
- package/dist/scheduler-vercel.d.ts +2 -2
- package/dist/scheduler-vercel.js +1 -1
- package/dist/{server-DjPhHnbI.d.ts → server-DgCrSuhB.d.ts} +5 -3
- package/dist/server-DgCrSuhB.d.ts.map +1 -0
- package/dist/{server-B2XNevQA.js → server-DlLyvaSH.js} +140 -81
- package/dist/server-DlLyvaSH.js.map +1 -0
- package/dist/server.d.ts +3 -3
- package/dist/server.js +1 -1
- package/dist/{store-RJO35BMj.d.ts → store-DGHeBtIQ.d.ts} +2 -2
- package/dist/{store-RJO35BMj.d.ts.map → store-DGHeBtIQ.d.ts.map} +1 -1
- package/dist/store-memory.d.ts +1 -1
- package/dist/store-memory.js +2 -2
- package/dist/store-postgres.d.ts +1 -1
- package/dist/store-postgres.js +2 -2
- package/dist/{store-redis-core-DT01r4GZ.js → store-redis-core-z-ykbyMg.js} +3 -3
- package/dist/{store-redis-core-DT01r4GZ.js.map → store-redis-core-z-ykbyMg.js.map} +1 -1
- package/dist/store-redis-http.d.ts +1 -1
- package/dist/store-redis-http.js +2 -2
- package/dist/store-redis.d.ts +1 -1
- package/dist/store-redis.js +2 -2
- package/dist/store-sqlite.d.ts +1 -1
- package/dist/store-sqlite.js +2 -2
- package/dist/{wire-B6te_wns.js → wire--yji6mO3.js} +2 -2
- package/dist/{wire-B6te_wns.js.map → wire--yji6mO3.js.map} +1 -1
- package/docs/actors/01-introduction.mdx +189 -0
- package/docs/actors/02-concurrency.mdx +154 -0
- package/docs/actors/03-timers.mdx +120 -0
- package/docs/actors/04-routes.mdx +352 -0
- package/docs/actors/meta.ts +1 -0
- package/docs/concepts/meta.ts +1 -0
- package/docs/guides/10-transports.mdx +72 -22
- package/docs/guides/meta.ts +1 -0
- package/docs/index.mdx +3 -0
- package/docs/reference/01-api.mdx +30 -12
- package/docs/reference/02-errors.mdx +33 -0
- package/docs/reference/meta.ts +1 -0
- package/examples/playground/app/page.tsx +10 -1
- package/examples/playground/app/vault/[vaultId]/route.ts +19 -0
- package/examples/playground/app/vault/page.tsx +12 -0
- package/examples/playground/app/vault/server.ts +9 -0
- package/examples/playground/app/vault/vault-client.tsx +124 -0
- package/examples/playground/app/vault/vault.test.ts +147 -0
- package/examples/playground/app/vault/vault.ts +119 -0
- package/examples/playground/package.json +1 -1
- package/package.json +7 -1
- package/src/actor-client.ts +132 -0
- package/src/actor-react.ts +143 -0
- package/src/actor-shared.ts +356 -0
- package/src/actor.browser.ts +12 -0
- package/src/actor.ts +914 -0
- package/src/client.ts +341 -88
- package/src/errors.ts +15 -0
- package/src/index.ts +1 -1
- package/src/server-fetch.ts +51 -23
- package/src/server.ts +13 -3
- package/src/session-socket.ts +216 -81
- package/dist/contract-jIfaR085.d.ts.map +0 -1
- package/dist/server-B2XNevQA.js.map +0 -1
- package/dist/server-DjPhHnbI.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"actor.js","names":["contract","createContract"],"sources":["../src/actor.ts"],"sourcesContent":["/**\n * experimental-a2/actor — durable actors over the log. Server-only\n * (handlers are server code); the browser condition resolves to a\n * throwing stub, and the browser surfaces are experimental-a2/actor/client\n * and experimental-a2/actor/react.\n *\n * An actor is defined over a protocol — its state shape and event\n * vocabulary, as types — and one complete `handlers` bag:\n *\n * ```ts\n * interface Counter {\n * state: { count: number }\n * events: { increment: object; add: { by: number } }\n * }\n * const counter = actor<Counter>({\n * name: 'counter',\n * state: { count: 0 },\n * handlers: {\n * increment: (ctx) => {\n * ctx.state.count++\n * },\n * add: (ctx, input) => {\n * ctx.state.count += input.by\n * },\n * },\n * })\n * ```\n *\n * Handlers are serial by default: one at a time per instance (a lane —\n * the state's write lock), `ctx.state` a mutable draft committed\n * atomically with completion. A handler holding slow I/O opts out of\n * the lane with `{ concurrent: true, handle }`: it runs in parallel,\n * reads state as a snapshot, and mutates by sending events whose\n * serial handlers decide against fresh state. `ctx.send.eventName(...)`\n * is typed by the protocol and buffered — committed atomically with\n * the handler's completion, so a reserve and its trigger can never\n * half-happen.\n *\n * A thrown `NonRetriableError` is an answer (settled, delivered to a\n * waiting caller); any other error retries like every A2 handler\n * failure; a crash re-runs against the same pre-state. Everything\n * compiles to contract + reducer + laned handlers + returned events —\n * no new store operations, no new wire.\n */\n\n// oxlint-disable no-await-in-loop -- a call awaits its answer: drain, read\n// the tail, repeat until the message settles. Sequential by nature.\n\nimport {\n ACTOR_FAILED_EVENT,\n ACTOR_LANE,\n ACTOR_STATE_EVENT,\n ActorRefusedError,\n actorFailedSchema,\n actorReducer,\n actorStateSchema,\n isJsonTree,\n openPresenceDefs,\n} from './actor-shared.ts'\nimport type {\n ActorClientEventDefs,\n ActorConcurrentContext,\n ActorContext,\n ActorFailedPayload,\n ActorPresenceOf,\n ActorProtocol,\n ActorScheduleOptions,\n ActorScheduleSend,\n ActorSend,\n ActorStatePayload,\n} from './actor-shared.ts'\nimport { parsePresenceSibling } from './push-envelope.ts'\nimport type { ParsedPushPresence } from './push-envelope.ts'\nimport { contract as createContract } from './contract.ts'\nimport type { PresencePatch, PresenceSnapshot } from './contract.ts'\nimport type { Contract, EventDefs } from './contract.ts'\nimport type { Reducer } from './reducer.ts'\nimport { A2Error, NonRetriableError } from './errors.ts'\nimport { createServer } from './server.ts'\nimport { setServerFetchHooks } from './server-fetch.ts'\nimport { sseResponse } from './sse.ts'\nimport type { A2Scheduler, A2Server, HandlerEntry, Session } from './server.ts'\nimport type { A2Store } from './store.ts'\nimport type { StandardSchemaV1 } from './standard-schema.ts'\nimport type { A2Telemetry } from './telemetry.ts'\n\nexport type {\n ActorConcurrentContext,\n ActorContext,\n ActorPresenceMap,\n ActorPresenceOf,\n ActorPresenceValues,\n ActorProtocol,\n ActorScheduleOptions,\n ActorScheduleSend,\n ActorSend,\n} from './actor-shared.ts'\nexport { ActorRefusedError } from './actor-shared.ts'\n\n/**\n * One event's handler: ordinary server code. Serial by default — read\n * `ctx.state`, perform I/O, mutate `ctx.state`, one atomic commit at\n * return. `{ concurrent: true, handle }` opts the handler out of the\n * lane for slow I/O: state becomes a snapshot read and mutations\n * happen by sending events. The input is typed by the protocol; the\n * wire hands handlers parsed JSON, so a wire-exposed event guards its\n * input in its first line (`schema.parse(input)` if you like schemas —\n * userland either way).\n */\nexport type ActorHandler<D extends ActorProtocol, K extends keyof D['events']> =\n | ((ctx: ActorContext<D>, input: D['events'][K]) => void | Promise<void>)\n | {\n concurrent: true\n handle: (\n ctx: ActorConcurrentContext<D>,\n input: D['events'][K],\n ) => void | Promise<void>\n }\n\n/**\n * Mark a handler concurrent — off the lane, in parallel with the lane\n * and with other concurrent handlers, `ctx.state()` a snapshot read.\n * Sugar for the structural `{ concurrent: true, handle }` form:\n *\n * ```ts\n * handlers: {\n * transfer: concurrent(async (ctx, input) => {\n * await bank.transfer(input, { idempotencyKey: input.ref })\n * ctx.send.settle({ ref: input.ref })\n * }),\n * }\n * ```\n */\nexport function concurrent<Ctx, I>(\n handle: (ctx: Ctx, input: I) => void | Promise<void>,\n): { concurrent: true; handle: (ctx: Ctx, input: I) => void | Promise<void> } {\n return { concurrent: true, handle }\n}\n\nexport type ActorOptions<D extends ActorProtocol> = {\n /** Identity — prefixes storage keys; one contract per actor definition. */\n name: string\n /** The initial state — checked against the protocol, a plain JSON tree. */\n state: D['state']\n /**\n * One handler per declared event — completeness and payload shapes\n * are compile-checked against the protocol.\n */\n handlers: { [K in keyof D['events']]: ActorHandler<D, K> }\n store?: A2Store\n scheduler?: A2Scheduler\n telemetry?: A2Telemetry\n} & ([ActorPresenceOf<D>] extends [never]\n ? { presence?: never }\n : {\n /**\n * The wire bit for the protocol's `presence` vocabulary — types\n * erase, so the runtime needs one value to arm the presence\n * lanes (frames on GET, envelopes on POST). Required exactly\n * when the protocol declares `presence`; the vocabulary itself\n * is typed there. Values are validated to the JSON floor and\n * pass through `authorize` as `{ type: 'presence' }` operations;\n * meaning stays with your renderers — treat values as user\n * input.\n */\n presence: true\n })\n\n/**\n * One HTTP operation `handle.fetch` is about to serve — the actor\n * mirror of core's `A2Operation`. `authorize` sees it before any\n * write or subscription; returning `false` answers 403.\n */\nexport type ActorOperation =\n | {\n readonly type: 'stream'\n readonly id: string\n readonly startAfter: number\n }\n | {\n readonly type: 'call'\n readonly id: string\n readonly event: string\n readonly input: unknown\n readonly messageId?: string\n }\n | {\n readonly type: 'presence'\n readonly id: string\n readonly participant: string\n readonly values: Readonly<Record<string, unknown>>\n }\n\nexport type ActorFetchOptions<D extends ActorProtocol> = {\n /** Per-operation policy — authentication happened in your route. */\n authorize?: (operation: ActorOperation) => boolean | Promise<boolean>\n /**\n * Request-time projection: what this mount's audience sees. Applied\n * to every state frame on the stream AND to call answers (the two\n * untrusted lanes must agree, or the call lane leaks what the\n * stream hides). The definition stays audience-agnostic — different\n * routes project the same actor differently, and per-viewer views\n * are just closures over the route's auth. Output is held to the\n * JSON-tree floor like everything else. Transport-agnostic: applied\n * at frame emission, so any wire the door speaks emits projected\n * frames. Absent, the full state ships (the trusted default).\n */\n view?: (state: D['state']) => unknown\n}\n\nexport type ActorSendOptions = {\n /** Explicit message id — makes retries of this send idempotent. */\n id?: string\n}\n\nexport type ActorCallOptions = ActorSendOptions & {\n /** How long to await the answer before rejecting the wait (default 30s). */\n timeoutMs?: number\n}\n\nexport type ActorCallResult<S> = {\n /** The actor's state after this message was processed. */\n state: S\n /** Log index of the state commit that answered this message. */\n index: number\n}\n\ntype CallMethod<\n D extends ActorProtocol,\n K extends keyof D['events'],\n> = {} extends D['events'][K]\n ? (\n input?: D['events'][K],\n options?: ActorCallOptions,\n ) => Promise<ActorCallResult<D['state']>>\n : (\n input: D['events'][K],\n options?: ActorCallOptions,\n ) => Promise<ActorCallResult<D['state']>>\n\ntype SendMethod<\n D extends ActorProtocol,\n K extends keyof D['events'],\n> = {} extends D['events'][K]\n ? (\n input?: D['events'][K],\n options?: ActorSendOptions,\n ) => Promise<{ id: string; index: number }>\n : (\n input: D['events'][K],\n options?: ActorSendOptions,\n ) => Promise<{ id: string; index: number }>\n\n/** One instance: typed calls and sends, reads, the managed door, the escape hatch. */\nexport type ActorHandle<D extends ActorProtocol> = {\n readonly id: string\n /**\n * Send the event and await its answer: the state after the handler\n * ran, or a rejection with `ActorRefusedError`. Serial events only —\n * concurrent handlers produce no answer to await; `send` them.\n */\n readonly call: { readonly [K in keyof D['events']]: CallMethod<D, K> }\n /** Cast: validate, append the event durably, return without waiting. */\n readonly send: { readonly [K in keyof D['events']]: SendMethod<D, K> }\n /** Snapshot read — never queues behind pending messages. */\n readonly state: () => Promise<ActorCallResult<D['state']>>\n /**\n * The managed door — the actor mirror of `server.fetch`, bound to\n * this instance. GET streams the state plane (`a2.actor.state`\n * commits only, `?index` resume, heartbeat, deadline rotation);\n * POST is the call lane `createActorClient` speaks (`{ event,\n * input, messageId? }` → the answer, 409 for a refusal). Your route\n * authenticates and picks the instance; `authorize` sees every\n * operation. Custom endpoints are route code around this call.\n */\n readonly fetch: (\n request: Request,\n options?: ActorFetchOptions<D>,\n ) => Promise<Response>\n /** Escape hatch: the raw A2 session (history, stream, schedule). */\n readonly session: Session<EventDefs>\n}\n\nexport type ActorDefinition<D extends ActorProtocol> = {\n readonly name: string\n /**\n * Type-only carrier of the protocol, so clients deriving from\n * `typeof def` can see the vocabularies (`experimental-a2/actor/react`\n * types `presence` from it). Never a runtime value.\n */\n readonly protocol?: D\n /** The assembled contract — declared events plus the reserved a2.actor.* pair. */\n readonly contract: Contract<EventDefs>\n /** The underlying A2 server — `server.fetch` mounts the full session wire. */\n readonly server: A2Server<EventDefs>\n /** The state fold — same identity as the client's follower fold. */\n readonly reducer: Reducer<ActorClientEventDefs<D['state']>, D['state']>\n actor(id: string): ActorHandle<D>\n}\n\n// Object-mechanics names, not surface names: events live in their own\n// bags, so nothing else is reserved.\nconst UNSAFE_EVENT_NAMES = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst forbidden = (): Response =>\n Response.json({ error: 'the operation is not authorized' }, { status: 403 })\n\nconst CALL_TIMEOUT_MS = 30_000\nconst CALL_POLL_MS = 25\n\n/** Declared events accept any JSON tree; `undefined` normalizes to `{}`. */\nconst jsonInputSchema: StandardSchemaV1<unknown> = {\n '~standard': {\n version: 1,\n vendor: 'a2',\n validate(value) {\n if (value === undefined || value === null) return { value: {} }\n if (!isJsonTree(value)) {\n return {\n issues: [{ message: 'event input must be a plain JSON tree' }],\n }\n }\n return { value }\n },\n },\n}\n\nconst describeError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms))\n\ntype NormalizedHandler<D extends ActorProtocol> =\n | {\n kind: 'serial'\n handle: (ctx: ActorContext<D>, input: unknown) => void | Promise<void>\n }\n | {\n kind: 'concurrent'\n handle: (\n ctx: ActorConcurrentContext<D>,\n input: unknown,\n ) => void | Promise<void>\n }\n\n/**\n * Define and serve an actor over its protocol: a named, durable\n * instance-per-id with serialized state handlers, concurrent I/O\n * handlers, and typed self-sends.\n */\nexport function actor<D extends ActorProtocol>(\n options: ActorOptions<D>,\n): ActorDefinition<D> {\n const { name } = options\n\n const handlersByEvent = new Map<string, NormalizedHandler<D>>()\n const events: Record<string, StandardSchemaV1> = {\n [ACTOR_STATE_EVENT]: actorStateSchema(),\n [ACTOR_FAILED_EVENT]: actorFailedSchema,\n }\n for (const [eventName, def] of Object.entries(\n options.handlers as Record<string, ActorHandler<D, keyof D['events']>>,\n )) {\n if (UNSAFE_EVENT_NAMES.has(eventName)) {\n throw new TypeError(\n `actor '${name}': '${eventName}' collides with object plumbing and cannot name an event`,\n )\n }\n if (eventName.startsWith('a2.')) {\n throw new TypeError(\n `actor '${name}': event names starting with 'a2.' are reserved`,\n )\n }\n handlersByEvent.set(\n eventName,\n typeof def === 'function'\n ? {\n kind: 'serial',\n handle: def as (\n ctx: ActorContext<D>,\n input: unknown,\n ) => void | Promise<void>,\n }\n : {\n kind: 'concurrent',\n handle: def.handle as (\n ctx: ActorConcurrentContext<D>,\n input: unknown,\n ) => void | Promise<void>,\n },\n )\n events[eventName] = jsonInputSchema\n }\n\n const reducer = actorReducer({ name, state: options.state })\n // The server's contract carries every event type; the reducer only\n // folds state commits. Same fold, same identity — the widening is a\n // typing formality.\n const serverReducer = reducer as unknown as Reducer<EventDefs, D['state']>\n\n // The typed durable-timer surface: immediate handoff to the\n // configured scheduler through the handler session, so timer\n // identity is scoped to the triggering message and re-runs address\n // the same timer (core §6). Not buffered — see ActorScheduleSend.\n const makeSchedule = (\n schedule: (\n name: string,\n timing: { delay?: string; at?: Date },\n event: { type: string; payload: unknown },\n ) => Promise<void>,\n ): ActorScheduleSend<D['events']> => {\n const surface: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(surface, eventName, {\n value: (input: unknown, scheduleOptions: ActorScheduleOptions) => {\n const { name: taskName, ...timing } = scheduleOptions\n return schedule(taskName ?? eventName, timing, {\n type: eventName,\n payload: input ?? {},\n })\n },\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n return surface as ActorScheduleSend<D['events']>\n }\n\n // The typed self-send surface: per-invocation buffers behind one\n // shared method record shape. defineProperty so event names like\n // 'constructor'-adjacent identifiers can never touch prototypes.\n const makeSend = (\n buffer: { type: string; payload: unknown }[],\n ): ActorSend<D['events']> => {\n const send: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(send, eventName, {\n value: (input?: unknown) => {\n buffer.push({ type: eventName, payload: input ?? {} })\n },\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n return send as ActorSend<D['events']>\n }\n\n const handlers: Record<string, HandlerEntry<EventDefs>> = {}\n for (const [eventName, def] of handlersByEvent) {\n if (def.kind === 'concurrent') {\n // No lane: concurrent handlers run in parallel — with the lane\n // and with each other. They cannot write state (no draft to\n // commit), so no serialization is needed for correctness; slow\n // I/O lives here without blocking the actor.\n handlers[eventName] = async (ctx) => {\n const sends: { type: string; payload: unknown }[] = []\n try {\n await def.handle(\n {\n id: ctx.event.id,\n attempt: ctx.attempt,\n signal: ctx.signal,\n send: makeSend(sends),\n schedule: makeSchedule((taskName, timing, event) =>\n ctx.session.schedule(\n taskName,\n timing as Parameters<typeof ctx.session.schedule>[1],\n event,\n ),\n ),\n state: async () => {\n const { state, index } = await ctx.session.state(\n serverReducer,\n { through: 'latest' },\n )\n return { state, index }\n },\n },\n ctx.event.payload,\n )\n } catch (error) {\n if (!(error instanceof NonRetriableError)) throw error\n // A terminal failure is recorded for audit; nothing awaits a\n // concurrent handler, so the marker is history, not an\n // answer. Buffered sends are discarded — refusals are total,\n // so compensate by completing (send then return), never by\n // throwing.\n const payload: ActorFailedPayload = {\n message: ctx.event.id,\n event: eventName,\n error: describeError(error),\n }\n return { type: ACTOR_FAILED_EVENT, payload }\n }\n // Sends commit atomically with settlement; re-runs converge on\n // the same deterministic message ids.\n return sends\n }\n continue\n }\n handlers[eventName] = {\n // One lane for every serial handler of one instance: the next\n // message starts only after the previous one completed, and\n // completion commits the state event atomically —\n // read-modify-write on `ctx.state` is safe by exclusion, not by\n // liveness.\n lane: ACTOR_LANE,\n handler: async (ctx) => {\n // Explicitly 'latest', not the event-relative default: prior\n // lane messages commit *after* this message was appended, so\n // their state commits carry higher indexes than the trigger —\n // an event-relative read would miss them and lose updates.\n // 'latest' is deterministic here because the lane makes this\n // attempt the only possible writer while it runs.\n const { state } = await ctx.session.state(serverReducer, {\n through: 'latest',\n })\n const draft = structuredClone(state)\n const sends: { type: string; payload: unknown }[] = []\n try {\n await def.handle(\n {\n state: draft,\n id: ctx.event.id,\n attempt: ctx.attempt,\n signal: ctx.signal,\n send: makeSend(sends),\n schedule: makeSchedule((taskName, timing, event) =>\n ctx.session.schedule(\n taskName,\n timing as Parameters<typeof ctx.session.schedule>[1],\n event,\n ),\n ),\n },\n ctx.event.payload,\n )\n } catch (error) {\n // A NonRetriableError is an answer: settle the message,\n // record the refusal, deliver it to the waiting caller —\n // no retry, no failure budget spent (buffered sends are\n // discarded with the draft: refusals are total). Every\n // other throw is an ordinary A2 handler failure: rethrown\n // into core's retry machinery (backoff, ten-failure\n // budget, dead letter) — including surrendered lease\n // aborts, which core recognizes by identity.\n if (!(error instanceof NonRetriableError)) throw error\n const payload: ActorFailedPayload = {\n message: ctx.event.id,\n event: eventName,\n error: describeError(error),\n }\n return { type: ACTOR_FAILED_EVENT, payload }\n }\n // One returned batch: buffered sends plus the state commit —\n // committed atomically with completion, so a reserve and its\n // trigger can never half-happen. The state event stays the\n // outcome marker a waiting call resolves on. (Unconditional\n // for now; a dirty check is a compatible later optimization.)\n const payload: ActorStatePayload<D['state']> = {\n state: draft,\n event: eventName,\n message: ctx.event.id,\n }\n return [...sends, { type: ACTOR_STATE_EVENT, payload }]\n },\n }\n }\n\n const presenceEnabled = (options as { presence?: unknown }).presence === true\n // The '*' catch-all arms an open server-side vocabulary: the\n // protocol types field names at compile time, the floor validates\n // every value, and `authorize` sees every set. See openPresenceDefs.\n const contract = presenceEnabled\n ? createContract({ name, events, presence: openPresenceDefs })\n : createContract({ name, events })\n const server = createServer({\n contract,\n handlers,\n ...(options.store ? { store: options.store } : {}),\n ...(options.scheduler ? { scheduler: options.scheduler } : {}),\n ...(options.telemetry ? { telemetry: options.telemetry } : {}),\n })\n // Single-writer discipline on the underlying session wire too: if an\n // application mounts `def.server.fetch`, browsers may push declared\n // events, never authored state or failure records.\n setServerFetchHooks(server, {\n validateIngress: ({ events: pushed }) => {\n for (const event of pushed) {\n if (event.type.startsWith('a2.actor.')) {\n throw new TypeError(\n `'${event.type}' is reserved — only a handler's completion can author it`,\n )\n }\n }\n },\n })\n\n const makeHandle = (id: string): ActorHandle<D> => {\n const session = server.session(id)\n\n const sendEvent = async (\n eventName: string,\n input: unknown,\n sendOptions?: ActorSendOptions,\n ): Promise<{ id: string; index: number }> => {\n const [message] = await session.append({\n type: eventName,\n payload: input ?? {},\n ...(sendOptions?.id ? { id: sendOptions.id } : {}),\n })\n if (!message) throw new Error('append returned no event')\n return { id: message.id, index: message.index }\n }\n\n const callEvent = async (\n eventName: string,\n input: unknown,\n callOptions?: ActorCallOptions,\n ): Promise<ActorCallResult<D['state']>> => {\n if (handlersByEvent.get(eventName)?.kind === 'concurrent') {\n throw new TypeError(\n `actor '${name}': '${eventName}' is concurrent — it produces no answer to await; send it instead`,\n )\n }\n const message = await sendEvent(eventName, input, callOptions)\n const deadline = Date.now() + (callOptions?.timeoutMs ?? CALL_TIMEOUT_MS)\n let cursor = message.index + 1\n for (;;) {\n // Drain participates in processing (usually answering inline in\n // this invocation); claims arbitrate if another process runs.\n await server.drain(id)\n const tail = await session.history({ gte: cursor })\n for (const event of tail) {\n if (event.type === ACTOR_STATE_EVENT) {\n const payload = event.payload as ActorStatePayload<D['state']>\n if (payload.message === message.id) {\n return { state: payload.state, index: event.index }\n }\n }\n if (event.type === ACTOR_FAILED_EVENT) {\n const payload = event.payload as ActorFailedPayload\n if (payload.message === message.id) {\n throw new ActorRefusedError(eventName, message.id, payload.error)\n }\n }\n }\n const last = tail[tail.length - 1]\n if (last) cursor = last.index + 1\n if (Date.now() >= deadline) {\n throw new Error(\n `actor '${name}': timed out waiting for '${eventName}' (message ${message.id})`,\n )\n }\n await sleep(CALL_POLL_MS)\n }\n }\n\n const readState = async (): Promise<ActorCallResult<D['state']>> => {\n const { state, index } = await session.state(serverReducer)\n return { state, index }\n }\n\n const applyView = (\n view: (state: D['state']) => unknown,\n state: D['state'],\n ): unknown => {\n const viewed = view(state)\n if (!isJsonTree(viewed)) {\n throw new TypeError(\n `actor '${name}': the view returned a value that is not a plain JSON tree`,\n )\n }\n return viewed\n }\n\n const streamStates = async function* (\n startAfter: number,\n view?: (state: D['state']) => unknown,\n ) {\n // With presence armed, the session interleaves presence items\n // (snapshot, then patches) between log events. They are\n // ephemeral audience data, not actor state: they pass through\n // untouched — views project state, never peers — and they never\n // advance the resume frontier.\n const source: AsyncIterable<\n | Awaited<ReturnType<typeof session.history>>[number]\n | PresencePatch\n | PresenceSnapshot\n > = presenceEnabled\n ? (\n session as unknown as {\n stream(options: {\n startAfter: number\n presence: true\n }): AsyncIterable<PresencePatch | PresenceSnapshot>\n }\n ).stream({ startAfter, presence: true })\n : session.stream({ startAfter })\n for await (const item of source) {\n if (!('type' in item)) {\n yield item\n continue\n }\n const event = item\n // The state plane only: subscribers see what the actor is,\n // never other callers' inputs. Refusals answer only their\n // caller (the POST 409); the full mailbox stays server-side.\n if (event.type !== ACTOR_STATE_EVENT) continue\n if (!view) {\n yield event\n continue\n }\n const payload = event.payload as ActorStatePayload<D['state']>\n yield {\n ...event,\n payload: { ...payload, state: applyView(view, payload.state) },\n }\n }\n }\n\n // The managed door — the actor mirror of `server.fetch`: GET is\n // the state-plane SSE (`a2.actor.state` commits only, `?index`\n // resume), POST is the call lane (`{ event, input, messageId? }`\n // → the answer, 409 for a refusal). Authentication happens in the\n // surrounding route; per-operation policy in `authorize`.\n const handleFetch = async (\n request: Request,\n fetchOptions?: ActorFetchOptions<D>,\n ): Promise<Response> => {\n const authorized = async (operation: ActorOperation): Promise<boolean> =>\n (await fetchOptions?.authorize?.(Object.freeze(operation))) !== false\n\n if (request.method === 'GET') {\n const url = new URL(request.url)\n const raw = Number(url.searchParams.get('index'))\n const startAfter = Number.isSafeInteger(raw) && raw >= 0 ? raw : 0\n if (!(await authorized({ type: 'stream', id, startAfter }))) {\n return forbidden()\n }\n return sseResponse(streamStates(startAfter, fetchOptions?.view))\n }\n if (request.method !== 'POST') {\n return new Response(null, {\n status: 405,\n headers: { allow: 'GET, POST' },\n })\n }\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return Response.json({ error: 'invalid JSON body' }, { status: 400 })\n }\n const record =\n typeof body === 'object' && body !== null\n ? (body as Record<string, unknown>)\n : {}\n if ('presence' in record) {\n // A presence envelope — what the follower client's\n // `setPresence` posts. Events never ride this lane: writes to\n // the actor are calls.\n if (!presenceEnabled) {\n return Response.json(\n { error: `actor '${name}' declares no presence` },\n { status: 400 },\n )\n }\n const pushedEvents = record['events']\n if (\n pushedEvents !== undefined &&\n (!Array.isArray(pushedEvents) || pushedEvents.length > 0)\n ) {\n return Response.json(\n { error: 'the actor wire takes calls, not event pushes' },\n { status: 400 },\n )\n }\n let patch: ParsedPushPresence\n try {\n const parsed = parsePresenceSibling(record['presence'])\n if (!parsed) throw new TypeError('presence must be an object')\n patch = parsed\n } catch (error) {\n return Response.json({ error: describeError(error) }, { status: 400 })\n }\n if (\n !(await authorized({\n type: 'presence',\n id,\n participant: patch.participant,\n values: patch.values,\n }))\n ) {\n return forbidden()\n }\n try {\n await (\n session as unknown as {\n setPresence(patch: ParsedPushPresence): Promise<void>\n }\n ).setPresence(patch)\n } catch (error) {\n if (\n error instanceof A2Error &&\n (error.code === 'INVALID_PAYLOAD' ||\n error.code === 'UNKNOWN_PRESENCE_FIELD')\n ) {\n return Response.json({ error: error.message }, { status: 400 })\n }\n throw error\n }\n return Response.json([])\n }\n const eventName = record['event']\n if (\n typeof eventName !== 'string' ||\n handlersByEvent.get(eventName)?.kind !== 'serial'\n ) {\n return Response.json({ error: 'unknown event' }, { status: 400 })\n }\n const messageId = record['messageId']\n if (messageId !== undefined && typeof messageId !== 'string') {\n return Response.json({ error: 'invalid messageId' }, { status: 400 })\n }\n const input = record['input']\n if (\n !(await authorized({\n type: 'call',\n id,\n event: eventName,\n input,\n ...(messageId === undefined ? {} : { messageId }),\n }))\n ) {\n return forbidden()\n }\n try {\n const result = await callEvent(\n eventName,\n input,\n messageId === undefined ? undefined : { id: messageId },\n )\n return Response.json(\n fetchOptions?.view\n ? {\n state: applyView(fetchOptions.view, result.state),\n index: result.index,\n }\n : result,\n )\n } catch (error) {\n if (error instanceof ActorRefusedError) {\n return Response.json(\n {\n error: error.message,\n event: error.event,\n messageId: error.messageId,\n },\n { status: 409 },\n )\n }\n if (\n error instanceof A2Error &&\n (error.code === 'INVALID_PAYLOAD' ||\n error.code === 'UNKNOWN_EVENT_TYPE')\n ) {\n return Response.json({ error: error.message }, { status: 400 })\n }\n throw error\n }\n }\n\n const call: Record<string, unknown> = {}\n const send: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(call, eventName, {\n value: (input?: unknown, callOptions?: ActorCallOptions) =>\n callEvent(eventName, input, callOptions),\n enumerable: true,\n configurable: true,\n writable: false,\n })\n Object.defineProperty(send, eventName, {\n value: (input?: unknown, sendOptions?: ActorSendOptions) =>\n sendEvent(eventName, input, sendOptions),\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n const handle: ActorHandle<D> = {\n id,\n session,\n call: call as ActorHandle<D>['call'],\n send: send as ActorHandle<D>['send'],\n state: readState,\n fetch: handleFetch,\n }\n return handle\n }\n\n return {\n name,\n contract,\n server,\n reducer,\n actor: makeHandle,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqIA,SAAgB,WACd,QAC4E;CAC5E,OAAO;EAAE,YAAY;EAAM;CAAO;AACpC;AAqKA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;AAE5E,MAAM,kBACJ,SAAS,KAAK,EAAE,OAAO,kCAAkC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE7E,MAAM,kBAAkB;AACxB,MAAM,eAAe;;AAGrB,MAAM,kBAA6C,EACjD,aAAa;CACX,SAAS;CACT,QAAQ;CACR,SAAS,OAAO;EACd,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,EAAE,OAAO,CAAC,EAAE;EAC9D,IAAI,CAAC,WAAW,KAAK,GACnB,OAAO,EACL,QAAQ,CAAC,EAAE,SAAS,wCAAwC,CAAC,EAC/D;EAEF,OAAO,EAAE,MAAM;CACjB;AACF,EACF;AAEA,MAAM,iBAAiB,UACrB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,SAAS,OACb,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAoBlD,SAAgB,MACd,SACoB;CACpB,MAAM,EAAE,S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U;GAEnB,IAAI;IACF,MAAM,SAAS,MAAM,UACnB,WACA,OACA,cAAc,KAAA,IAAY,KAAA,IAAY,EAAE,IAAI,UAAU,CACxD;IACA,OAAO,SAAS,KACd,cAAc,OACV;KACE,OAAO,UAAU,aAAa,MAAM,OAAO,KAAK;KAChD,OAAO,OAAO;IAChB,IACA,MACN;GACF,SAAS,OAAO;IACd,IAAI,iBAAiB,mBACnB,OAAO,SAAS,KACd;KACE,OAAO,MAAM;KACb,OAAO,MAAM;KACb,WAAW,MAAM;IACnB,GACA,EAAE,QAAQ,IAAI,CAChB;IAEF,IACE,iBAAiB,YAChB,MAAM,SAAS,qBACd,MAAM,SAAS,uBAEjB,OAAO,SAAS,KAAK,EAAE,OAAO,MAAM,QAAQ,GAAG,EAAE,QAAQ,IAAI,CAAC;IAEhE,MAAM;GACR;EACF;EAEA,MAAM,OAAgC,CAAC;EACvC,MAAM,OAAgC,CAAC;EACvC,KAAK,MAAM,aAAa,gBAAgB,KAAK,GAAG;GAC9C,OAAO,eAAe,MAAM,WAAW;IACrC,QAAQ,OAAiB,gBACvB,UAAU,WAAW,OAAO,WAAW;IACzC,YAAY;IACZ,cAAc;IACd,UAAU;GACZ,CAAC;GACD,OAAO,eAAe,MAAM,WAAW;IACrC,QAAQ,OAAiB,gBACvB,UAAU,WAAW,OAAO,WAAW;IACzC,YAAY;IACZ,cAAc;IACd,UAAU;GACZ,CAAC;EACH;EAUA,OAAO;GAPL;GACA;GACM;GACA;GACN,OAAO;GACP,OAAO;EAEG;CACd;CAEA,OAAO;EACL;EACA,UAAA;EACA;EACA;EACA,OAAO;CACT;AACF"}
|
package/dist/ai-server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { n as A2Server, p as ServerOptions } from "./server-
|
|
1
|
+
import { a as ContractEvent, s as EventDefs } from "./reducer-DJKWm3cp.js";
|
|
2
|
+
import { n as A2Server, p as ServerOptions } from "./server-DgCrSuhB.js";
|
|
3
3
|
import { AIEventDefs, AIState, AgentDefinition, AgentToolContext, AgentToolEventDefs } from "./ai.js";
|
|
4
4
|
import { Instructions, LanguageModel, TextStreamPart, ToolSet, ToolSet as ToolSet$1, UIMessage, UIMessageChunk, streamText } from "ai";
|
|
5
5
|
//#region src/ai-sdk-step.d.ts
|
package/dist/ai-server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as A2Error } from "./errors-
|
|
1
|
+
import { t as A2Error } from "./errors-DCk6ch5n.js";
|
|
2
2
|
import { f as consumeSchedulerSendFailure, p as installAmbientToolScopeStorage } from "./internal-DRXJ56EI.js";
|
|
3
|
-
import { r as setServerFetchHooks, t as createServer } from "./server-
|
|
3
|
+
import { r as setServerFetchHooks, t as createServer } from "./server-DlLyvaSH.js";
|
|
4
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
5
|
import { convertToModelMessages, stepCountIs, streamText, toUIMessageStream } from "ai";
|
|
6
6
|
//#region src/ai-sdk-step.ts
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { s as HandlerContext } from "./server-
|
|
1
|
+
import { h as StandardSchemaV1, i as Contract, r as AppendInput, s as EventDefs, t as Reducer } from "./reducer-DJKWm3cp.js";
|
|
2
|
+
import { s as HandlerContext } from "./server-DgCrSuhB.js";
|
|
3
3
|
import { FinishReason, JSONValue, LanguageModelUsage, UIMessage, UIMessageChunk } from "ai";
|
|
4
4
|
//#region src/ai.d.ts
|
|
5
5
|
type AgentStatus = "idle" | "generating" | "waiting" | "failed" | "closed";
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as ContractEvent, c as PresenceDefs, l as PresenceMap, p as WithPresence, r as AppendInput, s as EventDefs, t as Reducer, u as PresencePatch } from "./reducer-DJKWm3cp.js";
|
|
2
2
|
//#region src/client.d.ts
|
|
3
3
|
type ConnectionStatus = "idle" | "connecting" | "live" | "closed";
|
|
4
4
|
/**
|
|
@@ -141,19 +141,25 @@ type A2Client<D extends EventDefs, S, P extends PresenceDefs = Record<never, nev
|
|
|
141
141
|
session(sessionId: string, options?: SessionOptions<D, S>): SessionClient<D, S, P>;
|
|
142
142
|
};
|
|
143
143
|
/**
|
|
144
|
-
* The wire the client rides. The
|
|
144
|
+
* The wire the client rides. The first form is one route serving GET
|
|
145
145
|
* (SSE stream) + POST (push). `http` splits the verbs across two
|
|
146
146
|
* routes, for when platform duration limits differ per verb. `ws`
|
|
147
|
-
* rides everything
|
|
148
|
-
*
|
|
147
|
+
* rides everything over WebSocket, one socket per session by default.
|
|
148
|
+
* Multiplexing every session of the client is an explicit opt-in.
|
|
149
149
|
*/
|
|
150
|
-
type
|
|
150
|
+
type SessionUrl = string | ((sessionId: string) => string);
|
|
151
|
+
type ClientApi = SessionUrl | {
|
|
151
152
|
type: "http";
|
|
152
|
-
push:
|
|
153
|
-
stream:
|
|
153
|
+
push: SessionUrl;
|
|
154
|
+
stream: SessionUrl;
|
|
155
|
+
} | {
|
|
156
|
+
type: "ws";
|
|
157
|
+
url: SessionUrl;
|
|
158
|
+
multiplex?: false;
|
|
154
159
|
} | {
|
|
155
160
|
type: "ws";
|
|
156
161
|
url: string;
|
|
162
|
+
multiplex: true;
|
|
157
163
|
};
|
|
158
164
|
/**
|
|
159
165
|
* The socket surface the `ws` transport drives — satisfied structurally
|
|
@@ -198,5 +204,5 @@ type CreateClientOptions<D extends EventDefs, S, P extends PresenceDefs = Record
|
|
|
198
204
|
};
|
|
199
205
|
declare function createClient<D extends EventDefs, S, P extends PresenceDefs = Record<never, never>>(options: CreateClientOptions<D, S, P>): A2Client<D, S, P>;
|
|
200
206
|
//#endregion
|
|
201
|
-
export { A2Client, ClientApi, ClientWebSocket, ClientWebSocketConstructor, Connection, ConnectionStatus, CreateClientOptions, HistoryState, LoadHistoryOptions, PushResult, SessionClient, SessionClientPresence, SessionOptions, SessionSnapshot, createClient };
|
|
207
|
+
export { A2Client, ClientApi, ClientWebSocket, ClientWebSocketConstructor, Connection, ConnectionStatus, CreateClientOptions, HistoryState, LoadHistoryOptions, PushResult, SessionClient, SessionClientPresence, SessionOptions, SessionSnapshot, SessionUrl, createClient };
|
|
202
208
|
//# sourceMappingURL=client.d.ts.map
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;KAqDY;;;;;;;KAQA;EACN;;EAEA;;EAEA;;EAEA,OAAO;;EAEP;EAAgB;;EAChB;;;;;;;;;;KAUM,WAAW,UAAU,aAAa,QAAQ,cAAc;WACzD,WAAW,QAAQ,cAAc;;KAGhC;;;;;;EAMV;;EAEA;;;KAIU;;EAEV;;EAEA;;EAEA;;;KAIU,gBACV,UAAU,WACV,GACA,UAAU,eAAe,wBACvB,aACF;;EAGE,UAAU,YAAY;;;EAIxB,OAAO;;;;;EAKP,QAAQ,cAAc;;;EAGtB;;EAEA,SAAS;EACT,YAAY;;;;;;;KAQF,sBAAsB,UAAU;;;;;;;;;;EAU1C,YAAY,QAAQ,cAAc;;KAGxB,cACV,UAAU,WACV,GACA,UAAU,eAAe,wBACvB,aAAa,GAAG,sBAAsB;WAC/B;EACT,UAAU;EACV,eAAe,gBAAgB,GAAG,GAAG;;;;;;;;;;EAUrC,QAAQ,QAAQ,YAAY,OAAO,WAAW;;;;;;;;;;;EAW9C,YAAY,UAAU,qBAAqB,QAAQ,cAAc;;;;;;;;;EASjE;;;;;;EAMA;;KAGU,eAAe,UAAU,WAAW;EAC9C,eAAe;EACf;;EAEA,gBAAgB,cAAc;;;EAG9B;;KAGU,SACV,UAAU,WACV,GACA,UAAU,eAAe;EAEzB,QACE,mBACA,UAAU,eAAe,GAAG,KAC3B,cAAc,GAAG,GAAG;;;;;;;;;KAUb,wBAAwB;KAExB,YACR;EACE;EAAc,MAAM;EAAY,QAAQ;;EAExC;EAAY,KAAK;EAAY;;EAE7B;EAAY;EAAa;;;;;;;KAOnB;WACD;EACT,KAAK;EACL,MAAM,eAAe;EACrB,iBAAiB,cAAc;EAC/B,iBACE,iBACA,WAAW;IAAS;;EAEtB,iBACE,eACA,WAAW;IAAS;IAAc;;EAEpC,iBAAiB,eAAe;;KAGtB,kCAAkC,gBAAgB;KAElD,oBACV,UAAU,WACV,GACA,UAAU,eAAe;EAEzB,SAAS,QAAQ,GAAG,GAAG;;EAEvB,KAAK;;EAEL,eAAe,WAAW;;;EAG1B,YAAY;;;EAGZ;;;;;;;;EAQA;;iBAi6Bc,aACd,UAAU,WACV,GACA,UAAU,eAAe,sBACzB,SAAS,oBAAoB,GAAG,GAAG,KAAK,SAAS,GAAG,GAAG"}
|
package/dist/client.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as validateSync } from "./validate-XKT4FSNn.js";
|
|
2
|
-
import { t as A2Error } from "./errors-
|
|
3
|
-
import { a as PRESENCE_TIMINGS, c as STREAM_TIMINGS, h as nullProtoRecord } from "./internal-DRXJ56EI.js";
|
|
4
|
-
import { c as isWireEvent, d as parseSocketFrame, f as presencePatchFromWire, l as isWirePresencePatch, m as presenceSnapshotFromWire, o as eventFromWire, r as errorFromWire, u as isWirePresenceSnapshot } from "./wire
|
|
2
|
+
import { t as A2Error } from "./errors-DCk6ch5n.js";
|
|
3
|
+
import { a as PRESENCE_TIMINGS, c as STREAM_TIMINGS, h as nullProtoRecord, o as RESERVED_PARTICIPANT_IDS } from "./internal-DRXJ56EI.js";
|
|
4
|
+
import { c as isWireEvent, d as parseSocketFrame, f as presencePatchFromWire, l as isWirePresencePatch, m as presenceSnapshotFromWire, o as eventFromWire, r as errorFromWire, u as isWirePresenceSnapshot } from "./wire--yji6mO3.js";
|
|
5
5
|
//#region src/client.ts
|
|
6
6
|
/**
|
|
7
7
|
* experimental-a2/client — the framework-agnostic session client.
|
|
@@ -20,10 +20,15 @@ import { c as isWireEvent, d as parseSocketFrame, f as presencePatchFromWire, l
|
|
|
20
20
|
const PUSH_ATTEMPTS = 3;
|
|
21
21
|
const DEFAULT_GC_TIME_MS = 3e5;
|
|
22
22
|
const DEFAULT_HISTORY_LIMIT = 50;
|
|
23
|
+
const sessionUrl = (url, sessionId) => {
|
|
24
|
+
const resolved = typeof url === "function" ? url(sessionId) : url;
|
|
25
|
+
if (typeof resolved !== "string") throw new TypeError("a session URL function must return a string");
|
|
26
|
+
return resolved;
|
|
27
|
+
};
|
|
23
28
|
const httpTransport = (routes, fetchImpl, presence) => ({
|
|
24
29
|
async *connect({ sessionId, startAfter, signal }) {
|
|
25
|
-
const
|
|
26
|
-
const res = await fetchImpl(`${
|
|
30
|
+
const streamUrl = sessionUrl(routes.stream, sessionId);
|
|
31
|
+
const res = await fetchImpl(`${streamUrl}${streamUrl.includes("?") ? "&" : "?"}sessionId=${encodeURIComponent(sessionId)}&index=${startAfter}`, {
|
|
27
32
|
headers: { accept: "text/event-stream" },
|
|
28
33
|
signal
|
|
29
34
|
});
|
|
@@ -75,7 +80,7 @@ const httpTransport = (routes, fetchImpl, presence) => ({
|
|
|
75
80
|
}
|
|
76
81
|
},
|
|
77
82
|
async push(body) {
|
|
78
|
-
const res = await fetchImpl(routes.push, {
|
|
83
|
+
const res = await fetchImpl(sessionUrl(routes.push, body.sessionId), {
|
|
79
84
|
method: "POST",
|
|
80
85
|
headers: { "content-type": "application/json" },
|
|
81
86
|
body: JSON.stringify(body)
|
|
@@ -88,8 +93,8 @@ const httpTransport = (routes, fetchImpl, presence) => ({
|
|
|
88
93
|
throw errorFromWire(await res.json().catch(() => null)) ?? new A2Error("STORE_UNAVAILABLE", `push failed with ${res.status}`);
|
|
89
94
|
},
|
|
90
95
|
async history({ sessionId, gte, lte }) {
|
|
91
|
-
const
|
|
92
|
-
const res = await fetchImpl(`${
|
|
96
|
+
const streamUrl = sessionUrl(routes.stream, sessionId);
|
|
97
|
+
const res = await fetchImpl(`${streamUrl}${streamUrl.includes("?") ? "&" : "?"}sessionId=${encodeURIComponent(sessionId)}>e=${gte}<e=${lte}`, { headers: { accept: "application/json" } });
|
|
93
98
|
if (!res.ok) throw errorFromWire(await res.json().catch(() => null)) ?? new A2Error("STORE_UNAVAILABLE", `history failed with ${res.status}`);
|
|
94
99
|
const rows = await res.json();
|
|
95
100
|
if (!Array.isArray(rows) || !rows.every(isWireEvent)) throw new A2Error("STORE_UNAVAILABLE", "history response was not a list of events");
|
|
@@ -98,7 +103,7 @@ const httpTransport = (routes, fetchImpl, presence) => ({
|
|
|
98
103
|
sendPresence(envelope) {
|
|
99
104
|
(async () => {
|
|
100
105
|
try {
|
|
101
|
-
await (await fetchImpl(routes.push, {
|
|
106
|
+
await (await fetchImpl(sessionUrl(routes.push, envelope.sessionId), {
|
|
102
107
|
method: "POST",
|
|
103
108
|
headers: { "content-type": "application/json" },
|
|
104
109
|
body: JSON.stringify(envelope)
|
|
@@ -109,6 +114,217 @@ const httpTransport = (routes, fetchImpl, presence) => ({
|
|
|
109
114
|
});
|
|
110
115
|
/** `WebSocket.OPEN` — fixed by the spec, identical in every runtime. */
|
|
111
116
|
const WS_OPEN = 1;
|
|
117
|
+
const webSocketUrl = (value) => {
|
|
118
|
+
let resolved;
|
|
119
|
+
if (/^(https?|wss?):\/\//i.test(value)) resolved = new URL(value);
|
|
120
|
+
else {
|
|
121
|
+
const base = globalThis.location?.href;
|
|
122
|
+
if (base === void 0) throw new TypeError(`cannot resolve the relative ws url '${value}' without a browser location — pass an absolute ws:// or wss:// url`);
|
|
123
|
+
resolved = new URL(value, base);
|
|
124
|
+
}
|
|
125
|
+
if (resolved.protocol === "http:") resolved.protocol = "ws:";
|
|
126
|
+
else if (resolved.protocol === "https:") resolved.protocol = "wss:";
|
|
127
|
+
return resolved;
|
|
128
|
+
};
|
|
129
|
+
const socketReadyWaiters = () => {
|
|
130
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
131
|
+
const notify = (sessionId) => {
|
|
132
|
+
const waiters = sessions.get(sessionId);
|
|
133
|
+
if (!waiters) return;
|
|
134
|
+
sessions.delete(sessionId);
|
|
135
|
+
for (const waiter of waiters) waiter();
|
|
136
|
+
};
|
|
137
|
+
const wait = (sessionId, maxWaitMs) => new Promise((resolve) => {
|
|
138
|
+
let waiters = sessions.get(sessionId);
|
|
139
|
+
if (!waiters) {
|
|
140
|
+
waiters = /* @__PURE__ */ new Set();
|
|
141
|
+
sessions.set(sessionId, waiters);
|
|
142
|
+
}
|
|
143
|
+
let settled = false;
|
|
144
|
+
const done = () => {
|
|
145
|
+
if (settled) return;
|
|
146
|
+
settled = true;
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
waiters.delete(done);
|
|
149
|
+
if (waiters.size === 0) sessions.delete(sessionId);
|
|
150
|
+
resolve();
|
|
151
|
+
};
|
|
152
|
+
const timer = setTimeout(done, maxWaitMs);
|
|
153
|
+
timer.unref?.();
|
|
154
|
+
waiters.add(done);
|
|
155
|
+
});
|
|
156
|
+
return {
|
|
157
|
+
notify,
|
|
158
|
+
wait
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
const rejectPendingAcks = (pending) => {
|
|
162
|
+
if (pending.size === 0) return;
|
|
163
|
+
const error = new A2Error("STORE_UNAVAILABLE", "socket closed with the ack outstanding");
|
|
164
|
+
for (const waiter of pending.values()) waiter.reject(error);
|
|
165
|
+
pending.clear();
|
|
166
|
+
};
|
|
167
|
+
const sessionWsTransport = (url, webSocketImpl, presence) => {
|
|
168
|
+
const connections = /* @__PURE__ */ new Map();
|
|
169
|
+
const ready = socketReadyWaiters();
|
|
170
|
+
let nextReq = 1;
|
|
171
|
+
const socketUrl = (sessionId, startAfter) => {
|
|
172
|
+
const resolved = webSocketUrl(sessionUrl(url, sessionId));
|
|
173
|
+
resolved.searchParams.set("sessionId", sessionId);
|
|
174
|
+
resolved.searchParams.set("index", String(startAfter));
|
|
175
|
+
return resolved.href;
|
|
176
|
+
};
|
|
177
|
+
return {
|
|
178
|
+
async *connect({ sessionId, startAfter, signal }) {
|
|
179
|
+
if (webSocketImpl === void 0) throw new TypeError("no WebSocket implementation available — pass one via createClient({ webSocket }) where the global is missing");
|
|
180
|
+
const socket = new webSocketImpl(socketUrl(sessionId, startAfter));
|
|
181
|
+
const connection = {
|
|
182
|
+
socket,
|
|
183
|
+
pending: /* @__PURE__ */ new Map()
|
|
184
|
+
};
|
|
185
|
+
connections.set(sessionId, connection);
|
|
186
|
+
const queue = [];
|
|
187
|
+
let ended = false;
|
|
188
|
+
let failure = null;
|
|
189
|
+
let wake = null;
|
|
190
|
+
const notify = () => {
|
|
191
|
+
wake?.();
|
|
192
|
+
wake = null;
|
|
193
|
+
};
|
|
194
|
+
const finish = (error) => {
|
|
195
|
+
if (ended) return;
|
|
196
|
+
ended = true;
|
|
197
|
+
failure = error;
|
|
198
|
+
if (connections.get(sessionId) === connection) connections.delete(sessionId);
|
|
199
|
+
rejectPendingAcks(connection.pending);
|
|
200
|
+
notify();
|
|
201
|
+
};
|
|
202
|
+
socket.addEventListener("open", () => {
|
|
203
|
+
if (connections.get(sessionId) !== connection || ended) return;
|
|
204
|
+
queue.push({ kind: "ping" });
|
|
205
|
+
notify();
|
|
206
|
+
ready.notify(sessionId);
|
|
207
|
+
});
|
|
208
|
+
socket.addEventListener("message", (event) => {
|
|
209
|
+
if (connections.get(sessionId) !== connection || ended) return;
|
|
210
|
+
if (typeof event.data !== "string") return;
|
|
211
|
+
const frame = parseSocketFrame(event.data);
|
|
212
|
+
if (frame === null) return;
|
|
213
|
+
switch (frame.kind) {
|
|
214
|
+
case "ack": {
|
|
215
|
+
const waiter = connection.pending.get(frame.req);
|
|
216
|
+
if (waiter === void 0) return;
|
|
217
|
+
connection.pending.delete(frame.req);
|
|
218
|
+
if (frame.sessionId !== void 0 || "events" in frame && frame.events.some((row) => row.sessionId !== sessionId)) {
|
|
219
|
+
waiter.reject(new A2Error("STORE_UNAVAILABLE", "ack does not belong to the socket session"));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if ("events" in frame) waiter.resolve(frame.events);
|
|
223
|
+
else waiter.reject(frame.error);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
case "event":
|
|
227
|
+
if (frame.event.sessionId !== sessionId) return;
|
|
228
|
+
queue.push({
|
|
229
|
+
kind: "event",
|
|
230
|
+
event: frame.event
|
|
231
|
+
});
|
|
232
|
+
break;
|
|
233
|
+
case "presence":
|
|
234
|
+
if (presence && frame.sessionId === void 0) queue.push({
|
|
235
|
+
kind: "presence",
|
|
236
|
+
patch: frame.patch
|
|
237
|
+
});
|
|
238
|
+
break;
|
|
239
|
+
case "presence-snapshot":
|
|
240
|
+
if (presence && frame.sessionId === void 0) queue.push({
|
|
241
|
+
kind: "presence-snapshot",
|
|
242
|
+
snapshot: frame.snapshot
|
|
243
|
+
});
|
|
244
|
+
break;
|
|
245
|
+
case "ping":
|
|
246
|
+
queue.push(frame);
|
|
247
|
+
break;
|
|
248
|
+
case "subscribed":
|
|
249
|
+
case "unsubscribed": return;
|
|
250
|
+
}
|
|
251
|
+
notify();
|
|
252
|
+
});
|
|
253
|
+
socket.addEventListener("close", (event) => {
|
|
254
|
+
finish(event.code === 1e3 ? null : /* @__PURE__ */ new Error(`socket closed (${event.code}${event.reason ? `: ${event.reason}` : ""})`));
|
|
255
|
+
});
|
|
256
|
+
socket.addEventListener("error", () => {
|
|
257
|
+
finish(/* @__PURE__ */ new Error("socket error"));
|
|
258
|
+
});
|
|
259
|
+
const onAbort = () => {
|
|
260
|
+
finish(signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("stream aborted"));
|
|
261
|
+
try {
|
|
262
|
+
socket.close(1e3);
|
|
263
|
+
} catch {}
|
|
264
|
+
};
|
|
265
|
+
if (signal.aborted) onAbort();
|
|
266
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
267
|
+
try {
|
|
268
|
+
for (;;) {
|
|
269
|
+
while (queue.length > 0) yield queue.shift();
|
|
270
|
+
if (ended) {
|
|
271
|
+
if (failure) throw failure;
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
await new Promise((resolve) => {
|
|
275
|
+
wake = resolve;
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
} finally {
|
|
279
|
+
signal.removeEventListener("abort", onAbort);
|
|
280
|
+
finish(null);
|
|
281
|
+
try {
|
|
282
|
+
socket.close(1e3);
|
|
283
|
+
} catch {}
|
|
284
|
+
}
|
|
285
|
+
},
|
|
286
|
+
async push(body) {
|
|
287
|
+
const connection = connections.get(body.sessionId);
|
|
288
|
+
if (connection === void 0 || connection.socket.readyState !== WS_OPEN) throw new A2Error("STORE_UNAVAILABLE", "no open socket for the session");
|
|
289
|
+
const req = nextReq;
|
|
290
|
+
nextReq += 1;
|
|
291
|
+
return await new Promise((resolve, reject) => {
|
|
292
|
+
connection.pending.set(req, {
|
|
293
|
+
resolve,
|
|
294
|
+
reject
|
|
295
|
+
});
|
|
296
|
+
const frame = {
|
|
297
|
+
kind: "push",
|
|
298
|
+
req,
|
|
299
|
+
events: body.events
|
|
300
|
+
};
|
|
301
|
+
try {
|
|
302
|
+
connection.socket.send(JSON.stringify(frame));
|
|
303
|
+
} catch (cause) {
|
|
304
|
+
connection.pending.delete(req);
|
|
305
|
+
reject(new A2Error("STORE_UNAVAILABLE", "socket send failed", { cause }));
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
},
|
|
309
|
+
awaitReady(sessionId, maxWaitMs) {
|
|
310
|
+
if (connections.get(sessionId)?.socket.readyState === WS_OPEN) return Promise.resolve();
|
|
311
|
+
return ready.wait(sessionId, maxWaitMs);
|
|
312
|
+
},
|
|
313
|
+
sendPresence(envelope) {
|
|
314
|
+
const connection = connections.get(envelope.sessionId);
|
|
315
|
+
if (connection === void 0 || connection.socket.readyState !== WS_OPEN) return;
|
|
316
|
+
const frame = {
|
|
317
|
+
kind: "presence",
|
|
318
|
+
...envelope.presence
|
|
319
|
+
};
|
|
320
|
+
try {
|
|
321
|
+
connection.socket.send(JSON.stringify(frame));
|
|
322
|
+
} catch {
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
};
|
|
112
328
|
const wakeChannel = (channel) => {
|
|
113
329
|
channel.wake?.();
|
|
114
330
|
channel.wake = null;
|
|
@@ -119,34 +335,16 @@ const subscribeFrame = (sessions) => {
|
|
|
119
335
|
sessions
|
|
120
336
|
});
|
|
121
337
|
};
|
|
122
|
-
const
|
|
338
|
+
const multiplexedWsTransport = (url, webSocketImpl, presence) => {
|
|
123
339
|
const channels = /* @__PURE__ */ new Map();
|
|
124
340
|
const pending = /* @__PURE__ */ new Map();
|
|
125
341
|
/** Push retries parked in `awaitReady`, flushed per session on its
|
|
126
342
|
* subscribe confirmation. */
|
|
127
|
-
const
|
|
343
|
+
const ready = socketReadyWaiters();
|
|
128
344
|
let socket = null;
|
|
129
345
|
let socketOpen = false;
|
|
130
346
|
let watchdog;
|
|
131
347
|
let nextReq = 1;
|
|
132
|
-
const flushReadyWaiters = (sessionId) => {
|
|
133
|
-
const waiters = readyWaiters.get(sessionId);
|
|
134
|
-
if (!waiters) return;
|
|
135
|
-
readyWaiters.delete(sessionId);
|
|
136
|
-
for (const waiter of waiters) waiter();
|
|
137
|
-
};
|
|
138
|
-
const socketUrl = () => {
|
|
139
|
-
let resolved;
|
|
140
|
-
if (/^(https?|wss?):\/\//i.test(url)) resolved = new URL(url);
|
|
141
|
-
else {
|
|
142
|
-
const base = globalThis.location?.href;
|
|
143
|
-
if (base === void 0) throw new TypeError(`cannot resolve the relative ws url '${url}' without a browser location — pass an absolute ws:// or wss:// url`);
|
|
144
|
-
resolved = new URL(url, base);
|
|
145
|
-
}
|
|
146
|
-
if (resolved.protocol === "http:") resolved.protocol = "ws:";
|
|
147
|
-
else if (resolved.protocol === "https:") resolved.protocol = "wss:";
|
|
148
|
-
return resolved.href;
|
|
149
|
-
};
|
|
150
348
|
const trySend = (data) => {
|
|
151
349
|
if (socket === null || !socketOpen) return;
|
|
152
350
|
try {
|
|
@@ -169,11 +367,7 @@ const wsTransport = (url, webSocketImpl, presence) => {
|
|
|
169
367
|
socketOpen = false;
|
|
170
368
|
clearTimeout(watchdog);
|
|
171
369
|
watchdog = void 0;
|
|
172
|
-
|
|
173
|
-
const rejection = new A2Error("STORE_UNAVAILABLE", "socket closed with the ack outstanding");
|
|
174
|
-
for (const waiter of pending.values()) waiter.reject(rejection);
|
|
175
|
-
pending.clear();
|
|
176
|
-
}
|
|
370
|
+
rejectPendingAcks(pending);
|
|
177
371
|
return current;
|
|
178
372
|
};
|
|
179
373
|
const failSocket = (failure) => {
|
|
@@ -218,7 +412,7 @@ const wsTransport = (url, webSocketImpl, presence) => {
|
|
|
218
412
|
if (channel === void 0 || channel.ended || channel.live) return;
|
|
219
413
|
channel.live = true;
|
|
220
414
|
deliver(channel, { kind: "ping" });
|
|
221
|
-
|
|
415
|
+
ready.notify(frame.sessionId);
|
|
222
416
|
return;
|
|
223
417
|
}
|
|
224
418
|
case "unsubscribed": {
|
|
@@ -267,7 +461,7 @@ const wsTransport = (url, webSocketImpl, presence) => {
|
|
|
267
461
|
const ensureSocket = () => {
|
|
268
462
|
if (socket !== null) return;
|
|
269
463
|
if (webSocketImpl === void 0) throw new TypeError("no WebSocket implementation available — pass one via createClient({ webSocket }) where the global is missing");
|
|
270
|
-
const created = new webSocketImpl(
|
|
464
|
+
const created = new webSocketImpl(webSocketUrl(url).href);
|
|
271
465
|
socket = created;
|
|
272
466
|
socketOpen = false;
|
|
273
467
|
armWatchdog(created);
|
|
@@ -378,25 +572,7 @@ const wsTransport = (url, webSocketImpl, presence) => {
|
|
|
378
572
|
awaitReady(sessionId, maxWaitMs) {
|
|
379
573
|
const channel = channels.get(sessionId);
|
|
380
574
|
if (channel !== void 0 && channel.live && !channel.ended && socketOpen) return Promise.resolve();
|
|
381
|
-
return
|
|
382
|
-
let waiters = readyWaiters.get(sessionId);
|
|
383
|
-
if (!waiters) {
|
|
384
|
-
waiters = /* @__PURE__ */ new Set();
|
|
385
|
-
readyWaiters.set(sessionId, waiters);
|
|
386
|
-
}
|
|
387
|
-
let settled = false;
|
|
388
|
-
const done = () => {
|
|
389
|
-
if (settled) return;
|
|
390
|
-
settled = true;
|
|
391
|
-
clearTimeout(timer);
|
|
392
|
-
waiters.delete(done);
|
|
393
|
-
if (waiters.size === 0) readyWaiters.delete(sessionId);
|
|
394
|
-
resolve();
|
|
395
|
-
};
|
|
396
|
-
const timer = setTimeout(done, maxWaitMs);
|
|
397
|
-
timer.unref?.();
|
|
398
|
-
waiters.add(done);
|
|
399
|
-
});
|
|
575
|
+
return ready.wait(sessionId, maxWaitMs);
|
|
400
576
|
},
|
|
401
577
|
sendPresence(envelope) {
|
|
402
578
|
const channel = channels.get(envelope.sessionId);
|
|
@@ -411,7 +587,7 @@ const wsTransport = (url, webSocketImpl, presence) => {
|
|
|
411
587
|
};
|
|
412
588
|
};
|
|
413
589
|
const transportFor = (api, fetchImpl, webSocketImpl, presence) => {
|
|
414
|
-
if (typeof api === "string") return httpTransport({
|
|
590
|
+
if (typeof api === "string" || typeof api === "function") return httpTransport({
|
|
415
591
|
push: api,
|
|
416
592
|
stream: api
|
|
417
593
|
}, fetchImpl, presence);
|
|
@@ -419,7 +595,11 @@ const transportFor = (api, fetchImpl, webSocketImpl, presence) => {
|
|
|
419
595
|
push: api.push,
|
|
420
596
|
stream: api.stream
|
|
421
597
|
}, fetchImpl, presence);
|
|
422
|
-
|
|
598
|
+
if (api.multiplex === true) {
|
|
599
|
+
if (typeof api.url !== "string") throw new TypeError("a multiplexed WebSocket URL must be a string");
|
|
600
|
+
return multiplexedWsTransport(api.url, webSocketImpl, presence);
|
|
601
|
+
}
|
|
602
|
+
return sessionWsTransport(api.url, webSocketImpl, presence);
|
|
423
603
|
};
|
|
424
604
|
function createClient(options) {
|
|
425
605
|
const { reducer, api } = options;
|
|
@@ -659,7 +839,7 @@ function createClient(options) {
|
|
|
659
839
|
const validated = nullProtoRecord();
|
|
660
840
|
for (const [field, value] of Object.entries(values)) {
|
|
661
841
|
if (value === void 0) continue;
|
|
662
|
-
const schema = Object.hasOwn(presenceDefs, field) ? presenceDefs[field] : void 0;
|
|
842
|
+
const schema = Object.hasOwn(presenceDefs, field) ? presenceDefs[field] : RESERVED_PARTICIPANT_IDS.has(field) ? void 0 : presenceDefs["*"];
|
|
663
843
|
if (!schema) throw new A2Error("UNKNOWN_PRESENCE_FIELD", `no presence field '${field}' in the reducer's vocabulary`);
|
|
664
844
|
if (value === null) {
|
|
665
845
|
validated[field] = null;
|