@rotorsoft/act-http 1.11.2 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -5
- package/dist/.tsbuildinfo +1 -1
- package/dist/@types/api/actor.d.ts +4 -6
- package/dist/@types/api/actor.d.ts.map +1 -1
- package/dist/@types/api/dispatch.d.ts +46 -1
- package/dist/@types/api/dispatch.d.ts.map +1 -1
- package/dist/@types/api/sse-wiring.d.ts +2 -2
- package/dist/@types/api/sse-wiring.d.ts.map +1 -1
- package/dist/@types/hono/index.d.ts +80 -13
- package/dist/@types/hono/index.d.ts.map +1 -1
- package/dist/@types/openapi/index.d.ts.map +1 -1
- package/dist/@types/sse/broadcast.d.ts +4 -2
- package/dist/@types/sse/broadcast.d.ts.map +1 -1
- package/dist/@types/trpc/index.d.ts +107 -35
- package/dist/@types/trpc/index.d.ts.map +1 -1
- package/dist/api/index.cjs +1 -3
- package/dist/api/index.cjs.map +1 -1
- package/dist/api/index.js +1 -1
- package/dist/{chunk-QM6YP2XH.js → chunk-QSH2Y3YR.js} +2 -2
- package/dist/chunk-QSH2Y3YR.js.map +1 -0
- package/dist/{chunk-75DA7NJI.js → chunk-YEDAY2PC.js} +2 -4
- package/dist/chunk-YEDAY2PC.js.map +1 -0
- package/dist/hono/index.cjs +1 -3
- package/dist/hono/index.cjs.map +1 -1
- package/dist/hono/index.js +2 -2
- package/dist/hono/index.js.map +1 -1
- package/dist/openapi/index.cjs +102 -34
- package/dist/openapi/index.cjs.map +1 -1
- package/dist/openapi/index.js +103 -35
- package/dist/openapi/index.js.map +1 -1
- package/dist/sse/index.cjs +2 -1
- package/dist/sse/index.cjs.map +1 -1
- package/dist/sse/index.js +2 -1
- package/dist/sse/index.js.map +1 -1
- package/dist/trpc/index.cjs +2 -8
- package/dist/trpc/index.cjs.map +1 -1
- package/dist/trpc/index.js +3 -7
- package/dist/trpc/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-75DA7NJI.js.map +0 -1
- package/dist/chunk-QM6YP2XH.js.map +0 -1
package/dist/trpc/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
make_dispatch
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-QSH2Y3YR.js";
|
|
4
4
|
import {
|
|
5
5
|
SseConnectionCounter,
|
|
6
6
|
resolveSseConfig,
|
|
7
7
|
runSseSubscription,
|
|
8
8
|
toApiError
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-YEDAY2PC.js";
|
|
10
10
|
import {
|
|
11
11
|
external_exports
|
|
12
12
|
} from "../chunk-WZ6QI2OI.js";
|
|
@@ -21,14 +21,10 @@ import {
|
|
|
21
21
|
TRPCError
|
|
22
22
|
} from "@trpc/server";
|
|
23
23
|
function authenticated(extractor) {
|
|
24
|
-
|
|
25
|
-
ctx,
|
|
26
|
-
next
|
|
27
|
-
}) {
|
|
24
|
+
return async ({ ctx, next }) => {
|
|
28
25
|
const actor = await extractor(ctx);
|
|
29
26
|
return next({ ctx: { ...ctx, actor } });
|
|
30
27
|
};
|
|
31
|
-
return middleware;
|
|
32
28
|
}
|
|
33
29
|
function to_trpc_error(err) {
|
|
34
30
|
const { status, body } = toApiError(err);
|
package/dist/trpc/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/trpc/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/trpc\n *\n * tRPC subpath of the auto-generated API. Walks the\n * registry of a built `Act` once at function call and emits a typed\n * router that exposes every registered action as a flat `mutation`,\n * matching the shape hand-written tRPC routers in the Act ecosystem\n * already use.\n *\n * Usage:\n *\n * ```ts\n * import { trpc } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user: { id: string; name: string }; tenant: string };\n *\n * const router = trpc<Ctx, typeof app>(app, {\n * actor: (ctx) => {\n * const { user } = ctx as Ctx; // the extractor receives `unknown`\n * return { id: user.id, name: user.name };\n * },\n * stream: (action, input, ctx) => `tenant-${ctx.tenant}`,\n * });\n *\n * // Client sees:\n * // appRouter.PressKey.mutate({ key: \"5\" })\n * // appRouter.OpenTicket.mutate({ title: \"...\" })\n * ```\n *\n * The route shape is flat: one procedure per registered action at\n * the top level. Action names are the unique identifiers across\n * the registry (the framework already enforces no duplicates), so\n * an extra namespace tier would be overhead in the common case.\n * See `libs/act-http/README.md` for the full surface walkthrough.\n *\n * **Actor lives on the context.** The generator wires an internal\n * tRPC middleware that runs the host's\n * {@link TrpcOptions.actor | actor extractor} once per call and\n * injects the resolved {@link Actor} onto the downstream context as\n * `ctx.actor`. Every generated mutation reads from there — auth\n * resolves at the procedure boundary, not inside each action body,\n * and any composed middleware (logging, tracing) sees the same\n * `ctx.actor`. The middleware factory is also exported as\n * {@link authenticated} for hosts that need to compose it into\n * their own procedure chain.\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 (this one, Hono,\n * OpenAPI) ride the same utilities so a client talking to two\n * transports never sees two error shapes for the same framework\n * error.\n */\nimport { type Actor, validate } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport {\n type AnyTRPCMiddlewareFunction,\n type AnyTRPCMutationProcedure,\n type AnyTRPCRootTypes,\n initTRPC,\n type TRPCBuiltRouter,\n TRPCError,\n} from \"@trpc/server\";\nimport { z } from \"zod\";\nimport { type ActSurface, make_dispatch } from \"../api/dispatch.js\";\nimport {\n type ActorExtractor,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n toApiError,\n} from \"../api/index.js\";\n\n/**\n * Per-call options for {@link trpc}. The host supplies the three\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the tRPC context, returns the\n * `Actor` that flows onto `ctx.actor` for every generated\n * procedure (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated action input, and the original tRPC context; returns\n * the target stream. Singleton aggregates return a constant;\n * per-tenant aggregates pull from input or context.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * When set, the procedure threads the resolved value through\n * `target.expectedVersion` so `app.do` refuses to commit if the\n * stream has moved. Hosts typically read it from an `If-Match`\n * header on the underlying HTTP request, or pull it from the\n * client's last-known snapshot. Returning `undefined` skips the\n * check for that call — handy when only some actions are\n * concurrency-sensitive.\n * - `idempotency` (optional) — when set, the procedure honors\n * `Idempotency-Key` via the shared\n * {@link withIdempotency} helper. The host supplies the\n * `IdempotencyStore` and a `keyFrom` extractor that reads the key\n * out of the tRPC context (typically a header). A duplicate of a key\n * that already succeeded throws a `CONFLICT` `TRPCError` — the\n * receiver-side convention of \"ack the duplicate\" doesn't carry\n * over because the contract intentionally does not cache the\n * original handler's result. A duplicate that arrives while the\n * original is still running throws a retryable\n * `SERVICE_UNAVAILABLE` (503) instead: the original may yet fail and\n * release the key, and a client told \"already used\" would never retry.\n *\n * @template Ctx The host's tRPC context shape. Flows end-to-end —\n * procedures see this exact context type (plus `actor`) at\n * runtime.\n */\nexport type TrpcOptions<Ctx> = {\n readonly actor: ActorExtractor;\n readonly stream: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n ctx: Ctx\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom: (ctx: Ctx) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * subscription per unique state name in the registry, grouped on\n * the returned router as\n * `router.subscribe.<stateName>.useSubscription({ stream })`.\n * Each subscription yields `{ kind: \"state\", data }` once with\n * the cached state (when present) and then `{ kind: \"patch\",\n * data }` for every patch the shared\n * {@link SseOptions.channel} publishes. The per-process\n * connection cap surfaces as a `TOO_MANY_REQUESTS` `TRPCError`.\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};\n\n/**\n * Build a tRPC middleware that runs an {@link ActorExtractor} once\n * per call and forwards the resolved {@link Actor} on the\n * downstream context as `ctx.actor`. The generator at\n * {@link trpc} uses this internally; it's also exported so hosts\n * that want to compose their own procedure chain (logging,\n * tracing, custom auth flavors) can wire it directly:\n *\n * ```ts\n * import { initTRPC } from \"@trpc/server\";\n * import { authenticated } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user?: { id: string; name: string } };\n * const t = initTRPC.context<Ctx>().create();\n *\n * const authed = t.procedure.use(\n * authenticated((ctx) => {\n * if (!ctx.user) throw new Error(\"not authenticated\");\n * return { id: ctx.user.id, name: ctx.user.name };\n * })\n * );\n *\n * // Inside any procedure built off `authed`, `ctx.actor: Actor`.\n * ```\n *\n * The middleware is unaware of the host's `t` instance — it returns\n * a structurally-typed function that any tRPC `procedure.use(...)`\n * accepts. Errors thrown by the extractor surface unchanged\n * (typically wrap them as `TRPCError({ code: \"UNAUTHORIZED\" })`\n * in the extractor body).\n */\nexport function authenticated(\n extractor: ActorExtractor\n): AnyTRPCMiddlewareFunction {\n // tRPC's middleware function type lives behind\n // `unstable-core-do-not-import`; we satisfy it structurally with the\n // shape `procedure.use(...)` actually requires (an `{ ctx, next }`\n // bag whose `next` callback is invoked once with the augmented ctx)\n // and cast the structurally-typed result up to the named export. The\n // type cast carries no `any`; both sides are structurally compatible\n // at the call site.\n const middleware = async function actor_middleware({\n ctx,\n next,\n }: {\n ctx: object;\n next: (opts: { ctx: object }) => Promise<unknown>;\n }) {\n const actor = await extractor(ctx);\n return next({ ctx: { ...ctx, actor } });\n };\n return middleware as unknown as AnyTRPCMiddlewareFunction;\n}\n\n/**\n * Map a thrown framework error onto a `TRPCError`. Known errors get\n * their conventional tRPC code (`ConcurrencyError` → `PRECONDITION_FAILED`,\n * `StreamClosedError` → `NOT_FOUND`, `ValidationError` →\n * `UNPROCESSABLE_CONTENT`, etc.); unknown throws\n * surface as `INTERNAL_SERVER_ERROR`. Every act-http transport\n * passes through the same {@link toApiError} table,\n * so a client talking to both this subpath and the REST sibling\n * sees one envelope per framework error.\n *\n * @internal\n */\nfunction to_trpc_error(err: unknown): TRPCError {\n const { status, body } = toApiError(err);\n const code = status_to_trpc_code(status);\n return new TRPCError({\n code,\n message: body.detail ?? body.error,\n cause: err instanceof Error ? err : undefined,\n });\n}\n\n/**\n * Minimal status → tRPC code map. Only the statuses\n * {@link ERROR_MAP} produces (plus 500) appear here; anything else\n * collapses to `INTERNAL_SERVER_ERROR`.\n *\n * @internal\n */\nfunction status_to_trpc_code(status: number): TRPCError[\"code\"] {\n switch (status) {\n case 400:\n return \"BAD_REQUEST\";\n case 409:\n return \"CONFLICT\";\n case 410:\n // StreamClosedError is HTTP 410 Gone. tRPC has no 410 code, so map to\n // NOT_FOUND (404) — its closest \"resource is gone\" semantics. This is\n // the one unavoidable cross-transport status difference (Hono/OpenAPI\n // keep 410); see auto-generated-api.md.\n return \"NOT_FOUND\";\n case 412:\n // ConcurrencyError is HTTP 412 Precondition Failed. Map by error\n // identity, not by round-tripping the status: PRECONDITION_FAILED\n // serializes back to 412, matching Hono/OpenAPI.\n return \"PRECONDITION_FAILED\";\n case 422:\n return \"UNPROCESSABLE_CONTENT\";\n default:\n return \"INTERNAL_SERVER_ERROR\";\n }\n}\n\n/**\n * Generated router type — one mutation procedure per action name in\n * `TApp`'s registry. Mapped over the concrete action keys so\n * `createTRPCReact<typeof router>()` sees specific procedure names\n * (`PressKey`, `Clear`, …) instead of a wide `Record<string, ...>`\n * index signature — which is what trips tRPC React's\n * \"useContext / Provider / useUtils collides\" check on widely-typed\n * routers.\n *\n * @internal\n */\ntype GeneratedRouter<TApp> = TRPCBuiltRouter<\n AnyTRPCRootTypes,\n TApp extends { registry: { actions: infer TActions } }\n ? { [K in keyof TActions]: AnyTRPCMutationProcedure }\n : Record<string, AnyTRPCMutationProcedure>\n>;\n\n/**\n * Build a typed tRPC router from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one flat mutation per\n * action under `router.<actionName>`. The framework already enforces\n * no duplicate action names across states, so a flat tier reads\n * cleanly at the client and matches the hand-written router shape\n * adopters already have. Each mutation:\n *\n * 1. Runs the internal {@link authenticated} — `options.actor`\n * resolves the {@link Actor} once and injects it onto\n * `ctx.actor`.\n * 2. Resolves the target stream via `options.stream(name, input, ctx)`.\n * 3. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — throws `CONFLICT` on a duplicate of a\n * committed key, `SERVICE_UNAVAILABLE` on one still in flight.\n * 4. Calls `app.do(name, { stream, actor: ctx.actor }, input)`.\n * 5. Maps any thrown framework error onto a `TRPCError` via\n * {@link toApiError}.\n *\n * The returned router's procedure inputs come straight from each\n * action's Zod schema; outputs are the framework's\n * `Snapshot<TState, TEvents>[]` shape. Strong typing flows\n * end-to-end via tRPC's normal inference path — the client sees\n * `appRouter.Calculator.PressKey.mutate({ key: \"5\" })` as a typed\n * call without any codegen.\n *\n * @template Ctx The tRPC context shape the host's runtime feeds in.\n * Flows through `actor`, `stream`, and `idempotency.keyFrom` so\n * the operator's existing context types just work. The internal\n * middleware augments `Ctx` with `{ actor: Actor }` on the\n * downstream procedure context.\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, and (optional) idempotency seams.\n * @returns A tRPC router covering every registered action, grouped\n * by owning state.\n */\nexport function trpc<\n Ctx extends object = object,\n TApp extends ActSurface = ActSurface,\n>(app: TApp, options: TrpcOptions<Ctx>): GeneratedRouter<TApp> {\n const t = initTRPC.context<Ctx>().create();\n const dispatch = make_dispatch<Ctx>(app, options, options.idempotency?.store);\n\n // Resolve the actor inline per mutation instead of via\n // `t.procedure.use(authenticated(...))`. The middleware path threads\n // tRPC's internal `Unwrap` type into each procedure's inferred shape,\n // which the d.ts emitter can't name portably (`unstable-core-do-not-\n // import` has a hashed file name that varies per build). Inlining\n // sidesteps the issue entirely — the standalone `authenticated`\n // export still works for hosts who want middleware composition.\n /**\n * Run the actor extractor for a generated procedure, mapping a\n * \"throw to deny\" onto `UNAUTHORIZED` rather than a framework 500.\n *\n * Shared by mutations and subscriptions, so a denied caller gets\n * neither a mutation nor a live subscription.\n */\n const resolve_actor = async (host_ctx: Ctx): Promise<Actor> => {\n try {\n return await options.actor(host_ctx);\n } catch (err) {\n throw new TRPCError({\n code: \"UNAUTHORIZED\",\n message: err instanceof Error ? err.message : undefined,\n cause: err instanceof Error ? err : undefined,\n });\n }\n };\n\n const handlers: Record<\n string,\n ReturnType<ReturnType<typeof t.procedure.input>[\"mutation\"]>\n > = {};\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const action_schema = state.actions[action_name];\n handlers[action_name] = t.procedure\n // Passthrough parser: tRPC's own `.input()` validation is deliberately\n // bypassed because a Zod failure there surfaces as a hardcoded\n // BAD_REQUEST (400) that never reaches `to_trpc_error`. Validation runs\n // in the resolver (below) instead, so a malformed body maps to the SAME\n // 422 / ApiError a `ValidationError` thrown inside `app.do` produces,\n // as Hono and OpenAPI do.\n .input((raw: unknown) => raw)\n .mutation(async ({ input, ctx }) => {\n const host_ctx = ctx as unknown as Ctx;\n // Resolve the actor first, mirroring Hono's `authenticated` middleware:\n // a \"throw to deny\" from the extractor is 401 UNAUTHORIZED, not a 500.\n // The actor step is auth — distinct from a framework error inside\n // `app.do`, which the main try below maps via `to_trpc_error`.\n const actor: Actor = await resolve_actor(host_ctx);\n try {\n // Validate the payload before the stream / expectedVersion resolvers\n // see it, mirroring Hono's zValidator-then-handler order. `validate`\n // throws the framework `ValidationError`, which `to_trpc_error` maps\n // to 422 / UNPROCESSABLE_CONTENT with the shared ApiError envelope.\n // The resolvers get the parsed value, but `app.do` gets the\n // raw `input`: it parses again itself, and a second parse of the\n // output would run every `.transform()` twice.\n const validated = validate(\n action_name,\n input as never,\n action_schema as never\n );\n const outcome = await dispatch(\n action_name,\n validated,\n input,\n host_ctx,\n actor,\n () => options.idempotency?.keyFrom(host_ctx)\n );\n if (outcome.kind === \"done\") return outcome.result;\n throw new TRPCError(\n outcome.kind === \"missing-key\"\n ? { code: \"BAD_REQUEST\", message: \"Idempotency-Key required\" }\n : outcome.kind === \"in-flight\"\n ? {\n code: \"SERVICE_UNAVAILABLE\",\n message:\n \"Idempotency-Key in flight; the original request has not finished, retry later\",\n }\n : {\n code: \"CONFLICT\",\n message:\n \"Idempotency-Key already used; original result not cached\",\n }\n );\n } catch (err) {\n if (err instanceof TRPCError) throw err;\n throw to_trpc_error(err);\n }\n });\n }\n\n if (options.sse) {\n // SSE subscriptions mount under the `subscribe` key of the same router\n // as the action mutations, so an action named `subscribe` would be\n // silently replaced. Refuse it at generation instead.\n if (\"subscribe\" in app.registry.actions)\n throw new Error(\n 'trpc: an action named \"subscribe\" collides with the SSE subscription router (router.subscribe.<stateName>); rename the action or generate the router without `sse`.'\n );\n const sse_config = resolveSseConfig(options.sse);\n const sse_counter = new SseConnectionCounter(sse_config.maxConnections);\n const state_names = new Set(\n Object.values(app.registry.actions).map((a) => a.name)\n );\n const sse_handlers: Record<string, unknown> = {};\n for (const state_name of state_names) {\n sse_handlers[state_name] = t.procedure\n .input(z.object({ stream: z.string().min(1) }))\n .subscription(async function* ({ input, ctx, signal }) {\n // Step 1 of the documented subscription contract: the actor\n // extractor runs before a slot is taken or a frame is yielded,\n // so a denying extractor denies the open. Hono gets this from\n // the `authenticated` middleware it mounts across `/api/*`;\n // this generator is where the same rule lives for tRPC, which\n // resolves the actor inline rather than through middleware.\n await resolve_actor(ctx as unknown as Ctx);\n yield* runSseSubscription(\n sse_config.channel,\n input.stream,\n sse_counter,\n signal,\n {\n maxPending: sse_config.maxPendingPerConnection,\n on_cap_exceeded: () => {\n throw new TRPCError({\n code: \"TOO_MANY_REQUESTS\",\n message: \"max concurrent SSE subscriptions reached\",\n });\n },\n }\n );\n });\n }\n handlers.subscribe = t.router(sse_handlers as never) as never;\n }\n\n // The runtime router IS structurally compatible with\n // `GeneratedRouter<TApp>` (one mutation per action key), but tRPC's\n // `BuiltRouter` carries an internal `Unwrap<Ctx>` that the d.ts\n // emitter can't name portably. Bridging through `unknown` keeps the\n // caller-visible type clean (specific procedure names, no\n // index-signature widening that trips React tRPC's collision check).\n return t.router(handlers) as unknown as GeneratedRouter<TApp>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuDA,SAAqB,gBAAgB;AAErC;AAAA,EAIE;AAAA,EAEA;AAAA,OACK;AAiHA,SAAS,cACd,WAC2B;AAQ3B,QAAM,aAAa,eAAe,iBAAiB;AAAA,IACjD;AAAA,IACA;AAAA,EACF,GAGG;AACD,UAAM,QAAQ,MAAM,UAAU,GAAG;AACjC,WAAO,KAAK,EAAE,KAAK,EAAE,GAAG,KAAK,MAAM,EAAE,CAAC;AAAA,EACxC;AACA,SAAO;AACT;AAcA,SAAS,cAAc,KAAyB;AAC9C,QAAM,EAAE,QAAQ,KAAK,IAAI,WAAW,GAAG;AACvC,QAAM,OAAO,oBAAoB,MAAM;AACvC,SAAO,IAAI,UAAU;AAAA,IACnB;AAAA,IACA,SAAS,KAAK,UAAU,KAAK;AAAA,IAC7B,OAAO,eAAe,QAAQ,MAAM;AAAA,EACtC,CAAC;AACH;AASA,SAAS,oBAAoB,QAAmC;AAC9D,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAKH,aAAO;AAAA,IACT,KAAK;AAIH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AA0DO,SAAS,KAGd,KAAW,SAAkD;AAC7D,QAAM,IAAI,SAAS,QAAa,EAAE,OAAO;AACzC,QAAM,WAAW,cAAmB,KAAK,SAAS,QAAQ,aAAa,KAAK;AAgB5E,QAAM,gBAAgB,OAAO,aAAkC;AAC7D,QAAI;AACF,aAAO,MAAM,QAAQ,MAAM,QAAQ;AAAA,IACrC,SAAS,K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ACtE,UAAM,cAAc,IAAI;AAAA,MACtB,OAAO,OAAO,IAAI,SAAS,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,IACvD;AACA,UAAM,eAAwC,CAAC;AAC/C,eAAW,cAAc,aAAa;AACpC,mBAAa,UAAU,IAAI,EAAE,UAC1B,MAAM,iBAAE,OAAO,EAAE,QAAQ,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,EAC7C,aAAa,iBAAiB,EAAE,OAAO,KAAK,OAAO,GAAG;AAOrD,cAAM,cAAc,GAAqB;AACzC,eAAO;AAAA,UACL,WAAW;AAAA,UACX,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA;AAAA,YACE,YAAY,WAAW;AAAA,YACvB,iBAAiB,MAAM;AACrB,oBAAM,IAAI,UAAU;AAAA,gBAClB,MAAM;AAAA,gBACN,SAAS;AAAA,cACX,CAAC;AAAA,YACH;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACL;AACA,aAAS,YAAY,EAAE,OAAO,YAAqB;AAAA,EACrD;AAQA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/trpc/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n * @module act-http/trpc\n *\n * tRPC subpath of the auto-generated API. Walks the\n * registry of a built `Act` once at function call and emits a typed\n * router that exposes every registered action as a flat `mutation`,\n * matching the shape hand-written tRPC routers in the Act ecosystem\n * already use.\n *\n * Usage:\n *\n * ```ts\n * import { trpc } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user: { id: string; name: string }; tenant: string };\n *\n * const router = trpc<Ctx, typeof app>(app, {\n * actor: (ctx) => ({ id: ctx.user.id, name: ctx.user.name }),\n * stream: (action, input, ctx) => `tenant-${ctx.tenant}`,\n * });\n *\n * // Client sees:\n * // appRouter.PressKey.mutate({ key: \"5\" })\n * // appRouter.OpenTicket.mutate({ title: \"...\" })\n * ```\n *\n * The route shape is flat: one procedure per registered action at\n * the top level. Action names are the unique identifiers across\n * the registry (the framework already enforces no duplicates), so\n * an extra namespace tier would be overhead in the common case.\n * See `libs/act-http/README.md` for the full surface walkthrough.\n *\n * **Actor lives on the context.** The generator wires an internal\n * tRPC middleware that runs the host's\n * {@link TrpcOptions.actor | actor extractor} once per call and\n * injects the resolved {@link Actor} onto the downstream context as\n * `ctx.actor`. Every generated mutation reads from there — auth\n * resolves at the procedure boundary, not inside each action body,\n * and any composed middleware (logging, tracing) sees the same\n * `ctx.actor`. The middleware factory is also exported as\n * {@link authenticated} for hosts that need to compose it into\n * their own procedure chain.\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 (this one, Hono,\n * OpenAPI) ride the same utilities so a client talking to two\n * transports never sees two error shapes for the same framework\n * error.\n */\nimport { type Actor, validate } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport {\n initTRPC,\n type TRPCBuiltRouter,\n type TRPCDefaultErrorShape,\n TRPCError,\n type TRPCMiddlewareFunction,\n type TRPCMutationProcedure,\n type TRPCSubscriptionProcedure,\n} from \"@trpc/server\";\nimport { z } from \"zod\";\nimport {\n type ActionResult,\n type ActSurface,\n type AppActions,\n type AppState,\n type AppStateNames,\n make_dispatch,\n type ResolverArgs,\n} from \"../api/dispatch.js\";\nimport {\n type ActorExtractor,\n resolveSseConfig,\n runSseSubscription,\n SseConnectionCounter,\n type SseOptions,\n type SseSubscriptionFrame,\n toApiError,\n} from \"../api/index.js\";\n\n/**\n * Per-call options for {@link trpc}. The host supplies the three\n * seams the package can't make decisions on:\n *\n * - `actor` — auth resolver. Receives the tRPC context, returns the\n * `Actor` that flows onto `ctx.actor` for every generated\n * procedure (via an internal {@link authenticated}).\n * - `stream` — stream-id resolver. Receives the action name, the\n * validated action input, and the original tRPC context; returns\n * the target stream. Singleton aggregates return a constant;\n * per-tenant aggregates pull from input or context.\n * - `expectedVersion` (optional) — optimistic-concurrency resolver.\n * When set, the procedure threads the resolved value through\n * `target.expectedVersion` so `app.do` refuses to commit if the\n * stream has moved. Hosts typically read it from an `If-Match`\n * header on the underlying HTTP request, or pull it from the\n * client's last-known snapshot. Returning `undefined` leaves the\n * call to the version the action loads; a number pins it, and a\n * pinned conflict is never retried.\n * - `idempotency` (optional) — when set, the procedure honors\n * `Idempotency-Key` via the shared\n * {@link withIdempotency} helper. The host supplies the\n * `IdempotencyStore` and a `keyFrom` extractor that reads the key\n * out of the tRPC context (typically a header). A duplicate of a key\n * that already succeeded throws a `CONFLICT` `TRPCError` — the\n * receiver-side convention of \"ack the duplicate\" doesn't carry\n * over because the contract intentionally does not cache the\n * original handler's result. A duplicate that arrives while the\n * original is still running throws a retryable\n * `SERVICE_UNAVAILABLE` (503) instead: the original may yet fail and\n * release the key, and a client told \"already used\" would never retry.\n *\n * @template Ctx The host's tRPC context shape. Flows end-to-end —\n * procedures see this exact context type (plus `actor`) at\n * runtime.\n */\nexport type TrpcOptions<Ctx, TApp = ActSurface> = {\n readonly actor: ActorExtractor<Ctx>;\n readonly stream: (\n ...args: ResolverArgs<TApp, NoInfer<Ctx>>\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n ...args: ResolverArgs<TApp, NoInfer<Ctx>>\n ) => number | undefined | Promise<number | undefined>;\n readonly idempotency?: {\n readonly store: IdempotencyStore;\n readonly keyFrom: (ctx: Ctx) => string | undefined;\n };\n /**\n * Optional SSE wiring. When set, the generator emits one\n * subscription per unique state name in the registry, grouped on\n * the returned router as\n * `router.subscribe.<stateName>.useSubscription({ stream })`.\n * Each subscription yields `{ kind: \"state\", data }` once with\n * the cached state (when present) and then `{ kind: \"patch\",\n * data }` for every patch the shared\n * {@link SseOptions.channel} publishes. The per-process\n * connection cap surfaces as a `TOO_MANY_REQUESTS` `TRPCError`.\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};\n\n/**\n * Build a tRPC middleware that runs an {@link ActorExtractor} once\n * per call and forwards the resolved {@link Actor} on the\n * downstream context as `ctx.actor`. The generator at\n * {@link trpc} uses this internally; it's also exported so hosts\n * that want to compose their own procedure chain (logging,\n * tracing, custom auth flavors) can wire it directly:\n *\n * ```ts\n * import { initTRPC } from \"@trpc/server\";\n * import { authenticated } from \"@rotorsoft/act-http/trpc\";\n *\n * type Ctx = { user?: { id: string; name: string } };\n * const t = initTRPC.context<Ctx>().create();\n *\n * const authed = t.procedure.use(\n * authenticated((ctx) => {\n * if (!ctx.user) throw new Error(\"not authenticated\");\n * return { id: ctx.user.id, name: ctx.user.name };\n * })\n * );\n *\n * // Inside any procedure built off `authed`, `ctx.actor: Actor`.\n * ```\n *\n * The middleware is unaware of the host's `t` instance — it returns\n * a structurally-typed function that any tRPC `procedure.use(...)`\n * accepts. Errors thrown by the extractor surface unchanged\n * (typically wrap them as `TRPCError({ code: \"UNAUTHORIZED\" })`\n * in the extractor body).\n */\nexport function authenticated<Ctx extends object = object>(\n extractor: ActorExtractor<Ctx>\n): TRPCMiddlewareFunction<Ctx, object, object, { actor: Actor }, unknown> {\n return async ({ ctx, next }) => {\n // tRPC hands over `Ctx` as `Simplify<Overwrite<Ctx, …>>`, which TypeScript\n // can't prove is `Ctx` while `Ctx` is generic.\n const actor = await extractor(ctx as unknown as Ctx);\n return next({ ctx: { ...ctx, actor } });\n };\n}\n\n/**\n * Map a thrown framework error onto a `TRPCError`. Known errors get\n * their conventional tRPC code (`ConcurrencyError` → `PRECONDITION_FAILED`,\n * `StreamClosedError` → `NOT_FOUND`, `ValidationError` →\n * `UNPROCESSABLE_CONTENT`, etc.); unknown throws\n * surface as `INTERNAL_SERVER_ERROR`. Every act-http transport\n * passes through the same {@link toApiError} table,\n * so a client talking to both this subpath and the REST sibling\n * sees one envelope per framework error.\n *\n * @internal\n */\nfunction to_trpc_error(err: unknown): TRPCError {\n const { status, body } = toApiError(err);\n const code = status_to_trpc_code(status);\n return new TRPCError({\n code,\n message: body.detail ?? body.error,\n cause: err instanceof Error ? err : undefined,\n });\n}\n\n/**\n * Minimal status → tRPC code map. Only the statuses\n * {@link ERROR_MAP} produces (plus 500) appear here; anything else\n * collapses to `INTERNAL_SERVER_ERROR`.\n *\n * @internal\n */\nfunction status_to_trpc_code(status: number): TRPCError[\"code\"] {\n switch (status) {\n case 400:\n return \"BAD_REQUEST\";\n case 409:\n return \"CONFLICT\";\n case 410:\n // StreamClosedError is HTTP 410 Gone. tRPC has no 410 code, so map to\n // NOT_FOUND (404) — its closest \"resource is gone\" semantics. This is\n // the one unavoidable cross-transport status difference (Hono/OpenAPI\n // keep 410); see auto-generated-api.md.\n return \"NOT_FOUND\";\n case 412:\n // ConcurrencyError is HTTP 412 Precondition Failed. Map by error\n // identity, not by round-tripping the status: PRECONDITION_FAILED\n // serializes back to 412, matching Hono/OpenAPI.\n return \"PRECONDITION_FAILED\";\n case 422:\n return \"UNPROCESSABLE_CONTENT\";\n default:\n return \"INTERNAL_SERVER_ERROR\";\n }\n}\n\n/** The root types of the router {@link trpc} builds over `Ctx`. */\ntype GeneratedRoot<Ctx extends object> = {\n ctx: Ctx;\n meta: object;\n errorShape: TRPCDefaultErrorShape;\n transformer: false;\n};\n\n/**\n * One mutation per action of `TApp`: the action's payload in, the\n * snapshots `app.do` returns out. Mapped over the concrete action names,\n * so `createTRPCReact<typeof router>()` sees `PressKey`, `Clear`, …\n * instead of an index signature, which trips tRPC React's collision check.\n */\ntype ActionProcedures<TApp> = {\n [K in keyof AppActions<TApp> & string]: TRPCMutationProcedure<{\n input: AppActions<TApp>[K];\n output: ActionResult<TApp, K>;\n meta: object;\n }>;\n};\n\n/** One subscription per state of `TApp`, yielding that state's frames. */\ntype SubscribeRouter<TApp> = {\n subscribe: {\n [N in AppStateNames<TApp>]: TRPCSubscriptionProcedure<{\n input: { stream: string };\n output: AsyncIterable<SseSubscriptionFrame<AppState<TApp, N>>, void, any>;\n meta: object;\n }>;\n };\n};\n\n/** The router {@link trpc} builds: the actions, and the subscriptions with `sse`. */\nexport type GeneratedRouter<\n Ctx extends object,\n TApp,\n TRecord,\n> = TRPCBuiltRouter<GeneratedRoot<Ctx>, ActionProcedures<TApp> & TRecord>;\n\n/**\n * Build a typed tRPC router from a built `Act` instance.\n *\n * Walks `app.registry.actions` once and emits one flat mutation per\n * action under `router.<actionName>`. The framework already enforces\n * no duplicate action names across states, so a flat tier reads\n * cleanly at the client and matches the hand-written router shape\n * adopters already have. Each mutation:\n *\n * 1. Runs the internal {@link authenticated} — `options.actor`\n * resolves the {@link Actor} once and injects it onto\n * `ctx.actor`.\n * 2. Resolves the target stream via `options.stream(name, input, ctx)`.\n * 3. (Optionally) claims the `Idempotency-Key` via\n * {@link withIdempotency} — throws `CONFLICT` on a duplicate of a\n * committed key, `SERVICE_UNAVAILABLE` on one still in flight.\n * 4. Calls `app.do(name, { stream, actor: ctx.actor }, input)`.\n * 5. Maps any thrown framework error onto a `TRPCError` via\n * {@link toApiError}.\n *\n * The router is typed from `TApp`: each mutation takes its action's\n * payload and returns the `Snapshot[]` `app.do` returns, and with `sse`\n * each `subscribe.<state>` yields that state's frames, so a client sees\n * `client.PressKey.mutate({ key: \"5\" })` as a typed call without\n * codegen. Pass `TApp` whenever you pass `Ctx`.\n *\n * @template Ctx The tRPC context shape the host's runtime feeds in.\n * Flows through `actor`, `stream`, and `idempotency.keyFrom` so\n * the operator's existing context types just work. The internal\n * middleware augments `Ctx` with `{ actor: Actor }` on the\n * downstream procedure context.\n *\n * @param app A built `Act` orchestrator.\n * @param options Auth, stream, and (optional) idempotency seams.\n * @returns A tRPC router with one mutation per registered action.\n */\nexport function trpc<\n Ctx extends object = object,\n TApp extends ActSurface = ActSurface,\n>(\n app: TApp,\n options: TrpcOptions<Ctx, TApp> & { readonly sse: SseOptions }\n): GeneratedRouter<Ctx, TApp, SubscribeRouter<TApp>>;\nexport function trpc<\n Ctx extends object = object,\n TApp extends ActSurface = ActSurface,\n>(\n app: TApp,\n options: TrpcOptions<Ctx, TApp>\n): GeneratedRouter<Ctx, TApp, unknown>;\nexport function trpc<Ctx extends object, TApp extends ActSurface>(\n app: TApp,\n options: TrpcOptions<Ctx>\n): unknown {\n const t = initTRPC.context<Ctx>().create();\n const dispatch = make_dispatch<Ctx>(app, options, options.idempotency?.store);\n\n // Resolve the actor inline per mutation instead of via\n // `t.procedure.use(authenticated(...))`. The middleware path threads\n // tRPC's internal `Unwrap` type into each procedure's inferred shape,\n // which the d.ts emitter can't name portably (`unstable-core-do-not-\n // import` has a hashed file name that varies per build). Inlining\n // sidesteps the issue entirely — the standalone `authenticated`\n // export still works for hosts who want middleware composition.\n /**\n * Run the actor extractor for a generated procedure, mapping a\n * \"throw to deny\" onto `UNAUTHORIZED` rather than a framework 500.\n *\n * Shared by mutations and subscriptions, so a denied caller gets\n * neither a mutation nor a live subscription.\n */\n const resolve_actor = async (host_ctx: Ctx): Promise<Actor> => {\n try {\n return await options.actor(host_ctx);\n } catch (err) {\n throw new TRPCError({\n code: \"UNAUTHORIZED\",\n message: err instanceof Error ? err.message : undefined,\n cause: err instanceof Error ? err : undefined,\n });\n }\n };\n\n const handlers: Record<\n string,\n ReturnType<ReturnType<typeof t.procedure.input>[\"mutation\"]>\n > = {};\n for (const [action_name, state] of Object.entries(app.registry.actions)) {\n const action_schema = state.actions[action_name];\n handlers[action_name] = t.procedure\n // Passthrough parser: tRPC's own `.input()` validation is deliberately\n // bypassed because a Zod failure there surfaces as a hardcoded\n // BAD_REQUEST (400) that never reaches `to_trpc_error`. Validation runs\n // in the resolver (below) instead, so a malformed body maps to the SAME\n // 422 / ApiError a `ValidationError` thrown inside `app.do` produces,\n // as Hono and OpenAPI do.\n .input((raw: unknown) => raw)\n .mutation(async ({ input, ctx }) => {\n const host_ctx = ctx as unknown as Ctx;\n // Resolve the actor first, mirroring Hono's `authenticated` middleware:\n // a \"throw to deny\" from the extractor is 401 UNAUTHORIZED, not a 500.\n // The actor step is auth — distinct from a framework error inside\n // `app.do`, which the main try below maps via `to_trpc_error`.\n const actor: Actor = await resolve_actor(host_ctx);\n try {\n // Validate the payload before the stream / expectedVersion resolvers\n // see it, mirroring Hono's zValidator-then-handler order. `validate`\n // throws the framework `ValidationError`, which `to_trpc_error` maps\n // to 422 / UNPROCESSABLE_CONTENT with the shared ApiError envelope.\n // The resolvers get the parsed value, but `app.do` gets the\n // raw `input`: it parses again itself, and a second parse of the\n // output would run every `.transform()` twice.\n const validated = validate(\n action_name,\n input as never,\n action_schema as never\n );\n const outcome = await dispatch(\n action_name,\n validated,\n input,\n host_ctx,\n actor,\n () => options.idempotency?.keyFrom(host_ctx)\n );\n if (outcome.kind === \"done\") return outcome.result;\n throw new TRPCError(\n outcome.kind === \"missing-key\"\n ? { code: \"BAD_REQUEST\", message: \"Idempotency-Key required\" }\n : outcome.kind === \"in-flight\"\n ? {\n code: \"SERVICE_UNAVAILABLE\",\n message:\n \"Idempotency-Key in flight; the original request has not finished, retry later\",\n }\n : {\n code: \"CONFLICT\",\n message:\n \"Idempotency-Key already used; original result not cached\",\n }\n );\n } catch (err) {\n if (err instanceof TRPCError) throw err;\n throw to_trpc_error(err);\n }\n });\n }\n\n if (options.sse) {\n // SSE subscriptions mount under the `subscribe` key of the same router\n // as the action mutations, so an action named `subscribe` would be\n // silently replaced. Refuse it at generation instead.\n if (\"subscribe\" in app.registry.actions)\n throw new Error(\n 'trpc: an action named \"subscribe\" collides with the SSE subscription router (router.subscribe.<stateName>); rename the action or generate the router without `sse`.'\n );\n const sse_config = resolveSseConfig(options.sse);\n const sse_counter = new SseConnectionCounter(sse_config.maxConnections);\n const state_names = new Set(\n Object.values(app.registry.actions).map((a) => a.name)\n );\n const sse_handlers: Record<string, unknown> = {};\n for (const state_name of state_names) {\n sse_handlers[state_name] = t.procedure\n .input(z.object({ stream: z.string().min(1) }))\n .subscription(async function* ({ input, ctx, signal }) {\n // Step 1 of the documented subscription contract: the actor\n // extractor runs before a slot is taken or a frame is yielded,\n // so a denying extractor denies the open. Hono gets this from\n // the `authenticated` middleware it mounts across `/api/*`;\n // this generator is where the same rule lives for tRPC, which\n // resolves the actor inline rather than through middleware.\n await resolve_actor(ctx as unknown as Ctx);\n yield* runSseSubscription(\n sse_config.channel,\n input.stream,\n sse_counter,\n signal,\n {\n maxPending: sse_config.maxPendingPerConnection,\n on_cap_exceeded: () => {\n throw new TRPCError({\n code: \"TOO_MANY_REQUESTS\",\n message: \"max concurrent SSE subscriptions reached\",\n });\n },\n }\n );\n });\n }\n handlers.subscribe = t.router(sse_handlers as never) as never;\n }\n\n // Built in a loop over the registry, so its type is the overloads'.\n return t.router(handlers);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,SAAqB,gBAAgB;AAErC;AAAA,EACE;AAAA,EAGA;AAAA,OAIK;AAsHA,SAAS,cACd,WACwE;AACxE,SAAO,OAAO,EAAE,KAAK,KAAK,MAAM;AAG9B,UAAM,QAAQ,MAAM,UAAU,GAAqB;AACnD,WAAO,KAAK,EAAE,KAAK,EAAE,GAAG,KAAK,MAAM,EAAE,CAAC;AAAA,EACxC;AACF;AAcA,SAAS,cAAc,KAAyB;AAC9C,QAAM,EAAE,QAAQ,KAAK,IAAI,WAAW,GAAG;AACvC,QAAM,OAAO,oBAAoB,MAAM;AACvC,SAAO,IAAI,UAAU;AAAA,IACnB;AAAA,IACA,SAAS,KAAK,UAAU,KAAK;AAAA,IAC7B,OAAO,eAAe,QAAQ,MAAM;AAAA,EACtC,CAAC;AACH;AASA,SAAS,oBAAoB,QAAmC;AAC9D,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAKH,aAAO;AAAA,IACT,KAAK;AAIH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AA4FO,SAAS,KACd,KACA,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AAA,IACF,CAAC;AAAA,EACL;AAEA,MAAI,QAAQ,KAAK;AAIf,QAAI,eAAe,IAAI,SAAS;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AACF,UAAM,aAAa,iBAAiB,QAAQ,GAAG;AAC/C,UAAM,cAAc,IAAI,qBAAqB,WAAW,cAAc;AACtE,UAAM,cAAc,IAAI;AAAA,MACtB,OAAO,OAAO,IAAI,SAAS,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,IACvD;AACA,UAAM,eAAwC,CAAC;AAC/C,eAAW,cAAc,aAAa;AACpC,mBAAa,UAAU,IAAI,EAAE,UAC1B,MAAM,iBAAE,OAAO,EAAE,QAAQ,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,EAC7C,aAAa,iBAAiB,EAAE,OAAO,KAAK,OAAO,GAAG;AAOrD,cAAM,cAAc,GAAqB;AACzC,eAAO;AAAA,UACL,WAAW;AAAA,UACX,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA;AAAA,YACE,YAAY,WAAW;AAAA,YACvB,iBAAiB,MAAM;AACrB,oBAAM,IAAI,UAAU;AAAA,gBAClB,MAAM;AAAA,gBACN,SAAS;AAAA,cACX,CAAC;AAAA,YACH;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACL;AACA,aAAS,YAAY,EAAE,OAAO,YAAqB;AAAA,EACrD;AAGA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rotorsoft/act-http",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.12.0",
|
|
5
5
|
"description": "HTTP integrations for act apps — webhooks and SSE",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"typescript",
|
|
@@ -91,7 +91,7 @@
|
|
|
91
91
|
},
|
|
92
92
|
"peerDependencies": {
|
|
93
93
|
"@hono/node-server": "^2.1.5",
|
|
94
|
-
"@rotorsoft/act": "^1.
|
|
94
|
+
"@rotorsoft/act": "^1.36.0",
|
|
95
95
|
"@rotorsoft/act-ops": "^0.2.11",
|
|
96
96
|
"@trpc/server": ">=11.19.0",
|
|
97
97
|
"express": "^5.3.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/errors.ts","../src/api/idempotency.ts","../src/api/sse-wiring.ts"],"sourcesContent":["import {\n ConcurrencyError,\n InvariantError,\n NonRetryableError,\n PreconditionError,\n StreamClosedError,\n ValidationError,\n} from \"@rotorsoft/act\";\n\n/**\n * Uniform error envelope shipped over the wire by every act-http\n * transport. Hosts get the same shape from REST, tRPC, and OpenAPI —\n * a client that talks to two transports doesn't have to invent two\n * error parsers.\n *\n * - `error` — the framework error name (`\"ValidationError\"`,\n * `\"PreconditionError\"`, …). Stable identifier, safe to switch on.\n * - `detail` — the framework's message text. Human-readable; not\n * parsed by clients.\n * - `code` — a machine-readable status code from {@link ERROR_MAP}\n * for clients that prefer enum-style branching over name strings.\n */\nexport type ApiError = {\n error: string;\n detail?: string;\n code?: string;\n};\n\n/**\n * Status + code pair for one known framework error.\n */\nexport type ErrorMapEntry = {\n status: number;\n code: string;\n};\n\n/**\n * The single table that maps framework error types to HTTP status\n * codes and machine-readable codes. One table, three consumers\n * (Hono, tRPC, OpenAPI) — cross-transport consistency by\n * construction.\n *\n * Operators wanting different mappings wrap the generated transport\n * rather than mutating this — the consistency is the load-bearing\n * property, not the specific status codes.\n */\nexport const ERROR_MAP = {\n ValidationError: { status: 422, code: \"VALIDATION\" },\n PreconditionError: { status: 409, code: \"PRECONDITION\" },\n /** @deprecated Thrown only by the deprecated `.given` rules. Removed in 2.0. */\n InvariantError: { status: 409, code: \"INVARIANT\" },\n ConcurrencyError: { status: 412, code: \"CONCURRENCY\" },\n StreamClosedError: { status: 410, code: \"STREAM_CLOSED\" },\n NonRetryableError: { status: 400, code: \"NON_RETRYABLE\" },\n} as const satisfies Record<string, ErrorMapEntry>;\n\nconst lookup_known = (\n err: unknown\n): { name: keyof typeof ERROR_MAP } | null => {\n if (err instanceof ValidationError) return { name: \"ValidationError\" };\n // Before `InvariantError`, which it extends.\n if (err instanceof PreconditionError) return { name: \"PreconditionError\" };\n if (err instanceof InvariantError) return { name: \"InvariantError\" };\n if (err instanceof ConcurrencyError) return { name: \"ConcurrencyError\" };\n if (err instanceof StreamClosedError) return { name: \"StreamClosedError\" };\n if (err instanceof NonRetryableError) return { name: \"NonRetryableError\" };\n return null;\n};\n\n/**\n * Translate an unknown thrown value into the canonical\n * {@link ApiError} envelope plus HTTP status. Each transport's error\n * boundary calls this once and forwards the result to the wire.\n *\n * Known framework errors map per {@link ERROR_MAP}. Everything else\n * surfaces as a 500 with `code: \"INTERNAL\"`; the `detail` field is\n * populated when the throw was an `Error` instance, omitted\n * otherwise (a thrown string or object doesn't get to leak its\n * payload to the client).\n */\nexport function toApiError(err: unknown): { status: number; body: ApiError } {\n const known = lookup_known(err);\n if (known) {\n const entry = ERROR_MAP[known.name];\n return {\n status: entry.status,\n body: {\n error: known.name,\n detail: (err as Error).message,\n code: entry.code,\n },\n };\n }\n if (err instanceof Error) {\n return {\n status: 500,\n body: { error: \"InternalError\", detail: err.message, code: \"INTERNAL\" },\n };\n }\n return {\n status: 500,\n body: { error: \"InternalError\", code: \"INTERNAL\" },\n };\n}\n","import type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\n\n/**\n * Result of a {@link withIdempotency} call.\n *\n * - `{ deduped: false, result }` — the claim was fresh; the handler\n * ran and produced `result`.\n * - `{ deduped: true }` — the claim was already taken; the handler\n * was *not* invoked. The caller decides how to respond (typically\n * a 2xx with no body, matching the receiver-side convention).\n *\n * Note: the contract does not cache the previous response. A\n * duplicate call returns the deduped marker only — replaying the\n * original handler's output would require a response-caching\n * adapter, which is out of scope here. The receiver-side convention\n * (and the convention the generated transports follow) is \"ack the\n * duplicate; do nothing else.\"\n */\nexport type IdempotencyResult<T> =\n | { deduped: false; result: T }\n | { deduped: true };\n\n/**\n * Wrap an action handler so the framework honors `Idempotency-Key`\n * dedup. Acquires the key via {@link IdempotencyStore.claim} (a\n * *tentative* reservation), runs the handler exactly when the claim\n * was fresh, and skips the handler entirely on a duplicate.\n *\n * The claim is finalized two-phase: on handler success the key is\n * {@link IdempotencyStore.commit committed} so later retries dedup;\n * on handler failure it is {@link IdempotencyStore.release released}\n * and the rejection re-thrown, so the sender's retry re-processes\n * instead of the delivery being permanently dropped. The tentative\n * claim still dedups a concurrent duplicate mid-flight.\n *\n * Reuses the contract `@rotorsoft/act-ops/idempotency` already\n * defines for the receiver-side `Idempotency-Key` story. A single\n * `IdempotencyStore` implementation covers both halves of the \"Act\n * over the wire\" surface — receiver and generated API.\n */\nexport async function withIdempotency<T>(\n store: IdempotencyStore,\n key: string,\n handler: () => Promise<T>\n): Promise<IdempotencyResult<T>> {\n const fresh = await store.claim(key);\n if (!fresh) {\n return { deduped: true };\n }\n let result: T;\n try {\n result = await handler();\n } catch (err) {\n await store.release(key);\n throw err;\n }\n await store.commit(key);\n return { deduped: false, result };\n}\n","import { z } from \"zod\";\nimport type { BroadcastChannel } from \"../sse/broadcast.js\";\nimport {\n type BroadcastState,\n is_version_neutral,\n type PatchMessage,\n resync_frame,\n} from \"../sse/types.js\";\n\n/**\n * SSE wiring options shared by the auto-generated `trpc` and `hono`\n * transports. When supplied, each transport emits one streaming\n * subscription per registered state name, all reading from the same\n * host-supplied {@link BroadcastChannel}.\n *\n * The host owns publication: every `app.do(...)` call site must\n * forward the resulting snapshots to `channel.publish(...)` for\n * subscribers to see updates. The framework deliberately doesn't\n * auto-publish because the derived state usually needs app-specific\n * overlays (presence, computed fields) that only the host can supply.\n *\n * Defaults are sized for typical business-app dashboards (dozens to\n * hundreds of human viewers per process). Both numeric knobs are\n * validated at transport-function construction; out-of-range values\n * throw `ZodError` immediately so misconfiguration surfaces at startup\n * instead of at first connection (the framework-wide convention for\n * config bags — see .claude/rules/config-validation.md).\n */\nexport type SseOptions = {\n /**\n * The {@link BroadcastChannel} the generator's subscriptions hook\n * into. Host owns its lifecycle; the generator does not construct\n * one for you because the channel's `<S>` shape is app-specific and\n * passing it in keeps the type chain typed end-to-end at the host.\n */\n // `any`: the channel's BroadcastState shape is opaque to the generator — narrowing it would force every state into one structural bound that doesn't fit real apps\n readonly channel: BroadcastChannel<any>;\n /**\n * Hard cap on concurrent open subscriptions per generator\n * instance. The 501st simultaneous open returns `503` (Hono) or\n * throws `TOO_MANY_REQUESTS` (tRPC) — never a silent stall.\n *\n * Default `500`. Validated range `[1, 10_000]`. Above 10k the\n * framework refuses to construct: at that point the FD ceiling\n * and per-connection memory force horizontal scaling regardless\n * of tuning, so the right move is sticky LB + per-process cap,\n * not a higher single-process limit.\n */\n readonly maxConnections?: number;\n /**\n * Keep-alive cadence in milliseconds. Most reverse proxies idle\n * connections out after ~60 seconds; the default `30_000` stays\n * comfortably under.\n *\n * Validated range `[15_000, 300_000]`. Under 15 s wastes\n * bandwidth on a business workload; over 5 min risks proxy drops.\n */\n readonly heartbeatMs?: number;\n /**\n * Hard cap on the per-connection in-memory backlog of undelivered\n * broadcast frames. A consumer that stalls (slow client, paused\n * tab) can't drain frames as fast as a busy stream publishes them;\n * without a bound the backlog grows until the process runs out of\n * memory. When the backlog is full the oldest **version-keyed** frame\n * is dropped to make room for the newest: the consumer sees the\n * version gap, reports `behind`, and refetches, so it still converges\n * on current state having skipped intermediate versions it was too\n * slow to see.\n *\n * Version-neutral frames (`_overlay`, `_resync`) are never dropped\n * silently — they create no gap to notice, so a backlog made only of\n * them collapses into a single `_resync` instead.\n *\n * Default `256`. Validated range `[1, 100_000]`.\n */\n readonly maxPendingPerConnection?: number;\n};\n\n/**\n * Resolved SSE configuration after validation and default expansion.\n * Internal — the resolved values are what every transport actually\n * runs against.\n *\n * @internal\n */\nexport type SseConfig = {\n readonly channel: BroadcastChannel<BroadcastState>;\n readonly maxConnections: number;\n readonly heartbeatMs: number;\n readonly maxPendingPerConnection: number;\n};\n\n/**\n * Default cap on concurrent open subscriptions per generator\n * instance. Sized for typical business-app dashboards (dozens to a\n * few hundred viewers); high enough not to surprise small\n * deployments, low enough not to mask a missing horizontal-scale\n * strategy on big ones.\n */\nexport const DEFAULT_SSE_MAX_CONNECTIONS = 500;\n\n/**\n * Default keep-alive cadence (30 s). Sits comfortably under the\n * 60 s idle timeout most reverse proxies impose.\n */\nexport const DEFAULT_SSE_HEARTBEAT_MS = 30_000;\n\n/**\n * Default cap on the per-connection undelivered-frame backlog. Sized\n * so a briefly-stalled consumer on a busy stream keeps recent history\n * without letting a permanently-wedged client pin unbounded memory.\n * At overflow the oldest version-keyed frame is dropped: it is a full\n * version-keyed patch, so the consumer sees the gap and converges on\n * current state regardless of which intermediate versions it missed.\n * Version-neutral frames create no gap, so they collapse into a\n * `_resync` rather than being dropped silently.\n */\nexport const DEFAULT_SSE_MAX_PENDING_PER_CONNECTION = 256;\n\n/**\n * Zod schema for the numeric knobs on {@link SseOptions}. Defaults,\n * ranges, and (eventual) integer constraints live in one place — same\n * declarative-validation pattern the rest of the framework uses for\n * configuration shapes.\n *\n * @internal\n */\nconst SseOptionsSchema = z.object({\n maxConnections: z\n .number()\n .int()\n .min(1)\n .max(10_000)\n .default(DEFAULT_SSE_MAX_CONNECTIONS),\n heartbeatMs: z\n .number()\n .int()\n .min(15_000)\n .max(300_000)\n .default(DEFAULT_SSE_HEARTBEAT_MS),\n maxPendingPerConnection: z\n .number()\n .int()\n .min(1)\n .max(100_000)\n .default(DEFAULT_SSE_MAX_PENDING_PER_CONNECTION),\n});\n\n/**\n * Validate and apply defaults to host-supplied {@link SseOptions}.\n *\n * Out-of-range values throw at the call site — each transport calls\n * this once at the start of `hono(...)` / `trpc(...)` so\n * misconfiguration surfaces at construction, not at first\n * connection.\n */\nexport function resolveSseConfig(options: SseOptions): SseConfig {\n const parsed = SseOptionsSchema.parse({\n maxConnections: options.maxConnections,\n heartbeatMs: options.heartbeatMs,\n maxPendingPerConnection: options.maxPendingPerConnection,\n });\n return {\n channel: options.channel,\n maxConnections: parsed.maxConnections,\n heartbeatMs: parsed.heartbeatMs,\n maxPendingPerConnection: parsed.maxPendingPerConnection,\n };\n}\n\n/**\n * Per-generator concurrent-open counter. Constructed once inside\n * `hono(...)` / `trpc(...)` and consulted at every subscription\n * open: failure to acquire means the cap has been hit and the\n * transport reports `503` / `TOO_MANY_REQUESTS` to the caller.\n *\n * The counter is intentionally process-local. SSE doesn't multiplex\n * across processes; operators wanting more than `maxConnections`\n * viewers run multiple processes behind a sticky load balancer.\n */\nexport class SseConnectionCounter {\n public readonly limit: number;\n private _open = 0;\n\n constructor(limit: number) {\n this.limit = limit;\n }\n\n /**\n * Reserve one slot. Returns `true` when accepted (caller must\n * eventually {@link release} the slot, even on error paths) or\n * `false` when the cap is already reached.\n */\n acquire(): boolean {\n if (this._open >= this.limit) return false;\n this._open++;\n return true;\n }\n\n /**\n * Free a previously-{@link acquire}d slot. Always runs from a\n * `finally` block in the transport's subscription handler so\n * crashed handlers don't leak count.\n */\n release(): void {\n if (this._open > 0) this._open--;\n }\n\n /** Currently-open count. Test/observability hook. */\n get open(): number {\n return this._open;\n }\n}\n\n/**\n * Wrap a fire-and-forget Promise-returning operation so its\n * rejection is swallowed in place of leaking an unhandled\n * rejection. Used by the Hono heartbeat tick (the interval callback\n * isn't `await`ed, so its rejection has nowhere to go) and by any\n * other \"best-effort write\" the transports run.\n *\n * Pure: same input → same output, no side effects on the caller.\n * Returns the chained Promise so the caller can also `await`\n * completion if they want to (the Hono heartbeat doesn't).\n */\nexport function fireAndForget<T>(op: () => Promise<T>): Promise<T | undefined> {\n return op().catch(() => undefined);\n}\n\n/**\n * Frame yielded by the per-state SSE subscription generator. The\n * initial cached state (when present) arrives as `kind: \"state\"`;\n * every subsequent broadcast publication arrives as `kind: \"patch\"`\n * with the channel's `PatchMessage` payload.\n */\nexport type SseSubscriptionFrame<S> =\n | { readonly kind: \"state\"; readonly data: S }\n | { readonly kind: \"patch\"; readonly data: unknown };\n\n/**\n * Subscription accounting hook. Implementations have a chance to\n * acquire a slot before the loop starts and to release it once the\n * loop's `finally` block runs — used by the tRPC side to enforce\n * `maxConnections` from inside the generator, where it can throw\n * `TRPCError` cleanly. Hono enforces the cap outside the loop (so a\n * full counter returns `503` *before* streamSSE writes headers), then\n * passes `undefined` here.\n */\nexport type SseAccounting = {\n acquire(): boolean;\n release(): void;\n};\n\n/**\n * Per-subscription knobs for {@link runSseSubscription}, bundled so the\n * two transports (and their tests) pass one options object rather than\n * a growing positional tail.\n */\nexport type RunSseOptions = {\n /**\n * Invoked when {@link SseAccounting.acquire} returns `false` (the\n * connection cap is full). tRPC throws `TRPCError` here to reject the\n * subscription cleanly from inside the generator; Hono enforces the\n * cap outside the loop and omits this.\n */\n readonly on_cap_exceeded?: () => never;\n /**\n * Upper bound on the per-connection undelivered-frame backlog. When\n * the backlog reaches this many frames the oldest is dropped to make\n * room for the newest (drop-oldest). Defaults to\n * {@link DEFAULT_SSE_MAX_PENDING_PER_CONNECTION} when omitted.\n */\n readonly maxPending?: number;\n};\n\n/**\n * The shared subscription loop both transports run. Optionally\n * acquires one slot on the supplied {@link SseAccounting}, yields the\n * cached state (when present), then forwards every channel\n * publication as a `kind: \"patch\"` frame until either the consumer\n * breaks (calling `iter.return()`) or the supplied abort signal fires.\n *\n * Exported as the testable seam — the Hono and tRPC sibling\n * generators wrap this so the signal-driven cleanup and counter\n * accounting live in one place.\n */\n// `any`: the channel's BroadcastState shape is opaque to the loop — narrowing it would force every state into one structural bound that doesn't fit real apps\nexport async function* runSseSubscription<S extends { _v: number } = any>(\n channel: BroadcastChannel<S>,\n stream_id: string,\n accounting: SseAccounting | undefined,\n signal: AbortSignal | undefined,\n options?: RunSseOptions\n): AsyncGenerator<SseSubscriptionFrame<S>> {\n // Track whether we actually reserved a slot. Releasing in `finally`\n // unconditionally would decrement the counter below the true open\n // count when acquire() fails without an `on_cap_exceeded` handler —\n // inflating the effective cap over time. Only release what we\n // acquired.\n let acquired = false;\n if (accounting) {\n acquired = accounting.acquire();\n if (!acquired && options?.on_cap_exceeded) {\n options.on_cap_exceeded();\n }\n }\n const max_pending =\n options?.maxPending ?? DEFAULT_SSE_MAX_PENDING_PER_CONNECTION;\n const pending: unknown[] = [];\n let resolve_wait: (() => void) | null = null;\n const unsubscribe = channel.subscribe(stream_id, (msg) => {\n enqueue(msg as PatchMessage<never>);\n resolve_wait?.();\n });\n /**\n * Bound the per-connection backlog: a stalled consumer (slow client,\n * paused tab) can't drain as fast as a busy stream publishes, so a frame\n * has to go.\n *\n * Which frame is not arbitrary. A version-keyed patch can be dropped\n * safely — the client sees the version gap, reports `behind`, and\n * refetches. A version-neutral frame (`_overlay`, `_resync`) carries no\n * versions at all, so dropping one leaves no gap to notice and the update\n * is lost silently. So: evict the oldest version-keyed frame if\n * there is one, and only if the whole backlog is version-neutral collapse\n * it into the single frame that says \"you missed something\".\n */\n const enqueue = (msg: PatchMessage<never>) => {\n if (pending.length < max_pending) {\n pending.push(msg);\n return;\n }\n const versioned = pending.findIndex(\n (m) => !is_version_neutral(m as PatchMessage<never>)\n );\n if (versioned >= 0) {\n pending.splice(versioned, 1);\n pending.push(msg);\n return;\n }\n // Every pending frame is version-neutral. Collapsing them into one\n // resync loses no signal — a resync supersedes anything it replaces,\n // including `msg` when the cap leaves no room for it.\n pending.splice(0, pending.length, resync_frame());\n if (pending.length < max_pending) pending.push(msg);\n };\n\n const on_abort = () => resolve_wait?.();\n signal?.addEventListener(\"abort\", on_abort);\n try {\n const cached = channel.state(stream_id);\n if (cached !== undefined) {\n yield { kind: \"state\", data: cached };\n }\n while (!signal?.aborted) {\n if (pending.length === 0) {\n await new Promise<void>((resolve) => {\n resolve_wait = resolve;\n });\n if (signal?.aborted) break;\n }\n const msg = pending.shift();\n yield { kind: \"patch\", data: msg };\n }\n } finally {\n signal?.removeEventListener(\"abort\", on_abort);\n unsubscribe();\n if (acquired) accounting?.release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,MAAI;AACF,UAAM,SAAS,QAAQ,MAAM,SAAS;AACtC,QAAI,WAAW,QAAW;AACxB,YAAM,EAAE,MAAM,SAAS,MAAM,OAAO;AAAA,IACtC;AACA,WAAO,CAAC,QAAQ,SAAS;AACvB,UAAI,QAAQ,WAAW,GAAG;AACxB,cAAM,IAAI,QAAc,CAAC,YAAY;AACnC,yBAAe;AAAA,QACjB,CAAC;AACD,YAAI,QAAQ,QAAS;AAAA,MACvB;AACA,YAAM,MAAM,QAAQ,MAAM;AAC1B,YAAM,EAAE,MAAM,SAAS,MAAM,IAAI;AAAA,IACnC;AAAA,EACF,UAAE;AACA,YAAQ,oBAAoB,SAAS,QAAQ;AAC7C,gBAAY;AACZ,QAAI,SAAU,aAAY,QAAQ;AAAA,EACpC;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/dispatch.ts"],"sourcesContent":["import type { Actor, Target } from \"@rotorsoft/act\";\nimport type { IdempotencyStore } from \"@rotorsoft/act-ops/idempotency\";\nimport { withIdempotency } from \"./idempotency.js\";\nimport { track_in_flight } from \"./in-flight.js\";\n\n/**\n * The Act surface the generated transports walk: the registry's action\n * name → owning-state map and `do(...)`. A structural bound lets `TApp`\n * infer to the caller's concrete `Act<...>` without leaking the variance of\n * its nested types, and without `any`.\n */\nexport type 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\n/** The target resolvers a generated transport takes, over its own context. */\ntype TargetResolvers<C> = {\n readonly stream: (\n action_name: string,\n input: unknown,\n ctx: C\n ) => string | Promise<string>;\n readonly expectedVersion?: (\n action_name: string,\n input: unknown,\n ctx: C\n ) => number | undefined | Promise<number | undefined>;\n};\n\n/** What one generated action call came to; each transport maps the refusals. */\nexport type Dispatched =\n | { kind: \"done\"; result: unknown }\n | { kind: \"missing-key\" }\n | { kind: \"in-flight\" }\n | { kind: \"conflict\" };\n\n/**\n * One generated action call: resolve the target from the validated input,\n * then run `app.do` on the raw payload (it parses again itself, and a second\n * parse of the parsed value would run every `.transform()` twice), under\n * `Idempotency-Key` dedup when a store is set. A duplicate of a key still\n * running is `in-flight`, since the original may yet fail and release it;\n * one already committed is `conflict`.\n */\nexport function make_dispatch<C>(\n app: ActSurface,\n resolvers: TargetResolvers<C>,\n store: IdempotencyStore | undefined\n) {\n // Counts claims per key, to tell the two kinds of duplicate apart.\n const tracker = store && track_in_flight(store);\n return async (\n action_name: string,\n input: unknown,\n payload: unknown,\n ctx: C,\n actor: Actor,\n key: () => string | undefined\n ): Promise<Dispatched> => {\n const stream = await resolvers.stream(action_name, input, ctx);\n const expected = await resolvers.expectedVersion?.(action_name, input, ctx);\n const target =\n expected === undefined\n ? { stream, actor }\n : { stream, actor, expectedVersion: expected };\n const run = () => app.do(action_name, target, payload);\n if (!tracker) return { kind: \"done\", result: await run() };\n const k = key();\n if (!k) return { kind: \"missing-key\" };\n const outcome = await withIdempotency(tracker.store, k, run);\n if (!outcome.deduped) return { kind: \"done\", result: outcome.result };\n return { kind: tracker.in_flight(k) ? \"in-flight\" : \"conflict\" };\n };\n}\n"],"mappings":";;;;;;;;AAqDO,SAAS,cACd,KACA,WACA,OACA;AAEA,QAAM,UAAU,SAAS,gBAAgB,KAAK;AAC9C,SAAO,OACL,aACA,OACA,SACA,KACA,OACA,QACwB;AACxB,UAAM,SAAS,MAAM,UAAU,OAAO,aAAa,OAAO,GAAG;AAC7D,UAAM,WAAW,MAAM,UAAU,kBAAkB,aAAa,OAAO,GAAG;AAC1E,UAAM,SACJ,aAAa,SACT,EAAE,QAAQ,MAAM,IAChB,EAAE,QAAQ,OAAO,iBAAiB,SAAS;AACjD,UAAM,MAAM,MAAM,IAAI,GAAG,aAAa,QAAQ,OAAO;AACrD,QAAI,CAAC,QAAS,QAAO,EAAE,MAAM,QAAQ,QAAQ,MAAM,IAAI,EAAE;AACzD,UAAM,IAAI,IAAI;AACd,QAAI,CAAC,EAAG,QAAO,EAAE,MAAM,cAAc;AACrC,UAAM,UAAU,MAAM,gBAAgB,QAAQ,OAAO,GAAG,GAAG;AAC3D,QAAI,CAAC,QAAQ,QAAS,QAAO,EAAE,MAAM,QAAQ,QAAQ,QAAQ,OAAO;AACpE,WAAO,EAAE,MAAM,QAAQ,UAAU,CAAC,IAAI,cAAc,WAAW;AAAA,EACjE;AACF;","names":[]}
|