@dreamboard-games/sdk 0.5.0-alpha.35 → 0.5.0-alpha.37

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/protocol/protocol.ts","../src/shared/protocol/compact-frame.ts","../src/shared/protocol/schema.ts","../src/headless/sources/static.ts","../src/shared/protocol/players.ts","../src/shared/protocol/digest.ts","../src/shared/protocol/projection.ts","../src/headless/sources/lifecycle.ts"],"sourcesContent":["import type {\n GameplayBasis,\n InteractionDescriptor,\n PluginGameplayFrame,\n PluginSessionDescriptor,\n} from \"./frame.js\";\nimport type { RuntimeJson } from \"../runtime-json.js\";\nimport type { CompactGameplayFrame } from \"./compact-frame.js\";\n\nexport const DREAMBOARD_PLUGIN_PROTOCOL = \"dreamboard-plugin\" as const;\nexport const DREAMBOARD_PLUGIN_PROTOCOL_VERSION = 11 as const;\n\nexport type InteractionResult =\n | {\n readonly clientActionId: string;\n readonly accepted: true;\n }\n | {\n readonly type: \"interaction.result\";\n readonly clientActionId: string;\n readonly accepted: false;\n readonly errorCode: string;\n readonly message?: string;\n };\n\nexport interface SubmitInteractionCommand {\n readonly type: \"interaction.submit\";\n readonly clientActionId: string;\n readonly basis: GameplayBasis;\n readonly interactionId: string;\n readonly params: RuntimeJson;\n}\n\nexport interface CancelInteractionCommand {\n readonly type: \"interaction.cancel\";\n readonly clientActionId: string;\n readonly basis: GameplayBasis;\n readonly interactionId: string;\n}\n\nexport type HostToPluginPayload =\n | {\n readonly type: \"runtime.init\";\n readonly session: PluginSessionDescriptor;\n }\n | {\n readonly type: \"gameplay.frame\";\n readonly frame: PluginGameplayFrame;\n /** Confirms a durable action covered by this frame. Independent of causedBy. */\n readonly acknowledgedClientActionId?: string;\n }\n | {\n readonly type: \"gameplay.compact-frame\";\n readonly frame: CompactGameplayFrame;\n readonly acknowledgedClientActionId?: string;\n }\n | Extract<InteractionResult, { accepted: false }>;\n\nexport type PluginToHostPayload =\n | { readonly type: \"runtime.ready\" }\n | {\n readonly type: \"runtime.capabilities\";\n readonly compactGameplayFrames: true;\n }\n | { readonly type: \"runtime.resume\"; readonly pendingClientActionId?: string }\n | {\n readonly type: \"runtime.ack\";\n /** Echoes the host envelope sequence. It is delivery order only. */\n readonly sequence: number;\n readonly clientReceivedAtMs?: number;\n readonly clientRenderedAtMs?: number;\n }\n | SubmitInteractionCommand\n | CancelInteractionCommand\n | {\n readonly type: \"runtime.error\";\n readonly message: string;\n readonly code?: string;\n };\n\nexport interface PluginProtocolEnvelope<Payload> {\n readonly protocol: typeof DREAMBOARD_PLUGIN_PROTOCOL;\n readonly version: typeof DREAMBOARD_PLUGIN_PROTOCOL_VERSION;\n readonly channelId: string;\n /** Delivery order only. It is not a game revision. */\n readonly sequence: number;\n readonly payload: Payload;\n}\n\nexport type HostToPluginEnvelope = PluginProtocolEnvelope<HostToPluginPayload>;\nexport type PluginToHostEnvelope = PluginProtocolEnvelope<PluginToHostPayload>;\n\nexport type ActionSetVersionInput = {\n readonly version: number;\n readonly availableInteractions: readonly InteractionDescriptor[];\n};\n","import type { ZoneInteractionRefs } from \"../interaction-schema.js\";\nimport type { InteractionDescriptor, PluginGameplayFrame } from \"./frame.js\";\n\n/** Self-contained hosted snapshot. References are local to this frame. */\nexport type CompactGameplayFrame = Omit<\n PluginGameplayFrame,\n \"availableInteractions\" | \"zones\"\n> & {\n readonly interactionsByRef: Readonly<Record<string, InteractionDescriptor>>;\n readonly availableInteractionRefs: readonly string[];\n readonly zones: Readonly<\n Record<string, Readonly<Record<string, ZoneInteractionRefs>>>\n >;\n};\n\n/** Traverses references without reparsing descriptors for every card. */\nexport function visitInteractionRefs(\n frame: Pick<CompactGameplayFrame, \"availableInteractionRefs\" | \"zones\">,\n visit: (ref: string, path: (string | number)[]) => void,\n): void {\n frame.availableInteractionRefs.forEach((ref, index) =>\n visit(ref, [\"availableInteractionRefs\", index]),\n );\n for (const [zoneId, hosts] of Object.entries(frame.zones)) {\n for (const [hostId, zone] of Object.entries(hosts)) {\n for (const [cardId, refs] of Object.entries(zone.playableByCardId)) {\n refs.forEach((ref, index) =>\n visit(ref, [\n \"zones\",\n zoneId,\n hostId,\n \"playableByCardId\",\n cardId,\n index,\n ]),\n );\n }\n }\n }\n}\n\n/** Hydrates a schema-admitted frame, retaining the shared descriptor objects. */\nexport function hydrateCompactGameplayFrame(\n frame: CompactGameplayFrame,\n): PluginGameplayFrame {\n const { interactionsByRef, availableInteractionRefs, zones, ...base } = frame;\n const hydrate = (refs: readonly string[]) =>\n refs.map((ref) => interactionsByRef[ref]);\n return {\n ...base,\n availableInteractions: hydrate(availableInteractionRefs),\n zones: Object.fromEntries(\n Object.entries(zones).map(([zoneId, hosts]) => [\n zoneId,\n Object.fromEntries(\n Object.entries(hosts).map(([hostId, zone]) => [\n hostId,\n {\n ...zone,\n playableByCardId: Object.fromEntries(\n Object.entries(zone.playableByCardId).map(([cardId, refs]) => [\n cardId,\n hydrate(refs),\n ]),\n ),\n },\n ]),\n ),\n ]),\n ),\n };\n}\n","import { PlayerIdSchema } from \"../domain/player-identity.js\";\nimport { ViewCardSchema } from \"../domain/cards.js\";\nimport * as ReducerWireZod from \"../runtime-schema\";\nimport * as z from \"zod\";\nimport {\n DREAMBOARD_PLUGIN_PROTOCOL,\n DREAMBOARD_PLUGIN_PROTOCOL_VERSION,\n} from \"./protocol.js\";\nimport { RuntimeJsonSchema } from \"../runtime-json.js\";\nimport {\n BoardProjectionSchema,\n ProjectedTileSchema,\n} from \"../seat-topology-schema.js\";\nimport type {\n GameOutcome,\n GameplayBasis,\n PluginGameplayFrame,\n PluginSessionDescriptor,\n ZoneHandlesSnapshot,\n} from \"./frame.js\";\nimport type {\n HostToPluginPayload,\n InteractionResult,\n PluginProtocolEnvelope,\n PluginToHostPayload,\n} from \"./protocol.js\";\n\nexport const GameEventDetailSchema =\n ReducerWireZod.ProjectedGameEventDetailSchema;\nexport const SystemActionEventSchema = ReducerWireZod.SystemActionEventSchema;\nexport const GameEventSchema = ReducerWireZod.ProjectedGameEventSchema;\nexport const SeatProjectionBundleSchema =\n ReducerWireZod.SeatProjectionBundleSchema;\n\nexport { PlayerIdSchema } from \"../domain/player-identity.js\";\n\nexport const PluginPlayerSummarySchema = z\n .object({\n playerId: PlayerIdSchema,\n displayName: z.string(),\n color: z.string().optional(),\n })\n .strict();\n\nexport const PluginSessionDescriptorSchema = z\n .object({\n sessionId: z.string().min(1),\n players: z.array(PluginPlayerSummarySchema),\n assets: z.record(z.string(), z.instanceof(Blob)).optional(),\n })\n .strict() satisfies z.ZodType<PluginSessionDescriptor>;\n\nexport {\n InteractionCommitPolicySchema,\n InputSelectionSchema,\n InputDomainSchema,\n InteractionChoiceOptionSchema,\n InteractionInputDescriptorSchema,\n InteractionAvailabilitySchema,\n InteractionDescriptorSchema,\n} from \"../interaction-schema.js\";\nimport {\n InteractionDescriptorSchema,\n ZoneInteractionRefsSchema,\n} from \"../interaction-schema.js\";\nimport {\n visitInteractionRefs,\n type CompactGameplayFrame,\n} from \"./compact-frame.js\";\n\nexport const ZoneHandlesSnapshotSchema = z\n .object({\n tiles: z.array(ProjectedTileSchema),\n cardIds: z.array(z.string()),\n cardViewsById: z.record(z.string(), ViewCardSchema),\n cardBacksById: z.record(z.string(), z.string()),\n playableByCardId: z.record(\n z.string(),\n z.array(InteractionDescriptorSchema),\n ),\n shuffled: z.literal(true).optional(),\n })\n .strict() satisfies z.ZodType<ZoneHandlesSnapshot>;\n\nexport const SimultaneousPhaseSnapshotSchema =\n ReducerWireZod.SimultaneousPhaseProjectionSchema;\n\nexport const GameplayBasisSchema = z\n .object({\n sessionId: z.string().min(1),\n version: z.number().int().nonnegative(),\n actionSetVersion: z.string().min(1),\n perspectivePlayerId: PlayerIdSchema,\n })\n .strict() satisfies z.ZodType<GameplayBasis>;\n\nexport const GameOutcomeSchema =\n ReducerWireZod.GameOutcomeSchema satisfies z.ZodType<GameOutcome>;\n\nconst ProjectedViewSchema = z\n .record(z.string(), RuntimeJsonSchema)\n .superRefine((view, context) => {\n if (!Object.hasOwn(view, \"boards\")) return;\n const boards = BoardProjectionSchema.safeParse(view.boards);\n if (!boards.success) {\n for (const issue of boards.error.issues) {\n context.addIssue({\n code: \"custom\",\n path: [\"boards\", ...issue.path],\n message: issue.message,\n });\n }\n }\n });\n\nexport const SeatFrameSchema = z\n .object({\n players: z.array(PlayerIdSchema),\n causedBy: z.string().min(1).optional(),\n events: z.array(GameEventSchema).max(32),\n view: ProjectedViewSchema.nullable(),\n flow: z\n .object({\n currentPhase: z.string().nullable(),\n activePlayers: z.array(PlayerIdSchema),\n simultaneousPhase: SimultaneousPhaseSnapshotSchema.nullable(),\n })\n .strict(),\n availableInteractions: z.array(InteractionDescriptorSchema),\n zones: z.record(\n z.string(),\n z.record(z.string(), ZoneHandlesSnapshotSchema),\n ),\n })\n .strict();\n\nexport const PluginGameplayFrameSchema = SeatFrameSchema.extend({\n basis: GameplayBasisSchema,\n}) satisfies z.ZodType<PluginGameplayFrame>;\n\nexport const CompactGameplayFrameSchema = PluginGameplayFrameSchema.omit({\n availableInteractions: true,\n zones: true,\n})\n .extend({\n interactionsByRef: z.record(z.string(), InteractionDescriptorSchema),\n availableInteractionRefs: z.array(z.string()),\n zones: z.record(\n z.string(),\n z.record(z.string(), ZoneInteractionRefsSchema),\n ),\n })\n .superRefine((frame, context) => {\n const reachable = new Set<string>();\n visitInteractionRefs(frame, (ref, path) => {\n reachable.add(ref);\n if (!Object.hasOwn(frame.interactionsByRef, ref)) {\n context.addIssue({\n code: \"custom\",\n path,\n message: `Missing interaction reference '${ref}'.`,\n });\n }\n });\n for (const ref of Object.keys(frame.interactionsByRef)) {\n if (!reachable.has(ref)) {\n context.addIssue({\n code: \"custom\",\n path: [\"interactionsByRef\", ref],\n message: `Unused interaction reference '${ref}'.`,\n });\n }\n }\n }) satisfies z.ZodType<CompactGameplayFrame>;\n\n/** Only rejections are standalone wire results; success accompanies a frame. */\nexport const InteractionResultSchema = z\n .object({\n type: z.literal(\"interaction.result\"),\n clientActionId: z.string().min(1),\n accepted: z.literal(false),\n errorCode: z.string().min(1),\n message: z.string().optional(),\n })\n .strict() satisfies z.ZodType<\n Extract<InteractionResult, { accepted: false }>\n>;\n\nexport const SubmitInteractionCommandSchema = z\n .object({\n type: z.literal(\"interaction.submit\"),\n clientActionId: z.string().min(1),\n basis: GameplayBasisSchema,\n interactionId: z.string().min(1),\n params: RuntimeJsonSchema,\n })\n .strict();\n\nexport const CancelInteractionCommandSchema =\n SubmitInteractionCommandSchema.omit({ params: true })\n .extend({ type: z.literal(\"interaction.cancel\") })\n .strict();\n\nexport const HostToPluginPayloadSchema = z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"runtime.init\"),\n session: PluginSessionDescriptorSchema,\n })\n .strict(),\n z\n .object({\n type: z.literal(\"gameplay.frame\"),\n frame: PluginGameplayFrameSchema,\n acknowledgedClientActionId: z.string().min(1).optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"gameplay.compact-frame\"),\n frame: CompactGameplayFrameSchema,\n acknowledgedClientActionId: z.string().min(1).optional(),\n })\n .strict(),\n InteractionResultSchema,\n]) satisfies z.ZodType<HostToPluginPayload>;\n\nexport const PluginToHostPayloadSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"runtime.ready\") }).strict(),\n z\n .object({\n type: z.literal(\"runtime.capabilities\"),\n compactGameplayFrames: z.literal(true),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"runtime.resume\"),\n pendingClientActionId: z.string().min(1).optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"runtime.ack\"),\n sequence: z.number().int().nonnegative(),\n clientReceivedAtMs: z.number().finite().optional(),\n clientRenderedAtMs: z.number().finite().optional(),\n })\n .strict(),\n SubmitInteractionCommandSchema,\n CancelInteractionCommandSchema,\n z\n .object({\n type: z.literal(\"runtime.error\"),\n message: z.string(),\n code: z.string().optional(),\n })\n .strict(),\n]) satisfies z.ZodType<PluginToHostPayload>;\n\nexport function createPluginProtocolEnvelopeSchema<Payload>(\n payloadSchema: z.ZodType<Payload>,\n): z.ZodType<PluginProtocolEnvelope<Payload>> {\n return z\n .object({\n protocol: z.literal(DREAMBOARD_PLUGIN_PROTOCOL),\n version: z.literal(DREAMBOARD_PLUGIN_PROTOCOL_VERSION),\n channelId: z.string().min(1),\n sequence: z.number().int().nonnegative(),\n payload: payloadSchema,\n })\n .strict();\n}\n\nexport const HostToPluginEnvelopeSchema = createPluginProtocolEnvelopeSchema(\n HostToPluginPayloadSchema,\n);\n\nexport const PluginToHostEnvelopeSchema = createPluginProtocolEnvelopeSchema(\n PluginToHostPayloadSchema,\n);\n\nexport function parsePluginSessionDescriptor(\n value: unknown,\n): PluginSessionDescriptor {\n return PluginSessionDescriptorSchema.parse(value);\n}\n\nexport function parsePluginGameplayFrame(value: unknown): PluginGameplayFrame {\n return PluginGameplayFrameSchema.parse(value);\n}\n\nexport function parseHostToPluginEnvelope(\n value: unknown,\n): PluginProtocolEnvelope<HostToPluginPayload> {\n return HostToPluginEnvelopeSchema.parse(value);\n}\n\nexport function parsePluginToHostEnvelope(\n value: unknown,\n): PluginProtocolEnvelope<PluginToHostPayload> {\n return PluginToHostEnvelopeSchema.parse(value);\n}\n","import { createStore } from \"@tanstack/store\";\nimport * as z from \"zod\";\nimport {\n SeatFrameSchema,\n PluginPlayerSummarySchema,\n} from \"../../shared/protocol/schema.js\";\nimport { immutableCopy } from \"../../shared/immutable.js\";\nimport type { GameSource, SourceSnapshot, SourceState } from \"./types.js\";\n\nexport const SourceSnapshotSchema = z\n .object({\n me: z.string().min(1),\n causedBy: z.string().min(1).optional(),\n players: z.array(PluginPlayerSummarySchema),\n frame: SeatFrameSchema,\n version: z.number().int().nonnegative(),\n })\n .strict();\n\n/** A read-only fixture source accepts the public seat snapshot, never wire basis. */\nexport function staticSource(input: SourceSnapshot): GameSource {\n const snapshot = immutableCopy(SourceSnapshotSchema.parse(input));\n if (!snapshot.players.some((player) => player.playerId === snapshot.me))\n throw new Error(\"Gameplay seat is absent from session.\");\n const store = createStore<SourceState>(\n Object.freeze({\n snapshot,\n connection: \"ready\",\n request: null,\n failure: null,\n }),\n );\n return {\n store: {\n get: () => store.get(),\n subscribe: (listener) => store.subscribe(listener),\n },\n dispose() {\n store.setState((state) =>\n Object.freeze({\n snapshot: state.snapshot,\n connection: \"closed\",\n request: null,\n failure: null,\n }),\n );\n },\n };\n}\n","/** Stable seat colors shared by hosted and local gameplay. */\nexport const PLAYER_SEAT_COLORS = [\n \"#2563EB\",\n \"#DC2626\",\n \"#059669\",\n \"#7C3AED\",\n \"#DB2777\",\n \"#0891B2\",\n \"#65A30D\",\n \"#EA580C\",\n] as const;\n\nexport function playerSeatColor(seatIndex: number): string {\n return PLAYER_SEAT_COLORS[seatIndex % PLAYER_SEAT_COLORS.length];\n}\n","import type { PluginGameplayFrame } from \"./frame.js\";\nimport {\n type ActionSetVersionInput,\n type SubmitInteractionCommand,\n type CancelInteractionCommand,\n} from \"./protocol.js\";\nimport {\n canonicalizePluginRuntimeJson,\n digestPluginRuntimeJson,\n encodeCanonicalPluginRuntimeJson,\n} from \"./json.js\";\n\nexport {\n canonicalizePluginRuntimeJson,\n digestPluginRuntimeJson,\n encodeCanonicalPluginRuntimeJson,\n};\n\nexport function computePluginActionSetVersion(\n input: ActionSetVersionInput,\n): string {\n return digestPluginRuntimeJson({\n digestVersion: \"plugin-action-set@6\",\n version: input.version,\n availableInteractions: input.availableInteractions,\n });\n}\n\nexport function digestPluginGameplayFrame(frame: PluginGameplayFrame): string {\n return digestPluginRuntimeJson({\n digestVersion: \"plugin-gameplay-frame@6\",\n frame,\n });\n}\n\nexport function digestPluginCommandRequest(\n command: SubmitInteractionCommand | CancelInteractionCommand,\n): string {\n return digestPluginRuntimeJson({\n digestVersion: \"plugin-command-request@6\",\n command,\n });\n}\n","import { canonicalizePluginRuntimeJson } from \"./json\";\nimport {\n PluginGameplayFrameSchema,\n SeatProjectionBundleSchema,\n} from \"./schema.js\";\nimport type {\n InteractionDescriptor,\n PlayerId,\n PluginGameplayFrame,\n ReducerSeatProjectionBundle,\n} from \"./frame.js\";\nimport {\n hydrateCompactGameplayFrame,\n visitInteractionRefs,\n type CompactGameplayFrame,\n} from \"./compact-frame.js\";\nimport type * as Wire from \"../runtime-types.js\";\nimport type { RuntimeJson } from \"../runtime-json.js\";\n\nexport interface MaterializePluginGameplayFrameInput {\n readonly players: readonly PlayerId[];\n readonly causedBy?: string;\n readonly currentPhase: string | null;\n readonly activePlayers: readonly PlayerId[];\n readonly dynamicProjection: ReducerSeatProjectionBundle;\n readonly perspectivePlayerId: PlayerId;\n\n readonly sessionId: string;\n readonly version: number;\n readonly actionSetVersion: string;\n}\n\nexport function materializePluginGameplayFrame(\n input: MaterializePluginGameplayFrameInput,\n): PluginGameplayFrame {\n const dynamicProjection = SeatProjectionBundleSchema.parse(\n canonicalizePluginRuntimeJson(input.dynamicProjection),\n );\n return PluginGameplayFrameSchema.parse(\n hydrateCompactGameplayFrame(\n materializeCompactGameplayFrame({ ...input, dynamicProjection }),\n ),\n );\n}\n\n/** Selects one seat from an already schema-validated all-seat projection. */\nexport function materializeCompactGameplayFrame(\n input: Omit<MaterializePluginGameplayFrameInput, \"dynamicProjection\"> & {\n readonly dynamicProjection: Wire.SeatProjectionBundle;\n },\n): CompactGameplayFrame {\n const { dynamicProjection } = input;\n if (\n dynamicProjection.referenceBasis.sessionId !== input.sessionId ||\n dynamicProjection.referenceBasis.version !== input.version\n ) {\n throw new Error(\n \"Projection reference basis does not match the frame basis.\",\n );\n }\n const registry = dynamicProjection.interactionsByRef ?? {};\n const seat = dynamicProjection.seats[input.perspectivePlayerId];\n const availableInteractionRefs = seat?.availableInteractionRefs ?? [];\n const zones = seat?.zones ?? {};\n const selected = new Map<string, InteractionDescriptor>();\n visitInteractionRefs({ availableInteractionRefs, zones }, (ref, path) => {\n if (selected.has(ref)) return;\n if (!Object.hasOwn(registry, ref)) {\n throw new Error(\n `Seat projection ${path.join(\".\")} references '${ref}', which is missing from interactionsByRef.`,\n );\n }\n selected.set(ref, registry[ref]);\n });\n\n const frame = {\n players: input.players,\n ...(input.causedBy === undefined ? {} : { causedBy: input.causedBy }),\n events: seat?.events ?? [],\n basis: {\n sessionId: input.sessionId,\n version: input.version,\n actionSetVersion: input.actionSetVersion,\n perspectivePlayerId: input.perspectivePlayerId,\n },\n view: materializeView(seat?.view, seat?.boards),\n flow: {\n currentPhase: input.currentPhase,\n activePlayers: [...input.activePlayers],\n simultaneousPhase: dynamicProjection.simultaneousPhase ?? null,\n },\n interactionsByRef: Object.fromEntries(selected),\n availableInteractionRefs,\n zones,\n } satisfies CompactGameplayFrame;\n\n return frame;\n}\n\nfunction materializeView(\n seatView: unknown,\n seatBoards: ReducerSeatProjectionBundle[\"seats\"][string][\"boards\"],\n): RuntimeJson | null {\n const parts = [\n seatView,\n seatBoards === undefined ? undefined : { boards: seatBoards },\n ].filter((part) => part !== undefined && part !== null);\n if (parts.length === 0) return null;\n // Admitting schemas guarantee records and reject authored `boards` fields.\n return Object.assign({}, ...parts) as Record<string, RuntimeJson>;\n}\n","import { playerSeatColor } from \"../../shared/protocol/players.js\";\nimport { createStore } from \"@tanstack/store\";\nimport {\n PluginSessionDescriptorSchema,\n InteractionResultSchema,\n PluginToHostPayloadSchema,\n} from \"../../shared/protocol/schema.js\";\nimport type {\n GameplayBasis,\n PluginGameplayFrame,\n PluginSessionDescriptor,\n PluginPlayerSummary,\n} from \"../../shared/protocol/frame.js\";\nimport { immutableCopy } from \"../../shared/immutable.js\";\nimport type {\n CommandSource,\n SourceCommand,\n SourceContext,\n SourceState,\n SubmitResult,\n} from \"./types.js\";\n\ninterface Pending {\n readonly command: SourceCommand;\n readonly resolve: (result: SubmitResult) => void;\n readonly reject: (error: Error) => void;\n}\n\n/** Adapter-private lifecycle. Transport callbacks must belong to this lifetime. */\nexport function createSourceLifecycle(options: {\n context?: SourceContext;\n send(command: SourceCommand): void;\n recover(pendingClientActionId?: string): void;\n close(): void;\n timeoutMs?: number;\n followHostSeat?: boolean;\n}) {\n let context = options.context ? immutableCopy(options.context) : null;\n const store = createStore<SourceState>(\n Object.freeze({\n snapshot: null,\n connection: \"connecting\",\n request: null,\n failure: null,\n }),\n );\n let session: Omit<PluginSessionDescriptor, \"assets\"> | null = null;\n let assetUrls: Readonly<Record<string, string>> | null = null;\n const playerSummaries = new Map<string, PluginPlayerSummary>();\n let basis: GameplayBasis | null = null;\n let pending: Pending | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let recovered = false;\n let closed = false;\n const clearTimer = () => {\n clearTimeout(timer);\n timer = undefined;\n };\n const publish = (state: SourceState) => {\n if (state.request) Object.freeze(state.request);\n store.setState(() => Object.freeze(state));\n };\n const recovering = () => {\n if (closed) return;\n publish({ ...store.get(), connection: \"recovering\", failure: null });\n };\n const close = (failure: Error | null) => {\n if (closed) return;\n closed = true;\n clearTimer();\n for (const url of Object.values(assetUrls ?? {})) URL.revokeObjectURL(url);\n pending?.reject(failure ?? new Error(\"Gameplay source disposed.\"));\n pending = null;\n options.close();\n const snapshot = store.get().snapshot;\n publish(\n failure\n ? {\n connection: \"failed\",\n snapshot,\n request: null,\n failure: Object.freeze(failure),\n }\n : { connection: \"closed\", snapshot, request: null, failure: null },\n );\n };\n const fail = (error: Error) => close(error);\n const arm = () => {\n clearTimer();\n timer = setTimeout(() => {\n if (recovered) {\n fail(new Error(\"Gameplay source recovery timed out.\"));\n return;\n }\n recovered = true;\n recovering();\n try {\n options.recover(pending?.command.clientActionId);\n if (pending) options.send(pending.command);\n if (pending) arm();\n } catch (error) {\n fail(asError(error));\n }\n }, options.timeoutMs ?? 10_000);\n };\n const start = async (\n operation: \"submit\" | \"cancel\",\n interactionId: string,\n params?: unknown,\n ) => {\n const state = store.get();\n if (closed || state.connection !== \"ready\" || !basis)\n return Promise.reject(new Error(\"Gameplay source is not open.\"));\n if (pending)\n return Promise.reject(\n new Error(\"A gameplay interaction is already pending.\"),\n );\n const command = immutableCopy(\n PluginToHostPayloadSchema.parse({\n type:\n operation === \"cancel\" ? \"interaction.cancel\" : \"interaction.submit\",\n clientActionId: crypto.randomUUID(),\n basis,\n interactionId,\n ...(operation === \"cancel\" ? {} : { params }),\n }) as SourceCommand,\n );\n recovered = false;\n const promise = new Promise<SubmitResult>((resolve, reject) => {\n pending = { command, resolve, reject };\n });\n publish({\n ...state,\n request: {\n clientActionId: command.clientActionId,\n interactionId,\n operation,\n },\n });\n arm();\n try {\n options.send(command);\n } catch (error) {\n fail(asError(error));\n }\n return promise;\n };\n const source: CommandSource = {\n store: {\n get: () => store.get(),\n subscribe: (listener) => store.subscribe(listener),\n },\n submit: (interactionId, params) => start(\"submit\", interactionId, params),\n cancel: (interactionId) => start(\"cancel\", interactionId),\n dispose: () => close(null),\n };\n return {\n source,\n retry() {\n if (closed || !pending) return;\n try {\n options.send(pending.command);\n } catch (error) {\n fail(asError(error));\n }\n },\n fail,\n recovering,\n session(value: unknown) {\n if (closed) return;\n const { assets, ...parsed } = PluginSessionDescriptorSchema.parse(value);\n if (\n (context?.sessionId ?? session?.sessionId) &&\n parsed.sessionId !== (context?.sessionId ?? session?.sessionId)\n ) {\n fail(new Error(\"Gameplay session changed.\"));\n return;\n }\n session ??= immutableCopy(parsed);\n // Hosts repeat initialization until ready; the first delivery wins.\n assetUrls ??= Object.fromEntries(\n Object.entries(assets ?? {}).map(([path, blob]) => [\n path,\n URL.createObjectURL(blob),\n ]),\n );\n },\n // Transport adapters admit frames before entering this shared lifecycle.\n frame(parsed: PluginGameplayFrame, acknowledgedClientActionId?: string) {\n if (closed) return;\n if (!session) {\n fail(new Error(\"Gameplay frame arrived before session metadata.\"));\n return;\n }\n context ??= {\n sessionId: session.sessionId,\n playerId: parsed.basis.perspectivePlayerId,\n };\n if (parsed.basis.sessionId !== context.sessionId) {\n fail(new Error(\"Gameplay authority session changed.\"));\n return;\n }\n const changedSeat = parsed.basis.perspectivePlayerId !== context.playerId;\n if (changedSeat && !options.followHostSeat) {\n fail(new Error(\"Gameplay perspective changed.\"));\n return;\n }\n if (!parsed.players.includes(parsed.basis.perspectivePlayerId)) {\n fail(new Error(\"Gameplay seat is absent from session.\"));\n return;\n }\n if (changedSeat) {\n clearTimer();\n pending?.reject(new Error(\"Gameplay perspective changed.\"));\n pending = null;\n recovered = false;\n context = { ...context, playerId: parsed.basis.perspectivePlayerId };\n }\n const confirmed =\n pending && pending.command.clientActionId === acknowledgedClientActionId\n ? pending\n : null;\n if (confirmed) {\n clearTimer();\n pending = null;\n recovered = false;\n }\n if (!changedSeat && basis && parsed.basis.version <= basis.version) {\n if (confirmed || store.get().connection === \"recovering\") {\n publish({\n ...store.get(),\n snapshot: store.get().snapshot!,\n request: confirmed ? null : store.get().request,\n connection: \"ready\",\n failure: null,\n });\n }\n confirmed?.resolve({ accepted: true });\n return;\n }\n const { basis: nextBasis, ...frame } = immutableCopy(\n withCardImageUrls(parsed, assetUrls),\n );\n basis = nextBasis;\n publish({\n failure: null,\n request: changedSeat || confirmed ? null : store.get().request,\n snapshot: Object.freeze({\n me: context.playerId,\n players: Object.freeze(\n frame.players.map((playerId, index) => {\n let summary = playerSummaries.get(playerId);\n if (!summary) {\n const metadata = session!.players.find(\n (player) => player.playerId === playerId,\n );\n summary = Object.freeze({\n playerId,\n displayName: metadata?.displayName ?? `Player ${index + 1}`,\n color: metadata?.color ?? playerSeatColor(index),\n });\n playerSummaries.set(playerId, summary);\n }\n return summary;\n }),\n ),\n ...(frame.causedBy === undefined ? {} : { causedBy: frame.causedBy }),\n frame: Object.freeze(frame),\n version: basis.version,\n }),\n connection: \"ready\",\n });\n confirmed?.resolve({ accepted: true });\n },\n result(value: unknown) {\n if (closed) return;\n const result = InteractionResultSchema.parse(value);\n if (!pending || result.clientActionId !== pending.command.clientActionId)\n return;\n const rejected = pending;\n clearTimer();\n pending = null;\n publish({\n snapshot: store.get().snapshot!,\n request: null,\n connection: \"ready\",\n failure: null,\n });\n rejected.resolve(\n immutableCopy({\n accepted: false,\n errorCode: result.errorCode,\n ...(result.message === undefined ? {} : { message: result.message }),\n }),\n );\n },\n };\n}\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/** Replaces card image paths in card views and hidden card backs with delivered URLs. */\nfunction withCardImageUrls(\n frame: PluginGameplayFrame,\n urls: Readonly<Record<string, string>> | null,\n): PluginGameplayFrame {\n if (urls === null || Object.keys(urls).length === 0) return frame;\n return {\n ...frame,\n zones: Object.fromEntries(\n Object.entries(frame.zones).map(([zoneId, hosts]) => [\n zoneId,\n Object.fromEntries(\n Object.entries(hosts).map(([hostId, zone]) => [\n hostId,\n {\n ...zone,\n cardViewsById: Object.fromEntries(\n Object.entries(zone.cardViewsById).map(([cardId, card]) => [\n cardId,\n {\n ...card,\n frontImage:\n card.frontImage === undefined\n ? undefined\n : (urls[card.frontImage] ?? card.frontImage),\n backImage:\n card.backImage === undefined\n ? undefined\n : (urls[card.backImage] ?? card.backImage),\n },\n ]),\n ),\n cardBacksById: Object.fromEntries(\n Object.entries(zone.cardBacksById).map(([cardId, path]) => [\n cardId,\n urls[path] ?? path,\n ]),\n ),\n },\n ]),\n ),\n ]),\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AASO,IAAM,6BAA6B;AACnC,IAAM,qCAAqC;;;ACM3C,SAAS,qBACd,OACA,OACM;AACN,QAAM,yBAAyB;AAAA,IAAQ,CAAC,KAAK,UAC3C,MAAM,KAAK,CAAC,4BAA4B,KAAK,CAAC;AAAA,EAChD;AACA,aAAW,CAAC,QAAQ,KAAK,KAAK,OAAO,QAAQ,MAAM,KAAK,GAAG;AACzD,eAAW,CAAC,QAAQ,IAAI,KAAK,OAAO,QAAQ,KAAK,GAAG;AAClD,iBAAW,CAAC,QAAQ,IAAI,KAAK,OAAO,QAAQ,KAAK,gBAAgB,GAAG;AAClE,aAAK;AAAA,UAAQ,CAAC,KAAK,UACjB,MAAM,KAAK;AAAA,YACT;AAAA,YACA;AAAA,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;AAAA,cACH;AAAA,cACA,eAAe,OAAO;AAAA,gBACpB,OAAO,QAAQ,KAAK,aAAa,EAAE,IAAI,CAAC,CAAC,QAAQ,IAAI,MAAM;AAAA,kBACzD;AAAA,kBACA,KAAK,IAAI,KAAK;AAAA,gBAChB,CAAC;AAAA,cACH;AAAA,YACF;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["SystemActionEventSchema","SeatProjectionBundleSchema","GameOutcomeSchema","z","SeatProjectionBundleSchema","createStore","createStore"]}
@@ -3456,6 +3456,7 @@ function createTrustedRuntimeScope(definition, options = {}) {
3456
3456
  }
3457
3457
  return {
3458
3458
  definition,
3459
+ errorMessages: new Map(Object.entries(definition.contract.errors ?? {})),
3459
3460
  manifest,
3460
3461
  diagnostics: createReducerDiagnosticsEmitter(options.diagnostics),
3461
3462
  registry,
@@ -4051,10 +4052,15 @@ function valueSourceForCollector(context, inputKey, collector) {
4051
4052
  complete: true,
4052
4053
  values: function* () {
4053
4054
  if (!eligible) return;
4054
- for (const candidate of resolved.values()) {
4055
- if (Array.isArray(candidate) && candidate.some(
4056
- (value) => canonicalJson(value) === canonicalJson(fixedValue)
4057
- ))
4055
+ let remaining = resolved;
4056
+ if (typeof fixedValue === "string" && selection.min <= 1 && (selection.max === void 0 || selection.max >= 1)) {
4057
+ yield [fixedValue];
4058
+ if (selection.max === 1) return;
4059
+ remaining = applySelection(base, { ...selection, min: 2 }, domain);
4060
+ }
4061
+ const key = canonicalJson(fixedValue);
4062
+ for (const candidate of remaining.values()) {
4063
+ if (Array.isArray(candidate) && candidate.some((value) => canonicalJson(value) === key))
4058
4064
  yield candidate;
4059
4065
  }
4060
4066
  }
@@ -4597,15 +4603,11 @@ function explanationAvailability(decision) {
4597
4603
  }
4598
4604
  }
4599
4605
  function createInteractionDecisionResolver(scope, authorization, options = {}) {
4600
- const contractErrors = scope.definition.contract.errors ?? {};
4601
- function defaultMessageForCode(code) {
4602
- return contractErrors[code];
4603
- }
4604
4606
  function issueFromRule(rule, message) {
4605
4607
  return {
4606
4608
  ruleId: rule.ruleId,
4607
4609
  errorCode: rule.errorCode,
4608
- message: message ?? rule.message ?? defaultMessageForCode(rule.errorCode)
4610
+ message: message ?? rule.message ?? scope.errorMessages.get(rule.errorCode)
4609
4611
  };
4610
4612
  }
4611
4613
  function issueFromRuleValidationResult(rule, result) {
@@ -4615,7 +4617,7 @@ function createInteractionDecisionResolver(scope, authorization, options = {}) {
4615
4617
  return {
4616
4618
  ruleId: rule.ruleId,
4617
4619
  errorCode: result.errorCode,
4618
- message: result.message ?? rule.message ?? defaultMessageForCode(result.errorCode)
4620
+ message: result.message ?? rule.message ?? scope.errorMessages.get(result.errorCode)
4619
4621
  };
4620
4622
  }
4621
4623
  return void 0;
@@ -5110,7 +5112,7 @@ function createInteractionDecisionResolver(scope, authorization, options = {}) {
5110
5112
  ruleId: rule.id,
5111
5113
  outcome: "notEvaluated",
5112
5114
  errorCode: rule.errorCode,
5113
- message: rule.message ?? defaultMessageForCode(rule.errorCode)
5115
+ message: rule.message ?? scope.errorMessages.get(rule.errorCode)
5114
5116
  });
5115
5117
  continue;
5116
5118
  }
@@ -6796,18 +6798,26 @@ function createProjectionBuilder(scope, interactions) {
6796
6798
  function createDescriptorRegistry(timing) {
6797
6799
  const byRef = {};
6798
6800
  const byHash = /* @__PURE__ */ new Map();
6801
+ const byDescriptor = /* @__PURE__ */ new Map();
6799
6802
  return {
6800
6803
  add(descriptor, actorSeat) {
6801
6804
  return measureProjectionTiming(timing, "descriptorHashMs", () => {
6805
+ const key = `${actorSeat}:${encodeCanonicalPluginRuntimeJson(descriptor)}`;
6806
+ const cached = byDescriptor.get(key);
6807
+ if (cached) return cached;
6802
6808
  const enriched = descriptorWithBrowserReplayDigests(
6803
6809
  descriptor,
6804
6810
  actorSeat
6805
6811
  );
6806
6812
  const fingerprint = encodeCanonicalPluginRuntimeJson(enriched);
6807
6813
  const existing = byHash.get(fingerprint);
6808
- if (existing) return existing;
6814
+ if (existing) {
6815
+ byDescriptor.set(key, existing);
6816
+ return existing;
6817
+ }
6809
6818
  const base = typeof enriched.interactionId === "string" && enriched.interactionId.length > 0 ? enriched.interactionId : "interaction";
6810
6819
  const ref = `${base}:${fnv1a64(fingerprint)}`;
6820
+ byDescriptor.set(key, ref);
6811
6821
  byHash.set(fingerprint, ref);
6812
6822
  byRef[ref] = enriched;
6813
6823
  return ref;
@@ -7409,6 +7419,7 @@ function createReducerBundle(definition, options = {}) {
7409
7419
  });
7410
7420
  const result = executor.dispatch(combinedState, input, referenceBasis);
7411
7421
  if (result.type === "reject") {
7422
+ result.message ??= scope.errorMessages.get(result.errorCode);
7412
7423
  scope.diagnostics.event({
7413
7424
  type: "submitRejected",
7414
7425
  submissionId,
@@ -7495,4 +7506,4 @@ export {
7495
7506
  createProjectionBuilder,
7496
7507
  createReducerBundle
7497
7508
  };
7498
- //# sourceMappingURL=chunk-UGWQKBR6.js.map
7509
+ //# sourceMappingURL=chunk-UARMSWDA.js.map