@rotorsoft/act-http 1.9.1 → 1.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/@types/sse/broadcast.d.ts.map +1 -1
- package/dist/hono/index.cjs +1 -1
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.js +1 -1
- package/dist/hono/index.js.map +1 -1
- package/dist/sse/index.cjs +15 -2
- package/dist/sse/index.cjs.map +1 -1
- package/dist/sse/index.js +15 -2
- package/dist/sse/index.js.map +1 -1
- package/package.json +8 -8
package/dist/hono/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
import "../chunk-WGFX4G27.js";
|
|
10
10
|
import "../chunk-PZ5AY32C.js";
|
|
11
11
|
|
|
12
|
-
// ../../node_modules/.pnpm/@hono+zod-validator@0.9.0_hono@4.
|
|
12
|
+
// ../../node_modules/.pnpm/@hono+zod-validator@0.9.0_hono@4.13.1_zod@4.4.3/node_modules/@hono/zod-validator/dist/index.mjs
|
|
13
13
|
import { validator } from "hono/validator";
|
|
14
14
|
function zValidatorFunction(target, schema, hook, options) {
|
|
15
15
|
return validator(target, async (value, c) => {
|
package/dist/hono/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../node_modules/.pnpm/@hono+zod-validator@0.9.0_hono@4.12.34_zod@4.4.3/node_modules/@hono/zod-validator/src/index.ts","../../src/hono/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Context, Env, Input, MiddlewareHandler, TypedResponse, ValidationTargets } from 'hono'\nimport { validator } from 'hono/validator'\nimport type { InferInput } from 'hono/validator'\nimport type * as v3 from 'zod/v3'\nimport type { ZodSafeParseResult as v4ZodSafeParseResult } from 'zod/v4'\nimport type * as v4 from 'zod/v4/core'\n\ntype ZodSchema = v3.ZodType | v4.$ZodType\ntype ZodError<T extends ZodSchema> = T extends v4.$ZodType\n ? v4.$ZodError<v4.output<T>>\n : v3.ZodError\ntype ZodSafeParseResult<T, T2, T3 extends ZodSchema> = T3 extends v4.$ZodType\n ? v4ZodSafeParseResult<T>\n : v3.SafeParseReturnType<T, T2>\ntype zInput<T> = T extends v3.ZodType ? v3.input<T> : T extends v4.$ZodType ? v4.input<T> : never\ntype zOutput<T> = T extends v3.ZodType ? v3.output<T> : T extends v4.$ZodType ? v4.output<T> : never\ntype zInfer<T> = T extends v3.ZodType ? v3.infer<T> : T extends v4.$ZodType ? v4.infer<T> : never\n\n// Failure variant of `safeParseAsync`'s return value.\n// Mirrors the runtime body returned by `c.json(result, 400)` on validation failure.\ntype ZodValidatorFailureBody<T extends ZodSchema> = T extends v4.$ZodType\n ? Extract<v4ZodSafeParseResult<v4.output<T>>, { success: false }>\n : T extends v3.ZodType\n ? Extract<v3.SafeParseReturnType<v3.input<T>, v3.output<T>>, { success: false }>\n : never\n\ntype ZodValidatorFailureResponse<T extends ZodSchema> = Response &\n TypedResponse<ZodValidatorFailureBody<T>, 400, 'json'>\n\nexport type Hook<\n T,\n E extends Env,\n P extends string,\n Target extends keyof ValidationTargets = keyof ValidationTargets,\n O = {},\n Schema extends ZodSchema = any,\n> = (\n result: ({ success: true; data: T } | { success: false; error: ZodError<Schema>; data: T }) & {\n target: Target\n },\n c: Context<E, P>\n) => Response | void | TypedResponse<O> | Promise<Response | void | TypedResponse<O>>\n\ntype HasUndefined<T> = undefined extends T ? true : false\n\ntype ExtractValidationResponse<VF> = VF extends (value: any, c: any) => infer R\n ? R extends Promise<infer PR>\n ? PR extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : PR extends Response\n ? PR\n : PR extends undefined\n ? never\n : never\n : R extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : R extends Response\n ? R\n : R extends undefined\n ? never\n : never\n : never\n\ntype ValidationFunctionOption<T extends ZodSchema, Target extends keyof ValidationTargets> = {\n validationFunction: (\n schema: T,\n value: ValidationTargets[Target]\n ) => ZodSafeParseResult<any, any, T> | Promise<ZodSafeParseResult<any, any, T>>\n}\n\ntype DefaultInput<Target extends keyof ValidationTargets, In, Out> = {\n in: HasUndefined<In> extends true\n ? {\n [K in Target]?: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n : {\n [K in Target]: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n out: { [K in Target]: Out }\n}\n\n// without hook (with or without options)\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n>(\n target: Target,\n schema: T,\n hook?: undefined,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n\n// with hook and options\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>>\n\n// implementation\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n):\n | MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n | MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>> {\n // @ts-expect-error not typed well\n return validator(target, async (value: ValidationTargets[Target], c) => {\n let validatorValue = value\n\n // in case where our `target` === `header`, Hono parses all of the headers into lowercase.\n // this might not match the Zod schema, so we want to make sure that we account for that when parsing the schema.\n if ((target === 'header' && '_def' in schema) || (target === 'header' && '_zod' in schema)) {\n // create an object that maps lowercase schema keys to lowercase\n // @ts-expect-error the schema is a Zod Schema\n const schemaKeys = Object.keys('in' in schema ? schema.in.shape : schema.shape)\n const caseInsensitiveKeymap = Object.fromEntries(\n schemaKeys.map((key) => [key.toLowerCase(), key])\n )\n\n validatorValue = Object.fromEntries(\n Object.entries(value).map(([key, value]) => [caseInsensitiveKeymap[key] || key, value])\n )\n }\n\n const result =\n options && options.validationFunction\n ? await options.validationFunction(schema, validatorValue)\n : // @ts-expect-error z4.$ZodType has safeParseAsync\n await schema.safeParseAsync(validatorValue)\n\n if (hook) {\n const hookResult = await hook({ data: validatorValue, ...result, target }, c)\n if (hookResult) {\n if (hookResult instanceof Response) {\n return hookResult\n }\n\n if ('response' in hookResult) {\n return hookResult.response\n }\n }\n }\n\n if (!result.success) {\n return c.json(result, 400)\n }\n\n return result.data as zInfer<T>\n })\n}\n\nexport const zValidator: typeof zValidatorFunction = zValidatorFunction\n","/**\n * @packageDocumentation\n * @module act-http/hono\n *\n * Hono subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a Hono\n * app with one `POST /actions/<name>` route per registered action,\n * Zod-validated bodies, and the shared error envelope.\n *\n * Usage:\n *\n * ```ts\n * import { hono } from \"@rotorsoft/act-http/hono\";\n *\n * const api = hono(app, {\n * actor: (c) => ({ id: c.req.header(\"x-user-id\")!, name: \"...\" }),\n * stream: (action, input, c) => `tenant-${c.req.header(\"x-tenant\")}`,\n * });\n *\n * // Mounts at /api by default — pass `basePath` to override.\n * // POST /api/actions/OpenTicket body: { title } → 200 Snapshot[] | 4xx ApiError\n * ```\n *\n * The route shape matches the flat tRPC sibling at\n * `@rotorsoft/act-http/trpc`: one endpoint per action, no\n * state-name tier. Action names are unique across the registry —\n * the framework enforces no duplicates — so an extra namespace\n * level would be overhead. Queries live in a follow-up; this\n * slice is mutations only.\n *\n * **Actor lives on the context.** The generator wires an internal\n * middleware that runs the host's\n * {@link HonoOptions.actor | actor extractor} once per call and\n * stashes the resolved {@link Actor} under `c.get(\"actor\")`. Every\n * generated route reads from there — auth resolves at one seam,\n * downstream middleware (logging, tracing) sees the same actor.\n * The middleware factory is also exported as {@link authenticated}\n * for hosts that want to compose it into their own Hono chain\n * alongside hand-written routes.\n *\n * Composes the shared utilities at `@rotorsoft/act-http/api`:\n * {@link ActorExtractor} for the auth seam, {@link toApiError} for\n * the uniform error → status / code mapping, {@link withIdempotency}\n * for `Idempotency-Key` dedup. Three transports (tRPC, this one,\n * OpenAPI) ride the same utilities so a client speaking two of\n * them never sees two shapes for the same framework error.\n */\nimport { zValidator } from \"@hono/zod-validator\";\nimport type { Actor, Target } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { Hono } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport {\n type ActorExtractor,\n type ApiError,\n fireAndForget,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Hono context variables this subpath contributes. The generic on\n * the returned middleware threads it through so routes downstream\n * of {@link authenticated} see `c.get(\"actor\")` typed without a\n * manual cast.\n */\nexport type ActMiddlewareVariables = {\n actor: Actor;\n};\n\n/**\n * Per-call options for {@link hono}. The host supplies the four\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the Hono context, returns the\n * `Actor` that flows onto `c.get(\"actor\")` for every generated\n * route (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated body, and the Hono context; returns the target\n * stream. Singleton aggregates return a constant; per-tenant\n * aggregates pull from headers, path, or body.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * Hosts typically read it from an `If-Match` header on the\n * request, or from the client's last-known snapshot. Returning\n * `undefined` skips the check for that call — handy when only\n * some actions are concurrency-sensitive.\n * - `idempotency` (optional) — when set, the route honors\n * `Idempotency-Key` via {@link withIdempotency}. The host\n * supplies the `IdempotencyStore`; `keyFrom` defaults to reading\n * the `Idempotency-Key` header. On a duplicate claim, the route\n * responds `409 Conflict` — the contract intentionally doesn't\n * cache the original handler's result, matching the\n * receiver-side \"ack the duplicate\" semantics.\n * - `basePath` (optional, default `\"/api\"`) — Hono basePath the\n * routes mount under.\n */\nexport type HonoOptions = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n c: Context\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n c: Context\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom?: (c: Context) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * `GET <basePath>/sse/<stateName>?stream=<streamId>` per unique\n * state name in the registry. The endpoint runs the host\n * {@link actor} extractor, looks up the streamId from\n * `?stream=...`, opens a `text/event-stream`, yields the cached\n * state (if any), and forwards every patch published to the\n * shared {@link SseOptions.channel}. A heartbeat keeps proxies\n * from idling the connection out; the per-process connection cap\n * returns `503 Service Unavailable` (with `Retry-After: 1`) when\n * full so operators never see silent stalls.\n *\n * Off by default — most APIs don't expose live state to every\n * client, and opening one is widening both the auth and cost\n * surface.\n */\n readonly sse?: SseOptions;\n readonly basePath?: string;\n};\n\n/**\n * Build a Hono middleware that runs an {@link ActorExtractor} once\n * per call and stashes the resolved {@link Actor} under\n * `c.set(\"actor\", ...)` so downstream routes can read it via\n * `c.get(\"actor\")`. The generator at {@link hono} uses this\n * internally; it's also exported so hosts that want to compose\n * their own route chain (logging, tracing, custom auth flavors)\n * can wire it directly:\n *\n * ```ts\n * import { Hono } from \"hono\";\n * import { authenticated, type ActMiddlewareVariables } from \"@rotorsoft/act-http/hono\";\n *\n * const api = new Hono<{ Variables: ActMiddlewareVariables }>();\n * api.use(\"*\", authenticated((c) => resolveUserFromJwt(c)));\n * api.get(\"/me\", (c) => c.json(c.get(\"actor\"))); // typed\n * ```\n *\n * Errors thrown by the extractor surface as `401 Unauthorized` with\n * the shared {@link ApiError} envelope.\n */\nexport function authenticated(\n extractor: ActorExtractor\n): MiddlewareHandler<{ Variables: ActMiddlewareVariables }> {\n return async (c, next) => {\n try {\n const actor = await extractor(c);\n c.set(\"actor\", actor);\n await next();\n } catch (err) {\n const body: ApiError = {\n error: \"Unauthorized\",\n detail: err instanceof Error ? err.message : undefined,\n code: \"UNAUTHORIZED\",\n };\n return c.json(body, 401);\n }\n };\n}\n\nconst default_key_from = (c: Context): string | undefined =>\n c.req.header(\"idempotency-key\");\n\n/**\n * Build a typed Hono REST surface from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one\n * `POST /actions/<actionName>` per action under the configured\n * `basePath` (default `/api`). Each route:\n *\n * 1. Runs the internal {@link authenticated} middleware —\n * `options.actor` resolves the {@link Actor} once and stashes\n * it under `c.get(\"actor\")`.\n * 2. Validates the JSON body against the action's Zod schema via\n * `@hono/zod-validator`. Failures short-circuit with `422`.\n * 3. Resolves the target stream via\n * `options.stream(name, input, c)`.\n * 4. (Optionally) resolves `expectedVersion` for optimistic\n * concurrency.\n * 5. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — responds `409` on duplicate.\n * 6. Calls\n * `app.do(name, { stream, actor, expectedVersion? }, input)`.\n * 7. Maps any thrown framework error onto the shared\n * {@link ApiError} envelope via {@link toApiError}, returning\n * the conventional HTTP status (`409` / `412` for concurrency,\n * `422` for validation, `400` for non-retryable, etc.).\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, expected-version, idempotency, and\n * base-path seams.\n * @returns A Hono app covering every registered action under\n * `<basePath>/actions/<name>`.\n */\n/**\n * Structural shape of the Act surface this generator walks at\n * runtime — the registry's action-name → owning-state map plus the\n * `do(...)` dispatch. Letting TApp infer to the caller's concrete\n * `Act<...>` against this structural bound keeps nested variance\n * out of the signature and avoids `any` in either direction.\n *\n * @internal\n */\ntype ActSurface = {\n readonly registry: {\n actions: Record<\n string,\n {\n readonly name: string;\n readonly actions: Record<string, unknown>;\n }\n >;\n };\n do(action: string, target: Target, payload: unknown): Promise<unknown>;\n};\n\nexport function hono<TApp extends ActSurface = ActSurface>(\n app: TApp,\n options: HonoOptions\n): Hono<{ Variables: ActMiddlewareVariables }> {\n const base_path = options.basePath ?? \"/api\";\n const api = new Hono<{ Variables: ActMiddlewareVariables }>().basePath(\n base_path\n );\n api.use(\"*\", authenticated(options.actor));\n\n const key_from = options.idempotency?.keyFrom ?? default_key_from;\n\n // Wire SSE subscriptions before the mutation routes so the\n // `/sse/*` paths sit alongside `/actions/*`. The cap counter is\n // shared by every state-name's GET route on this generator\n // instance so a noisy room on one state doesn't get a free pass\n // on another.\n if (options.sse) {\n const sse_config = resolveSseConfig(options.sse);\n const sse_counter = new SseConnectionCounter(sse_config.maxConnections);\n const state_names = new Set<string>();\n for (const action of Object.values(app.registry.actions)) {\n state_names.add(action.name);\n }\n for (const state_name of state_names) {\n api.get(`/sse/${state_name}`, async (c) => {\n const stream_id = c.req.query(\"stream\");\n if (!stream_id) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"stream query parameter is required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n if (!sse_counter.acquire()) {\n c.header(\"Retry-After\", \"1\");\n const body: ApiError = {\n error: \"ServiceUnavailable\",\n detail: \"max concurrent SSE connections reached\",\n code: \"SSE_BUSY\",\n };\n return c.json(body, 503);\n }\n // The route already acquired the slot above so streamSSE\n // could return `503` before writing headers if the cap was\n // full. The shared loop runs without accounting; the route\n // releases the slot in `finally`.\n const controller = new AbortController();\n return streamSSE(c, async (sse_stream) => {\n sse_stream.onAbort(() => controller.abort());\n const heartbeat = setInterval(() => {\n fireAndForget(() =>\n sse_stream.writeSSE({ event: \"ping\", data: \"\" })\n );\n }, sse_config.heartbeatMs);\n try {\n for await (const frame of runSseSubscription(\n sse_config.channel,\n stream_id,\n undefined,\n controller.signal,\n { maxPending: sse_config.maxPendingPerConnection }\n )) {\n await sse_stream.writeSSE({\n event: frame.kind,\n data: JSON.stringify(frame.data),\n });\n }\n } finally {\n clearInterval(heartbeat);\n sse_counter.release();\n }\n });\n });\n }\n }\n\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const schema = state.actions[action_name];\n api.post(\n `/actions/${action_name}`,\n // Custom hook funnels body-schema failures through the same\n // ApiError envelope + 422 status an in-`do` ValidationError maps\n // to (ERROR_MAP.ValidationError). Without it, @hono/zod-validator\n // short-circuits with its own 400 + raw body — two statuses and\n // two shapes for the same \"malformed input\" failure class on one\n // endpoint. The OpenAPI doc only documents the 422/ApiError path.\n zValidator(\"json\", schema as never, (result, c) => {\n if (!result.success) {\n // `result.error` is a ZodError; the schema's `never` typing\n // erases its shape, so read `.message` through a narrow cast.\n const message = (result.error as { message?: string }).message;\n const body: ApiError = {\n error: \"ValidationError\",\n detail: message,\n code: \"VALIDATION\",\n };\n return c.json(body, 422);\n }\n }),\n async (c) => {\n try {\n const input = c.req.valid(\"json\" as never) as unknown;\n const actor = c.get(\"actor\");\n const stream = await options.stream(action_name, input, c);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, input, c)\n : undefined;\n const target =\n expected_version === undefined\n ? { stream, actor }\n : { stream, actor, expectedVersion: expected_version };\n\n if (options.idempotency) {\n const key = key_from(c);\n if (!key) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"Idempotency-Key required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n const outcome = await withIdempotency(\n options.idempotency.store,\n key,\n () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped) {\n const body: ApiError = {\n error: \"Conflict\",\n detail:\n \"Idempotency-Key already used; original result not cached\",\n code: \"CONFLICT\",\n };\n return c.json(body, 409);\n }\n return c.json(outcome.result);\n }\n\n const snapshots = await app.do(\n action_name as never,\n target as never,\n input as never\n );\n return c.json(snapshots);\n } catch (err) {\n const { status, body } = toApiError(err);\n // Hono types narrow `status` to its known status-number union;\n // `toApiError` returns a numeric status from a closed set that\n // matches but TypeScript can't prove it through the union.\n return c.json(body, status as 400 | 409 | 410 | 412 | 422 | 500);\n }\n }\n );\n }\n\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;AAuHA,SAAS,mBAYP,QACA,QACA,MACA,SAGgE;AAEhE,SAAO,UAAU,QAAQ,OAAO,OAAkC,MAAM;AACtE,QAAI,iBAAiB;AAIrB,QAAK,WAAW,YAAY,UAAU,UAAY,WAAW,YAAY,UAAU,QAAS;AAG1F,YAAM,aAAa,OAAO,KAAK,QAAQ,SAAS,OAAO,GAAG,QAAQ,OAAO,KAAK;AAC9E,YAAM,wBAAwB,OAAO,YACnC,WAAW,IAAA,CAAK,QAAQ,CAAC,IAAI,YAAY,GAAG,GAAG,CAAC,CAClD;AAEA,uBAAiB,OAAO,YACtB,OAAO,QAAQ,KAAK,EAAE,IAAA,CAAK,CAAC,KAAKA,MAAA,MAAW,CAAC,sBAAsB,GAAA,KAAQ,KAAKA,MAAK,CAAC,CACxF;IACF;AAEA,UAAM,SACJ,WAAW,QAAQ,qBACf,MAAM,QAAQ,mBAAmB,QAAQ,cAAc,IAEvD,MAAM,OAAO,eAAe,cAAc;AAEhD,QAAI,MAAM;AACR,YAAM,aAAa,MAAM,KAAK;QAAE,MAAM;QAAgB,GAAG;QAAQ;MAAO,GAAG,CAAC;AAC5E,UAAI,YAAY;AACd,YAAI,sBAAsB,SACxB,QAAO;AAGT,YAAI,cAAc,WAChB,QAAO,WAAW;MAEtB;IACF;AAEA,QAAI,CAAC,OAAO,QACV,QAAO,EAAE,KAAK,QAAQ,GAAG;AAG3B,WAAO,OAAO;EAChB,CAAC;AACH;AAEA,IAAa,aAAwC;;;ACrI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npm/@hono+zod-validator@0.9.0_hono@4.13.1_zod@4.4.3/node_modules/@hono/zod-validator/src/index.ts","../../src/hono/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Context, Env, Input, MiddlewareHandler, TypedResponse, ValidationTargets } from 'hono'\nimport { validator } from 'hono/validator'\nimport type { InferInput } from 'hono/validator'\nimport type * as v3 from 'zod/v3'\nimport type { ZodSafeParseResult as v4ZodSafeParseResult } from 'zod/v4'\nimport type * as v4 from 'zod/v4/core'\n\ntype ZodSchema = v3.ZodType | v4.$ZodType\ntype ZodError<T extends ZodSchema> = T extends v4.$ZodType\n ? v4.$ZodError<v4.output<T>>\n : v3.ZodError\ntype ZodSafeParseResult<T, T2, T3 extends ZodSchema> = T3 extends v4.$ZodType\n ? v4ZodSafeParseResult<T>\n : v3.SafeParseReturnType<T, T2>\ntype zInput<T> = T extends v3.ZodType ? v3.input<T> : T extends v4.$ZodType ? v4.input<T> : never\ntype zOutput<T> = T extends v3.ZodType ? v3.output<T> : T extends v4.$ZodType ? v4.output<T> : never\ntype zInfer<T> = T extends v3.ZodType ? v3.infer<T> : T extends v4.$ZodType ? v4.infer<T> : never\n\n// Failure variant of `safeParseAsync`'s return value.\n// Mirrors the runtime body returned by `c.json(result, 400)` on validation failure.\ntype ZodValidatorFailureBody<T extends ZodSchema> = T extends v4.$ZodType\n ? Extract<v4ZodSafeParseResult<v4.output<T>>, { success: false }>\n : T extends v3.ZodType\n ? Extract<v3.SafeParseReturnType<v3.input<T>, v3.output<T>>, { success: false }>\n : never\n\ntype ZodValidatorFailureResponse<T extends ZodSchema> = Response &\n TypedResponse<ZodValidatorFailureBody<T>, 400, 'json'>\n\nexport type Hook<\n T,\n E extends Env,\n P extends string,\n Target extends keyof ValidationTargets = keyof ValidationTargets,\n O = {},\n Schema extends ZodSchema = any,\n> = (\n result: ({ success: true; data: T } | { success: false; error: ZodError<Schema>; data: T }) & {\n target: Target\n },\n c: Context<E, P>\n) => Response | void | TypedResponse<O> | Promise<Response | void | TypedResponse<O>>\n\ntype HasUndefined<T> = undefined extends T ? true : false\n\ntype ExtractValidationResponse<VF> = VF extends (value: any, c: any) => infer R\n ? R extends Promise<infer PR>\n ? PR extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : PR extends Response\n ? PR\n : PR extends undefined\n ? never\n : never\n : R extends TypedResponse<infer T, infer S, infer F>\n ? Response & TypedResponse<T, S, F>\n : R extends Response\n ? R\n : R extends undefined\n ? never\n : never\n : never\n\ntype ValidationFunctionOption<T extends ZodSchema, Target extends keyof ValidationTargets> = {\n validationFunction: (\n schema: T,\n value: ValidationTargets[Target]\n ) => ZodSafeParseResult<any, any, T> | Promise<ZodSafeParseResult<any, any, T>>\n}\n\ntype DefaultInput<Target extends keyof ValidationTargets, In, Out> = {\n in: HasUndefined<In> extends true\n ? {\n [K in Target]?: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n : {\n [K in Target]: [In] extends [ValidationTargets[K]] ? In : InferInput<In, K>\n }\n out: { [K in Target]: Out }\n}\n\n// without hook (with or without options)\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n>(\n target: Target,\n schema: T,\n hook?: undefined,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n\n// with hook and options\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n): MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>>\n\n// implementation\nfunction zValidatorFunction<\n T extends ZodSchema,\n Target extends keyof ValidationTargets,\n E extends Env,\n P extends string,\n HookFn extends Hook<InferredValue, E, P, Target, {}, T>,\n In = zInput<T>,\n Out = zOutput<T>,\n I extends Input = DefaultInput<Target, In, Out>,\n V extends I = I,\n InferredValue = zInfer<T>,\n>(\n target: Target,\n schema: T,\n hook?: HookFn,\n options?: ValidationFunctionOption<T, Target>\n):\n | MiddlewareHandler<E, P, V, ZodValidatorFailureResponse<T>>\n | MiddlewareHandler<E, P, V, ExtractValidationResponse<HookFn>> {\n // @ts-expect-error not typed well\n return validator(target, async (value: ValidationTargets[Target], c) => {\n let validatorValue = value\n\n // in case where our `target` === `header`, Hono parses all of the headers into lowercase.\n // this might not match the Zod schema, so we want to make sure that we account for that when parsing the schema.\n if ((target === 'header' && '_def' in schema) || (target === 'header' && '_zod' in schema)) {\n // create an object that maps lowercase schema keys to lowercase\n // @ts-expect-error the schema is a Zod Schema\n const schemaKeys = Object.keys('in' in schema ? schema.in.shape : schema.shape)\n const caseInsensitiveKeymap = Object.fromEntries(\n schemaKeys.map((key) => [key.toLowerCase(), key])\n )\n\n validatorValue = Object.fromEntries(\n Object.entries(value).map(([key, value]) => [caseInsensitiveKeymap[key] || key, value])\n )\n }\n\n const result =\n options && options.validationFunction\n ? await options.validationFunction(schema, validatorValue)\n : // @ts-expect-error z4.$ZodType has safeParseAsync\n await schema.safeParseAsync(validatorValue)\n\n if (hook) {\n const hookResult = await hook({ data: validatorValue, ...result, target }, c)\n if (hookResult) {\n if (hookResult instanceof Response) {\n return hookResult\n }\n\n if ('response' in hookResult) {\n return hookResult.response\n }\n }\n }\n\n if (!result.success) {\n return c.json(result, 400)\n }\n\n return result.data as zInfer<T>\n })\n}\n\nexport const zValidator: typeof zValidatorFunction = zValidatorFunction\n","/**\n * @packageDocumentation\n * @module act-http/hono\n *\n * Hono subpath for the auto-generated API epic (#835). Walks the\n * registry of a built `Act` once at function call and emits a Hono\n * app with one `POST /actions/<name>` route per registered action,\n * Zod-validated bodies, and the shared error envelope.\n *\n * Usage:\n *\n * ```ts\n * import { hono } from \"@rotorsoft/act-http/hono\";\n *\n * const api = hono(app, {\n * actor: (c) => ({ id: c.req.header(\"x-user-id\")!, name: \"...\" }),\n * stream: (action, input, c) => `tenant-${c.req.header(\"x-tenant\")}`,\n * });\n *\n * // Mounts at /api by default — pass `basePath` to override.\n * // POST /api/actions/OpenTicket body: { title } → 200 Snapshot[] | 4xx ApiError\n * ```\n *\n * The route shape matches the flat tRPC sibling at\n * `@rotorsoft/act-http/trpc`: one endpoint per action, no\n * state-name tier. Action names are unique across the registry —\n * the framework enforces no duplicates — so an extra namespace\n * level would be overhead. Queries live in a follow-up; this\n * slice is mutations only.\n *\n * **Actor lives on the context.** The generator wires an internal\n * middleware that runs the host's\n * {@link HonoOptions.actor | actor extractor} once per call and\n * stashes the resolved {@link Actor} under `c.get(\"actor\")`. Every\n * generated route reads from there — auth resolves at one seam,\n * downstream middleware (logging, tracing) sees the same actor.\n * The middleware factory is also exported as {@link authenticated}\n * for hosts that want to compose it into their own Hono chain\n * alongside hand-written routes.\n *\n * Composes the shared utilities at `@rotorsoft/act-http/api`:\n * {@link ActorExtractor} for the auth seam, {@link toApiError} for\n * the uniform error → status / code mapping, {@link withIdempotency}\n * for `Idempotency-Key` dedup. Three transports (tRPC, this one,\n * OpenAPI) ride the same utilities so a client speaking two of\n * them never sees two shapes for the same framework error.\n */\nimport { zValidator } from \"@hono/zod-validator\";\nimport type { Actor, Target } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport type { Context, MiddlewareHandler } from \"hono\";\nimport { Hono } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport {\n type ActorExtractor,\n type ApiError,\n fireAndForget,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n withIdempotency,\n} from \"../api/index.js\";\n\n/**\n * Hono context variables this subpath contributes. The generic on\n * the returned middleware threads it through so routes downstream\n * of {@link authenticated} see `c.get(\"actor\")` typed without a\n * manual cast.\n */\nexport type ActMiddlewareVariables = {\n actor: Actor;\n};\n\n/**\n * Per-call options for {@link hono}. The host supplies the four\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the Hono context, returns the\n * `Actor` that flows onto `c.get(\"actor\")` for every generated\n * route (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated body, and the Hono context; returns the target\n * stream. Singleton aggregates return a constant; per-tenant\n * aggregates pull from headers, path, or body.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * Hosts typically read it from an `If-Match` header on the\n * request, or from the client's last-known snapshot. Returning\n * `undefined` skips the check for that call — handy when only\n * some actions are concurrency-sensitive.\n * - `idempotency` (optional) — when set, the route honors\n * `Idempotency-Key` via {@link withIdempotency}. The host\n * supplies the `IdempotencyStore`; `keyFrom` defaults to reading\n * the `Idempotency-Key` header. On a duplicate claim, the route\n * responds `409 Conflict` — the contract intentionally doesn't\n * cache the original handler's result, matching the\n * receiver-side \"ack the duplicate\" semantics.\n * - `basePath` (optional, default `\"/api\"`) — Hono basePath the\n * routes mount under.\n */\nexport type HonoOptions = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n c: Context\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n c: Context\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom?: (c: Context) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * `GET <basePath>/sse/<stateName>?stream=<streamId>` per unique\n * state name in the registry. The endpoint runs the host\n * {@link actor} extractor, looks up the streamId from\n * `?stream=...`, opens a `text/event-stream`, yields the cached\n * state (if any), and forwards every patch published to the\n * shared {@link SseOptions.channel}. A heartbeat keeps proxies\n * from idling the connection out; the per-process connection cap\n * returns `503 Service Unavailable` (with `Retry-After: 1`) when\n * full so operators never see silent stalls.\n *\n * Off by default — most APIs don't expose live state to every\n * client, and opening one is widening both the auth and cost\n * surface.\n */\n readonly sse?: SseOptions;\n readonly basePath?: string;\n};\n\n/**\n * Build a Hono middleware that runs an {@link ActorExtractor} once\n * per call and stashes the resolved {@link Actor} under\n * `c.set(\"actor\", ...)` so downstream routes can read it via\n * `c.get(\"actor\")`. The generator at {@link hono} uses this\n * internally; it's also exported so hosts that want to compose\n * their own route chain (logging, tracing, custom auth flavors)\n * can wire it directly:\n *\n * ```ts\n * import { Hono } from \"hono\";\n * import { authenticated, type ActMiddlewareVariables } from \"@rotorsoft/act-http/hono\";\n *\n * const api = new Hono<{ Variables: ActMiddlewareVariables }>();\n * api.use(\"*\", authenticated((c) => resolveUserFromJwt(c)));\n * api.get(\"/me\", (c) => c.json(c.get(\"actor\"))); // typed\n * ```\n *\n * Errors thrown by the extractor surface as `401 Unauthorized` with\n * the shared {@link ApiError} envelope.\n */\nexport function authenticated(\n extractor: ActorExtractor\n): MiddlewareHandler<{ Variables: ActMiddlewareVariables }> {\n return async (c, next) => {\n try {\n const actor = await extractor(c);\n c.set(\"actor\", actor);\n await next();\n } catch (err) {\n const body: ApiError = {\n error: \"Unauthorized\",\n detail: err instanceof Error ? err.message : undefined,\n code: \"UNAUTHORIZED\",\n };\n return c.json(body, 401);\n }\n };\n}\n\nconst default_key_from = (c: Context): string | undefined =>\n c.req.header(\"idempotency-key\");\n\n/**\n * Build a typed Hono REST surface from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one\n * `POST /actions/<actionName>` per action under the configured\n * `basePath` (default `/api`). Each route:\n *\n * 1. Runs the internal {@link authenticated} middleware —\n * `options.actor` resolves the {@link Actor} once and stashes\n * it under `c.get(\"actor\")`.\n * 2. Validates the JSON body against the action's Zod schema via\n * `@hono/zod-validator`. Failures short-circuit with `422`.\n * 3. Resolves the target stream via\n * `options.stream(name, input, c)`.\n * 4. (Optionally) resolves `expectedVersion` for optimistic\n * concurrency.\n * 5. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — responds `409` on duplicate.\n * 6. Calls\n * `app.do(name, { stream, actor, expectedVersion? }, input)`.\n * 7. Maps any thrown framework error onto the shared\n * {@link ApiError} envelope via {@link toApiError}, returning\n * the conventional HTTP status (`409` / `412` for concurrency,\n * `422` for validation, `400` for non-retryable, etc.).\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, expected-version, idempotency, and\n * base-path seams.\n * @returns A Hono app covering every registered action under\n * `<basePath>/actions/<name>`.\n */\n/**\n * Structural shape of the Act surface this generator walks at\n * runtime — the registry's action-name → owning-state map plus the\n * `do(...)` dispatch. Letting TApp infer to the caller's concrete\n * `Act<...>` against this structural bound keeps nested variance\n * out of the signature and avoids `any` in either direction.\n *\n * @internal\n */\ntype ActSurface = {\n readonly registry: {\n actions: Record<\n string,\n {\n readonly name: string;\n readonly actions: Record<string, unknown>;\n }\n >;\n };\n do(action: string, target: Target, payload: unknown): Promise<unknown>;\n};\n\nexport function hono<TApp extends ActSurface = ActSurface>(\n app: TApp,\n options: HonoOptions\n): Hono<{ Variables: ActMiddlewareVariables }> {\n const base_path = options.basePath ?? \"/api\";\n const api = new Hono<{ Variables: ActMiddlewareVariables }>().basePath(\n base_path\n );\n api.use(\"*\", authenticated(options.actor));\n\n const key_from = options.idempotency?.keyFrom ?? default_key_from;\n\n // Wire SSE subscriptions before the mutation routes so the\n // `/sse/*` paths sit alongside `/actions/*`. The cap counter is\n // shared by every state-name's GET route on this generator\n // instance so a noisy room on one state doesn't get a free pass\n // on another.\n if (options.sse) {\n const sse_config = resolveSseConfig(options.sse);\n const sse_counter = new SseConnectionCounter(sse_config.maxConnections);\n const state_names = new Set<string>();\n for (const action of Object.values(app.registry.actions)) {\n state_names.add(action.name);\n }\n for (const state_name of state_names) {\n api.get(`/sse/${state_name}`, async (c) => {\n const stream_id = c.req.query(\"stream\");\n if (!stream_id) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"stream query parameter is required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n if (!sse_counter.acquire()) {\n c.header(\"Retry-After\", \"1\");\n const body: ApiError = {\n error: \"ServiceUnavailable\",\n detail: \"max concurrent SSE connections reached\",\n code: \"SSE_BUSY\",\n };\n return c.json(body, 503);\n }\n // The route already acquired the slot above so streamSSE\n // could return `503` before writing headers if the cap was\n // full. The shared loop runs without accounting; the route\n // releases the slot in `finally`.\n const controller = new AbortController();\n return streamSSE(c, async (sse_stream) => {\n sse_stream.onAbort(() => controller.abort());\n const heartbeat = setInterval(() => {\n fireAndForget(() =>\n sse_stream.writeSSE({ event: \"ping\", data: \"\" })\n );\n }, sse_config.heartbeatMs);\n try {\n for await (const frame of runSseSubscription(\n sse_config.channel,\n stream_id,\n undefined,\n controller.signal,\n { maxPending: sse_config.maxPendingPerConnection }\n )) {\n await sse_stream.writeSSE({\n event: frame.kind,\n data: JSON.stringify(frame.data),\n });\n }\n } finally {\n clearInterval(heartbeat);\n sse_counter.release();\n }\n });\n });\n }\n }\n\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const schema = state.actions[action_name];\n api.post(\n `/actions/${action_name}`,\n // Custom hook funnels body-schema failures through the same\n // ApiError envelope + 422 status an in-`do` ValidationError maps\n // to (ERROR_MAP.ValidationError). Without it, @hono/zod-validator\n // short-circuits with its own 400 + raw body — two statuses and\n // two shapes for the same \"malformed input\" failure class on one\n // endpoint. The OpenAPI doc only documents the 422/ApiError path.\n zValidator(\"json\", schema as never, (result, c) => {\n if (!result.success) {\n // `result.error` is a ZodError; the schema's `never` typing\n // erases its shape, so read `.message` through a narrow cast.\n const message = (result.error as { message?: string }).message;\n const body: ApiError = {\n error: \"ValidationError\",\n detail: message,\n code: \"VALIDATION\",\n };\n return c.json(body, 422);\n }\n }),\n async (c) => {\n try {\n const input = c.req.valid(\"json\" as never) as unknown;\n const actor = c.get(\"actor\");\n const stream = await options.stream(action_name, input, c);\n const expected_version = options.expectedVersion\n ? await options.expectedVersion(action_name, input, c)\n : undefined;\n const target =\n expected_version === undefined\n ? { stream, actor }\n : { stream, actor, expectedVersion: expected_version };\n\n if (options.idempotency) {\n const key = key_from(c);\n if (!key) {\n const body: ApiError = {\n error: \"BadRequest\",\n detail: \"Idempotency-Key required\",\n code: \"BAD_REQUEST\",\n };\n return c.json(body, 400);\n }\n const outcome = await withIdempotency(\n options.idempotency.store,\n key,\n () =>\n app.do(action_name as never, target as never, input as never)\n );\n if (outcome.deduped) {\n const body: ApiError = {\n error: \"Conflict\",\n detail:\n \"Idempotency-Key already used; original result not cached\",\n code: \"CONFLICT\",\n };\n return c.json(body, 409);\n }\n return c.json(outcome.result);\n }\n\n const snapshots = await app.do(\n action_name as never,\n target as never,\n input as never\n );\n return c.json(snapshots);\n } catch (err) {\n const { status, body } = toApiError(err);\n // Hono types narrow `status` to its known status-number union;\n // `toApiError` returns a numeric status from a closed set that\n // matches but TypeScript can't prove it through the union.\n return c.json(body, status as 400 | 409 | 410 | 412 | 422 | 500);\n }\n }\n );\n }\n\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;AAuHA,SAAS,mBAYP,QACA,QACA,MACA,SAGgE;AAEhE,SAAO,UAAU,QAAQ,OAAO,OAAkC,MAAM;AACtE,QAAI,iBAAiB;AAIrB,QAAK,WAAW,YAAY,UAAU,UAAY,WAAW,YAAY,UAAU,QAAS;AAG1F,YAAM,aAAa,OAAO,KAAK,QAAQ,SAAS,OAAO,GAAG,QAAQ,OAAO,KAAK;AAC9E,YAAM,wBAAwB,OAAO,YACnC,WAAW,IAAA,CAAK,QAAQ,CAAC,IAAI,YAAY,GAAG,GAAG,CAAC,CAClD;AAEA,uBAAiB,OAAO,YACtB,OAAO,QAAQ,KAAK,EAAE,IAAA,CAAK,CAAC,KAAKA,MAAA,MAAW,CAAC,sBAAsB,GAAA,KAAQ,KAAKA,MAAK,CAAC,CACxF;IACF;AAEA,UAAM,SACJ,WAAW,QAAQ,qBACf,MAA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AACA,mBAAO,EAAE,KAAK,QAAQ,MAAM;AAAA,UAC9B;AAEA,gBAAM,YAAY,MAAM,IAAI;AAAA,YAC1B;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,iBAAO,EAAE,KAAK,SAAS;AAAA,QACzB,SAAS,KAAK;AACZ,gBAAM,EAAE,QAAQ,KAAK,IAAI,WAAW,GAAG;AAIvC,iBAAO,EAAE,KAAK,MAAM,MAA2C;AAAA,QACjE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["value"]}
|
package/dist/sse/index.cjs
CHANGED
|
@@ -116,6 +116,16 @@ function fan_out(subs, msg, on_error) {
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
}
|
|
119
|
+
var wire_safe = (patch2) => {
|
|
120
|
+
if (patch2 === null || typeof patch2 !== "object") return patch2;
|
|
121
|
+
if (Array.isArray(patch2)) return patch2.map(wire_safe);
|
|
122
|
+
const proto = Object.getPrototypeOf(patch2);
|
|
123
|
+
if (proto !== Object.prototype && proto !== null) return patch2;
|
|
124
|
+
const out = {};
|
|
125
|
+
for (const [k, v] of Object.entries(patch2))
|
|
126
|
+
out[k] = v === void 0 ? null : wire_safe(v);
|
|
127
|
+
return out;
|
|
128
|
+
};
|
|
119
129
|
var BroadcastChannel = class {
|
|
120
130
|
channels = /* @__PURE__ */ new Map();
|
|
121
131
|
state_cache;
|
|
@@ -146,7 +156,7 @@ var BroadcastChannel = class {
|
|
|
146
156
|
const baseV = state._v - patches.length;
|
|
147
157
|
const msg = {};
|
|
148
158
|
patches.forEach((p, i) => {
|
|
149
|
-
msg[baseV + i + 1] = p;
|
|
159
|
+
msg[baseV + i + 1] = wire_safe(p);
|
|
150
160
|
});
|
|
151
161
|
fan_out(
|
|
152
162
|
this.channels.get(streamId),
|
|
@@ -174,7 +184,10 @@ var BroadcastChannel = class {
|
|
|
174
184
|
}
|
|
175
185
|
const state = (0, import_act_patch2.patch)(prev, overlay_patch);
|
|
176
186
|
this.state_cache.set(streamId, state);
|
|
177
|
-
const msg = {
|
|
187
|
+
const msg = {
|
|
188
|
+
[state._v]: wire_safe(overlay_patch),
|
|
189
|
+
_overlay: true
|
|
190
|
+
};
|
|
178
191
|
fan_out(
|
|
179
192
|
this.channels.get(streamId),
|
|
180
193
|
msg,
|
package/dist/sse/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n * - No baseline (fresh client) → the genesis patch (version 0) folds onto init\n * state; a first patch at version ≥ 1 is \"behind\" (can't build from init)\n * - Overlay frame ({@link PatchMessage._overlay}) at the current version →\n * merged on top of cached state, `_v` unchanged (presence / computed\n * fields reach caught-up clients instead of being dropped as stale)\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n // Distinguish an *absent* baseline from a real version-0 baseline (#1346).\n // Act assigns the first event of any stream `version = 0`, so a fresh client\n // (no cache) must resume from a pre-baseline watermark of -1 — otherwise the\n // `?? 0` default collides with a genuine version-0 genesis patch and drops\n // it as \"stale\". A present baseline keeps its own `_v`.\n const hasBaseline = cached != null;\n const cachedV = cached?._v ?? -1;\n // `overlay` is a non-numeric marker key, not a version — exclude it.\n const versions = Object.keys(msg)\n .map(Number)\n .filter((v) => Number.isInteger(v))\n .sort((a, b) => a - b);\n\n // Server-forced resync: it could not construct a patch (e.g. `overlay()`\n // found the baseline evicted), so the client must refetch. Checked before\n // anything else — a resync frame carries no versions, and the empty-frame\n // branch below would otherwise report it as `stale`, which is the one\n // answer that does NOT refetch (#1423).\n if (msg._resync) return { ok: false, reason: \"behind\" };\n\n if (!versions.length) return { ok: false, reason: \"stale\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n // Overlay frame: a version-neutral update (presence, computed field) at the\n // current version. Handled EXHAUSTIVELY here — an overlay must never reach\n // the contiguous fold below, which would apply its payload as if it were\n // that version's domain patch. At exactly `cachedV + 1` that fold made the\n // client adopt presence data as version N, stamp itself caught up, and\n // never refetch — the real update for N lost permanently (#1419).\n if (msg._overlay) {\n // No baseline to merge onto: the client must fetch one.\n if (!cached) return { ok: false, reason: \"behind\" };\n // Caught up: merge on top, keeping _v (an overlay changes no version).\n if (maxV === cachedV)\n return {\n ok: true,\n state: { ...deep_merge(cached, msg[maxV]), _v: cachedV },\n };\n // Ahead by any amount: the client missed at least one domain patch.\n if (maxV > cachedV) return { ok: false, reason: \"behind\" };\n // Older than the baseline: genuinely stale.\n return { ok: false, reason: \"stale\" };\n }\n\n // A present baseline that already covers these versions is stale. A fresh\n // client (no baseline, cachedV = -1) can never be stale — its first\n // contiguous update is the genesis version 0.\n if (hasBaseline && maxV <= cachedV) return { ok: false, reason: \"stale\" };\n // A gap between the baseline (or the init floor -1) and the first patch means\n // missed versions — resync. For a fresh client this admits the genesis patch\n // (minV 0 === -1 + 1) but rejects a first patch at version >= 1, which cannot\n // be built from init state alone.\n if (minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n // No baseline → fold the genesis patch(es) onto init state ({}).\n let state = (cached ?? {}) as S;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { log } from \"@rotorsoft/act\";\nimport { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\n/**\n * Deliver a frame to every subscriber, containing each one individually.\n *\n * SSE subscribers are the least-trusted callbacks in the system — one per\n * connection, driven by network state. The unguarded loop this replaces let\n * the first thrower abort iteration, so every later subscriber lost the\n * frame and the exception escaped into the host's commit path (#1423). Same\n * containment principle the orchestrator applies to lifecycle listeners.\n * Guarding each callback rather than the loop is the point: one guard around\n * the whole loop would still let the first throw suppress the rest.\n *\n * @internal\n */\nfunction fan_out<S extends BroadcastState>(\n subs: Set<Subscriber<S>> | undefined,\n msg: PatchMessage<S>,\n on_error: (error: unknown) => void\n): void {\n if (!subs?.size) return;\n for (const cb of subs) {\n try {\n cb(msg);\n } catch (error) {\n on_error(error);\n }\n }\n}\n\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n\n /**\n * @param options.cacheSize - Max number of stream states kept in the LRU\n * cache (default 50).\n */\n private on_subscriber_error: (error: unknown, streamId: string) => void;\n private on_overlay_miss: (streamId: string) => void;\n\n constructor(options?: {\n cacheSize?: number;\n /**\n * Called when `overlay()` finds no cached baseline for the stream, so\n * the update cannot be broadcast. Live subscribers receive nothing and\n * have no way to notice — a host that cares should raise `cacheSize`,\n * re-`publish` the stream, or push the viewers to refetch. Defaults to a\n * no-op so existing behavior is unchanged apart from being observable.\n */\n onOverlayMiss?: (streamId: string) => void;\n /**\n * Called when a subscriber callback throws. The frame is still delivered\n * to every other subscriber and the publish still returns normally — a\n * bad consumer must not break the publisher (#1423). Defaults to the\n * framework's `log()` port, so it lands wherever the host already\n * routes framework logs.\n */\n onSubscriberError?: (error: unknown, streamId: string) => void;\n /**\n * Deprecated alias of `cacheSize` — removal in the next major. When\n * both are given, `cacheSize` wins.\n * @deprecated use `cacheSize`\n */\n cache_size?: number;\n }) {\n this.state_cache = new StateCache<S>(\n options?.cacheSize ?? options?.cache_size ?? 50\n );\n this.on_overlay_miss = options?.onOverlayMiss ?? (() => {});\n this.on_subscriber_error =\n options?.onSubscriberError ??\n ((error, streamId) =>\n log().error(error, `sse subscriber threw for \"${streamId}\"`));\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n this.state_cache.set(streamId, state);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = p;\n });\n\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) {\n // No baseline to read-modify-write, so nothing is broadcast — and\n // because no frame is emitted there is nothing for a live client to\n // classify as `behind`, so it never refetches either. Unlike a domain\n // commit (which repopulates the cache via `publish`), an overlay-only\n // stream never recovers. The defaults make this reachable rather than\n // exotic: `cacheSize` is 50 while a host may hold far more live\n // subscriptions, and cache promotion happens at connect time, so a\n // busy-but-not-committing stream ages out while fully subscribed.\n //\n // Emit a resync frame so live subscribers refetch instead of silently\n // missing the update forever (#1423). `on_overlay_miss` still fires so\n // a host can count these — a steady stream of them means `cacheSize`\n // is too small for the working set.\n this.on_overlay_miss(streamId);\n const resync: PatchMessage<S> = { _resync: true } as PatchMessage<S>;\n fan_out(this.channels.get(streamId), resync, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n // Still `undefined`: no overlay state was produced, and callers use the\n // return value as \"the patch I broadcast\", which a resync is not.\n return undefined;\n }\n\n const state = apply_patch(prev, overlay_patch) as S;\n this.state_cache.set(streamId, state);\n\n // `_overlay: true` marks this as a version-neutral update so a caught-up\n // client applies it at the current version instead of dropping it as\n // stale (the key equals the client's cachedV). Ordinary patches omit it.\n const msg: PatchMessage<S> = { [state._v]: overlay_patch, _overlay: true };\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n subscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** @deprecated use `overlay` — removal in the next major */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n return this.overlay(streamId, overlay_patch);\n }\n\n /** @deprecated use `subscriberCount` — removal in the next major */\n get_subscriber_count(streamId: string): number {\n return this.subscriberCount(streamId);\n }\n\n /** @deprecated use `state` — removal in the next major */\n get_state(streamId: string): S | undefined {\n return this.state(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n\n constructor(maxSize = 50) {\n this.maxSize = maxSize;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n this.cache.delete(this.cache.keys().next().value!);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n\n /** @deprecated use `online` — removal in the next major */\n get_online(streamId: string): Set<string> {\n return this.online(streamId);\n }\n\n /** @deprecated use `isOnline` — removal in the next major */\n is_online(streamId: string, identity_id: string): boolean {\n return this.isOnline(streamId, identity_id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCA,IAAAA,oBAAsB;;;ACvCtB,uBAAoC;AAuC7B,SAAS,kBACd,KACA,QACgB;AAMhB,QAAM,cAAc,UAAU;AAC9B,QAAM,UAAU,QAAQ,MAAM;AAE9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,OAAO,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC,EACjC,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAOvB,MAAI,IAAI,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEtD,MAAI,CAAC,SAAS,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAE1D,QAAM,OAAO,SAAS,CAAC;AACvB,QAAM,OAAO,SAAS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kB,aAA8B;AACvD,YAAQ,KAAK,QAAQ,IAAI,QAAQ,GAAG,IAAI,WAAW,KAAK,KAAK;AAAA,EAC/D;AAAA;AAAA,EAGA,WAAW,UAA+B;AACxC,WAAO,KAAK,OAAO,QAAQ;AAAA,EAC7B;AAAA;AAAA,EAGA,UAAU,UAAkB,aAA8B;AACxD,WAAO,KAAK,SAAS,UAAU,WAAW;AAAA,EAC5C;AACF;","names":["import_act_patch","deep_merge","import_act_patch","apply_patch"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n * - No baseline (fresh client) → the genesis patch (version 0) folds onto init\n * state; a first patch at version ≥ 1 is \"behind\" (can't build from init)\n * - Overlay frame ({@link PatchMessage._overlay}) at the current version →\n * merged on top of cached state, `_v` unchanged (presence / computed\n * fields reach caught-up clients instead of being dropped as stale)\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n // Distinguish an *absent* baseline from a real version-0 baseline (#1346).\n // Act assigns the first event of any stream `version = 0`, so a fresh client\n // (no cache) must resume from a pre-baseline watermark of -1 — otherwise the\n // `?? 0` default collides with a genuine version-0 genesis patch and drops\n // it as \"stale\". A present baseline keeps its own `_v`.\n const hasBaseline = cached != null;\n const cachedV = cached?._v ?? -1;\n // `overlay` is a non-numeric marker key, not a version — exclude it.\n const versions = Object.keys(msg)\n .map(Number)\n .filter((v) => Number.isInteger(v))\n .sort((a, b) => a - b);\n\n // Server-forced resync: it could not construct a patch (e.g. `overlay()`\n // found the baseline evicted), so the client must refetch. Checked before\n // anything else — a resync frame carries no versions, and the empty-frame\n // branch below would otherwise report it as `stale`, which is the one\n // answer that does NOT refetch (#1423).\n if (msg._resync) return { ok: false, reason: \"behind\" };\n\n if (!versions.length) return { ok: false, reason: \"stale\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n // Overlay frame: a version-neutral update (presence, computed field) at the\n // current version. Handled EXHAUSTIVELY here — an overlay must never reach\n // the contiguous fold below, which would apply its payload as if it were\n // that version's domain patch. At exactly `cachedV + 1` that fold made the\n // client adopt presence data as version N, stamp itself caught up, and\n // never refetch — the real update for N lost permanently (#1419).\n if (msg._overlay) {\n // No baseline to merge onto: the client must fetch one.\n if (!cached) return { ok: false, reason: \"behind\" };\n // Caught up: merge on top, keeping _v (an overlay changes no version).\n if (maxV === cachedV)\n return {\n ok: true,\n state: { ...deep_merge(cached, msg[maxV]), _v: cachedV },\n };\n // Ahead by any amount: the client missed at least one domain patch.\n if (maxV > cachedV) return { ok: false, reason: \"behind\" };\n // Older than the baseline: genuinely stale.\n return { ok: false, reason: \"stale\" };\n }\n\n // A present baseline that already covers these versions is stale. A fresh\n // client (no baseline, cachedV = -1) can never be stale — its first\n // contiguous update is the genesis version 0.\n if (hasBaseline && maxV <= cachedV) return { ok: false, reason: \"stale\" };\n // A gap between the baseline (or the init floor -1) and the first patch means\n // missed versions — resync. For a fresh client this admits the genesis patch\n // (minV 0 === -1 + 1) but rejects a first patch at version >= 1, which cannot\n // be built from init state alone.\n if (minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n // No baseline → fold the genesis patch(es) onto init state ({}).\n let state = (cached ?? {}) as S;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { log } from \"@rotorsoft/act\";\nimport { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\n/**\n * Deliver a frame to every subscriber, containing each one individually.\n *\n * SSE subscribers are the least-trusted callbacks in the system — one per\n * connection, driven by network state. The unguarded loop this replaces let\n * the first thrower abort iteration, so every later subscriber lost the\n * frame and the exception escaped into the host's commit path (#1423). Same\n * containment principle the orchestrator applies to lifecycle listeners.\n * Guarding each callback rather than the loop is the point: one guard around\n * the whole loop would still let the first throw suppress the rest.\n *\n * @internal\n */\nfunction fan_out<S extends BroadcastState>(\n subs: Set<Subscriber<S>> | undefined,\n msg: PatchMessage<S>,\n on_error: (error: unknown) => void\n): void {\n if (!subs?.size) return;\n for (const cb of subs) {\n try {\n cb(msg);\n } catch (error) {\n on_error(error);\n }\n }\n}\n\n/**\n * Rewrite `undefined`-valued keys to `null`, recursively.\n *\n * `@rotorsoft/act-patch` treats `undefined` and `null` as the same delete\n * signal, but `JSON.stringify` drops `undefined`-valued keys entirely — and\n * every SSE transport serializes frames as JSON. A reducer that clears a\n * field the idiomatic way (`{ left: undefined }`) therefore produced a frame\n * with no mention of `left` at all, so a live client kept the stale value\n * while stamping the new version — believing itself caught up, and never\n * refetching (#1471).\n *\n * `null` reaches the same `delete` branch in the patch applicator and\n * survives JSON, so normalizing here makes the two spellings equivalent on\n * the wire as they already are in memory.\n *\n * Only the broadcast frame is normalized. Server-side state is applied\n * through `apply_patch`, which handles `undefined` natively.\n */\nconst wire_safe = <T>(patch: T): T => {\n if (patch === null || typeof patch !== \"object\") return patch;\n if (Array.isArray(patch)) return patch.map(wire_safe) as T;\n // Non-plain objects (Date, Map, class instances) are left to whatever the\n // host's serializer already does with them; rewriting their internals\n // would change more than the delete signal.\n const proto = Object.getPrototypeOf(patch);\n if (proto !== Object.prototype && proto !== null) return patch;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(patch as Record<string, unknown>))\n out[k] = v === undefined ? null : wire_safe(v);\n return out as T;\n};\n\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n\n /**\n * @param options.cacheSize - Max number of stream states kept in the LRU\n * cache (default 50).\n */\n private on_subscriber_error: (error: unknown, streamId: string) => void;\n private on_overlay_miss: (streamId: string) => void;\n\n constructor(options?: {\n cacheSize?: number;\n /**\n * Called when `overlay()` finds no cached baseline for the stream, so\n * the update cannot be broadcast. Live subscribers receive nothing and\n * have no way to notice — a host that cares should raise `cacheSize`,\n * re-`publish` the stream, or push the viewers to refetch. Defaults to a\n * no-op so existing behavior is unchanged apart from being observable.\n */\n onOverlayMiss?: (streamId: string) => void;\n /**\n * Called when a subscriber callback throws. The frame is still delivered\n * to every other subscriber and the publish still returns normally — a\n * bad consumer must not break the publisher (#1423). Defaults to the\n * framework's `log()` port, so it lands wherever the host already\n * routes framework logs.\n */\n onSubscriberError?: (error: unknown, streamId: string) => void;\n /**\n * Deprecated alias of `cacheSize` — removal in the next major. When\n * both are given, `cacheSize` wins.\n * @deprecated use `cacheSize`\n */\n cache_size?: number;\n }) {\n this.state_cache = new StateCache<S>(\n options?.cacheSize ?? options?.cache_size ?? 50\n );\n this.on_overlay_miss = options?.onOverlayMiss ?? (() => {});\n this.on_subscriber_error =\n options?.onSubscriberError ??\n ((error, streamId) =>\n log().error(error, `sse subscriber threw for \"${streamId}\"`));\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n this.state_cache.set(streamId, state);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = wire_safe(p);\n });\n\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) {\n // No baseline to read-modify-write, so nothing is broadcast — and\n // because no frame is emitted there is nothing for a live client to\n // classify as `behind`, so it never refetches either. Unlike a domain\n // commit (which repopulates the cache via `publish`), an overlay-only\n // stream never recovers. The defaults make this reachable rather than\n // exotic: `cacheSize` is 50 while a host may hold far more live\n // subscriptions, and cache promotion happens at connect time, so a\n // busy-but-not-committing stream ages out while fully subscribed.\n //\n // Emit a resync frame so live subscribers refetch instead of silently\n // missing the update forever (#1423). `on_overlay_miss` still fires so\n // a host can count these — a steady stream of them means `cacheSize`\n // is too small for the working set.\n this.on_overlay_miss(streamId);\n const resync: PatchMessage<S> = { _resync: true } as PatchMessage<S>;\n fan_out(this.channels.get(streamId), resync, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n // Still `undefined`: no overlay state was produced, and callers use the\n // return value as \"the patch I broadcast\", which a resync is not.\n return undefined;\n }\n\n const state = apply_patch(prev, overlay_patch) as S;\n this.state_cache.set(streamId, state);\n\n // `_overlay: true` marks this as a version-neutral update so a caught-up\n // client applies it at the current version instead of dropping it as\n // stale (the key equals the client's cachedV). Ordinary patches omit it.\n const msg: PatchMessage<S> = {\n [state._v]: wire_safe(overlay_patch),\n _overlay: true,\n };\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n subscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** @deprecated use `overlay` — removal in the next major */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n return this.overlay(streamId, overlay_patch);\n }\n\n /** @deprecated use `subscriberCount` — removal in the next major */\n get_subscriber_count(streamId: string): number {\n return this.subscriberCount(streamId);\n }\n\n /** @deprecated use `state` — removal in the next major */\n get_state(streamId: string): S | undefined {\n return this.state(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n\n constructor(maxSize = 50) {\n this.maxSize = maxSize;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n this.cache.delete(this.cache.keys().next().value!);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n\n /** @deprecated use `online` — removal in the next major */\n get_online(streamId: string): Set<string> {\n return this.online(streamId);\n }\n\n /** @deprecated use `isOnline` — removal in the next major */\n is_online(streamId: string, identity_id: string): boolean {\n return this.isOnline(streamId, identity_id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCA,IAAAA,oBAAsB;;;ACvCtB,uBAAoC;AAuC7B,SAAS,kBACd,KACA,QACgB;AAMhB,QAAM,cAAc,UAAU;AAC9B,QAAM,UAAU,QAAQ,MAAM;AAE9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,OAAO,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC,EACjC,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAOvB,MAAI,IAAI,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEtD,MAAI,CAAC,SAAS,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAE1D,QAAM,OAAO,SAAS,CAAC;AACvB,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AAQzC,MAAI,IAAI,UAAU;AAEhB,QAAI,CAAC,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAElD,QAAI,SAAS;AACX,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO,EAAE,OAAG,iBAAAC,OAAW,QAAQ,IAAI,IAAI,CAAC,GAAG,IAAI,QAAQ;AAAA,MACzD;AAEF,QAAI,OAAO,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEzD,WAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAAA,EACtC;AAKA,MAAI,eAAe,QAAQ,QAAS,QAAO,EAAE,IAAI,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,SAAS,UAAkB,aAA8B;AACvD,YAAQ,KAAK,QAAQ,IAAI,QAAQ,GAAG,IAAI,WAAW,KAAK,KAAK;AAAA,EAC/D;AAAA;AAAA,EAGA,WAAW,UAA+B;AACxC,WAAO,KAAK,OAAO,QAAQ;AAAA,EAC7B;AAAA;AAAA,EAGA,UAAU,UAAkB,aAA8B;AACxD,WAAO,KAAK,SAAS,UAAU,WAAW;AAAA,EAC5C;AACF;","names":["import_act_patch","deep_merge","import_act_patch","patch","apply_patch"]}
|
package/dist/sse/index.js
CHANGED
|
@@ -90,6 +90,16 @@ function fan_out(subs, msg, on_error) {
|
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
+
var wire_safe = (patch2) => {
|
|
94
|
+
if (patch2 === null || typeof patch2 !== "object") return patch2;
|
|
95
|
+
if (Array.isArray(patch2)) return patch2.map(wire_safe);
|
|
96
|
+
const proto = Object.getPrototypeOf(patch2);
|
|
97
|
+
if (proto !== Object.prototype && proto !== null) return patch2;
|
|
98
|
+
const out = {};
|
|
99
|
+
for (const [k, v] of Object.entries(patch2))
|
|
100
|
+
out[k] = v === void 0 ? null : wire_safe(v);
|
|
101
|
+
return out;
|
|
102
|
+
};
|
|
93
103
|
var BroadcastChannel = class {
|
|
94
104
|
channels = /* @__PURE__ */ new Map();
|
|
95
105
|
state_cache;
|
|
@@ -120,7 +130,7 @@ var BroadcastChannel = class {
|
|
|
120
130
|
const baseV = state._v - patches.length;
|
|
121
131
|
const msg = {};
|
|
122
132
|
patches.forEach((p, i) => {
|
|
123
|
-
msg[baseV + i + 1] = p;
|
|
133
|
+
msg[baseV + i + 1] = wire_safe(p);
|
|
124
134
|
});
|
|
125
135
|
fan_out(
|
|
126
136
|
this.channels.get(streamId),
|
|
@@ -148,7 +158,10 @@ var BroadcastChannel = class {
|
|
|
148
158
|
}
|
|
149
159
|
const state = apply_patch(prev, overlay_patch);
|
|
150
160
|
this.state_cache.set(streamId, state);
|
|
151
|
-
const msg = {
|
|
161
|
+
const msg = {
|
|
162
|
+
[state._v]: wire_safe(overlay_patch),
|
|
163
|
+
_overlay: true
|
|
164
|
+
};
|
|
152
165
|
fan_out(
|
|
153
166
|
this.channels.get(streamId),
|
|
154
167
|
msg,
|
package/dist/sse/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n * - No baseline (fresh client) → the genesis patch (version 0) folds onto init\n * state; a first patch at version ≥ 1 is \"behind\" (can't build from init)\n * - Overlay frame ({@link PatchMessage._overlay}) at the current version →\n * merged on top of cached state, `_v` unchanged (presence / computed\n * fields reach caught-up clients instead of being dropped as stale)\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n // Distinguish an *absent* baseline from a real version-0 baseline (#1346).\n // Act assigns the first event of any stream `version = 0`, so a fresh client\n // (no cache) must resume from a pre-baseline watermark of -1 — otherwise the\n // `?? 0` default collides with a genuine version-0 genesis patch and drops\n // it as \"stale\". A present baseline keeps its own `_v`.\n const hasBaseline = cached != null;\n const cachedV = cached?._v ?? -1;\n // `overlay` is a non-numeric marker key, not a version — exclude it.\n const versions = Object.keys(msg)\n .map(Number)\n .filter((v) => Number.isInteger(v))\n .sort((a, b) => a - b);\n\n // Server-forced resync: it could not construct a patch (e.g. `overlay()`\n // found the baseline evicted), so the client must refetch. Checked before\n // anything else — a resync frame carries no versions, and the empty-frame\n // branch below would otherwise report it as `stale`, which is the one\n // answer that does NOT refetch (#1423).\n if (msg._resync) return { ok: false, reason: \"behind\" };\n\n if (!versions.length) return { ok: false, reason: \"stale\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n // Overlay frame: a version-neutral update (presence, computed field) at the\n // current version. Handled EXHAUSTIVELY here — an overlay must never reach\n // the contiguous fold below, which would apply its payload as if it were\n // that version's domain patch. At exactly `cachedV + 1` that fold made the\n // client adopt presence data as version N, stamp itself caught up, and\n // never refetch — the real update for N lost permanently (#1419).\n if (msg._overlay) {\n // No baseline to merge onto: the client must fetch one.\n if (!cached) return { ok: false, reason: \"behind\" };\n // Caught up: merge on top, keeping _v (an overlay changes no version).\n if (maxV === cachedV)\n return {\n ok: true,\n state: { ...deep_merge(cached, msg[maxV]), _v: cachedV },\n };\n // Ahead by any amount: the client missed at least one domain patch.\n if (maxV > cachedV) return { ok: false, reason: \"behind\" };\n // Older than the baseline: genuinely stale.\n return { ok: false, reason: \"stale\" };\n }\n\n // A present baseline that already covers these versions is stale. A fresh\n // client (no baseline, cachedV = -1) can never be stale — its first\n // contiguous update is the genesis version 0.\n if (hasBaseline && maxV <= cachedV) return { ok: false, reason: \"stale\" };\n // A gap between the baseline (or the init floor -1) and the first patch means\n // missed versions — resync. For a fresh client this admits the genesis patch\n // (minV 0 === -1 + 1) but rejects a first patch at version >= 1, which cannot\n // be built from init state alone.\n if (minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n // No baseline → fold the genesis patch(es) onto init state ({}).\n let state = (cached ?? {}) as S;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { log } from \"@rotorsoft/act\";\nimport { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\n/**\n * Deliver a frame to every subscriber, containing each one individually.\n *\n * SSE subscribers are the least-trusted callbacks in the system — one per\n * connection, driven by network state. The unguarded loop this replaces let\n * the first thrower abort iteration, so every later subscriber lost the\n * frame and the exception escaped into the host's commit path (#1423). Same\n * containment principle the orchestrator applies to lifecycle listeners.\n * Guarding each callback rather than the loop is the point: one guard around\n * the whole loop would still let the first throw suppress the rest.\n *\n * @internal\n */\nfunction fan_out<S extends BroadcastState>(\n subs: Set<Subscriber<S>> | undefined,\n msg: PatchMessage<S>,\n on_error: (error: unknown) => void\n): void {\n if (!subs?.size) return;\n for (const cb of subs) {\n try {\n cb(msg);\n } catch (error) {\n on_error(error);\n }\n }\n}\n\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n\n /**\n * @param options.cacheSize - Max number of stream states kept in the LRU\n * cache (default 50).\n */\n private on_subscriber_error: (error: unknown, streamId: string) => void;\n private on_overlay_miss: (streamId: string) => void;\n\n constructor(options?: {\n cacheSize?: number;\n /**\n * Called when `overlay()` finds no cached baseline for the stream, so\n * the update cannot be broadcast. Live subscribers receive nothing and\n * have no way to notice — a host that cares should raise `cacheSize`,\n * re-`publish` the stream, or push the viewers to refetch. Defaults to a\n * no-op so existing behavior is unchanged apart from being observable.\n */\n onOverlayMiss?: (streamId: string) => void;\n /**\n * Called when a subscriber callback throws. The frame is still delivered\n * to every other subscriber and the publish still returns normally — a\n * bad consumer must not break the publisher (#1423). Defaults to the\n * framework's `log()` port, so it lands wherever the host already\n * routes framework logs.\n */\n onSubscriberError?: (error: unknown, streamId: string) => void;\n /**\n * Deprecated alias of `cacheSize` — removal in the next major. When\n * both are given, `cacheSize` wins.\n * @deprecated use `cacheSize`\n */\n cache_size?: number;\n }) {\n this.state_cache = new StateCache<S>(\n options?.cacheSize ?? options?.cache_size ?? 50\n );\n this.on_overlay_miss = options?.onOverlayMiss ?? (() => {});\n this.on_subscriber_error =\n options?.onSubscriberError ??\n ((error, streamId) =>\n log().error(error, `sse subscriber threw for \"${streamId}\"`));\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n this.state_cache.set(streamId, state);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = p;\n });\n\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) {\n // No baseline to read-modify-write, so nothing is broadcast — and\n // because no frame is emitted there is nothing for a live client to\n // classify as `behind`, so it never refetches either. Unlike a domain\n // commit (which repopulates the cache via `publish`), an overlay-only\n // stream never recovers. The defaults make this reachable rather than\n // exotic: `cacheSize` is 50 while a host may hold far more live\n // subscriptions, and cache promotion happens at connect time, so a\n // busy-but-not-committing stream ages out while fully subscribed.\n //\n // Emit a resync frame so live subscribers refetch instead of silently\n // missing the update forever (#1423). `on_overlay_miss` still fires so\n // a host can count these — a steady stream of them means `cacheSize`\n // is too small for the working set.\n this.on_overlay_miss(streamId);\n const resync: PatchMessage<S> = { _resync: true } as PatchMessage<S>;\n fan_out(this.channels.get(streamId), resync, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n // Still `undefined`: no overlay state was produced, and callers use the\n // return value as \"the patch I broadcast\", which a resync is not.\n return undefined;\n }\n\n const state = apply_patch(prev, overlay_patch) as S;\n this.state_cache.set(streamId, state);\n\n // `_overlay: true` marks this as a version-neutral update so a caught-up\n // client applies it at the current version instead of dropping it as\n // stale (the key equals the client's cachedV). Ordinary patches omit it.\n const msg: PatchMessage<S> = { [state._v]: overlay_patch, _overlay: true };\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n subscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** @deprecated use `overlay` — removal in the next major */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n return this.overlay(streamId, overlay_patch);\n }\n\n /** @deprecated use `subscriberCount` — removal in the next major */\n get_subscriber_count(streamId: string): number {\n return this.subscriberCount(streamId);\n }\n\n /** @deprecated use `state` — removal in the next major */\n get_state(streamId: string): S | undefined {\n return this.state(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n\n constructor(maxSize = 50) {\n this.maxSize = maxSize;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n this.cache.delete(this.cache.keys().next().value!);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n\n /** @deprecated use `online` — removal in the next major */\n get_online(streamId: string): Set<string> {\n return this.online(streamId);\n }\n\n /** @deprecated use `isOnline` — removal in the next major */\n is_online(streamId: string, identity_id: string): boolean {\n return this.isOnline(streamId, identity_id);\n }\n}\n"],"mappings":";;;AAuCA,SAAS,aAAa;;;ACvCtB,SAAS,SAAS,kBAAkB;AAuC7B,SAAS,kBACd,KACA,QACgB;AAMhB,QAAM,cAAc,UAAU;AAC9B,QAAM,UAAU,QAAQ,MAAM;AAE9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,OAAO,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC,EACjC,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAOvB,MAAI,IAAI,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEtD,MAAI,CAAC,SAAS,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAE1D,QAAM,OAAO,SAAS,CAAC;AACvB,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AAQzC,MAAI,IAAI,UAAU;AAEhB,QAAI,CAAC,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;A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C,WAAO,KAAK,OAAO,QAAQ;AAAA,EAC7B;AAAA;AAAA,EAGA,UAAU,UAAkB,aAA8B;AACxD,WAAO,KAAK,SAAS,UAAU,WAAW;AAAA,EAC5C;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/sse/index.ts","../../src/sse/apply-patch.ts","../../src/sse/broadcast.ts","../../src/sse/state-cache.ts","../../src/sse/presence.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/sse\n *\n * Incremental state broadcast over SSE for act event-sourced apps.\n *\n * Server-side broadcast with domain patch forwarding, an LRU state cache,\n * presence tracking, and a client-side patch applicator with version\n * validation and resync detection.\n *\n * ## Architecture\n *\n * ```\n * app.do() → snapshots (each carries its domain patch)\n * │\n * ▼\n * deriveState(snap) ← app-specific (overlay presence, deadlines, etc.)\n * state._v = snap.event.version\n * │\n * ▼\n * broadcast.publish(streamId, state, patches)\n * │\n * ├── version-key each patch: { [baseV+1]: patch1, [baseV+2]: patch2 }\n * └── push to all SSE subscribers\n * │\n * ▼\n * Client: applyPatchMessage(msg, cached)\n * │\n * ├── contiguous → deep-merge patches in version order\n * ├── stale → skip (client already ahead)\n * └── behind → resync (client missed versions)\n * ```\n *\n * ## Version Contract\n *\n * `_v` is always the event store stream version (`snap.event.version`).\n * No separate version counters. The event store is the single source of truth.\n */\n\nexport { patch } from \"@rotorsoft/act-patch\";\nexport type { ApplyResult } from \"./apply-patch.js\";\nexport { applyPatchMessage } from \"./apply-patch.js\";\nexport { BroadcastChannel } from \"./broadcast.js\";\nexport { PresenceTracker } from \"./presence.js\";\nexport { StateCache } from \"./state-cache.js\";\nexport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n","import { patch as deep_merge } from \"@rotorsoft/act-patch\";\nimport type { BroadcastState, PatchMessage } from \"./types.js\";\n\n/**\n * Result of applying a patch message to cached client state.\n */\nexport type ApplyResult<S extends BroadcastState = BroadcastState> =\n | { ok: true; state: S }\n | { ok: false; reason: \"stale\" | \"behind\" };\n\n/**\n * Apply a version-keyed patch message to the client's cached state.\n *\n * ## Version logic\n *\n * - All patches older than cached → \"stale\" (client already ahead)\n * - Gap between cached version and first patch → \"behind\" (client missed versions, must resync)\n * - Contiguous from cached version → apply in order\n * - No baseline (fresh client) → the genesis patch (version 0) folds onto init\n * state; a first patch at version ≥ 1 is \"behind\" (can't build from init)\n * - Overlay frame ({@link PatchMessage._overlay}) at the current version →\n * merged on top of cached state, `_v` unchanged (presence / computed\n * fields reach caught-up clients instead of being dropped as stale)\n *\n * ## Usage (React Query)\n *\n * ```typescript\n * onData: (msg) => {\n * const cached = utils.get_state.get_data({ streamId });\n * const result = applyPatchMessage(msg, cached);\n * if (result.ok) {\n * utils.get_state.setData({ streamId }, result.state);\n * } else if (result.reason === \"behind\") {\n * utils.get_state.invalidate({ streamId }); // trigger full refetch\n * }\n * // \"stale\" → no-op, client already has newer state\n * }\n * ```\n */\nexport function applyPatchMessage<S extends BroadcastState>(\n msg: PatchMessage<S>,\n cached: S | null | undefined\n): ApplyResult<S> {\n // Distinguish an *absent* baseline from a real version-0 baseline (#1346).\n // Act assigns the first event of any stream `version = 0`, so a fresh client\n // (no cache) must resume from a pre-baseline watermark of -1 — otherwise the\n // `?? 0` default collides with a genuine version-0 genesis patch and drops\n // it as \"stale\". A present baseline keeps its own `_v`.\n const hasBaseline = cached != null;\n const cachedV = cached?._v ?? -1;\n // `overlay` is a non-numeric marker key, not a version — exclude it.\n const versions = Object.keys(msg)\n .map(Number)\n .filter((v) => Number.isInteger(v))\n .sort((a, b) => a - b);\n\n // Server-forced resync: it could not construct a patch (e.g. `overlay()`\n // found the baseline evicted), so the client must refetch. Checked before\n // anything else — a resync frame carries no versions, and the empty-frame\n // branch below would otherwise report it as `stale`, which is the one\n // answer that does NOT refetch (#1423).\n if (msg._resync) return { ok: false, reason: \"behind\" };\n\n if (!versions.length) return { ok: false, reason: \"stale\" };\n\n const minV = versions[0];\n const maxV = versions[versions.length - 1];\n\n // Overlay frame: a version-neutral update (presence, computed field) at the\n // current version. Handled EXHAUSTIVELY here — an overlay must never reach\n // the contiguous fold below, which would apply its payload as if it were\n // that version's domain patch. At exactly `cachedV + 1` that fold made the\n // client adopt presence data as version N, stamp itself caught up, and\n // never refetch — the real update for N lost permanently (#1419).\n if (msg._overlay) {\n // No baseline to merge onto: the client must fetch one.\n if (!cached) return { ok: false, reason: \"behind\" };\n // Caught up: merge on top, keeping _v (an overlay changes no version).\n if (maxV === cachedV)\n return {\n ok: true,\n state: { ...deep_merge(cached, msg[maxV]), _v: cachedV },\n };\n // Ahead by any amount: the client missed at least one domain patch.\n if (maxV > cachedV) return { ok: false, reason: \"behind\" };\n // Older than the baseline: genuinely stale.\n return { ok: false, reason: \"stale\" };\n }\n\n // A present baseline that already covers these versions is stale. A fresh\n // client (no baseline, cachedV = -1) can never be stale — its first\n // contiguous update is the genesis version 0.\n if (hasBaseline && maxV <= cachedV) return { ok: false, reason: \"stale\" };\n // A gap between the baseline (or the init floor -1) and the first patch means\n // missed versions — resync. For a fresh client this admits the genesis patch\n // (minV 0 === -1 + 1) but rejects a first patch at version >= 1, which cannot\n // be built from init state alone.\n if (minV > cachedV + 1) return { ok: false, reason: \"behind\" };\n\n // No baseline → fold the genesis patch(es) onto init state ({}).\n let state = (cached ?? {}) as S;\n for (const v of versions) {\n if (v <= cachedV) continue;\n state = { ...deep_merge(state, msg[v]), _v: v } as S;\n }\n return { ok: true, state };\n}\n","import { log } from \"@rotorsoft/act\";\nimport { patch as apply_patch } from \"@rotorsoft/act-patch\";\nimport { StateCache } from \"./state-cache.js\";\nimport type { BroadcastState, PatchMessage, Subscriber } from \"./types.js\";\n\n/**\n * Server-side broadcast channel for incremental state sync over SSE.\n *\n * Manages per-stream subscriber sets and an LRU state cache. When state\n * changes, forwards domain patches (from event handlers) to all subscribers\n * as version-keyed messages.\n *\n * ## Usage\n *\n * ```typescript\n * const broadcast = new BroadcastChannel<MyState>();\n *\n * // After every app.do():\n * const snaps = await app.do(...);\n * const patches = snaps.map(s => s.patch).filter(Boolean);\n * const state = deriveState(snaps.at(-1));\n * broadcast.publish(streamId, state, patches);\n *\n * // In SSE subscription:\n * const cleanup = broadcast.subscribe(streamId, (msg) => {\n * pending = msg;\n * resolve?.();\n * });\n *\n * // Initial state for reconnects:\n * const cached = broadcast.state(streamId);\n * ```\n *\n * ## Version Contract\n *\n * The `_v` field on state MUST be set from `snap.event.version` (the event\n * store's monotonic stream version) BEFORE calling `publish()`. This is the\n * single source of truth for ordering — no separate version counters.\n */\n/**\n * Deliver a frame to every subscriber, containing each one individually.\n *\n * SSE subscribers are the least-trusted callbacks in the system — one per\n * connection, driven by network state. The unguarded loop this replaces let\n * the first thrower abort iteration, so every later subscriber lost the\n * frame and the exception escaped into the host's commit path (#1423). Same\n * containment principle the orchestrator applies to lifecycle listeners.\n * Guarding each callback rather than the loop is the point: one guard around\n * the whole loop would still let the first throw suppress the rest.\n *\n * @internal\n */\nfunction fan_out<S extends BroadcastState>(\n subs: Set<Subscriber<S>> | undefined,\n msg: PatchMessage<S>,\n on_error: (error: unknown) => void\n): void {\n if (!subs?.size) return;\n for (const cb of subs) {\n try {\n cb(msg);\n } catch (error) {\n on_error(error);\n }\n }\n}\n\n/**\n * Rewrite `undefined`-valued keys to `null`, recursively.\n *\n * `@rotorsoft/act-patch` treats `undefined` and `null` as the same delete\n * signal, but `JSON.stringify` drops `undefined`-valued keys entirely — and\n * every SSE transport serializes frames as JSON. A reducer that clears a\n * field the idiomatic way (`{ left: undefined }`) therefore produced a frame\n * with no mention of `left` at all, so a live client kept the stale value\n * while stamping the new version — believing itself caught up, and never\n * refetching (#1471).\n *\n * `null` reaches the same `delete` branch in the patch applicator and\n * survives JSON, so normalizing here makes the two spellings equivalent on\n * the wire as they already are in memory.\n *\n * Only the broadcast frame is normalized. Server-side state is applied\n * through `apply_patch`, which handles `undefined` natively.\n */\nconst wire_safe = <T>(patch: T): T => {\n if (patch === null || typeof patch !== \"object\") return patch;\n if (Array.isArray(patch)) return patch.map(wire_safe) as T;\n // Non-plain objects (Date, Map, class instances) are left to whatever the\n // host's serializer already does with them; rewriting their internals\n // would change more than the delete signal.\n const proto = Object.getPrototypeOf(patch);\n if (proto !== Object.prototype && proto !== null) return patch;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(patch as Record<string, unknown>))\n out[k] = v === undefined ? null : wire_safe(v);\n return out as T;\n};\n\nexport class BroadcastChannel<S extends BroadcastState = BroadcastState> {\n private channels = new Map<string, Set<Subscriber<S>>>();\n private state_cache: StateCache<S>;\n\n /**\n * @param options.cacheSize - Max number of stream states kept in the LRU\n * cache (default 50).\n */\n private on_subscriber_error: (error: unknown, streamId: string) => void;\n private on_overlay_miss: (streamId: string) => void;\n\n constructor(options?: {\n cacheSize?: number;\n /**\n * Called when `overlay()` finds no cached baseline for the stream, so\n * the update cannot be broadcast. Live subscribers receive nothing and\n * have no way to notice — a host that cares should raise `cacheSize`,\n * re-`publish` the stream, or push the viewers to refetch. Defaults to a\n * no-op so existing behavior is unchanged apart from being observable.\n */\n onOverlayMiss?: (streamId: string) => void;\n /**\n * Called when a subscriber callback throws. The frame is still delivered\n * to every other subscriber and the publish still returns normally — a\n * bad consumer must not break the publisher (#1423). Defaults to the\n * framework's `log()` port, so it lands wherever the host already\n * routes framework logs.\n */\n onSubscriberError?: (error: unknown, streamId: string) => void;\n /**\n * Deprecated alias of `cacheSize` — removal in the next major. When\n * both are given, `cacheSize` wins.\n * @deprecated use `cacheSize`\n */\n cache_size?: number;\n }) {\n this.state_cache = new StateCache<S>(\n options?.cacheSize ?? options?.cache_size ?? 50\n );\n this.on_overlay_miss = options?.onOverlayMiss ?? (() => {});\n this.on_subscriber_error =\n options?.onSubscriberError ??\n ((error, streamId) =>\n log().error(error, `sse subscriber threw for \"${streamId}\"`));\n }\n\n /**\n * Publish domain patches from a commit.\n * patches[i] corresponds to version baseV + i + 1.\n *\n * @param streamId - The event store stream ID\n * @param state - Full state with `_v` set from `snap.event.version`\n * @param patches - Array of domain patches, one per emitted event\n */\n publish(\n streamId: string,\n state: S,\n patches: Partial<S>[] = []\n ): PatchMessage<S> {\n this.state_cache.set(streamId, state);\n\n const baseV = state._v - patches.length;\n const msg: PatchMessage<S> = {};\n patches.forEach((p, i) => {\n msg[baseV + i + 1] = wire_safe(p);\n });\n\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Publish a state update that doesn't change the event version\n * (e.g. presence overlay, computed field refresh).\n * Uses the same version as the cached state, single entry.\n */\n overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n const prev = this.state_cache.get(streamId);\n if (!prev) {\n // No baseline to read-modify-write, so nothing is broadcast — and\n // because no frame is emitted there is nothing for a live client to\n // classify as `behind`, so it never refetches either. Unlike a domain\n // commit (which repopulates the cache via `publish`), an overlay-only\n // stream never recovers. The defaults make this reachable rather than\n // exotic: `cacheSize` is 50 while a host may hold far more live\n // subscriptions, and cache promotion happens at connect time, so a\n // busy-but-not-committing stream ages out while fully subscribed.\n //\n // Emit a resync frame so live subscribers refetch instead of silently\n // missing the update forever (#1423). `on_overlay_miss` still fires so\n // a host can count these — a steady stream of them means `cacheSize`\n // is too small for the working set.\n this.on_overlay_miss(streamId);\n const resync: PatchMessage<S> = { _resync: true } as PatchMessage<S>;\n fan_out(this.channels.get(streamId), resync, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n // Still `undefined`: no overlay state was produced, and callers use the\n // return value as \"the patch I broadcast\", which a resync is not.\n return undefined;\n }\n\n const state = apply_patch(prev, overlay_patch) as S;\n this.state_cache.set(streamId, state);\n\n // `_overlay: true` marks this as a version-neutral update so a caught-up\n // client applies it at the current version instead of dropping it as\n // stale (the key equals the client's cachedV). Ordinary patches omit it.\n const msg: PatchMessage<S> = {\n [state._v]: wire_safe(overlay_patch),\n _overlay: true,\n };\n fan_out(this.channels.get(streamId), msg, (error) =>\n this.on_subscriber_error(error, streamId)\n );\n return msg;\n }\n\n /**\n * Subscribe to broadcast messages for a stream.\n * Returns a cleanup function that removes the subscription.\n */\n subscribe(streamId: string, cb: Subscriber<S>): () => void {\n if (!this.channels.has(streamId)) this.channels.set(streamId, new Set());\n this.channels.get(streamId)!.add(cb);\n return () => {\n this.channels.get(streamId)?.delete(cb);\n if (this.channels.get(streamId)?.size === 0) {\n this.channels.delete(streamId);\n }\n };\n }\n\n /** Get the number of subscribers for a stream. */\n subscriberCount(streamId: string): number {\n return this.channels.get(streamId)?.size ?? 0;\n }\n\n /** Get the cached state for a stream (for reconnects / initial SSE yield). */\n state(streamId: string): S | undefined {\n return this.state_cache.get(streamId);\n }\n\n /** @deprecated use `overlay` — removal in the next major */\n publish_overlay(\n streamId: string,\n overlay_patch: Partial<S>\n ): PatchMessage<S> | undefined {\n return this.overlay(streamId, overlay_patch);\n }\n\n /** @deprecated use `subscriberCount` — removal in the next major */\n get_subscriber_count(streamId: string): number {\n return this.subscriberCount(streamId);\n }\n\n /** @deprecated use `state` — removal in the next major */\n get_state(streamId: string): S | undefined {\n return this.state(streamId);\n }\n\n /** Direct access to the state cache (for app-specific reads like presence). */\n get cache(): StateCache<S> {\n return this.state_cache;\n }\n}\n","import type { BroadcastState } from \"./types.js\";\n\n/**\n * Generic LRU cache for aggregate state objects.\n *\n * Keyed by stream ID. Each entry stores the full state (with `_v` from the\n * event store). Used as the \"previous state\" baseline for computing patches,\n * and as the fast path for reconnects.\n *\n * The cache is shared between the broadcast hot path and read queries.\n * Projections should maintain their own cache to avoid double-apply bugs.\n */\nexport class StateCache<S extends BroadcastState = BroadcastState> {\n private cache = new Map<string, S>();\n private maxSize: number;\n\n constructor(maxSize = 50) {\n this.maxSize = maxSize;\n }\n\n /** Get a cached state, promoting it to MRU position. */\n get(key: string): S | undefined {\n const s = this.cache.get(key);\n if (s) {\n this.cache.delete(key);\n this.cache.set(key, s);\n }\n return s;\n }\n\n /** Set a cached state, evicting the LRU entry if at capacity. */\n set(key: string, state: S): void {\n this.cache.delete(key);\n this.cache.set(key, state);\n if (this.cache.size > this.maxSize) {\n this.cache.delete(this.cache.keys().next().value!);\n }\n }\n\n /** Remove a cached entry. */\n delete(key: string): void {\n this.cache.delete(key);\n }\n\n /** Check if a key exists in the cache. */\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n /** Current number of cached entries. */\n get size(): number {\n return this.cache.size;\n }\n\n /** Direct access to the underlying map (for iteration). */\n entries(): IterableIterator<[string, S]> {\n return this.cache.entries();\n }\n}\n","/**\n * Generic presence tracker — ref-counted online status per stream per identity.\n *\n * Supports multi-tab: each subscribe increments the ref count, each\n * unsubscribe decrements it. An identity is considered online when\n * ref count > 0.\n *\n * ## Usage\n *\n * ```typescript\n * const presence = new PresenceTracker();\n *\n * // On SSE connect:\n * presence.add(game_id, player_id);\n *\n * // On SSE disconnect:\n * presence.remove(game_id, player_id);\n *\n * // Query:\n * presence.online(game_id); // Set<string>\n * ```\n */\nexport class PresenceTracker {\n private streams = new Map<string, Map<string, number>>();\n\n /** Increment ref count for an identity on a stream. */\n add(streamId: string, identity_id: string): void {\n if (!this.streams.has(streamId)) this.streams.set(streamId, new Map());\n const counts = this.streams.get(streamId)!;\n counts.set(identity_id, (counts.get(identity_id) ?? 0) + 1);\n }\n\n /** Decrement ref count. Removes the identity when count reaches 0. */\n remove(streamId: string, identity_id: string): void {\n const counts = this.streams.get(streamId);\n if (!counts) return;\n const n = (counts.get(identity_id) ?? 1) - 1;\n if (n <= 0) counts.delete(identity_id);\n else counts.set(identity_id, n);\n if (counts.size === 0) this.streams.delete(streamId);\n }\n\n /** Get the set of online identity IDs for a stream. */\n online(streamId: string): Set<string> {\n const counts = this.streams.get(streamId);\n return counts ? new Set(counts.keys()) : new Set();\n }\n\n /** Check if a specific identity is online for a stream. */\n isOnline(streamId: string, identity_id: string): boolean {\n return (this.streams.get(streamId)?.get(identity_id) ?? 0) > 0;\n }\n\n /** @deprecated use `online` — removal in the next major */\n get_online(streamId: string): Set<string> {\n return this.online(streamId);\n }\n\n /** @deprecated use `isOnline` — removal in the next major */\n is_online(streamId: string, identity_id: string): boolean {\n return this.isOnline(streamId, identity_id);\n }\n}\n"],"mappings":";;;AAuCA,SAAS,aAAa;;;ACvCtB,SAAS,SAAS,kBAAkB;AAuC7B,SAAS,kBACd,KACA,QACgB;AAMhB,QAAM,cAAc,UAAU;AAC9B,QAAM,UAAU,QAAQ,MAAM;AAE9B,QAAM,WAAW,OAAO,KAAK,GAAG,EAC7B,IAAI,MAAM,EACV,OAAO,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC,EACjC,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAOvB,MAAI,IAAI,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEtD,MAAI,CAAC,SAAS,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAE1D,QAAM,OAAO,SAAS,CAAC;AACvB,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AAQzC,MAAI,IAAI,UAAU;AAEhB,QAAI,CAAC,OAAQ,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAElD,QAAI,SAAS;AACX,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO,EAAE,GAAG,WAAW,QAAQ,IAAI,IAAI,CAAC,GAAG,IAAI,QAAQ;AAAA,MACzD;AAEF,QAAI,OAAO,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAEzD,WAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAAA,EACtC;AAKA,MAAI,eAAe,QAAQ,QAAS,QAAO,EAAE,IAAI,OAAO,QAAQ,QAAQ;AAKxE,MAAI,OAAO,UAAU,EAAG,QAAO,EAAE,IAAI,OAAO,QAAQ,SAAS;AAG7D,MAAI,QAAS,UAAU,CAAC;AACxB,aAAW,KAAK,UAAU;AACxB,QAAI,KAAK,QAAS;AAClB,YAAQ,EAAE,GAAG,WAAW,OAAO,IAAI,CAAC,CAAC,GAAG,IAAI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AU,WAAW;AAAA,EAC5C;AACF;","names":["patch"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rotorsoft/act-http",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.9.
|
|
4
|
+
"version": "1.9.3",
|
|
5
5
|
"description": "HTTP integrations for act apps — webhooks and SSE",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"typescript",
|
|
@@ -90,13 +90,13 @@
|
|
|
90
90
|
"access": "public"
|
|
91
91
|
},
|
|
92
92
|
"peerDependencies": {
|
|
93
|
-
"@hono/node-server": "^2.0
|
|
93
|
+
"@hono/node-server": "^2.1.0",
|
|
94
94
|
"@trpc/server": ">=11.18.0",
|
|
95
95
|
"express": "^5.2.1",
|
|
96
96
|
"fastify": "^5.11.2",
|
|
97
|
-
"hono": "^4.
|
|
98
|
-
"@rotorsoft/act
|
|
99
|
-
"@rotorsoft/act": "^
|
|
97
|
+
"hono": "^4.13.1",
|
|
98
|
+
"@rotorsoft/act": "^1.25.1",
|
|
99
|
+
"@rotorsoft/act-ops": "^0.2.6"
|
|
100
100
|
},
|
|
101
101
|
"peerDependenciesMeta": {
|
|
102
102
|
"@rotorsoft/act-ops": {
|
|
@@ -122,15 +122,15 @@
|
|
|
122
122
|
"@rotorsoft/act-patch": "^1.2.7"
|
|
123
123
|
},
|
|
124
124
|
"devDependencies": {
|
|
125
|
-
"@hono/node-server": "^2.0
|
|
125
|
+
"@hono/node-server": "^2.1.0",
|
|
126
126
|
"@hono/zod-validator": "^0.9.0",
|
|
127
127
|
"@stryker-mutator/core": "^9.6.1",
|
|
128
128
|
"@stryker-mutator/vitest-runner": "^9.6.1",
|
|
129
129
|
"@trpc/server": "^11.18.0",
|
|
130
130
|
"@types/express": "^5.0.6",
|
|
131
131
|
"express": "^5.2.1",
|
|
132
|
-
"fastify": "^5.11.
|
|
133
|
-
"hono": "^4.
|
|
132
|
+
"fastify": "^5.11.2",
|
|
133
|
+
"hono": "^4.13.1",
|
|
134
134
|
"zod": "^4.4.3",
|
|
135
135
|
"@rotorsoft/act-ops": "^0.2.6"
|
|
136
136
|
},
|