@dreamboard-games/sdk 0.5.0-alpha.2 → 0.5.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +462 -53
  2. package/dist/board-element-CqtxU5VZ.d.ts +13 -0
  3. package/dist/chunk-3RFGPBES.js +1792 -0
  4. package/dist/chunk-3RFGPBES.js.map +1 -0
  5. package/dist/chunk-CZRPUWCT.js +1602 -0
  6. package/dist/chunk-CZRPUWCT.js.map +1 -0
  7. package/dist/chunk-DMSXVMYY.js +7199 -0
  8. package/dist/chunk-DMSXVMYY.js.map +1 -0
  9. package/dist/chunk-U6R7FAH4.js +630 -0
  10. package/dist/chunk-U6R7FAH4.js.map +1 -0
  11. package/dist/chunk-YT3RPO5J.js +635 -0
  12. package/dist/chunk-YT3RPO5J.js.map +1 -0
  13. package/dist/diagnostics-ZAPEBlJP.d.ts +64 -0
  14. package/dist/extract-CwJWDrSD.d.ts +6850 -0
  15. package/dist/index.d.ts +5177 -1
  16. package/dist/index.js +1990 -6
  17. package/dist/index.js.map +1 -1
  18. package/dist/react.d.ts +158 -0
  19. package/dist/react.js +1119 -0
  20. package/dist/react.js.map +1 -0
  21. package/dist/reducer.d.ts +1028 -97
  22. package/dist/reducer.js +4892 -125
  23. package/dist/reducer.js.map +1 -1
  24. package/dist/shortcuts-B_RrufOM.d.ts +822 -0
  25. package/dist/testing.d.ts +529 -569
  26. package/dist/testing.js +2588 -934
  27. package/dist/testing.js.map +1 -1
  28. package/dist/types-BxXRINRF.d.ts +118 -0
  29. package/package.json +39 -144
  30. package/dist/HandView-Bi2lxzQP.d.ts +0 -79
  31. package/dist/ResourceCounter-BFxJknqp.d.ts +0 -98
  32. package/dist/ThemeProvider-CElaL2ik.d.ts +0 -99
  33. package/dist/attributes-DbvyMbXw.d.ts +0 -68
  34. package/dist/browser-interaction.d.ts +0 -910
  35. package/dist/browser-interaction.js +0 -119
  36. package/dist/browser-interaction.js.map +0 -1
  37. package/dist/chunk-32PFKDV7.js +0 -11705
  38. package/dist/chunk-32PFKDV7.js.map +0 -1
  39. package/dist/chunk-3BAD4VC2.js +0 -263
  40. package/dist/chunk-3BAD4VC2.js.map +0 -1
  41. package/dist/chunk-3SKDNDPG.js +0 -104
  42. package/dist/chunk-3SKDNDPG.js.map +0 -1
  43. package/dist/chunk-5YV2WHJ4.js +0 -25
  44. package/dist/chunk-5YV2WHJ4.js.map +0 -1
  45. package/dist/chunk-ANRB4XKA.js +0 -90
  46. package/dist/chunk-ANRB4XKA.js.map +0 -1
  47. package/dist/chunk-BI4G3PM2.js +0 -1864
  48. package/dist/chunk-BI4G3PM2.js.map +0 -1
  49. package/dist/chunk-EVCLTY4Q.js +0 -935
  50. package/dist/chunk-EVCLTY4Q.js.map +0 -1
  51. package/dist/chunk-GDPKTBUR.js +0 -564
  52. package/dist/chunk-GDPKTBUR.js.map +0 -1
  53. package/dist/chunk-H6VDGFL5.js +0 -2903
  54. package/dist/chunk-H6VDGFL5.js.map +0 -1
  55. package/dist/chunk-LR3ZTWQF.js +0 -5960
  56. package/dist/chunk-LR3ZTWQF.js.map +0 -1
  57. package/dist/chunk-PF7L4BMG.js +0 -117
  58. package/dist/chunk-PF7L4BMG.js.map +0 -1
  59. package/dist/chunk-PN5O6GG2.js +0 -32
  60. package/dist/chunk-PN5O6GG2.js.map +0 -1
  61. package/dist/chunk-PZ5AY32C.js +0 -10
  62. package/dist/chunk-PZ5AY32C.js.map +0 -1
  63. package/dist/chunk-S2JEDVWH.js +0 -7165
  64. package/dist/chunk-S2JEDVWH.js.map +0 -1
  65. package/dist/chunk-T3ZKNUZ7.js +0 -1
  66. package/dist/chunk-T3ZKNUZ7.js.map +0 -1
  67. package/dist/chunk-UGH54WZ2.js +0 -223
  68. package/dist/chunk-UGH54WZ2.js.map +0 -1
  69. package/dist/chunk-VCDWP5VL.js +0 -746
  70. package/dist/chunk-VCDWP5VL.js.map +0 -1
  71. package/dist/chunk-VDXOF4FW.js +0 -69
  72. package/dist/chunk-VDXOF4FW.js.map +0 -1
  73. package/dist/chunk-WHR5UW3F.js +0 -1988
  74. package/dist/chunk-WHR5UW3F.js.map +0 -1
  75. package/dist/chunk-Y75CFE77.js +0 -17
  76. package/dist/chunk-Y75CFE77.js.map +0 -1
  77. package/dist/chunk-Z7QCREWI.js +0 -3435
  78. package/dist/chunk-Z7QCREWI.js.map +0 -1
  79. package/dist/chunk-ZZGN2ATS.js +0 -1941
  80. package/dist/chunk-ZZGN2ATS.js.map +0 -1
  81. package/dist/components-gAbIz7hK.d.ts +0 -1284
  82. package/dist/definitions-BgmV_GhC.d.ts +0 -300
  83. package/dist/diagnostics-DIi3ina7.d.ts +0 -50
  84. package/dist/digest.d.ts +0 -8
  85. package/dist/game-CsZScpcn.d.ts +0 -763
  86. package/dist/hex-board-view-aKkblDp6.d.ts +0 -1228
  87. package/dist/index-CcT9Q7N7.d.ts +0 -193
  88. package/dist/index.d-DjzoK7zn.d.ts +0 -2101
  89. package/dist/package-set.d.ts +0 -13
  90. package/dist/package-set.js +0 -12
  91. package/dist/package-set.js.map +0 -1
  92. package/dist/player-state-Cqpyeql0.d.ts +0 -371
  93. package/dist/plugin-runtime-contract.d.ts +0 -17
  94. package/dist/plugin-runtime-contract.js +0 -92
  95. package/dist/plugin-runtime-contract.js.map +0 -1
  96. package/dist/primitive-props-BNHDkgd7.d.ts +0 -16
  97. package/dist/protocol-dYgafTYY.d.ts +0 -314
  98. package/dist/reducer/advanced.d.ts +0 -82
  99. package/dist/reducer/advanced.js +0 -51
  100. package/dist/reducer/advanced.js.map +0 -1
  101. package/dist/reducer-contract.d.ts +0 -11
  102. package/dist/reducer-contract.js +0 -16
  103. package/dist/reducer-contract.js.map +0 -1
  104. package/dist/reference-games/index.d.ts +0 -31
  105. package/dist/reference-games/index.js +0 -48
  106. package/dist/reference-games/index.js.map +0 -1
  107. package/dist/runtime/primitives.d.ts +0 -250
  108. package/dist/runtime/primitives.js +0 -189
  109. package/dist/runtime/primitives.js.map +0 -1
  110. package/dist/runtime/runtime-api.d.ts +0 -2
  111. package/dist/runtime/runtime-api.js +0 -1
  112. package/dist/runtime/runtime-api.js.map +0 -1
  113. package/dist/runtime/workspace-contract.d.ts +0 -392
  114. package/dist/runtime/workspace-contract.js +0 -28
  115. package/dist/runtime/workspace-contract.js.map +0 -1
  116. package/dist/runtime-RJ5orDJU.d.ts +0 -1699
  117. package/dist/runtime-api-Bz5pwNU_.d.ts +0 -296
  118. package/dist/runtime-json-CQ9QbLZ5.d.ts +0 -5
  119. package/dist/runtime.d.ts +0 -83
  120. package/dist/runtime.js +0 -242
  121. package/dist/runtime.js.map +0 -1
  122. package/dist/schema.d.ts +0 -379
  123. package/dist/stale-contract-artifact-error-XLaweZtF.d.ts +0 -18
  124. package/dist/testing-compiler.d.ts +0 -37
  125. package/dist/testing-compiler.js +0 -272
  126. package/dist/testing-compiler.js.map +0 -1
  127. package/dist/testing-runtime.d.ts +0 -119
  128. package/dist/testing-runtime.js +0 -212
  129. package/dist/testing-runtime.js.map +0 -1
  130. package/dist/types-DJj5MJkl.d.ts +0 -256
  131. package/dist/types-DR7DoB1x.d.ts +0 -28
  132. package/dist/types-JWCYHmu7.d.ts +0 -122
  133. package/dist/types.d.ts +0 -1958
  134. package/dist/types.js +0 -14
  135. package/dist/types.js.map +0 -1
  136. package/dist/ui/components.d.ts +0 -17
  137. package/dist/ui/components.js +0 -216
  138. package/dist/ui/components.js.map +0 -1
  139. package/dist/ui/defaults.d.ts +0 -19
  140. package/dist/ui/defaults.js +0 -104
  141. package/dist/ui/defaults.js.map +0 -1
  142. package/dist/ui/player-state.d.ts +0 -2
  143. package/dist/ui/player-state.js +0 -1
  144. package/dist/ui/player-state.js.map +0 -1
  145. package/dist/ui/plugin-styles.css +0 -2
  146. package/dist/ui-contract-GTUPkf8z.d.ts +0 -1168
  147. package/dist/ui.d.ts +0 -317
  148. package/dist/ui.js +0 -277
  149. package/dist/ui.js.map +0 -1
  150. package/dist/views-BpuWcOyN.d.ts +0 -1641
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/reducer/authoring/effect.ts","../src/reducer/game-event.ts","../src/reducer/compose.ts"],"sourcesContent":["import { z } from \"zod\";\nimport type {\n AnySchema,\n EffectRollDieDefinition,\n EffectShuffleDefinition,\n EffectShufflePlayerZoneDefinition,\n} from \"../model\";\nimport type {\n ContinuationCallable,\n ResumableEffectKind,\n} from \"../model/spec/runtime-args\";\nimport type {\n AnyReducerGameContract,\n ContractManifest,\n ContractState,\n} from \"./types\";\n\nfunction createContinuationCallable<\n DataSchema extends AnySchema,\n ResponseSchema extends AnySchema,\n State extends {\n table: import(\"../model\").RuntimeTableRecord;\n flow: { currentPhase: string };\n },\n Manifest extends import(\"../model\").ManifestContract<\n import(\"../model\").TableOfState<State>\n >,\n EffectType extends ResumableEffectKind = ResumableEffectKind,\n>(definition: {\n id: string;\n data: DataSchema;\n response: ResponseSchema;\n effectKind?: EffectType;\n reduce: ContinuationCallable<\n DataSchema,\n State,\n Manifest,\n string,\n EffectType\n >[\"reduce\"];\n}): ContinuationCallable<DataSchema, State, Manifest, string, EffectType> {\n const continuation = ((data: z.infer<DataSchema>) => {\n return {\n id: continuation.id,\n data,\n };\n }) as ContinuationCallable<DataSchema, State, Manifest, string, EffectType>;\n continuation.id = definition.id;\n continuation.source = \"effect\";\n continuation.dataSchema = definition.data;\n continuation.responseSchema = definition.response;\n continuation.reduce = definition.reduce;\n if (definition.effectKind !== undefined) {\n continuation.effectKind = definition.effectKind;\n }\n return continuation;\n}\n\n// --- `defineEffect` ---\n//\n// Authoring factory for engine-side resumable effects (cues). An effect\n// is the registered bundle of continuation callable + optional reduce,\n// discriminated by `type` which aligns directly with `ResumableEffectKind`:\n//\n// defineEffect<GameContract>()({ type: \"rollDie\", id, context?, reduce? })\n// defineEffect<GameContract>()({ type: \"shuffleSharedZone\", id, context?, reduce? })\n//\n// Authored effects are registered under `phase.effects` and invoked from\n// a reducer via `fx.effect(effect, options)`. The wire protocol already\n// isolates the continuation payload into the ingress bundle's\n// `continuations` map keyed by `effectId`, so `fx.effect` never attaches\n// `resume: undefined` to the wire effect.\n//\n// Addressed player requests are *not* effects. Author them as\n// prompt-kind interactions via `defineInteraction({ kind: \"prompt\",\n// to, options, ... })`.\n\ntype EffectRollDieInput<\n Contract extends AnyReducerGameContract,\n Id extends string,\n ContextSchema extends AnySchema,\n> = {\n type: \"rollDie\";\n id: Id;\n context?: ContextSchema;\n reduce?: ContinuationCallable<\n ContextSchema,\n ContractState<Contract>,\n ContractManifest<Contract>,\n Id,\n \"rollDie\"\n >[\"reduce\"];\n};\n\ntype EffectShuffleInput<\n Contract extends AnyReducerGameContract,\n Id extends string,\n ContextSchema extends AnySchema,\n> = {\n type: \"shuffleSharedZone\";\n id: Id;\n context?: ContextSchema;\n reduce?: ContinuationCallable<\n ContextSchema,\n ContractState<Contract>,\n ContractManifest<Contract>,\n Id,\n \"shuffleSharedZone\"\n >[\"reduce\"];\n};\n\ntype EffectShufflePlayerZoneInput<\n Contract extends AnyReducerGameContract,\n Id extends string,\n ContextSchema extends AnySchema,\n> = {\n type: \"shufflePlayerZone\";\n id: Id;\n context?: ContextSchema;\n reduce?: ContinuationCallable<\n ContextSchema,\n ContractState<Contract>,\n ContractManifest<Contract>,\n Id,\n \"shufflePlayerZone\"\n >[\"reduce\"];\n};\n\nexport function defineEffect<Contract extends AnyReducerGameContract>() {\n type EffectInput =\n | EffectRollDieInput<Contract, string, AnySchema>\n | EffectShuffleInput<Contract, string, AnySchema>\n | EffectShufflePlayerZoneInput<Contract, string, AnySchema>;\n type EffectOutput =\n | EffectRollDieDefinition<\n string,\n AnySchema,\n ContractState<Contract>,\n ContractManifest<Contract>\n >\n | EffectShuffleDefinition<\n string,\n AnySchema,\n ContractState<Contract>,\n ContractManifest<Contract>\n >\n | EffectShufflePlayerZoneDefinition<\n string,\n AnySchema,\n ContractState<Contract>,\n ContractManifest<Contract>\n >;\n function effect<\n Id extends string,\n ContextSchema extends AnySchema = z.ZodObject<Record<string, never>>,\n >(\n definition: EffectRollDieInput<Contract, Id, ContextSchema>,\n ): EffectRollDieDefinition<\n Id,\n ContextSchema,\n ContractState<Contract>,\n ContractManifest<Contract>\n >;\n function effect<\n Id extends string,\n ContextSchema extends AnySchema = z.ZodObject<Record<string, never>>,\n >(\n definition: EffectShuffleInput<Contract, Id, ContextSchema>,\n ): EffectShuffleDefinition<\n Id,\n ContextSchema,\n ContractState<Contract>,\n ContractManifest<Contract>\n >;\n function effect<\n Id extends string,\n ContextSchema extends AnySchema = z.ZodObject<Record<string, never>>,\n >(\n definition: EffectShufflePlayerZoneInput<Contract, Id, ContextSchema>,\n ): EffectShufflePlayerZoneDefinition<\n Id,\n ContextSchema,\n ContractState<Contract>,\n ContractManifest<Contract>\n >;\n function effect(definition: EffectInput): EffectOutput {\n if (\n definition.type === \"rollDie\" ||\n definition.type === \"shuffleSharedZone\" ||\n definition.type === \"shufflePlayerZone\"\n ) {\n const effectKind: ResumableEffectKind = definition.type;\n if (!definition.reduce) {\n return {\n type: definition.type,\n id: definition.id,\n contextSchema: definition.context,\n } as EffectOutput;\n }\n const contextSchema = (definition.context ?? z.object({})) as AnySchema;\n const continuation = createContinuationCallable<\n AnySchema,\n AnySchema,\n ContractState<Contract>,\n ContractManifest<Contract>,\n ResumableEffectKind\n >({\n id: definition.id,\n data: contextSchema,\n response: z.unknown() as AnySchema,\n effectKind,\n reduce: definition.reduce,\n });\n return {\n type: definition.type,\n id: definition.id,\n contextSchema,\n __continuation: continuation,\n } as EffectOutput;\n }\n throw new Error(\n `defineEffect: unknown effect definition. Expected type 'rollDie' | 'shuffleSharedZone' | 'shufflePlayerZone'. Addressed prompts are authored as prompt-kind interactions via defineInteraction({ kind: \"prompt\" }).`,\n );\n }\n return effect;\n}\n","import type { SystemActionEvent } from \"./model\";\n\nexport const gameEvent = {\n systemAction(event: Omit<SystemActionEvent, \"kind\">): SystemActionEvent {\n return {\n kind: \"systemAction\",\n ...event,\n };\n },\n};\n","/**\n * State composition primitives.\n *\n * `pipe` threads a seed state through a sequence of `State -> State`\n * transformations, left to right. It is the preferred way to compose curried\n * writers (the `ops.*` namespace) in reducers:\n *\n * return accept(\n * pipe(state,\n * ops.spendPlayerResources({ playerId, resources: cost }),\n * ops.placePieceOnVertex({ boardId, vertexId, pieceId, ownerId: playerId }),\n * ),\n * );\n */\n/**\n * A state-preserving transformation.\n *\n * `Op<State>` is polymorphic in the exact input subtype — given a state `S`\n * that extends `State`, it returns the same `S`. This lets curried writers\n * from `ops.*` and author-written helpers thread through phase-scoped `pipe`\n * calls without losing the narrowed phase state type.\n */\nexport type Op<State> = <S extends State>(state: S) => S;\n\nexport function pipe<State>(\n state: State,\n ...ops: ReadonlyArray<Op<NoInfer<State>>>\n): State {\n let result = state;\n for (const op of ops) {\n result = op(result);\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;AAiBlB,SAAS,2BAWP,YAYwE;AACxE,QAAM,gBAAgB,CAAC,SAA8B;AACnD,WAAO;AAAA,MACL,IAAI,aAAa;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACA,eAAa,KAAK,WAAW;AAC7B,eAAa,SAAS;AACtB,eAAa,aAAa,WAAW;AACrC,eAAa,iBAAiB,WAAW;AACzC,eAAa,SAAS,WAAW;AACjC,MAAI,WAAW,eAAe,QAAW;AACvC,iBAAa,aAAa,WAAW;AAAA,EACvC;AACA,SAAO;AACT;AAwEO,SAAS,eAAwD;AAyDtE,WAAS,OAAO,YAAuC;AACrD,QACE,WAAW,SAAS,aACpB,WAAW,SAAS,uBACpB,WAAW,SAAS,qBACpB;AACA,YAAM,aAAkC,WAAW;AACnD,UAAI,CAAC,WAAW,QAAQ;AACtB,eAAO;AAAA,UACL,MAAM,WAAW;AAAA,UACjB,IAAI,WAAW;AAAA,UACf,eAAe,WAAW;AAAA,QAC5B;AAAA,MACF;AACA,YAAM,gBAAiB,WAAW,WAAW,EAAE,OAAO,CAAC,CAAC;AACxD,YAAM,eAAe,2BAMnB;AAAA,QACA,IAAI,WAAW;AAAA,QACf,MAAM;AAAA,QACN,UAAU,EAAE,QAAQ;AAAA,QACpB;AAAA,QACA,QAAQ,WAAW;AAAA,MACrB,CAAC;AACD,aAAO;AAAA,QACL,MAAM,WAAW;AAAA,QACjB,IAAI,WAAW;AAAA,QACf;AAAA,QACA,gBAAgB;AAAA,MAClB;AAAA,IACF;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;;;AC/NO,IAAM,YAAY;AAAA,EACvB,aAAa,OAA2D;AACtE,WAAO;AAAA,MACL,MAAM;AAAA,MACN,GAAG;AAAA,IACL;AAAA,EACF;AACF;;;ACeO,SAAS,KACd,UACG,KACI;AACP,MAAI,SAAS;AACb,aAAW,MAAM,KAAK;AACpB,aAAS,GAAG,MAAM;AAAA,EACpB;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/reducer/authoring/validation.ts","../src/reducer/authoring/steps.ts","../src/reducer/inputs/formInput.ts","../src/reducer/inputs/boardInput.ts","../src/reducer/inputs/targetRule.ts","../src/reducer/inputs/boardTarget.ts","../src/reducer/inputs/cardTarget.ts","../src/reducer/inputs/cardInput.ts","../src/reducer/inputs/positionInput.ts","../src/reducer/inputs/rngInput.ts","../src/reducer/inputs/many.ts","../src/reducer/inputs/tileTarget.ts","../src/reducer/inputs/tileInput.ts","../src/reducer/authoring/interaction.ts","../src/reducer/authoring/views.ts","../src/reducer/authoring/contract-authoring.ts","../src/reducer/authoring/contract.ts","../src/reducer/authoring/game.ts","../src/reducer/game-event.ts","../src/reducer/per-player.ts","../src/reducer/memoize.ts","../src/reducer/manifest/identity-runtime.ts","../src/reducer/manifest/manifest-validation.ts","../src/reducer/manifest/materialize.ts","../src/reducer/manifest/field-schemas.ts","../src/reducer/manifest/parse-json.ts","../src/reducer/manifest/compiler.ts","../src/reducer/manifest/generated-helpers.ts","../src/reducer/manifest/schema.ts","../src/reducer/manifest/hex-tiles.ts","../src/reducer/manifest/authoring.ts","../src/reducer.ts"],"sourcesContent":["import type { z } from \"zod\";\nimport { isManifestScopedSchema, type SchemaLike } from \"../model\";\nimport type { InputCollector } from \"../model\";\nimport {\n getObjectShape,\n getZodDef,\n isEnumKeyedRecordSchema,\n isPlainZodString,\n isSparseMapSchema,\n unwrapWrappers,\n} from \"../schema-helpers\";\n\n/**\n * Canonical set of manifest-scoped id field names. `defineGameContract`\n * uses this list to reject state schemas that describe one of these fields\n * with a raw `z.string()` instead of the corresponding branded enum from\n * `manifest.ids.*`.\n *\n * The rule of thumb is \"one way to do things\": if a field *is* a player id,\n * card id, zone id, etc. in the manifest, the authored state schema must\n * reuse the same literal/branded schema so generated types line up with the\n * runtime checks, instead of silently widening to `string`. Relation type tags\n * are open game-defined strings, not manifest membership IDs.\n */\nconst MANIFEST_SCOPED_ID_NAMES = [\n \"playerId\",\n \"cardId\",\n \"deckId\",\n \"handId\",\n \"zoneId\",\n \"sharedZoneId\",\n \"playerZoneId\",\n \"boardId\",\n \"boardTypeId\",\n \"boardBaseId\",\n \"edgeId\",\n \"edgeTypeId\",\n \"vertexId\",\n \"vertexTypeId\",\n \"spaceId\",\n \"spaceTypeId\",\n \"resourceId\",\n \"pieceId\",\n \"pieceTypeId\",\n \"dieId\",\n \"tileId\",\n \"tileTypeId\",\n \"dieTypeId\",\n \"cardSetId\",\n \"cardType\",\n] as const;\n\ntype ManifestScopedIdName = (typeof MANIFEST_SCOPED_ID_NAMES)[number];\n\nfunction matchManifestScopedIdName(\n key: string,\n): { name: ManifestScopedIdName; kind: \"singular\" | \"plural\" } | null {\n for (const name of MANIFEST_SCOPED_ID_NAMES) {\n const capitalized = `${name.charAt(0).toUpperCase()}${name.slice(1)}`;\n if (key === name || key.endsWith(capitalized)) {\n return { name, kind: \"singular\" };\n }\n const plural = `${name}s`;\n const capitalizedPlural = `${capitalized}s`;\n if (key === plural || key.endsWith(capitalizedPlural)) {\n return { name, kind: \"plural\" };\n }\n }\n return null;\n}\n\nexport function validateInteractionParamsSchema(\n schema: z.core.$ZodType,\n context: string,\n path: string,\n): void {\n const inner = unwrapWrappers(schema);\n if (isEnumKeyedRecordSchema(inner) && !isSparseMapSchema(inner)) {\n throw new Error(\n `${context}: ${path} uses an enum-keyed z.record(...), which parses as a total map at runtime. ` +\n `Use sparseMap(...) or sparseCounts(...) from @dreamboard-games/sdk/reducer instead so interaction params stay sparse and match runtime validation.`,\n );\n }\n\n const shape = getObjectShape(inner);\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape)) {\n validateInteractionParamsSchema(fieldSchema, context, `${path}.${key}`);\n }\n return;\n }\n\n const def = getZodDef(inner);\n if (def.type === \"array\" && def.element) {\n validateInteractionParamsSchema(def.element, context, `${path}[]`);\n return;\n }\n\n if (def.type === \"record\" && def.valueType) {\n validateInteractionParamsSchema(def.valueType, context, `${path}.*`);\n }\n}\n\nexport function validateInteractionInputsSchema(\n inputs: Record<string, InputCollector> | undefined,\n context: string,\n): void {\n if (!inputs) return;\n for (const [key, collector] of Object.entries(inputs)) {\n validateInteractionParamsSchema(collector.schema, context, `inputs.${key}`);\n }\n}\n\nexport function validateManyCommitPolicy(input: {\n inputs: Record<string, InputCollector> | undefined;\n commit?: { mode: string };\n context: string;\n}): void {\n if (input.commit?.mode !== \"autoWhenReady\") return;\n if (\n Object.values(input.inputs ?? {}).some(\n (collector) => collector.selection?.mode === \"many\",\n )\n ) {\n throw new Error(\n `${input.context}: interactions with many(...) inputs must use commit: { mode: \"manual\" }.`,\n );\n }\n}\n\nexport function validateInteractionLikeDefinition(\n input: {\n inputs?: Record<string, InputCollector>;\n steps?: { entries: readonly { key: string }[] };\n commit?: { mode: string };\n paramsSchema?: z.core.$ZodType;\n },\n context: string,\n): void {\n if (input.steps) {\n if (input.inputs !== undefined)\n throw new Error(\"An interaction declares inputs or steps, never both.\");\n if (input.steps.entries.length === 0)\n throw new Error(\"An interaction requires at least one step.\");\n const keys = input.steps.entries.map((entry) => entry.key);\n if (new Set(keys).size !== keys.length)\n throw new Error(\"Interaction step keys must be unique.\");\n }\n validateInteractionInputsSchema(input.inputs, context);\n validateManyCommitPolicy({\n inputs: input.inputs,\n commit: input.commit,\n context,\n });\n if (input.paramsSchema) {\n validateInteractionParamsSchema(\n input.paramsSchema,\n context,\n \"paramsSchema\",\n );\n }\n}\n\nexport function validateStateSchemaIdBranding(\n schema: z.core.$ZodType,\n scope: \"public\" | \"private\" | \"hidden\",\n): void {\n const def = getZodDef(schema);\n if (def.type !== \"object\") {\n return;\n }\n const shape = def.shape;\n for (const [key, fieldSchema] of Object.entries(shape)) {\n const match = matchManifestScopedIdName(key);\n if (!match) {\n continue;\n }\n const inner = unwrapWrappers(fieldSchema);\n if (match.kind === \"singular\") {\n if (isPlainZodString(inner) && !isManifestScopedSchema(inner)) {\n throw new Error(\n `defineGameContract: state.${scope}.${key} uses a raw z.string() ` +\n `but its name identifies it as a manifest-scoped '${match.name}'. ` +\n `Use manifest.ids.${match.name} ` +\n `so the branded literal union flows through state types.`,\n );\n }\n continue;\n }\n const innerDef = getZodDef(inner);\n if (match.kind === \"plural\" && innerDef.type === \"array\") {\n const element = unwrapWrappers(innerDef.element);\n if (isPlainZodString(element) && !isManifestScopedSchema(element)) {\n throw new Error(\n `defineGameContract: state.${scope}.${key} uses z.array(z.string()) ` +\n `but its name identifies it as manifest-scoped '${match.name}' values. ` +\n `Use z.array(manifest.ids.${match.name}) so the branded literal union flows through state types.`,\n );\n }\n }\n }\n}\n\nexport function validateDefineGamePhaseNames(definition: {\n contract: { readonly phases: Readonly<Record<string, unknown>> };\n phases: Record<string, unknown>;\n initialPhase?: string;\n}): void {\n const contractPhaseNames = Object.keys(definition.contract.phases);\n const declared = new Set(contractPhaseNames);\n const actual = new Set(Object.keys(definition.phases));\n const missing = [...declared].filter((name) => !actual.has(name));\n const extra = [...actual].filter((name) => !declared.has(name));\n if (missing.length > 0 || extra.length > 0) {\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(`missing: [${missing.join(\", \")}]`);\n }\n if (extra.length > 0) {\n parts.push(`extra: [${extra.join(\", \")}]`);\n }\n throw new Error(\n `defineGame: phases record does not match contract.phaseNames (${parts.join(\n \"; \",\n )}). Update contract.phaseNames or the phases record so they agree.`,\n );\n }\n if (\n definition.initialPhase !== undefined &&\n !declared.has(definition.initialPhase)\n ) {\n throw new Error(\n `defineGame: initialPhase '${definition.initialPhase}' is not declared in contract.phaseNames.`,\n );\n }\n}\n\nexport function validateDefineGamePhases(definition: {\n phases: Record<string, unknown>;\n}): void {\n for (const [phaseName, phase] of Object.entries(definition.phases)) {\n const phaseRecord =\n typeof phase === \"object\" && phase !== null\n ? (phase as {\n kind?: unknown;\n submit?: { inputs?: Record<string, InputCollector> };\n resolve?: unknown;\n interactions?: Record<string, unknown>;\n })\n : null;\n for (const interaction of Object.values(phaseRecord?.interactions ?? {})) {\n validateInteractionLikeDefinition(\n interaction as Parameters<typeof validateInteractionLikeDefinition>[0],\n \"defineInteraction\",\n );\n }\n if (!phaseRecord || phaseRecord.kind !== \"simultaneousPlayer\") {\n continue;\n }\n if (!phaseRecord.submit) {\n throw new Error(\n `defineGame: phases.${phaseName} is kind 'simultaneousPlayer' but does not declare submit.`,\n );\n }\n if (typeof phaseRecord.resolve !== \"function\") {\n throw new Error(\n `defineGame: phases.${phaseName} is kind 'simultaneousPlayer' but does not declare resolve.`,\n );\n }\n if (phaseRecord.interactions?.submit) {\n throw new Error(\n `defineGame: phases.${phaseName}.interactions.submit conflicts with the reserved simultaneous submit interaction id.`,\n );\n }\n validateInteractionLikeDefinition(\n phaseRecord.submit,\n `defineGame: phases.${phaseName}.submit`,\n );\n }\n}\n\nexport type ManifestIdSchemasOf<\n Ids extends Record<string, SchemaLike<unknown>>,\n> = {\n readonly [Key in keyof Ids]: Ids[Key] extends SchemaLike<infer Output>\n ? Ids[Key] & import(\"../model\").ManifestIdSchema<Output>\n : Ids[Key];\n};\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport { validateInteractionInputsSchema } from \"./validation\";\nimport type {\n CollectorState,\n InputCollector,\n ParamsOf,\n PlayerIdOfState,\n TableQueriesOfState,\n} from \"../model\";\n\ntype StepCollector = Exclude<InputCollector, { readonly kind: \"rng\" }>;\n\nexport type StepFactoryArgs<\n State extends CollectorState,\n Collectors extends Record<string, InputCollector>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n readonly state: State;\n readonly playerId: PlayerIdOfState<State>;\n readonly q: TableQueriesOfState<State, Definitions>;\n readonly selected: Readonly<ParamsOf<Collectors>>;\n};\n\nexport type InputStep<\n State extends CollectorState,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n readonly key: string;\n readonly resolve: {\n invoke(\n args: StepFactoryArgs<State, Record<string, InputCollector>, Definitions>,\n ): InputCollector;\n }[\"invoke\"];\n};\n\nexport type StepDefinition<\n Collectors extends Record<string, InputCollector>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n readonly collectors: Collectors;\n readonly entries: readonly InputStep<CollectorState, Definitions>[];\n};\n\n/** Ordered authoring definition. Only the committed values are persisted. */\nexport class InteractionSteps<\n State extends CollectorState,\n Collectors extends Record<string, InputCollector> = Record<never, never>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> {\n declare readonly collectors: Collectors;\n\n constructor(\n readonly entries: readonly InputStep<State, Definitions>[] = [],\n ) {}\n\n input<const Key extends string, Collector extends StepCollector>(\n key: Key extends keyof Collectors ? never : Key,\n collector:\n | Collector\n | ((args: StepFactoryArgs<State, Collectors, Definitions>) => Collector),\n ): InteractionSteps<State, Collectors & Record<Key, Collector>, Definitions> {\n if (this.entries.some((entry) => entry.key === key)) {\n throw new Error(`Duplicate interaction step '${key}'.`);\n }\n const factory =\n typeof collector === \"function\"\n ? (collector as InputStep<State, Definitions>[\"resolve\"])\n : () => collector;\n const resolve: InputStep<State, Definitions>[\"resolve\"] = (args) => {\n const resolved = factory(args);\n if (resolved.kind === \"rng\")\n throw new Error(\"Interaction steps cannot contain RNG collectors.\");\n validateInteractionInputsSchema({ [key]: resolved }, \"defineInteraction\");\n return resolved;\n };\n if (\n typeof collector !== \"function\" &&\n (collector as InputCollector).kind === \"rng\"\n ) {\n throw new Error(\"Interaction steps cannot contain RNG collectors.\");\n }\n if (typeof collector !== \"function\")\n validateInteractionInputsSchema(\n { [key]: collector },\n \"defineInteraction\",\n );\n return new InteractionSteps([...this.entries, { key, resolve }]);\n }\n}\n","import * as z from \"zod\";\nimport type { SchemaLike } from \"../model/table\";\nimport type { ManifestIdSchema } from \"../model/manifest\";\nimport type {\n BoundedNumberDomainDescriptor,\n ChoiceDomainDescriptor,\n ChoiceListDomainDescriptor,\n CollectorState,\n InputCollector,\n ResourceMapDomainDescriptor,\n} from \"../model/spec\";\nimport type { PlayerIdOfState } from \"../model/extract\";\nimport type { TableQueriesOfState } from \"../model/queries\";\n\ntype DomainContext<State extends CollectorState> = {\n state: State;\n playerId: PlayerIdOfState<State>;\n q: TableQueriesOfState<State>;\n};\n\ntype ManifestFormInputSchema =\n | ManifestIdSchema<unknown>\n | z.ZodOptional<ManifestIdSchema<unknown>>\n | z.ZodNullable<ManifestIdSchema<unknown>>;\n\ntype DomainNumber<State extends CollectorState> =\n number | ((context: DomainContext<State>) => number);\n\ntype ResourceMapInputOptions<State extends CollectorState> = {\n resources: ReadonlyArray<{\n resourceId: string;\n label?: string;\n icon?: string;\n min?: DomainNumber<State>;\n max: DomainNumber<State>;\n }>;\n};\n\ntype ChoiceValue = string | null;\n\ntype FormCollector<\n Schema extends SchemaLike<unknown>,\n State extends CollectorState,\n Domain extends\n | ResourceMapDomainDescriptor\n | BoundedNumberDomainDescriptor\n | ChoiceDomainDescriptor\n | ChoiceListDomainDescriptor,\n Value = z.infer<Schema>,\n> = Omit<InputCollector<Schema, State, \"form\", Value>, \"domain\"> & {\n readonly domain: (\n state: CollectorState,\n playerId: string,\n q: unknown,\n ) => Domain;\n};\n\ntype DomainChoice<Value extends ChoiceValue> = {\n value: Value;\n label: string;\n icon?: string;\n badge?: string;\n description?: string;\n disabled?: boolean;\n disabledReason?: string;\n};\n\ntype DomainChoicePresentation = {\n badge?: string;\n description?: string;\n disabled?: boolean;\n disabledReason?: string;\n};\n\ntype ResourceMapChoiceDecorator<State extends CollectorState> = (\n context: DomainContext<State> & {\n resourceId: string;\n label: string;\n icon?: string;\n },\n) => DomainChoicePresentation | null | undefined;\n\ntype ResourceMapChoiceSource<State extends CollectorState> =\n | \"resourceMap\"\n | {\n source: \"resourceMap\";\n decorate?: ResourceMapChoiceDecorator<State>;\n };\n\ntype DomainChoices<Value extends ChoiceValue, State extends CollectorState> =\n | ReadonlyArray<DomainChoice<Value>>\n | ResourceMapChoiceSource<State>\n | ((context: DomainContext<State>) => ReadonlyArray<DomainChoice<Value>>);\n\ntype ChoiceListDefaultValue<\n Value extends string,\n State extends CollectorState,\n> =\n | Value[]\n | \"all\"\n | ((\n context: DomainContext<State> & {\n choices: ReadonlyArray<DomainChoice<Value>>;\n },\n ) => Value[]);\n\ntype ChoiceDefaultValue<\n Value extends ChoiceValue,\n State extends CollectorState,\n> =\n | Value\n | ((\n context: DomainContext<State> & {\n choices: ReadonlyArray<DomainChoice<Value>>;\n },\n ) => Value);\n\ntype ChoiceDefaultResolver<\n Value extends ChoiceValue,\n State extends CollectorState,\n> = (\n context: DomainContext<State> & {\n choices: ReadonlyArray<DomainChoice<Value>>;\n },\n) => Value | undefined;\n\nfunction isResourceMapChoiceSource<State extends CollectorState>(\n choices: DomainChoices<ChoiceValue, State>,\n): choices is ResourceMapChoiceSource<State> {\n return (\n choices === \"resourceMap\" ||\n (typeof choices === \"object\" &&\n choices !== null &&\n !Array.isArray(choices) &&\n \"source\" in choices &&\n choices.source === \"resourceMap\")\n );\n}\n\nfunction resolveDomainNumber<State extends CollectorState>(\n value: DomainNumber<State> | undefined,\n context: DomainContext<State>,\n fallback: number,\n): number {\n if (typeof value === \"function\") return value(context);\n return value ?? fallback;\n}\n\nfunction resolveDomainChoices<\n Value extends ChoiceValue,\n State extends CollectorState,\n>(\n choices: DomainChoices<Value, State>,\n context: DomainContext<State>,\n): Array<{\n value: ChoiceValue;\n label: string;\n icon?: string;\n badge?: string;\n description?: string;\n disabled?: boolean;\n disabledReason?: string;\n}> {\n if (isResourceMapChoiceSource(choices)) {\n return resolveResourceMapChoices(choices, context);\n }\n const resolved = typeof choices === \"function\" ? choices(context) : choices;\n return resolved.map((choice) => ({\n value: choice.value,\n label: choice.label,\n icon: choice.icon,\n badge: choice.badge,\n description: choice.description,\n disabled: choice.disabled,\n disabledReason: choice.disabledReason,\n }));\n}\n\nfunction choiceValuesInclude(\n choices: ReadonlyArray<{ value: ChoiceValue }>,\n value: ChoiceValue,\n): boolean {\n return choices.some((choice) => Object.is(choice.value, value));\n}\n\nfunction assertChoiceDefaultInChoices(\n inputName: string,\n choices: ReadonlyArray<{ value: ChoiceValue }>,\n defaultValue: ChoiceValue,\n): void {\n if (choiceValuesInclude(choices, defaultValue)) return;\n const printable = defaultValue === null ? \"null\" : `'${defaultValue}'`;\n throw new Error(\n `${inputName} defaultValue ${printable} must be one of its choices. ` +\n \"If null is a valid value, add an explicit { value: null, label: ... } choice.\",\n );\n}\n\nfunction choiceSchema<Value extends ChoiceValue>(\n choices: ReadonlyArray<DomainChoice<Value>>,\n): SchemaLike<Value> {\n if (choices.length === 0) return z.never();\n return z.literal(choices.map((choice) => choice.value));\n}\n\nfunction resolveResourceMapChoices<State extends CollectorState>(\n choices: ResourceMapChoiceSource<State>,\n context: DomainContext<State>,\n): Array<{\n value: string;\n label: string;\n badge?: string;\n description?: string;\n disabled?: boolean;\n disabledReason?: string;\n}> {\n const firstPlayerId = context.state.table.playerOrder[0];\n const firstResourceMap =\n firstPlayerId === undefined\n ? undefined\n : context.state.table.resources[firstPlayerId];\n if (\n typeof firstResourceMap !== \"object\" ||\n firstResourceMap === null ||\n Array.isArray(firstResourceMap)\n ) {\n return [];\n }\n const decorate = choices === \"resourceMap\" ? undefined : choices.decorate;\n return Object.keys(firstResourceMap)\n .sort()\n .map((resourceId) => {\n const label = resourceId;\n const presentation = decorate?.({ ...context, resourceId, label });\n return {\n value: resourceId,\n label,\n badge: presentation?.badge,\n description: presentation?.description,\n disabled: presentation?.disabled,\n disabledReason: presentation?.disabledReason,\n };\n });\n}\n\nfunction createFormInput<\n Schema extends SchemaLike<unknown>,\n State extends CollectorState = CollectorState,\n>(\n schema: Schema,\n options?: { defaultValue?: z.infer<Schema> },\n): InputCollector<Schema, State, \"form\"> {\n return {\n kind: \"form\",\n schema,\n ...(options && \"defaultValue\" in options\n ? { defaultValue: options.defaultValue }\n : {}),\n };\n}\n\nfunction baseFormInput<\n Schema extends ManifestFormInputSchema & SchemaLike<unknown>,\n State extends CollectorState = CollectorState,\n>(schema: Schema): InputCollector<Schema, State, \"form\">;\nfunction baseFormInput<\n Schema extends ManifestFormInputSchema & SchemaLike<unknown>,\n State extends CollectorState = CollectorState,\n>(\n schema: Schema,\n options: { defaultValue: z.infer<Schema> },\n): InputCollector<Schema, State, \"form\"> & {\n readonly defaultValue: z.infer<Schema>;\n};\nfunction baseFormInput<\n Schema extends ManifestFormInputSchema & SchemaLike<unknown>,\n State extends CollectorState = CollectorState,\n>(\n schema: Schema,\n options?: { defaultValue?: z.infer<Schema> },\n): InputCollector<Schema, State, \"form\"> {\n return createFormInput(schema, options);\n}\n\nfunction resourceMapInput<State extends CollectorState = CollectorState>(\n options: ResourceMapInputOptions<State>,\n): FormCollector<\n z.ZodRecord<z.ZodString, z.ZodNumber>,\n State,\n ResourceMapDomainDescriptor\n>;\nfunction resourceMapInput<State extends CollectorState = CollectorState>(\n options: ResourceMapInputOptions<State> & {\n defaultValue: Record<string, number>;\n },\n): FormCollector<\n z.ZodRecord<z.ZodString, z.ZodNumber>,\n State,\n ResourceMapDomainDescriptor\n> & {\n readonly defaultValue: Record<string, number>;\n};\nfunction resourceMapInput<State extends CollectorState = CollectorState>(\n options: ResourceMapInputOptions<State> & {\n defaultValue?: Record<string, number>;\n },\n): FormCollector<\n z.ZodRecord<z.ZodString, z.ZodNumber>,\n State,\n ResourceMapDomainDescriptor\n> {\n return {\n kind: \"form\",\n schema: z.record(z.string(), z.number().int().nonnegative()),\n ...(\"defaultValue\" in options\n ? { defaultValue: options.defaultValue }\n : {}),\n domain: (state, playerId, q): ResourceMapDomainDescriptor => {\n const context = {\n state: state as State,\n playerId: playerId as PlayerIdOfState<State>,\n q: q as TableQueriesOfState<State>,\n };\n return {\n type: \"resourceMap\",\n resources: options.resources.map((resource) => ({\n resourceId: resource.resourceId,\n label: resource.label,\n icon: resource.icon,\n min: resolveDomainNumber(resource.min, context, 0),\n max: resolveDomainNumber(resource.max, context, 0),\n })),\n };\n },\n };\n}\n\nfunction numberInput<State extends CollectorState = CollectorState>(options: {\n min: DomainNumber<State>;\n max: DomainNumber<State>;\n step?: DomainNumber<State>;\n}): FormCollector<z.ZodNumber, State, BoundedNumberDomainDescriptor>;\nfunction numberInput<State extends CollectorState = CollectorState>(options: {\n min: DomainNumber<State>;\n max: DomainNumber<State>;\n step?: DomainNumber<State>;\n defaultValue: number;\n}): FormCollector<z.ZodNumber, State, BoundedNumberDomainDescriptor> & {\n readonly defaultValue: number;\n};\nfunction numberInput<State extends CollectorState = CollectorState>(options: {\n min: DomainNumber<State>;\n max: DomainNumber<State>;\n step?: DomainNumber<State>;\n defaultValue?: number;\n}): FormCollector<z.ZodNumber, State, BoundedNumberDomainDescriptor> {\n return {\n kind: \"form\",\n schema: z.number(),\n ...(\"defaultValue\" in options\n ? { defaultValue: options.defaultValue }\n : {}),\n domain: (state, playerId, q): BoundedNumberDomainDescriptor => {\n const context = {\n state: state as State,\n playerId: playerId as PlayerIdOfState<State>,\n q: q as TableQueriesOfState<State>,\n };\n return {\n type: \"boundedNumber\",\n min: resolveDomainNumber(options.min, context, 0),\n max: resolveDomainNumber(options.max, context, 0),\n step:\n options.step === undefined\n ? undefined\n : resolveDomainNumber(options.step, context, 1),\n };\n },\n };\n}\n\nfunction choiceInput<\n Value extends ChoiceValue,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: ReadonlyArray<DomainChoice<Value>>;\n defaultValue: Value;\n}): FormCollector<SchemaLike<Value>, State, ChoiceDomainDescriptor, Value> & {\n readonly defaultValue: Value;\n};\nfunction choiceInput<\n Value extends ChoiceValue,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: DomainChoices<Value, State>;\n defaultValue: Value;\n}): FormCollector<\n SchemaLike<ChoiceValue>,\n State,\n ChoiceDomainDescriptor,\n Value\n> & {\n readonly defaultValue: Value;\n};\nfunction choiceInput<\n Value extends ChoiceValue,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: ReadonlyArray<DomainChoice<Value>>;\n defaultValue: ChoiceDefaultResolver<Value, State>;\n}): FormCollector<SchemaLike<Value>, State, ChoiceDomainDescriptor, Value>;\nfunction choiceInput<\n Value extends ChoiceValue,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: DomainChoices<Value, State>;\n defaultValue: ChoiceDefaultResolver<Value, State>;\n}): FormCollector<\n SchemaLike<ChoiceValue>,\n State,\n ChoiceDomainDescriptor,\n Value\n>;\nfunction choiceInput<\n Value extends ChoiceValue,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: DomainChoices<Value, State>;\n defaultValue: ChoiceDefaultValue<Value, State>;\n}): FormCollector<\n SchemaLike<ChoiceValue>,\n State,\n ChoiceDomainDescriptor,\n Value\n> {\n const staticChoices = Array.isArray(options.choices) ? options.choices : null;\n const hasStaticDefault = typeof options.defaultValue !== \"function\";\n const staticDefault = options.defaultValue as ChoiceValue;\n if (staticChoices && hasStaticDefault) {\n assertChoiceDefaultInChoices(\n \"formInput.choice\",\n staticChoices,\n staticDefault,\n );\n }\n const schema = staticChoices\n ? choiceSchema<Value>(staticChoices)\n : z.string().nullable();\n const dynamicDefault =\n typeof options.defaultValue === \"function\"\n ? options.defaultValue\n : undefined;\n return {\n kind: \"form\",\n schema,\n ...(hasStaticDefault ? { defaultValue: staticDefault as Value } : {}),\n domain: (state, playerId, q): ChoiceDomainDescriptor => {\n const context = {\n state: state as State,\n playerId: playerId as PlayerIdOfState<State>,\n q: q as TableQueriesOfState<State>,\n };\n const choices = resolveDomainChoices(options.choices, context);\n if (hasStaticDefault) {\n assertChoiceDefaultInChoices(\n \"formInput.choice\",\n choices,\n staticDefault,\n );\n }\n return {\n type: \"choice\",\n choices,\n };\n },\n ...(dynamicDefault\n ? {\n resolveDefaultValue: (state, playerId, q, domain) => {\n const choices =\n domain.type === \"choice\"\n ? domain.choices.map((choice) => ({\n value: choice.value as Value,\n label: choice.label,\n icon: choice.icon,\n badge: choice.badge,\n description: choice.description,\n disabled: choice.disabled,\n disabledReason: choice.disabledReason,\n }))\n : [];\n const resolved = dynamicDefault({\n state: state as State,\n playerId: playerId as PlayerIdOfState<State>,\n q: q as TableQueriesOfState<State>,\n\n choices,\n });\n if (resolved === undefined) return undefined;\n assertChoiceDefaultInChoices(\"formInput.choice\", choices, resolved);\n return resolved;\n },\n }\n : {}),\n };\n}\n\ntype ChoiceListCollector<\n Value extends string,\n State extends CollectorState,\n> = InputCollector<z.ZodArray<z.ZodString>, State, \"form\", Value[]> & {\n readonly domain: (\n state: CollectorState,\n playerId: string,\n q: unknown,\n ) => ChoiceListDomainDescriptor;\n};\n\nfunction choiceListInput<\n Value extends string,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: DomainChoices<Value, State>;\n min?: DomainNumber<State>;\n max?: DomainNumber<State>;\n defaultValue: Value[];\n}): ChoiceListCollector<Value, State> & {\n readonly defaultValue: Value[];\n};\nfunction choiceListInput<\n Value extends string,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: DomainChoices<Value, State>;\n min?: DomainNumber<State>;\n max?: DomainNumber<State>;\n defaultValue?: ChoiceListDefaultValue<Value, State>;\n}): ChoiceListCollector<Value, State>;\nfunction choiceListInput<\n Value extends string,\n State extends CollectorState = CollectorState,\n>(options: {\n choices: DomainChoices<Value, State>;\n min?: DomainNumber<State>;\n max?: DomainNumber<State>;\n defaultValue?: ChoiceListDefaultValue<Value, State>;\n}): ChoiceListCollector<Value, State> {\n if (Array.isArray(options.choices) && options.choices.length === 0) {\n throw new Error(\"formInput.choiceList requires at least one choice.\");\n }\n const staticDefaultValue = Array.isArray(options.defaultValue)\n ? options.defaultValue\n : undefined;\n const dynamicDefaultValue =\n options.defaultValue === \"all\" || typeof options.defaultValue === \"function\"\n ? options.defaultValue\n : undefined;\n return {\n kind: \"form\",\n schema: z.array(z.string()),\n ...(staticDefaultValue !== undefined\n ? { defaultValue: staticDefaultValue }\n : {}),\n domain: (state, playerId, q): ChoiceListDomainDescriptor => {\n const context = {\n state: state as State,\n playerId: playerId as PlayerIdOfState<State>,\n q: q as TableQueriesOfState<State>,\n };\n const choices = resolveDomainChoices(options.choices, context).map(\n (choice) => ({\n ...choice,\n value: choice.value as string,\n }),\n );\n return {\n type: \"choiceList\",\n choices,\n min: resolveDomainNumber(options.min, context, 0),\n max: resolveDomainNumber(options.max, context, choices.length),\n };\n },\n ...(dynamicDefaultValue\n ? {\n resolveDefaultValue: (state, playerId, q, domain) => {\n const choices =\n domain.type === \"choiceList\"\n ? domain.choices.map((choice) => ({\n value: choice.value as Value,\n label: choice.label,\n icon: choice.icon,\n badge: choice.badge,\n description: choice.description,\n disabled: choice.disabled,\n disabledReason: choice.disabledReason,\n }))\n : [];\n if (dynamicDefaultValue === \"all\") {\n return choices.map((choice) => choice.value);\n }\n return dynamicDefaultValue({\n state: state as State,\n playerId: playerId as PlayerIdOfState<State>,\n q: q as TableQueriesOfState<State>,\n\n choices,\n });\n },\n }\n : {}),\n };\n}\n\ntype FormInputForState<State extends CollectorState> = {\n <Schema extends ManifestFormInputSchema & SchemaLike<unknown>>(\n schema: Schema,\n ): InputCollector<Schema, State, \"form\">;\n <Schema extends ManifestFormInputSchema & SchemaLike<unknown>>(\n schema: Schema,\n options: { defaultValue: z.infer<Schema> },\n ): InputCollector<Schema, State, \"form\"> & {\n readonly defaultValue: z.infer<Schema>;\n };\n resourceMap(\n options: ResourceMapInputOptions<State>,\n ): FormCollector<\n z.ZodRecord<z.ZodString, z.ZodNumber>,\n State,\n ResourceMapDomainDescriptor\n >;\n resourceMap(\n options: ResourceMapInputOptions<State> & {\n defaultValue: Record<string, number>;\n },\n ): FormCollector<\n z.ZodRecord<z.ZodString, z.ZodNumber>,\n State,\n ResourceMapDomainDescriptor\n > & {\n readonly defaultValue: Record<string, number>;\n };\n resourceChoices(options?: {\n decorate?: ResourceMapChoiceDecorator<State>;\n }): ResourceMapChoiceSource<State>;\n number: typeof numberInput<State>;\n choice<Value extends ChoiceValue>(options: {\n choices: ReadonlyArray<DomainChoice<Value>>;\n defaultValue: Value;\n }): FormCollector<SchemaLike<Value>, State, ChoiceDomainDescriptor, Value> & {\n readonly defaultValue: Value;\n };\n choice<Value extends ChoiceValue>(options: {\n choices: DomainChoices<Value, State>;\n defaultValue: Value;\n }): FormCollector<\n SchemaLike<ChoiceValue>,\n State,\n ChoiceDomainDescriptor,\n Value\n > & {\n readonly defaultValue: Value;\n };\n choice<Value extends ChoiceValue>(options: {\n choices: ReadonlyArray<DomainChoice<Value>>;\n defaultValue: ChoiceDefaultResolver<Value, State>;\n }): FormCollector<SchemaLike<Value>, State, ChoiceDomainDescriptor, Value>;\n choice<Value extends ChoiceValue>(options: {\n choices: DomainChoices<Value, State>;\n defaultValue: ChoiceDefaultResolver<Value, State>;\n }): FormCollector<\n SchemaLike<ChoiceValue>,\n State,\n ChoiceDomainDescriptor,\n Value\n >;\n choiceList<Value extends string>(options: {\n choices: DomainChoices<Value, State>;\n min?: DomainNumber<State>;\n max?: DomainNumber<State>;\n defaultValue: Value[];\n }): ChoiceListCollector<Value, State> & {\n readonly defaultValue: Value[];\n };\n choiceList<Value extends string>(options: {\n choices: DomainChoices<Value, State>;\n min?: DomainNumber<State>;\n max?: DomainNumber<State>;\n defaultValue?: ChoiceListDefaultValue<Value, State>;\n }): ChoiceListCollector<Value, State>;\n};\n\nfunction formInputForState<\n State extends CollectorState,\n>(): FormInputForState<State> {\n return Object.assign(baseFormInput.bind(undefined), {\n resourceMap: resourceMapInput<State>,\n resourceChoices: (options?: {\n decorate?: ResourceMapChoiceDecorator<State>;\n }) => formInput.resourceChoices<State>(options),\n number: numberInput<State>,\n choice: choiceInput,\n choiceList: choiceListInput,\n });\n}\n\n/**\n * Manifest-backed id input. Free-form Zod schemas are intentionally explicit:\n * if the runtime cannot disclose valid values or numeric bounds through a\n * manifest id or domain helper, use a custom interaction surface with an\n * explicit `paramsSchema` instead of the default form renderer.\n */\nexport const formInput = Object.assign(baseFormInput, {\n resourceMap: resourceMapInput,\n resourceChoices: <State extends CollectorState = CollectorState>(options?: {\n decorate?: ResourceMapChoiceDecorator<State>;\n }): ResourceMapChoiceSource<State> => ({\n source: \"resourceMap\",\n ...options,\n }),\n number: numberInput,\n choice: choiceInput,\n choiceList: choiceListInput,\n forState: formInputForState,\n});\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport type { PerPlayerInstanceId } from \"../../shared/domain/per-player-instance.js\";\nimport type { PlayerIdOfState, TableQueriesOfState } from \"../model\";\nimport * as z from \"zod\";\nimport type {\n BoardTargetDomainDescriptor,\n CollectorState,\n InputCollector,\n TargetKind,\n} from \"../model/spec\";\nimport {\n markManifestScopedSchema,\n type ManifestIdSchema,\n} from \"../model/manifest\";\nimport type {\n BoardIdTargetRule,\n BoardSpaceTargetRule,\n BoardSpaceTarget,\n} from \"./boardTarget\";\n\nexport type BoardSpaceInputSchema = z.ZodObject<{\n boardId: ManifestIdSchema<string, \"boardId\">;\n spaceId: z.ZodString;\n}>;\n\n/**\n * `boardInput.*` helpers produce collectors that accept a board-element id\n * (vertex / edge / space) scoped to one built `boardTarget` rule.\n *\n * Id typing:\n * The `Id` type parameter is the branded id for the board you target,\n * e.g. `HexVertexIdOfTable<Table, \"main\">` or\n * `SquareSpaceIdOfTable<Table, \"board\">`. Once tightened,\n * `ParamsOf<Collectors>` downstream typing reflects the branded id too.\n *\n * Eligibility:\n * Pass a built `boardTarget.*(...).where(...).build()` rule. The same rule\n * feeds server-authoritative eligible-target projection, submit validation,\n * and tests through its `bind({ state, playerId, q })` helper.\n *\n * Runtime vs. compile time:\n * At runtime the submitted value is a string. Branding is purely a\n * compile-time discipline.\n */\nfunction makeBoardCollector<\n Kind extends \"board-vertex\" | \"board-edge\" | \"board-space\",\n>(kind: Kind) {\n return function collector<\n State extends CollectorState = CollectorState,\n Id extends string = string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n >(options: {\n target: BoardIdTargetRule<\n State,\n Id,\n Kind extends `board-${infer Target extends Exclude<TargetKind, \"card\" | \"tile\">}`\n ? Target\n : never,\n Definitions\n >;\n }): InputCollector<z.ZodString, State, Kind, Id> {\n const target = options.target;\n const eligible = (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) => target.eligible({ state, playerId, q });\n // Assembly binds state/player/queries to one validated game contract.\n // Schemas check wire shape only; validateTarget must resolve a canonical\n // candidate before the runtime exposes the refined Id to authored reducers.\n // This is the explicit binding of both invariants into the runtime registry.\n // eslint-disable-next-line no-restricted-syntax -- Assembly binds these hooks to State; canonical target membership supplies Id after the string schema parses.\n return {\n kind,\n schema: z.string(),\n eligibleTargets: eligible,\n validateTarget: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n targetId: unknown,\n ) => target.validate({ state, playerId, q }, targetId),\n domain: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) =>\n ({\n type: \"boardTarget\",\n projection: \"resolved\",\n targetKind: target.targetKind,\n boardId: target.boardId,\n valueKind: \"board-id\",\n eligibleTargets: eligible(state, playerId, q),\n }) satisfies BoardTargetDomainDescriptor,\n meta: {\n targetKind: target.targetKind,\n boardId: target.boardId,\n valueKind: \"board-id\",\n },\n } as unknown as InputCollector<z.ZodString, State, Kind, Id>;\n };\n}\n\nexport const vertexInput = makeBoardCollector(\"board-vertex\");\nexport const edgeInput = makeBoardCollector(\"board-edge\");\nexport const spaceInput = makeBoardCollector(\"board-space\");\n\nexport function playerSpaceInput<\n State extends CollectorState = CollectorState,\n BoardId extends string = string,\n SpaceId extends string = string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(options: {\n target: BoardSpaceTargetRule<State, BoardId, SpaceId, Definitions>;\n}): InputCollector<\n BoardSpaceInputSchema,\n State,\n \"board-space\",\n BoardSpaceTarget<PerPlayerInstanceId<\"board\", BoardId>, SpaceId>\n> {\n const target = options.target;\n const boardIdSchema = markManifestScopedSchema(z.string(), \"boardId\");\n const eligible = (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) => target.eligible({ state, playerId, q });\n // Assembly binds state/player/queries to one validated game contract.\n // Schemas check wire shape only; validateTarget must resolve a canonical\n // candidate before the runtime exposes the refined Id to authored reducers.\n // This is the explicit binding of both invariants into the runtime registry.\n // eslint-disable-next-line no-restricted-syntax -- Assembly binds these hooks to State; the strict object schema and canonical target membership supply the player-space value.\n return {\n kind: \"board-space\",\n schema: z.strictObject({\n boardId: boardIdSchema,\n spaceId: z.string(),\n }),\n eligibleTargets: eligible,\n validateTarget: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n targetValue: unknown,\n ) => target.validate({ state, playerId, q }, targetValue),\n domain: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) =>\n ({\n type: \"boardTarget\",\n projection: \"resolved\",\n targetKind: \"space\",\n boardBaseId: target.boardBaseId,\n valueKind: \"board-space\",\n eligibleTargets: eligible(state, playerId, q),\n }) satisfies BoardTargetDomainDescriptor,\n meta: {\n targetKind: target.targetKind,\n boardBaseId: target.boardBaseId,\n valueKind: \"board-space\",\n },\n } as unknown as InputCollector<\n BoardSpaceInputSchema,\n State,\n \"board-space\",\n BoardSpaceTarget<PerPlayerInstanceId<\"board\", BoardId>, SpaceId>\n >;\n}\n\nexport const boardInput = {\n vertex: vertexInput,\n edge: edgeInput,\n space: spaceInput,\n playerSpace: playerSpaceInput,\n};\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport type { CollectorState } from \"../model/spec\";\nimport type { ValidationIssue } from \"../model/spec/runtime-args\";\nimport type { PlayerIdOfState } from \"../model/extract\";\nimport type { TableQueriesOfState } from \"../model/queries\";\n\nexport type TargetContext<\n State extends CollectorState,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n state: State;\n playerId: PlayerIdOfState<State>;\n q: TableQueriesOfState<State, Definitions>;\n};\n\nexport type TargetPredicateArgs<\n State extends CollectorState,\n Target,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetContext<State, Definitions> & {\n targetId: Target;\n};\n\nexport type TargetPredicate<\n State extends CollectorState,\n Target,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n id: string;\n errorCode: string;\n message?: string;\n test: (args: TargetPredicateArgs<State, Target, Definitions>) => boolean;\n};\n\nexport type BoundTargetRule<Target> = {\n readonly eligible: () => readonly Target[];\n readonly validate: (target: unknown) => ValidationIssue | null;\n readonly isEligible: (target: unknown) => boolean;\n};\n\nexport type TargetRule<\n State extends CollectorState,\n Target,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n readonly eligible: (\n ctx: TargetContext<State, Definitions>,\n ) => readonly Target[];\n readonly validate: (\n ctx: TargetContext<State, Definitions>,\n target: unknown,\n ) => ValidationIssue | null;\n readonly isEligible: (\n ctx: TargetContext<State, Definitions>,\n target: unknown,\n ) => boolean;\n readonly bind: (\n ctx: TargetContext<State, Definitions>,\n ) => BoundTargetRule<Target>;\n};\n\nexport type TargetRuleBuilder<\n State extends CollectorState,\n Target,\n Rule extends TargetRule<State, Target, Definitions>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = {\n readonly where: (\n predicate: TargetPredicate<State, Target, Definitions>,\n ) => TargetRuleBuilder<State, Target, Rule, Definitions>;\n readonly build: () => Rule;\n};\n\nexport type TargetCandidateResolver<\n State extends CollectorState,\n Target,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = (ctx: TargetContext<State, Definitions>) => readonly Target[];\n\nexport type TargetRuleOptions = {\n missingCandidateIssue?: ValidationIssue;\n equals?: (left: unknown, right: unknown) => boolean;\n};\n\nconst DEFAULT_MISSING_CANDIDATE_ISSUE: ValidationIssue = {\n errorCode: \"TARGET_NOT_ELIGIBLE\",\n message: \"Target is not eligible.\",\n};\n\nexport function createTargetRule<\n State extends CollectorState,\n Target,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(\n candidates: TargetCandidateResolver<State, Target, Definitions>,\n predicates: readonly TargetPredicate<State, Target, Definitions>[],\n options: TargetRuleOptions = {},\n): TargetRule<State, Target, Definitions> {\n const missingCandidateIssue =\n options.missingCandidateIssue ?? DEFAULT_MISSING_CANDIDATE_ISSUE;\n const equals = options.equals ?? Object.is;\n\n const validate = (\n ctx: TargetContext<State, Definitions>,\n target: unknown,\n ): ValidationIssue | null => {\n for (const candidate of candidates(ctx)) {\n if (!equals(candidate, target)) continue;\n for (const predicate of predicates) {\n if (!predicate.test({ ...ctx, targetId: candidate })) {\n return { errorCode: predicate.errorCode, message: predicate.message };\n }\n }\n return null;\n }\n return missingCandidateIssue;\n };\n\n const rule: TargetRule<State, Target, Definitions> = {\n eligible: (ctx) =>\n candidates(ctx).filter((targetId) => validate(ctx, targetId) == null),\n validate,\n isEligible: (ctx, target) => validate(ctx, target) == null,\n bind: (ctx) => ({\n eligible: () => rule.eligible(ctx),\n validate: (id) => rule.validate(ctx, id),\n isEligible: (id) => rule.isEligible(ctx, id),\n }),\n };\n\n return rule;\n}\n\nexport function createTargetRuleBuilder<\n State extends CollectorState,\n Target,\n Rule extends TargetRule<State, Target, Definitions>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(\n buildRule: (\n predicates: readonly TargetPredicate<State, Target, Definitions>[],\n ) => Rule,\n predicates: readonly TargetPredicate<State, Target, Definitions>[] = [],\n): TargetRuleBuilder<State, Target, Rule, Definitions> {\n return {\n where: (predicate) =>\n createTargetRuleBuilder(buildRule, [...predicates, predicate]),\n build: () => buildRule(predicates),\n };\n}\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport {\n perPlayerInstanceId,\n type PerPlayerInstanceId,\n} from \"../../shared/domain/per-player-instance.js\";\nimport {\n isBoardSpaceTarget,\n sameBoardSpaceTarget,\n type BoardSpaceTarget,\n} from \"../../shared/board-target\";\nexport type { BoardSpaceTarget } from \"../../shared/board-target\";\nimport type { CollectorState, TargetKind } from \"../model/spec\";\nimport type { BoardIdOfTable, TableOfState } from \"../model/extract\";\nimport type { TableQueriesOfState } from \"../model/queries\";\nimport {\n createTargetRule,\n createTargetRuleBuilder,\n type TargetPredicate,\n type TargetRule,\n type TargetRuleBuilder,\n} from \"./targetRule\";\n\nexport type BoardTargetPredicate<\n State extends CollectorState,\n Target,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetPredicate<State, Target, Definitions>;\n\ntype BoardTargetKind = Exclude<TargetKind, \"card\" | \"tile\">;\n\nexport type BoardIdTargetRule<\n State extends CollectorState,\n Id extends string,\n Kind extends BoardTargetKind = BoardTargetKind,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRule<State, Id, Definitions> & {\n readonly targetKind: Kind;\n readonly boardId: string;\n readonly valueKind: \"board-id\";\n};\nexport type BoardSpaceTargetRule<\n State extends CollectorState,\n BoardId extends string,\n SpaceId extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRule<\n State,\n BoardSpaceTarget<PerPlayerInstanceId<\"board\", BoardId>, SpaceId>,\n Definitions\n> & {\n readonly targetKind: \"space\";\n readonly boardBaseId: BoardId;\n readonly valueKind: \"board-space\";\n};\nexport type BoardTargetRule<\n State extends CollectorState,\n Target,\n Kind extends BoardTargetKind = BoardTargetKind,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRule<State, Target, Definitions> &\n (Target extends string\n ? {\n readonly targetKind: Kind;\n readonly boardId: string;\n readonly valueKind: \"board-id\";\n }\n : Target extends BoardSpaceTarget<\n PerPlayerInstanceId<\"board\", infer BoardId>,\n string\n >\n ? {\n readonly targetKind: \"space\";\n readonly boardBaseId: BoardId;\n readonly valueKind: \"board-space\";\n }\n : never);\nexport type BoardTargetBuilder<\n State extends CollectorState,\n Target,\n Kind extends BoardTargetKind = BoardTargetKind,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRuleBuilder<\n State,\n Target,\n BoardTargetRule<State, Target, Kind, Definitions>,\n Definitions\n>;\ntype BoardIdTargetBuilder<\n State extends CollectorState,\n Id extends string,\n Kind extends BoardTargetKind,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRuleBuilder<\n State,\n Id,\n BoardIdTargetRule<State, Id, Kind, Definitions>,\n Definitions\n>;\ntype BoardSpaceTargetBuilder<\n State extends CollectorState,\n BoardId extends string,\n SpaceId extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRuleBuilder<\n State,\n BoardSpaceTarget<PerPlayerInstanceId<\"board\", BoardId>, SpaceId>,\n BoardSpaceTargetRule<State, BoardId, SpaceId, Definitions>,\n Definitions\n>;\n\nfunction candidateIdsForKind<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(\n q: TableQueriesOfState<State, Definitions>,\n boardId: string,\n targetKind: BoardTargetKind,\n): readonly Id[] {\n const board = q.board(boardId as BoardIdOfTable<TableOfState<State>>).state;\n const collection:\n Readonly<Record<string, { id: string }>> | readonly { id: string }[] =\n targetKind === \"edge\"\n ? board.layout === \"generic\"\n ? []\n : board.edges\n : targetKind === \"vertex\"\n ? board.layout === \"generic\"\n ? []\n : board.vertices\n : board.spaces;\n // This builder binds Id to the selected board and target kind in the same State.\n return Object.values(collection).map((value) => value.id) as Id[];\n}\n\nfunction createBoardTargetBuilder<\n State extends CollectorState,\n Id extends string,\n Kind extends BoardTargetKind,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(\n targetKind: Kind,\n boardId: string,\n): BoardIdTargetBuilder<State, Id, Kind, Definitions> {\n return createTargetRuleBuilder<\n State,\n Id,\n BoardIdTargetRule<State, Id, Kind, Definitions>,\n Definitions\n >((predicates) => ({\n ...createTargetRule(\n ({ q }) =>\n candidateIdsForKind<State, Id, Definitions>(q, boardId, targetKind),\n predicates,\n {\n missingCandidateIssue: {\n errorCode: \"BOARD_TARGET_NOT_ELIGIBLE\",\n message: \"Board target is not eligible.\",\n },\n },\n ),\n boardId,\n targetKind,\n valueKind: \"board-id\",\n }));\n}\n\nfunction createPerPlayerBoardSpaceTargetBuilder<\n State extends CollectorState,\n BoardId extends string,\n SpaceId extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(\n boardId: BoardId,\n): BoardSpaceTargetBuilder<State, BoardId, SpaceId, Definitions> {\n type Target = BoardSpaceTarget<\n PerPlayerInstanceId<\"board\", BoardId>,\n SpaceId\n >;\n return createTargetRuleBuilder<\n State,\n Target,\n BoardSpaceTargetRule<State, BoardId, SpaceId, Definitions>,\n Definitions\n >((predicates) => ({\n ...createTargetRule(\n ({ state, q }) => {\n const spacesForPlayer = (playerId: string): readonly SpaceId[] =>\n candidateIdsForKind<State, SpaceId, Definitions>(\n q,\n perPlayerInstanceId(\"board\", boardId, playerId),\n \"space\",\n );\n return state.table.playerOrder.flatMap((playerId) =>\n spacesForPlayer(playerId).map((spaceId) => ({\n boardId: perPlayerInstanceId(\"board\", boardId, playerId),\n spaceId,\n })),\n );\n },\n predicates,\n {\n missingCandidateIssue: {\n errorCode: \"BOARD_TARGET_NOT_ELIGIBLE\",\n message: \"Board target is not eligible.\",\n },\n equals: (left, right) =>\n isBoardSpaceTarget(left) &&\n isBoardSpaceTarget(right) &&\n sameBoardSpaceTarget(left, right),\n },\n ),\n boardBaseId: boardId,\n targetKind: \"space\",\n valueKind: \"board-space\",\n }));\n}\n\nfunction makeBoardTargetFactory<Kind extends BoardTargetKind>(\n targetKind: Kind,\n) {\n return function target<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n >(boardId: string): BoardIdTargetBuilder<State, Id, Kind, Definitions> {\n return createBoardTargetBuilder<State, Id, Kind, Definitions>(\n targetKind,\n boardId,\n );\n };\n}\n\nexport const boardTarget = {\n edge: makeBoardTargetFactory(\"edge\"),\n vertex: makeBoardTargetFactory(\"vertex\"),\n space: makeBoardTargetFactory(\"space\"),\n playerSpace<\n State extends CollectorState,\n BoardId extends string,\n SpaceId extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n >(\n boardId: BoardId,\n ): BoardSpaceTargetBuilder<State, BoardId, SpaceId, Definitions> {\n return createPerPlayerBoardSpaceTargetBuilder<\n State,\n BoardId,\n SpaceId,\n Definitions\n >(boardId);\n },\n};\n","import { resolveZoneAccess } from \"../table/zones\";\nimport type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport type { CollectorState } from \"../model/spec\";\nimport type { ZoneDefinitions } from \"../model/table\";\nimport type { CardIdOfState } from \"../model/extract\";\nimport {\n createTargetRule,\n createTargetRuleBuilder,\n type TargetPredicate,\n type TargetRule,\n type TargetRuleBuilder,\n} from \"./targetRule\";\n\nexport type CardTargetPredicate<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetPredicate<State, Id, Definitions>;\n\nexport type CardTargetRule<\n State extends CollectorState,\n Id extends string,\n ZoneIds extends readonly string[] = readonly string[],\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRule<State, Id, Definitions> & {\n readonly zoneIds: ZoneIds;\n readonly zoneId: ZoneIds[number];\n readonly targetKind: \"card\";\n};\n\nexport type CardTargetBuilder<\n State extends CollectorState,\n Id extends string,\n ZoneIds extends readonly string[] = readonly string[],\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRuleBuilder<\n State,\n Id,\n CardTargetRule<State, Id, ZoneIds, Definitions>,\n Definitions\n>;\n\nfunction createCardTargetBuilder<\n State extends CollectorState,\n Id extends string,\n ZoneIds extends readonly string[],\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(\n zoneIds: ZoneIds,\n definitions: ZoneDefinitions,\n): CardTargetBuilder<State, Id, ZoneIds, Definitions> {\n return createTargetRuleBuilder<\n State,\n Id,\n CardTargetRule<State, Id, ZoneIds, Definitions>,\n Definitions\n >((predicates) => ({\n ...createTargetRule(\n ({ state, playerId, q }) => {\n // Authored zone selection is admitted through the compiled query owner;\n // the target builder's generic IDs refine that owner's runtime strings.\n const zones = q.zones as (\n zoneId: string,\n ) => Readonly<Record<string, readonly string[]>>;\n return zoneIds.flatMap((zoneId) => {\n const definition = definitions.zoneDefinitions[zoneId];\n return Object.entries(zones(zoneId)).flatMap(([hostId, cards]) =>\n resolveZoneAccess(\n state.table,\n definitions,\n definition,\n hostId,\n playerId,\n )\n ? cards.filter((id) => Object.hasOwn(state.table.cards, id))\n : [],\n );\n }) as Id[];\n },\n predicates,\n {\n missingCandidateIssue: {\n errorCode: \"CARD_TARGET_NOT_ELIGIBLE\",\n message: \"Card target is not eligible.\",\n },\n },\n ),\n zoneIds,\n zoneId: zoneIds[0],\n targetKind: \"card\",\n }));\n}\n\nexport const cardTarget = {\n zones<\n State extends CollectorState,\n Id extends string = CardIdOfState<State>,\n const ZoneIds extends readonly string[] = readonly string[],\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n >(\n zoneIds: ZoneIds,\n definitions: ZoneDefinitions,\n ): CardTargetBuilder<State, Id, ZoneIds, Definitions> {\n return createCardTargetBuilder<State, Id, ZoneIds, Definitions>(\n zoneIds,\n definitions,\n );\n },\n};\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport * as z from \"zod\";\nimport type { CollectorState, InputCollector } from \"../model/spec\";\nimport type { TableQueriesOfState } from \"../model/queries\";\nimport type { PlayerIdOfState } from \"../model/extract\";\nimport type { CardIdOfState } from \"../model/extract\";\nimport type { CardTargetRule } from \"./cardTarget\";\n\n/**\n * `cardInput` produces a collector backed by one built `cardTarget` rule.\n * The submitted value is a manifest-branded card id.\n *\n * The target rule feeds server-authoritative eligible-card projection, submit\n * validation, and tests through its `bind({ state, playerId, q })` helper.\n */\nexport function cardInput<\n State extends CollectorState = CollectorState,\n Id extends string = CardIdOfState<State>,\n const ZoneIds extends readonly string[] = readonly string[],\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(options: {\n target: CardTargetRule<State, Id, ZoneIds, Definitions>;\n}): InputCollector<z.ZodString, State, \"card\", Id> & {\n readonly meta: {\n readonly zoneId: ZoneIds[number];\n readonly zoneIds: ZoneIds;\n readonly targetKind: \"card\";\n };\n} {\n const target = options.target;\n const eligible = (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) => target.eligible({ state, playerId, q });\n // Assembly binds state, player, and queries to one validated game contract.\n // The string schema checks wire shape only. The runtime must also call\n // validateTarget before exposing a manifest Id to authored reducers; matching\n // a canonical candidate supplies that refinement. This assertion binds both\n // invariants when hooks enter the heterogeneous collector registry.\n // eslint-disable-next-line no-restricted-syntax -- Assembly binds these hooks to State; canonical card membership refines the parsed string to the manifest Id.\n return {\n kind: \"card\",\n schema: z.string(),\n eligibleTargets: eligible,\n validateTarget: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n targetId: unknown,\n ) => target.validate({ state, playerId, q }, targetId),\n domain: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) => ({\n type: \"cardTarget\" as const,\n projection: \"resolved\" as const,\n targetKind: target.targetKind,\n zoneIds: target.zoneIds,\n eligibleTargets: eligible(state, playerId, q),\n }),\n meta: {\n zoneId: target.zoneId,\n zoneIds: target.zoneIds,\n targetKind: target.targetKind,\n },\n } as unknown as InputCollector<z.ZodString, State, \"card\", Id> & {\n readonly meta: {\n readonly zoneId: ZoneIds[number];\n readonly zoneIds: ZoneIds;\n readonly targetKind: \"card\";\n };\n };\n}\n","import {\n isPositionTarget,\n PositionTargetSchema,\n zonePositions,\n type PositionTarget,\n} from \"../../shared/position-target.js\";\nimport { resolveZoneAccess } from \"../table/zones\";\nimport type { CollectorState, InputCollector } from \"../model/spec\";\nimport type { ZoneDefinitions } from \"../model/table\";\n\ntype ZoneSize = {\n readonly zoneId: string;\n readonly hostId: string;\n readonly size: number;\n};\n\n/**\n * `positionInput` collects an insertion point in one of the given zones, in\n * each host the player may reach: their own, shared ones and public ones.\n * Pair it with a card input and `tx.moveComponentToPosition` to reorder a\n * hand or place a card at a chosen depth.\n */\nexport function positionInput<\n State extends CollectorState = CollectorState,\n const ZoneIds extends readonly string[] = readonly string[],\n>(options: {\n zones: ZoneIds;\n definitions: ZoneDefinitions;\n}): InputCollector<\n typeof PositionTargetSchema,\n State,\n \"position\",\n PositionTarget<ZoneIds[number]>\n> & { readonly meta: { readonly zoneIds: ZoneIds } } {\n const { zones: zoneIds, definitions } = options;\n const sizes = (\n state: CollectorState,\n playerId: string,\n q: unknown,\n ): ZoneSize[] => {\n // The compiled query owner admits authored zone IDs; hosts come from state.\n const zones = (q as { zones(zoneId: string): Record<string, string[]> })\n .zones;\n return zoneIds.flatMap((zoneId) =>\n Object.entries(zones(zoneId)).flatMap(([hostId, ids]) =>\n resolveZoneAccess(\n state.table,\n definitions,\n definitions.zoneDefinitions[zoneId],\n hostId,\n playerId,\n )\n ? [{ zoneId, hostId, size: ids.length }]\n : [],\n ),\n );\n };\n return {\n kind: \"position\",\n schema: PositionTargetSchema,\n eligibleTargets: (state, playerId, q) =>\n zonePositions(sizes(state, playerId, q)),\n validateTarget: (state, playerId, q, target) =>\n isPositionTarget(target) &&\n sizes(state, playerId, q).some(\n (zone) =>\n zone.zoneId === target.zoneId &&\n zone.hostId === target.hostId &&\n target.index <= zone.size,\n )\n ? null\n : {\n errorCode: \"POSITION_NOT_ELIGIBLE\",\n message: \"Position is not eligible.\",\n },\n domain: (state, playerId, q) => ({\n type: \"zonePosition\" as const,\n zones: sizes(state, playerId, q),\n }),\n meta: { zoneIds },\n };\n}\n","import * as z from \"zod\";\nimport type { CollectorState, InputCollector } from \"../model/spec\";\n\n/**\n * `rngInput.*` helpers produce collectors whose value is *sampled by the\n * engine on submit* rather than supplied by the client. The schema pins\n * the exact output shape so `ParamsOf<Collectors>` sees precisely typed\n * results.\n *\n * Determinism:\n * Sampling happens inside `submitInteraction` only, never inside\n * reducer validation. This lets clients check a submission without\n * burning RNG state.\n */\n\ntype DieRoll = z.ZodObject<{ values: z.ZodArray<z.ZodNumber> }>;\ntype CoinFlip = z.ZodObject<{\n value: z.ZodEnum<{ heads: \"heads\"; tails: \"tails\" }>;\n}>;\n\n// The literal `kind: \"rng\"` is intentionally preserved in the return type\n// so `ClientParamsOf<Collectors>` can structurally detect engine-sampled\n// collectors and omit them from client-facing submit params.\ntype RngCollector<\n Schema extends DieRoll | CoinFlip,\n State extends CollectorState,\n> = InputCollector<Schema, State, \"rng\">;\n\n/**\n * Roll `count` d6s. The submitted value is `{ values: number[] }` with\n * `values.length === count` and each face `1..6`.\n */\nexport function d6<State extends CollectorState = CollectorState>(\n count: number = 1,\n): RngCollector<DieRoll, State> {\n return {\n kind: \"rng\",\n schema: z.object({\n values: z.array(z.number().int().min(1).max(6)).length(count),\n }),\n meta: { rng: \"d6\", count },\n };\n}\n\n/** Flip a coin. The submitted value is `{ value: \"heads\" | \"tails\" }`. */\nexport function coin<\n State extends CollectorState = CollectorState,\n>(): RngCollector<CoinFlip, State> {\n return {\n kind: \"rng\",\n schema: z.object({\n value: z.enum([\"heads\", \"tails\"]),\n }),\n meta: { rng: \"coin\" },\n };\n}\n\nexport const rngInput = { d6, coin };\n","import type {\n CollectorValueOf,\n CollectorValueWitness,\n} from \"../model/spec/inputs\";\nimport * as z from \"zod\";\nimport type {\n CollectorState,\n InputCollector,\n InputSelectionDescriptor,\n} from \"../model/spec\";\nimport type { SchemaLike } from \"../model/table\";\n\nexport type ManyOptions =\n | {\n count: number;\n distinct?: boolean;\n }\n | {\n min?: number;\n max?: number;\n distinct?: boolean;\n };\n\ntype NonRngCollector = InputCollector<SchemaLike<unknown>, CollectorState> & {\n readonly kind: Exclude<InputCollector[\"kind\"], \"rng\">;\n};\n\n/** Lift the value schema while retaining the collector's exact domain and routing. */\nexport type ManyInputCollector<Collector extends NonRngCollector> = Omit<\n Collector,\n | \"schema\"\n | \"selection\"\n | \"defaultValue\"\n | \"resolveDefaultValue\"\n | keyof CollectorValueWitness<unknown>\n> &\n CollectorValueWitness<CollectorValueOf<Collector>[]> & {\n readonly schema: z.ZodArray<Collector[\"schema\"]>;\n readonly selection: Extract<InputSelectionDescriptor, { mode: \"many\" }>;\n };\n\nfunction normalizeManyOptions(\n options: ManyOptions,\n): Extract<InputSelectionDescriptor, { mode: \"many\" }> {\n if (\"count\" in options) {\n assertNonNegativeInteger(options.count, \"many(...).count\");\n return {\n mode: \"many\",\n min: options.count,\n max: options.count,\n distinct: options.distinct,\n };\n }\n const min = options.min ?? 0;\n assertNonNegativeInteger(min, \"many(...).min\");\n if (options.max !== undefined) {\n assertNonNegativeInteger(options.max, \"many(...).max\");\n if (options.max < min) {\n throw new Error(\"many(...).max must be greater than or equal to min.\");\n }\n }\n return {\n mode: \"many\",\n min,\n max: options.max,\n distinct: options.distinct,\n };\n}\n\nfunction assertNonNegativeInteger(value: number, label: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative integer.`);\n }\n}\n\n// JavaScript callers can bypass the public NonRngCollector constraint.\nfunction assertManyKind(kind: InputCollector[\"kind\"]): void {\n if (kind === \"rng\") {\n throw new Error(\"many(...) cannot wrap rngInput collectors.\");\n }\n}\n\nexport function many<Collector extends NonRngCollector>(\n collector: Collector,\n options: ManyOptions,\n): ManyInputCollector<Collector> {\n assertManyKind(collector.kind);\n const {\n schema,\n selection: _selection,\n defaultValue: _defaultValue,\n resolveDefaultValue: _resolveDefaultValue,\n ...rest\n } = collector;\n void [_selection, _defaultValue, _resolveDefaultValue];\n return {\n // The witness is type-only; the runtime object carries no witness value.\n ...(rest as Omit<\n Collector,\n | \"schema\"\n | \"selection\"\n | \"defaultValue\"\n | \"resolveDefaultValue\"\n | keyof CollectorValueWitness<unknown>\n >),\n schema: z.array<Collector[\"schema\"]>(schema),\n selection: normalizeManyOptions(options),\n };\n}\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport type { CollectorState } from \"../model/spec\";\nimport type { TileIdOfState } from \"../model/extract\";\nimport {\n createTargetRule,\n createTargetRuleBuilder,\n type TargetPredicate,\n type TargetRule,\n type TargetRuleBuilder,\n} from \"./targetRule\";\n\nexport type TileTargetPredicate<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetPredicate<State, Id, Definitions>;\n\nexport type TileTargetRule<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRule<State, Id, Definitions> & {\n readonly targetKind: \"tile\";\n readonly zoneIds: readonly string[];\n readonly boardIds: readonly string[];\n};\nexport type TileTargetBuilder<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n> = TargetRuleBuilder<\n State,\n Id,\n TileTargetRule<State, Id, Definitions>,\n Definitions\n>;\n\nfunction createTileTargetBuilder<\n State extends CollectorState,\n Id extends string,\n Definitions extends TopologyDefinitions,\n>(\n zoneIds: readonly string[],\n boardIds: readonly string[],\n): TileTargetBuilder<State, Id, Definitions> {\n return createTargetRuleBuilder<\n State,\n Id,\n TileTargetRule<State, Id, Definitions>,\n Definitions\n >((predicates) => ({\n ...createTargetRule(\n ({ state, q }) => {\n const candidates = new Set<string>();\n const zones = q.zones as (\n zoneId: string,\n ) => Readonly<Record<string, readonly string[]>>;\n for (const zoneId of zoneIds)\n for (const ids of Object.values(zones(zoneId)))\n for (const id of ids)\n if (Object.hasOwn(state.table.tiles, id)) candidates.add(id);\n for (const [id, location] of Object.entries(\n state.table.componentLocations,\n ))\n if (\n Object.hasOwn(state.table.tiles, id) &&\n location.type === \"OnBoard\" &&\n boardIds.includes(location.boardId)\n )\n candidates.add(id);\n // Canonical inventory membership establishes the authored Id witness.\n return [...candidates] as Id[];\n },\n predicates,\n {\n missingCandidateIssue: {\n errorCode: \"TILE_TARGET_NOT_ELIGIBLE\",\n message: \"Tile target is not eligible.\",\n },\n },\n ),\n targetKind: \"tile\",\n zoneIds: Object.freeze([...zoneIds]),\n boardIds: Object.freeze([...boardIds]),\n }));\n}\n\n/** Inventory targets name tile instances, independently of their cell spaces. */\nexport const tileTarget = {\n zones<\n State extends CollectorState,\n Id extends string = TileIdOfState<State>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n >(zoneIds: readonly string[]): TileTargetBuilder<State, Id, Definitions> {\n return createTileTargetBuilder<State, Id, Definitions>(zoneIds, []);\n },\n boards<\n State extends CollectorState,\n Id extends string = TileIdOfState<State>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n >(boardIds: readonly string[]): TileTargetBuilder<State, Id, Definitions> {\n return createTileTargetBuilder<State, Id, Definitions>([], boardIds);\n },\n};\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport type { z } from \"zod\";\nimport type { CollectorState, InputCollector } from \"../model/spec\";\nimport type { TableQueriesOfState } from \"../model/queries\";\nimport type { PlayerIdOfState, TileIdOfState } from \"../model/extract\";\nimport type { TileTargetRule } from \"./tileTarget\";\n\n/** Trusted syntax uses the compiled inventory schema; client syntax uses seat references. */\nexport function tileInput<\n State extends CollectorState = CollectorState,\n Id extends string = TileIdOfState<State>,\n Definitions extends TopologyDefinitions = TopologyDefinitions,\n>(options: {\n target: TileTargetRule<State, Id, Definitions>;\n schema: z.ZodType<Id>;\n}): InputCollector<z.ZodType<Id>, State, \"tile\", Id> {\n const target = options.target;\n const eligible = (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) => target.eligible({ state, playerId, q });\n // eslint-disable-next-line no-restricted-syntax -- Assembly binds hooks to State; compiled syntax and canonical membership establish the inventory Id.\n return {\n kind: \"tile\",\n schema: options.schema,\n eligibleTargets: eligible,\n validateTarget: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n targetId: unknown,\n ) => target.validate({ state, playerId, q }, targetId),\n domain: (\n state: State,\n playerId: PlayerIdOfState<State>,\n q: TableQueriesOfState<State, Definitions>,\n ) => ({\n type: \"tileTarget\",\n projection: \"resolved\",\n targetKind: \"tile\",\n zoneIds: target.zoneIds,\n boardIds: target.boardIds,\n eligibleTargets: eligible(state, playerId, q),\n }),\n meta: {\n targetKind: \"tile\",\n zoneIds: target.zoneIds,\n boardIds: target.boardIds,\n },\n } as unknown as InputCollector<z.ZodType<Id>, State, \"tile\", Id>;\n}\n","import type {\n InputCollector,\n InteractionRule,\n InteractionSpec,\n} from \"../model\";\nimport type { ScopedPhaseState } from \"../model/spec/runtime-args\";\nimport type {\n AnyReducerGameContract,\n ContractErrorCode,\n ContractManifest,\n ContractState,\n InferPhaseState,\n PhaseStateInput,\n} from \"./types\";\nimport { validateInteractionLikeDefinition } from \"./validation\";\n\nexport function defineInteraction<\n Contract extends AnyReducerGameContract,\n PhaseState extends PhaseStateInput = import(\"../model\").SchemaLike<object>,\n>() {\n return <Collectors extends Record<string, InputCollector>>(\n definition: InteractionSpec<\n Collectors,\n ScopedPhaseState<ContractState<Contract>, InferPhaseState<PhaseState>>,\n ContractManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n ): InteractionSpec<\n Collectors,\n ScopedPhaseState<ContractState<Contract>, InferPhaseState<PhaseState>>,\n ContractManifest<Contract>,\n ContractErrorCode<Contract>\n > => {\n validateInteractionLikeDefinition(definition, \"defineInteraction\");\n return definition;\n };\n}\n\nexport function defineInteractionRule<\n Contract extends AnyReducerGameContract,\n PhaseState extends PhaseStateInput = import(\"../model\").SchemaLike<object>,\n>() {\n return <\n Collectors extends Record<string, InputCollector> = Record<\n string,\n InputCollector\n >,\n >(\n definition: InteractionRule<\n Collectors,\n ScopedPhaseState<ContractState<Contract>, InferPhaseState<PhaseState>>,\n ContractManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n ): InteractionRule<\n Collectors,\n ScopedPhaseState<ContractState<Contract>, InferPhaseState<PhaseState>>,\n ContractManifest<Contract>,\n ContractErrorCode<Contract>\n > => definition;\n}\n","import type { ViewData } from \"../model/spec/views\";\nimport type { ViewDefinition } from \"../model\";\nimport type {\n AnyReducerGameContract,\n ContractManifest,\n ContractState,\n} from \"./types\";\n\n/** Contextual typing for a view defined outside the game assembly module. */\nexport function defineView<Contract extends AnyReducerGameContract>() {\n return <Projection extends ViewData>(\n view: ViewDefinition<\n ContractState<Contract>,\n ContractManifest<Contract>,\n Projection\n >,\n ) => view;\n}\n","import type { TopologyDefinitions } from \"../../shared/domain/topology-definitions.js\";\nimport type { PerPlayerInstanceId } from \"../../shared/domain/per-player-instance.js\";\nimport { validatedReducerDefinition } from \"../model/definition\";\nimport type { ViewData } from \"../model/spec/views\";\nimport { InteractionSteps } from \"./steps\";\nimport type { ViewDefinition } from \"../model\";\nimport type { z } from \"zod\";\nimport type {\n ZoneIdOfTable,\n CardIdOfManifest,\n TileIdOfTable,\n BoardIdOfTable,\n SpaceIdOfTable,\n InputCollector,\n InteractionMap,\n InteractionRule,\n InteractionSpec,\n PhaseDefinition,\n PhaseMapOf,\n ReducerGameDefinition,\n ReducerGameDefinitionInput,\n OptionsOfContract,\n PlayerIdOfState,\n SchemaLike,\n TableOfManifest,\n TiledBoardIdOfTable,\n TiledEdgeIdOfTable,\n TiledVertexIdOfTable,\n ViewOfContract,\n} from \"../model\";\nimport type { ScopedPhaseState } from \"../model/spec/runtime-args\";\nimport type {\n BoardSpaceTarget,\n BoardSpaceInputSchema,\n PositionTarget,\n} from \"../inputs\";\nimport type { PositionTargetSchema } from \"../../shared/position-target.js\";\nimport type {\n TargetPredicate,\n TargetRule,\n TargetRuleBuilder,\n} from \"../inputs/targetRule\";\nimport type { CollectorState } from \"../model\";\nimport type { TableQueriesOfState } from \"../model/queries\";\nimport type { ReducerTransaction } from \"../transaction\";\nimport {\n boardInput,\n boardTarget,\n cardInput,\n cardTarget,\n positionInput,\n tileInput,\n tileTarget,\n formInput,\n rngInput,\n} from \"../inputs\";\nimport type {\n AnyReducerGameContract,\n ContractErrorCode,\n ContractManifest,\n ContractState,\n} from \"./types\";\nimport {\n validateDefineGamePhaseNames,\n validateDefineGamePhases,\n} from \"./validation\";\nimport { defineInteraction, defineInteractionRule } from \"./interaction\";\nimport { defineView } from \"./views\";\nexport type ContractWithPhases = AnyReducerGameContract & {\n readonly phases: Record<string, SchemaLike<object>>;\n};\n\ntype BoundState<Contract extends ContractWithPhases> = ContractState<Contract>;\n\ntype BoundManifest<Contract extends ContractWithPhases> =\n ContractManifest<Contract>;\n\ntype BoundTable<Contract extends ContractWithPhases> = TableOfManifest<\n BoundManifest<Contract>\n>;\n\ntype BoundPhaseState<\n Contract extends ContractWithPhases,\n PhaseStateSchema extends SchemaLike<object>,\n> = ScopedPhaseState<BoundState<Contract>, z.infer<PhaseStateSchema>>;\n\ntype BoundFormInputs<Contract extends ContractWithPhases> = ReturnType<\n typeof formInput.forState<BoundState<Contract>>\n>;\n\n/** The selected board owns the element namespace, including generic spaces. */\ntype BoundBoardInputOptions<\n Contract extends ContractWithPhases,\n BoardId,\n Id,\n> = {\n boardId: BoardId;\n where?: BoundWhere<Contract, Id>;\n};\ntype PlayerBoardBaseId<Contract extends ContractWithPhases> = {\n [\n B in keyof BoundManifest<Contract>[\"boardDefinitions\"] & string\n ]: BoundManifest<Contract>[\"boardDefinitions\"][B] extends {\n scope: \"perPlayer\";\n }\n ? B\n : never;\n}[keyof BoundManifest<Contract>[\"boardDefinitions\"] & string];\ntype PlayerBoardRuntimeId<Table, Base extends string> = Extract<\n BoardIdOfTable<Table>,\n PerPlayerInstanceId<\"board\", Base>\n>;\ntype BoundBoardInputs<Contract extends ContractWithPhases> = {\n vertex<\n B extends TiledBoardIdOfTable<\n BoundTable<Contract>,\n BoundManifest<Contract>\n >,\n >(\n options: BoundBoardInputOptions<\n Contract,\n B,\n TiledVertexIdOfTable<\n BoundTable<Contract>,\n NoInfer<B>,\n BoundManifest<Contract>\n >\n >,\n ): InputCollector<\n z.ZodString,\n BoundState<Contract>,\n \"board-vertex\",\n TiledVertexIdOfTable<BoundTable<Contract>, B, BoundManifest<Contract>>\n >;\n edge<\n B extends TiledBoardIdOfTable<\n BoundTable<Contract>,\n BoundManifest<Contract>\n >,\n >(\n options: BoundBoardInputOptions<\n Contract,\n B,\n TiledEdgeIdOfTable<\n BoundTable<Contract>,\n NoInfer<B>,\n BoundManifest<Contract>\n >\n >,\n ): InputCollector<\n z.ZodString,\n BoundState<Contract>,\n \"board-edge\",\n TiledEdgeIdOfTable<BoundTable<Contract>, B, BoundManifest<Contract>>\n >;\n space<B extends BoardIdOfTable<BoundTable<Contract>>>(\n options: BoundBoardInputOptions<\n Contract,\n B,\n SpaceIdOfTable<BoundTable<Contract>, NoInfer<B>, BoundManifest<Contract>>\n >,\n ): InputCollector<\n z.ZodString,\n BoundState<Contract>,\n \"board-space\",\n SpaceIdOfTable<BoundTable<Contract>, B, BoundManifest<Contract>>\n >;\n playerSpace<B extends PlayerBoardBaseId<Contract>>(options: {\n boardId: B;\n where?: BoundWhere<\n Contract,\n BoardSpaceTarget<\n PerPlayerInstanceId<\"board\", NoInfer<B>>,\n SpaceIdOfTable<\n BoundTable<Contract>,\n PlayerBoardRuntimeId<BoundTable<Contract>, NoInfer<B>>,\n BoundManifest<Contract>\n >\n >\n >;\n }): InputCollector<\n BoardSpaceInputSchema,\n BoundState<Contract>,\n \"board-space\",\n BoardSpaceTarget<\n PerPlayerInstanceId<\"board\", B>,\n SpaceIdOfTable<\n BoundTable<Contract>,\n PlayerBoardRuntimeId<BoundTable<Contract>, B>,\n BoundManifest<Contract>\n >\n >\n >;\n};\n\n/**\n * An eligibility predicate whose `errorCode` is checked against the model's\n * declared error codes. The unbound `TargetPredicate` accepts any string.\n */\nexport type BoundTargetPredicate<\n Contract extends ContractWithPhases,\n Target,\n> = Omit<\n TargetPredicate<BoundState<Contract>, Target, BoundManifest<Contract>>,\n \"errorCode\"\n> & {\n errorCode: ContractErrorCode<Contract>;\n};\n\ntype BoundWhere<Contract extends ContractWithPhases, Target> =\n | BoundTargetPredicate<Contract, Target>\n | readonly BoundTargetPredicate<Contract, Target>[];\n\ntype BoundCardCollector<\n Contract extends ContractWithPhases,\n Id extends string,\n ZoneIds extends readonly string[],\n> = InputCollector<z.ZodString, BoundState<Contract>, \"card\", Id> & {\n readonly meta: {\n readonly zoneId: ZoneIds[number];\n readonly zoneIds: ZoneIds;\n readonly targetKind: \"card\";\n };\n};\n\n/**\n * Card collector: the zones to draw candidates from and the predicates that\n * filter them. The target rule is built internally.\n */\ntype BoundCardInput<Contract extends ContractWithPhases> = <\n const ZoneIds extends readonly ZoneIdOfTable<BoundTable<Contract>>[],\n>(options: {\n from: ZoneIds;\n where?: BoundWhere<Contract, CardIdOfManifest<BoundManifest<Contract>>>;\n}) => BoundCardCollector<\n Contract,\n CardIdOfManifest<BoundManifest<Contract>>,\n ZoneIds\n>;\n\n/** Tile instances in authored zones or exact runtime boards. */\ntype BoundTileInput<Contract extends ContractWithPhases> = (\n options: (\n | { from: readonly ZoneIdOfTable<BoundTable<Contract>>[]; boards?: never }\n | {\n boards: readonly TiledBoardIdOfTable<\n BoundTable<Contract>,\n BoundManifest<Contract>\n >[];\n from?: never;\n }\n ) & {\n where?: BoundWhere<Contract, TileIdOfTable<BoundTable<Contract>>>;\n },\n) => InputCollector<\n z.ZodType<TileIdOfTable<BoundTable<Contract>>>,\n BoundState<Contract>,\n \"tile\",\n TileIdOfTable<BoundTable<Contract>>\n>;\n\n/**\n * An insertion point in one of the zones, in each host the player may reach.\n * `tx.moveComponentToPosition` places a card there.\n */\ntype BoundPositionInput<Contract extends ContractWithPhases> = <\n const ZoneIds extends readonly ZoneIdOfTable<BoundTable<Contract>>[],\n>(options: {\n zones: ZoneIds;\n}) => InputCollector<\n typeof PositionTargetSchema,\n BoundState<Contract>,\n \"position\",\n PositionTarget<ZoneIds[number]>\n> & { readonly meta: { readonly zoneIds: ZoneIds } };\n\ntype BoundRngInputs<Contract extends ContractWithPhases> = {\n d6(count?: number): ReturnType<typeof rngInput.d6<BoundState<Contract>>>;\n coin(): ReturnType<typeof rngInput.coin<BoundState<Contract>>>;\n};\n\nexport type BoundInputBuilders<Contract extends ContractWithPhases> = {\n readonly board: BoundBoardInputs<Contract>;\n readonly card: BoundCardInput<Contract>;\n readonly position: BoundPositionInput<Contract>;\n readonly tile: BoundTileInput<Contract>;\n readonly form: BoundFormInputs<Contract>;\n readonly rng: BoundRngInputs<Contract>;\n};\n\n/** Preserve each phase kind's required fields while binding its state schema. */\ntype PhaseDefinitionWithoutState<Definition> = Definition extends unknown\n ? Omit<Definition, \"state\">\n : never;\n\nexport type PhaseAuthoring<\n Contract extends ContractWithPhases,\n PhaseStateSchema extends SchemaLike<object>,\n> = {\n steps(): InteractionSteps<\n BoundPhaseState<Contract, PhaseStateSchema>,\n Record<never, never>,\n BoundManifest<Contract>\n >;\n interaction<Collectors extends Record<string, InputCollector>>(\n spec: Extract<\n InteractionSpec<\n Collectors,\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n { steps: unknown }\n >,\n ): Extract<\n InteractionSpec<\n Collectors,\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n { steps: unknown }\n >;\n interaction<Collectors extends Record<string, InputCollector>>(\n spec: Extract<\n InteractionSpec<\n Collectors,\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n { inputs: unknown }\n >,\n ): Extract<\n InteractionSpec<\n Collectors,\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n { inputs: unknown }\n >;\n rule<\n Collectors extends Record<string, InputCollector> = Record<\n string,\n InputCollector\n >,\n >(\n rule: InteractionRule<\n Collectors,\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>,\n ContractErrorCode<Contract>\n >,\n ): InteractionRule<\n Collectors,\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>,\n ContractErrorCode<Contract>\n >;\n define<\n SubmitCollectors extends Record<string, InputCollector> = Record<\n string,\n InputCollector\n >,\n Interactions extends InteractionMap<\n BoundPhaseState<Contract, PhaseStateSchema>,\n BoundManifest<Contract>\n > = Record<string, never>,\n const Kind extends \"player\" | \"simultaneousPlayer\" | \"auto\" =\n \"player\" | \"simultaneousPlayer\" | \"auto\",\n >(\n definition: PhaseDefinitionWithoutState<\n PhaseDefinition<\n PhaseStateSchema,\n BoundState<Contract>,\n BoundManifest<Contract>,\n SubmitCollectors,\n Interactions,\n OptionsOfContract<Contract>,\n ContractErrorCode<Contract>\n >\n > & { kind: Kind },\n ): PhaseDefinition<\n PhaseStateSchema,\n BoundState<Contract>,\n BoundManifest<Contract>,\n SubmitCollectors,\n Interactions,\n OptionsOfContract<Contract>,\n ContractErrorCode<Contract>\n > & { kind: Kind };\n readonly inputs: BoundInputBuilders<Contract>;\n /** Compile-time only. Reading any member at runtime throws. */\n readonly types: PhaseTypes<Contract, PhaseStateSchema>;\n};\n\n/**\n * Phantom type carriers for one phase: `typeof playing.types.State` is the\n * phase-scoped game state (`state.phase` narrowed to this phase's schema).\n */\nexport type PhaseTypes<\n Contract extends ContractWithPhases,\n PhaseStateSchema extends SchemaLike<object>,\n> = {\n readonly State: BoundPhaseState<Contract, PhaseStateSchema>;\n readonly PhaseState: z.infer<PhaseStateSchema>;\n readonly Tx: ReducerTransaction<\n BoundPhaseState<Contract, PhaseStateSchema>,\n ContractErrorCode<Contract>,\n BoundManifest<Contract>\n >;\n};\n\n/**\n * Phantom type carriers for the whole game. These replace the\n * `GameStateOf<GameContractOf<typeof model>>` chain: a module that has the\n * bound game value can write `typeof game.types.State` and stop there.\n */\nexport type ContractTypes<Contract extends ContractWithPhases> = {\n readonly Contract: Contract;\n readonly Options: OptionsOfContract<Contract>;\n readonly State: BoundState<Contract>;\n readonly Manifest: BoundManifest<Contract>;\n readonly ErrorCode: ContractErrorCode<Contract>;\n readonly PlayerId: PlayerIdOfState<BoundState<Contract>>;\n readonly Queries: TableQueriesOfState<\n BoundState<Contract>,\n BoundManifest<Contract>\n >;\n readonly Tx: ReducerTransaction<\n BoundState<Contract>,\n ContractErrorCode<Contract>,\n BoundManifest<Contract>\n >;\n};\n\nexport type GameAuthoring<Contract extends ContractWithPhases> = {\n readonly contract: Contract;\n view<Projection extends ViewData>(\n view: ViewDefinition<\n BoundState<Contract>,\n BoundManifest<Contract>,\n Projection\n >,\n ): ViewDefinition<BoundState<Contract>, BoundManifest<Contract>, Projection>;\n /** Compile-time only. Reading any member at runtime throws. */\n readonly types: ContractTypes<Contract>;\n /** Assemble the final game definition from phases and the seat view. */\n assemble<\n Definitions extends PhaseMapOf<Contract>,\n View extends ViewOfContract<Contract>,\n >(\n definition: ReducerGameDefinitionInput<Contract, Definitions, View>,\n ): ReducerGameDefinition<Contract, Definitions, View>;\n phase<Name extends keyof Contract[\"phases\"] & string>(\n name: Name,\n ): PhaseAuthoring<Contract, Contract[\"phases\"][Name]>;\n};\n\nconst PHANTOM_TYPES_MESSAGE =\n \"`.types` is a compile-time carrier: use it only in `typeof` positions.\";\n\nfunction phantomTypes<Types>(): Types {\n return new Proxy(Object.freeze({}), {\n get() {\n throw new TypeError(PHANTOM_TYPES_MESSAGE);\n },\n }) as Types;\n}\n\nfunction applyWhere<\n State extends CollectorState,\n Target,\n Rule extends TargetRule<State, Target, Definitions>,\n Definitions extends TopologyDefinitions,\n>(\n builder: TargetRuleBuilder<State, Target, Rule, Definitions>,\n where:\n | TargetPredicate<State, Target, Definitions>\n | readonly TargetPredicate<State, Target, Definitions>[]\n | undefined,\n): TargetRuleBuilder<State, Target, Rule, Definitions> {\n const predicates =\n where === undefined ? [] : \"test\" in where ? [where] : where;\n return predicates.reduce(\n (current, predicate) => current.where(predicate),\n builder,\n );\n}\n\nfunction createFusedCardInput<Contract extends ContractWithPhases>(\n contract: Contract,\n): BoundCardInput<Contract> {\n return (options) =>\n cardInput({\n target: applyWhere(\n cardTarget.zones<\n BoundState<Contract>,\n CardIdOfManifest<BoundManifest<Contract>>,\n typeof options.from,\n BoundManifest<Contract>\n >(options.from, contract.manifest),\n options.where,\n ).build(),\n });\n}\n\nfunction createFusedTileInput<Contract extends ContractWithPhases>(\n contract: Contract,\n): BoundTileInput<Contract> {\n return (options) => {\n const builder =\n options.from !== undefined\n ? tileTarget.zones<\n BoundState<Contract>,\n TileIdOfTable<BoundTable<Contract>>,\n BoundManifest<Contract>\n >(options.from)\n : tileTarget.boards<\n BoundState<Contract>,\n TileIdOfTable<BoundTable<Contract>>,\n BoundManifest<Contract>\n >(options.boards);\n return tileInput({\n target: applyWhere(builder, options.where).build(),\n // The bound contract owns the authoritative tile syntax and target IDs.\n schema: contract.manifest.ids.tileId as z.ZodType<\n TileIdOfTable<BoundTable<Contract>>\n >,\n });\n };\n}\n\nfunction createFusedBoardInputs<\n Contract extends ContractWithPhases,\n>(): BoundBoardInputs<Contract> {\n return {\n vertex: (options) =>\n boardInput.vertex({\n target: applyWhere(\n boardTarget.vertex<\n BoundState<Contract>,\n TiledVertexIdOfTable<\n BoundTable<Contract>,\n typeof options.boardId,\n BoundManifest<Contract>\n >,\n BoundManifest<Contract>\n >(options.boardId),\n options.where,\n ).build(),\n }),\n edge: (options) =>\n boardInput.edge({\n target: applyWhere(\n boardTarget.edge<\n BoundState<Contract>,\n TiledEdgeIdOfTable<\n BoundTable<Contract>,\n typeof options.boardId,\n BoundManifest<Contract>\n >,\n BoundManifest<Contract>\n >(options.boardId),\n options.where,\n ).build(),\n }),\n space: (options) =>\n boardInput.space({\n target: applyWhere(\n boardTarget.space<\n BoundState<Contract>,\n SpaceIdOfTable<\n BoundTable<Contract>,\n typeof options.boardId,\n BoundManifest<Contract>\n >,\n BoundManifest<Contract>\n >(options.boardId),\n options.where,\n ).build(),\n }),\n playerSpace: (options) =>\n boardInput.playerSpace({\n target: applyWhere(\n boardTarget.playerSpace<\n BoundState<Contract>,\n typeof options.boardId,\n SpaceIdOfTable<\n BoundTable<Contract>,\n PlayerBoardRuntimeId<\n BoundTable<Contract>,\n typeof options.boardId\n >,\n BoundManifest<Contract>\n >,\n BoundManifest<Contract>\n >(options.boardId),\n options.where,\n ).build(),\n }),\n };\n}\n\nfunction createBoundInputBuilders<Contract extends ContractWithPhases>(\n contract: Contract,\n): BoundInputBuilders<Contract> {\n return {\n board: createFusedBoardInputs<Contract>(),\n card: createFusedCardInput(contract),\n position: (options) =>\n positionInput({ zones: options.zones, definitions: contract.manifest }),\n tile: createFusedTileInput(contract),\n form: formInput.forState<BoundState<Contract>>(),\n rng: rngInput,\n };\n}\n\nfunction createPhaseAuthoring<\n Contract extends ContractWithPhases,\n PhaseStateSchema extends SchemaLike<object>,\n>(\n contract: Contract,\n schema: PhaseStateSchema,\n): PhaseAuthoring<Contract, PhaseStateSchema> {\n return {\n steps: () => new InteractionSteps(),\n interaction: defineInteraction<\n Contract,\n PhaseStateSchema\n >() as PhaseAuthoring<Contract, PhaseStateSchema>[\"interaction\"],\n rule: (rule) =>\n defineInteractionRule<Contract, PhaseStateSchema>()(\n rule as Parameters<\n ReturnType<typeof defineInteractionRule<Contract, PhaseStateSchema>>\n >[0],\n ) as typeof rule,\n define: (definition) => ({ ...definition, state: schema }),\n inputs: createBoundInputBuilders(contract),\n types: phantomTypes<PhaseTypes<Contract, PhaseStateSchema>>(),\n };\n}\n\nexport function createContractAuthoring<\n const Contract extends ContractWithPhases,\n>(contract: Contract): GameAuthoring<Contract> {\n const phases: Contract[\"phases\"] = contract.phases;\n const assemble: GameAuthoring<Contract>[\"assemble\"] = (definition) => {\n const game = { ...definition, contract };\n validateDefineGamePhaseNames(game);\n validateDefineGamePhases(game);\n return { ...game, [validatedReducerDefinition]: true };\n };\n return {\n contract,\n view: defineView<Contract>(),\n types: phantomTypes<ContractTypes<Contract>>(),\n assemble,\n phase: (name) => createPhaseAuthoring(contract, phases[name]),\n };\n}\n","import type { RuntimeRecord } from \"../model/table\";\nimport * as z from \"zod\";\nimport { createManifestStringLiteralSchema } from \"../model/manifest\";\nimport type {\n ReducerGameContract,\n ReducerManifestContract,\n RuntimeTableRecord,\n SchemaLike,\n StateDefinition,\n} from \"../model\";\nimport { validateStateSchemaIdBranding } from \"./validation\";\n\n/**\n * Narrows a manifest's `literals.phaseNames` and `ids.phaseName` to the\n * author-supplied phase-name tuple. Lets `defineGameContract` override the\n * codegen-emitted `phaseNames: readonly string[]` / `phaseName: z.string()`\n * placeholders so `PhaseNameOfContract<Contract>` resolves to a literal\n * union and flows through `tx.transition`, `PhaseMapOf`, and the flow\n * state's `currentPhase`.\n */\nexport type NarrowManifestPhaseNames<\n Manifest,\n PhaseNames extends readonly string[],\n> = Manifest & {\n literals: Manifest extends { literals: infer L }\n ? Omit<L, \"phaseNames\"> & { phaseNames: PhaseNames }\n : { phaseNames: PhaseNames };\n ids: Manifest extends { ids: infer I }\n ? Omit<I, \"phaseName\"> & { phaseName: z.ZodType<PhaseNames[number]> }\n : { phaseName: z.ZodType<PhaseNames[number]> };\n};\n\nexport type ReducerGameContractInput<\n Table extends RuntimeTableRecord,\n Manifest extends ReducerManifestContract<\n Table,\n string,\n string,\n string,\n string\n >,\n PublicSchema extends SchemaLike<object>,\n PrivateSchema extends SchemaLike<object>,\n HiddenSchema extends SchemaLike<object>,\n Phases extends Record<string, SchemaLike<object>>,\n Errors extends Record<string, string> | undefined = undefined,\n OptionsSchema extends SchemaLike<RuntimeRecord> = SchemaLike<\n Record<string, never>\n >,\n> = {\n manifest: Manifest;\n state: StateDefinition<PublicSchema, PrivateSchema, HiddenSchema>;\n phases: Phases;\n errors?: Errors;\n options?: OptionsSchema;\n};\n\nexport type DefinedGameContract<\n Table extends RuntimeTableRecord,\n Manifest extends ReducerManifestContract<\n Table,\n string,\n string,\n string,\n string\n >,\n PublicSchema extends SchemaLike<object>,\n PrivateSchema extends SchemaLike<object>,\n HiddenSchema extends SchemaLike<object>,\n Phases extends Record<string, SchemaLike<object>>,\n Errors extends Record<string, string> | undefined = undefined,\n OptionsSchema extends SchemaLike<RuntimeRecord> = SchemaLike<\n Record<string, never>\n >,\n> = ReducerGameContract<\n Table,\n NarrowManifestPhaseNames<Manifest, readonly (keyof Phases & string)[]>,\n PublicSchema,\n PrivateSchema,\n HiddenSchema,\n Phases,\n Errors,\n OptionsSchema\n> & {\n readonly phases: Phases;\n readonly errors: Errors;\n readonly phaseNames: readonly (keyof Phases & string)[];\n};\n\nfunction validateErrorMap(errors: Record<string, string> | undefined): void {\n if (!errors) return;\n const codePattern = /^[A-Z][A-Z0-9_]*$/;\n for (const [code, message] of Object.entries(errors)) {\n if (!codePattern.test(code)) {\n throw new Error(\n `defineGameContract: error code '${code}' must use UPPER_SNAKE_CASE.`,\n );\n }\n if (typeof message !== \"string\" || message.length === 0) {\n throw new Error(\n `defineGameContract: error code '${code}' must declare a non-empty default message.`,\n );\n }\n }\n}\n\n/** Options are persisted and parsed again when a session crosses the ingress boundary. */\nfunction validateOptionsSchema(schema: SchemaLike<RuntimeRecord>): void {\n z.toJSONSchema(schema, {\n override: ({ zodSchema }) => {\n const definition = zodSchema._zod.def;\n if (\n definition.type === \"pipe\" ||\n (\"coerce\" in definition && definition.coerce) ||\n definition.checks?.some((check) => check._zod.def.check === \"overwrite\")\n ) {\n throw new Error(\n \"Game options schemas must not transform or coerce persisted values.\",\n );\n }\n },\n });\n}\n\nexport function defineGameContract<\n Table extends RuntimeTableRecord,\n const Manifest extends ReducerManifestContract<\n Table,\n string,\n string,\n string,\n string\n >,\n PublicSchema extends SchemaLike<object>,\n PrivateSchema extends SchemaLike<object>,\n HiddenSchema extends SchemaLike<object>,\n const Phases extends Record<string, SchemaLike<object>>,\n const Errors extends Record<string, string> | undefined = undefined,\n OptionsSchema extends SchemaLike<RuntimeRecord> = SchemaLike<\n Record<string, never>\n >,\n>(\n definition: ReducerGameContractInput<\n Table,\n Manifest,\n PublicSchema,\n PrivateSchema,\n HiddenSchema,\n Phases,\n Errors,\n OptionsSchema\n >,\n): DefinedGameContract<\n Table,\n Manifest,\n PublicSchema,\n PrivateSchema,\n HiddenSchema,\n Phases,\n Errors,\n OptionsSchema\n> {\n validateStateSchemaIdBranding(definition.state.public, \"public\");\n validateStateSchemaIdBranding(definition.state.private, \"private\");\n validateStateSchemaIdBranding(definition.state.hidden, \"hidden\");\n validateErrorMap(definition.errors);\n const optionsSchema = definition.options ?? z.strictObject({});\n validateOptionsSchema(optionsSchema);\n const phaseNames = Object.keys(definition.phases) as (keyof Phases &\n string)[];\n if (phaseNames.length === 0) {\n throw new Error(\n \"defineGameContract: phases must be a non-empty record of phase schemas.\",\n );\n }\n for (const name of phaseNames) {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\n \"defineGameContract: phase names must be non-empty strings.\",\n );\n }\n }\n const phaseNameSchema = createManifestStringLiteralSchema(phaseNames);\n // eslint-disable-next-line no-restricted-syntax -- Both phaseNames and the replacement phase schema come from the same validated nonempty Phases keys.\n const narrowedManifest = {\n ...definition.manifest,\n literals: {\n ...definition.manifest.literals,\n phaseNames,\n },\n ids: {\n ...definition.manifest.ids,\n phaseName: phaseNameSchema,\n },\n } as unknown as NarrowManifestPhaseNames<\n Manifest,\n readonly (keyof Phases & string)[]\n >;\n const contract = {\n manifest: narrowedManifest,\n state: definition.state,\n phases: definition.phases,\n errors: definition.errors,\n options: optionsSchema,\n phaseNames,\n } as DefinedGameContract<\n Table,\n Manifest,\n PublicSchema,\n PrivateSchema,\n HiddenSchema,\n Phases,\n Errors,\n OptionsSchema\n >;\n return contract;\n}\n","import type { RuntimeRecord } from \"../model/table\";\nimport type {\n CompiledManifest,\n CompiledManifestWitness,\n} from \"../manifest/types\";\nimport type {\n ReducerManifestContract,\n RuntimeTableRecord,\n SchemaLike,\n} from \"../model\";\nimport { createContractAuthoring } from \"./contract-authoring\";\nimport {\n defineGameContract,\n type DefinedGameContract,\n type ReducerGameContractInput,\n} from \"./contract\";\n/** Bind a compiler-produced manifest to state schemas, phases and game assembly. */\nexport function createGame<\n Table extends RuntimeTableRecord,\n const Manifest extends ReducerManifestContract<\n Table,\n string,\n string,\n string,\n string\n > &\n CompiledManifestWitness<CompiledManifest<unknown>>,\n PublicSchema extends SchemaLike<object>,\n PrivateSchema extends SchemaLike<object>,\n HiddenSchema extends SchemaLike<object>,\n const Phases extends Record<string, SchemaLike<object>>,\n const Errors extends Record<string, string> | undefined = undefined,\n OptionsSchema extends SchemaLike<RuntimeRecord> = SchemaLike<\n Record<string, never>\n >,\n>(\n model: ReducerGameContractInput<\n Table,\n Manifest,\n PublicSchema,\n PrivateSchema,\n HiddenSchema,\n Phases,\n Errors,\n OptionsSchema\n >,\n): import(\"./contract-authoring\").GameAuthoring<\n DefinedGameContract<\n Table,\n Manifest,\n PublicSchema,\n PrivateSchema,\n HiddenSchema,\n Phases,\n Errors,\n OptionsSchema\n >\n> {\n return createContractAuthoring(defineGameContract(model));\n}\n","import type { SystemActionEvent } from \"./model\";\n\nexport const gameEvent = {\n systemAction(event: Omit<SystemActionEvent, \"kind\">): SystemActionEvent {\n return {\n kind: \"systemAction\",\n ...event,\n };\n },\n};\n","import { isPlayerIdValue } from \"../shared/domain/player-identity.js\";\nimport type { Brand } from \"./model/table\";\n\n/**\n * Opaque brand applied to a runtime player identifier.\n *\n * The reducer owns the branded `PlayerId` identity. Authors\n * obtain `PlayerId` values only through:\n * - `q.player.order()` / `q.player.current()` (reducer queries),\n * - engine-injected interaction and phase callback arguments,\n * - `asPlayerId(raw)` as an explicit escape hatch (e.g. ingress parsing).\n *\n * The brand is a phantom type: at runtime a `PlayerId` is just a string.\n * Do not JSON-serialize the brand marker; it exists purely at the type\n * level to block accidental literal comparisons such as\n * `playerId === \"player-1\"`.\n */\nexport type PlayerId = Brand<string, \"PlayerId\">;\n\n/**\n * Explicit conversion from a raw string to a branded `PlayerId`.\n *\n * Use at trust boundaries only (wire ingress, tests, fixtures). Inside\n * reducer logic, obtain `PlayerId` values from the engine instead of\n * constructing them yourself.\n */\nexport function asPlayerId(raw: string): PlayerId {\n return raw as PlayerId;\n}\n\n/**\n * Type guard that narrows `unknown` to `PlayerId` when the value is a\n * valid live player key. Does not validate against a specific player roster;\n * use manifest/ingress parsing for that.\n */\nexport function isPlayerId(value: unknown): value is PlayerId {\n return isPlayerIdValue(value);\n}\n","/** Cache a pure calculation by immutable object identity. Do not pass a mutable draft. */\nexport function memoize<A extends object, R>(fn: (a: A) => R): (a: A) => R {\n const cache = new WeakMap<A, R>();\n return (a) => {\n if (cache.has(a)) return cache.get(a)!;\n const value = fn(a);\n cache.set(a, value);\n return value;\n };\n}\n","import { parseBoardElementId } from \"../../shared/domain/board-element.js\";\nimport { parseTileSpaceId } from \"../../shared/domain/tile-space.js\";\nimport * as z from \"zod\";\nimport {\n perPlayerInstanceId,\n perPlayerInstanceSchema,\n type PerPlayerInstanceFamily,\n} from \"../../shared/domain/per-player-instance.js\";\n\n/** Count expansion precedes replication and preserves singleton authored IDs. */\nexport function expandBaseIds(baseId: string, count = 1): string[] {\n return count > 1\n ? Array.from({ length: count }, (_, i) => `${baseId}-${i + 1}`)\n : [baseId];\n}\nexport function renderCardInstanceIds(card: {\n id: string;\n count: number;\n}): string[] {\n return expandBaseIds(card.id, card.count);\n}\nexport function expandSeedIds(\n seeds: readonly {\n id?: string | null;\n typeId: string;\n count?: number | null;\n }[],\n): string[] {\n return seeds.flatMap((seed) =>\n expandBaseIds(seed.id ?? seed.typeId, seed.count ?? 1),\n );\n}\nexport function scopedInstances(\n family: PerPlayerInstanceFamily,\n baseIds: readonly string[],\n scope: \"shared\" | \"perPlayer\" | undefined,\n playerIds: readonly string[],\n): { id: string; playerId: string | null }[] {\n return baseIds.flatMap<{ id: string; playerId: string | null }>((baseId) =>\n scope === \"perPlayer\"\n ? playerIds.map((playerId) => ({\n id: perPlayerInstanceId(family, baseId, playerId),\n playerId,\n }))\n : [{ id: baseId, playerId: null }],\n );\n}\n\n/** Initial ownership comes from replication; visibility remains authored card data. */\nexport function initialCardMetadata(\n cardSets: readonly {\n cards: readonly {\n id: string;\n count: number;\n scope?: \"shared\" | \"perPlayer\";\n visibility?: { faceUp?: boolean };\n }[];\n }[],\n playerIds: readonly string[],\n) {\n const entries = cardSets.flatMap((set) =>\n set.cards.flatMap((card) =>\n scopedInstances(\n \"card\",\n renderCardInstanceIds(card),\n card.scope,\n playerIds,\n ).map((instance) => ({\n ...instance,\n faceUp: card.visibility?.faceUp ?? true,\n })),\n ),\n );\n return {\n ownerOfCard: Object.fromEntries(\n entries.map((instance) => [instance.id, instance.playerId]),\n ),\n visibility: Object.fromEntries(\n entries.map((instance) => [instance.id, { faceUp: instance.faceUp }]),\n ),\n };\n}\n\n/** One declaration policy for public ID schemas and staged field references. */\nexport function createInstanceDeclaration(\n family: PerPlayerInstanceFamily,\n entries: readonly {\n baseIds: readonly string[];\n scope?: \"shared\" | \"perPlayer\";\n }[],\n) {\n const shared = entries\n .filter((entry) => entry.scope !== \"perPlayer\")\n .flatMap((entry) => entry.baseIds);\n const replicated = entries\n .filter((entry) => entry.scope === \"perPlayer\")\n .flatMap((entry) => entry.baseIds);\n const schema = z.union([\n shared.length ? z.enum(shared) : z.never(),\n perPlayerInstanceSchema(family, replicated),\n ]);\n return {\n schema,\n accepts: (value: string) => schema.safeParse(value).success,\n };\n}\n\n/** Declared generic spaces or canonical cells of compatible tile inventory. */\nexport function createSpaceDeclaration(\n manifest: import(\"../../shared/domain/manifest.js\").GameTopologyManifest,\n boardBaseId?: string,\n) {\n const boards = (manifest.boards ?? []).filter(\n (board) => boardBaseId === undefined || board.id === boardBaseId,\n );\n const sharedSpaces = new Set(\n boards.flatMap((board) =>\n board.layout === \"generic\"\n ? (board.spaces ?? []).map((space) => space.id)\n : [],\n ),\n );\n const layouts = new Set(boards.map((board) => board.layout));\n const tiles = (manifest.tileTypes ?? [])\n .filter((type) => layouts.has(type.layout))\n .map((type) => ({\n cells: new Set(type.cells.map((cell) => cell.id)),\n inventory: createInstanceDeclaration(\n \"tile\",\n (manifest.tileSeeds ?? [])\n .filter((seed) => seed.typeId === type.id)\n .map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ),\n }));\n const accepts = (value: string) => {\n if (sharedSpaces.has(value)) return true;\n const parsed = parseTileSpaceId(value);\n return (\n parsed !== null &&\n tiles.some(\n (tile) =>\n tile.cells.has(parsed.cellId) &&\n tile.inventory.accepts(parsed.tileId),\n )\n );\n };\n return {\n accepts,\n schema: z.string().refine(accepts, \"Unknown declared space identity.\"),\n };\n}\n\nexport function createBoardElementDeclaration(\n manifest: import(\"../../shared/domain/manifest.js\").GameTopologyManifest,\n kind: \"edge\" | \"vertex\",\n boardBaseId?: string,\n) {\n const boards = (manifest.boards ?? [])\n .filter(\n (board) =>\n board.layout !== \"generic\" &&\n (boardBaseId === undefined || board.id === boardBaseId),\n )\n .map((board) => ({\n layout: board.layout,\n identity: createInstanceDeclaration(\"board\", [\n { baseIds: [board.id], scope: board.scope },\n ]),\n }));\n const accepts = (value: string) => {\n const parsed = parseBoardElementId(value);\n return (\n parsed !== null &&\n parsed.kind === kind &&\n boards.some(\n (board) =>\n board.layout === parsed.layout &&\n board.identity.accepts(parsed.boardId),\n )\n );\n };\n return {\n accepts,\n schema: z\n .string()\n .refine(accepts, `Unknown declared board ${kind} identity.`),\n };\n}\n","import {\n CARD_REFERENCE_PREFIX,\n isCardReferenceNamespace,\n} from \"../../shared/domain/cards.js\";\nimport { AuthoredTileDisclosureSchema } from \"../../shared/domain/tile-disclosure.js\";\nimport { TileTypeSpecSchema } from \"../../shared/domain/manifest-schema.js\";\nimport * as z from \"zod\";\nimport { renderCardInstanceIds, expandSeedIds } from \"./identity-runtime.js\";\nimport { GENERATED_ID_PREFIX } from \"../../shared/domain/per-player-instance.js\";\nimport { analyzeManifestStructure, fieldReferenceContext } from \"./materialize\";\nimport {\n fieldSchemaKeyIssues,\n schemaForCardType,\n createFieldValidatorResolver,\n} from \"./field-schemas\";\nimport type { FieldSchemaJson } from \"../../shared/domain/contracts.js\";\nimport type {\n BoardCard,\n BoardSpec,\n DieSeedSpec,\n PieceSeedSpec,\n ZoneSpec,\n TileSeedSpec,\n} from \"../../shared/domain/contracts.js\";\nimport type { GameTopologyManifest } from \"../../shared/domain/manifest.js\";\n\nexport type ManifestAuthoringValidationResult = {\n errors: string[];\n warnings: string[];\n};\n\nfunction collectDuplicateIdIssues(options: {\n entries: ReadonlyArray<{ id?: string | null; path: string }>;\n label: string;\n}): string[] {\n const issues: string[] = [];\n const pathsById = new Map<string, string[]>();\n\n for (const entry of options.entries) {\n const id = entry.id?.trim();\n if (!id) {\n continue;\n }\n const paths = pathsById.get(id) ?? [];\n paths.push(entry.path);\n pathsById.set(id, paths);\n }\n\n for (const [id, paths] of pathsById.entries()) {\n if (paths.length > 1) {\n issues.push(`${paths.join(\", \")}: Duplicate ${options.label} '${id}'.`);\n }\n }\n\n return issues;\n}\n\nconst PROTOTYPE_SENSITIVE_KEYS = new Set([\n \"__proto__\",\n \"prototype\",\n \"constructor\",\n]);\n\nfunction validateRecordKey(\n value: string | null | undefined,\n path: string,\n): string[] {\n if (value?.startsWith(GENERATED_ID_PREFIX))\n return [\n `${path}: authored identities must not begin with reserved prefix '${GENERATED_ID_PREFIX}'.`,\n ];\n if (!value || !PROTOTYPE_SENSITIVE_KEYS.has(value)) {\n return [];\n }\n return [\n `${path}: '${value}' is reserved and cannot be used as a generated record key.`,\n ];\n}\n\nfunction collectKeyIssues(\n entries: ReadonlyArray<{ value?: string | null; path: string }>,\n): string[] {\n return entries.flatMap(({ value, path }) => validateRecordKey(value, path));\n}\n\nfunction collectCardSchemaKeyIssues(\n cardSet: GameTopologyManifest[\"cardSets\"][number],\n path: string,\n): string[] {\n return fieldSchemaKeyIssues(cardSet.cardSchema, `${path}.cardSchema`);\n}\n\nfunction validatePlayerScopedSeedHomes(\n manifest: GameTopologyManifest,\n): string[] {\n const issues: string[] = [];\n const boardScopeById = new Map(\n (manifest.boards ?? []).map((board) => [board.id, board.scope] as const),\n );\n const zoneScopeById = new Map(\n (manifest.zones ?? []).map(\n (zone) => [zone.id, \"scope\" in zone ? zone.scope : undefined] as const,\n ),\n );\n\n const validateSeedHome = (\n seed: PieceSeedSpec | DieSeedSpec,\n path: string,\n label: \"Piece seed\" | \"Die seed\",\n ) => {\n const authoredId = seed.id ?? seed.typeId;\n if (seed.scope === \"perPlayer\") {\n return;\n }\n\n if (\n homeTargetsBoard(seed.home) &&\n boardScopeById.get(seed.home.boardId) === \"perPlayer\"\n ) {\n issues.push(\n `${path}.boardId: ${label} '${authoredId}' requires perPlayer scope because board '${seed.home.boardId}' has scope 'perPlayer'. Use perPlayer scope to resolve the player-scoped destination.`,\n );\n return;\n }\n\n if (\n seed.home?.type === \"zone\" &&\n zoneScopeById.get(seed.home.zoneId) === \"perPlayer\"\n ) {\n issues.push(\n `${path}.zoneId: ${label} '${authoredId}' requires perPlayer scope because zone '${seed.home.zoneId}' has scope 'perPlayer'. Use perPlayer scope to resolve the player-scoped destination.`,\n );\n }\n };\n\n for (const [index, seed] of (manifest.pieceSeeds ?? []).entries()) {\n validateSeedHome(seed, `manifest.pieceSeeds[${index}].home`, \"Piece seed\");\n }\n\n for (const [index, seed] of (manifest.dieSeeds ?? []).entries()) {\n validateSeedHome(seed, `manifest.dieSeeds[${index}].home`, \"Die seed\");\n }\n\n return issues;\n}\n\nfunction validateCardHomes(manifest: GameTopologyManifest): string[] {\n const issues: string[] = [];\n const boardScopeById = new Map(\n (manifest.boards ?? []).map((board) => [board.id, board.scope] as const),\n );\n const zoneScopeById = new Map(\n (manifest.zones ?? []).map(\n (zone) => [zone.id, \"scope\" in zone ? zone.scope : undefined] as const,\n ),\n );\n\n for (const [cardSetIndex, cardSet] of manifest.cardSets.entries()) {\n if (!cardSet.defaultHome) {\n issues.push(\n `manifest.cardSets[${cardSetIndex}].defaultHome: Card sets must declare defaultHome.`,\n );\n continue;\n }\n const validateCardHome = (\n home: BoardCard[\"home\"] | TileSeedSpec[\"home\"],\n path: string,\n label: string,\n ) => {\n if (\n home?.type === \"zone\" &&\n zoneScopeById.get(home.zoneId) === \"perPlayer\"\n ) {\n issues.push(\n `${path}.zoneId: ${label} cannot target per-player zone '${home.zoneId}' because shared card inventory has no replication origin. Place it during reducer setup instead.`,\n );\n }\n if (\n homeTargetsBoard(home) &&\n boardScopeById.get(home.boardId) === \"perPlayer\"\n ) {\n issues.push(\n `${path}.boardId: ${label} cannot target per-player board '${home.boardId}' because shared card inventory has no replication origin. Place it during reducer setup instead.`,\n );\n }\n };\n\n for (const [cardIndex, card] of cardSet.cards.entries()) {\n if (card.scope === \"perPlayer\") continue;\n const path =\n card.home === undefined\n ? `manifest.cardSets[${cardSetIndex}].defaultHome`\n : `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].home`;\n validateCardHome(\n card.home ?? cardSet.defaultHome,\n path,\n `Card '${card.id}'`,\n );\n }\n }\n\n return issues;\n}\n\nconst ASSET_IMAGE_PATH =\n /^assets\\/(?:[\\w-][\\w.-]*\\/)*[\\w-][\\w.-]*\\.(?:avif|gif|jpe?g|png|svg|webp)$/i;\n\n/** Card images are repository files that hosts publish and deliver offline. */\nfunction validateCardImages(manifest: GameTopologyManifest): string[] {\n return manifest.cardSets.flatMap((cardSet, cardSetIndex) =>\n cardSet.cards.flatMap((card, cardIndex) =>\n ([\"frontImage\", \"backImage\"] as const).flatMap((key) => {\n const image = card[key];\n return image === undefined || ASSET_IMAGE_PATH.test(image)\n ? []\n : [\n `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].${key}: '${image}' must be an image path under assets/, such as assets/cards/front.webp.`,\n ];\n }),\n ),\n );\n}\n\nfunction homeTargetsBoard(\n home:\n | BoardCard[\"home\"]\n | PieceSeedSpec[\"home\"]\n | DieSeedSpec[\"home\"]\n | TileSeedSpec[\"home\"]\n | undefined,\n): home is Extract<\n NonNullable<BoardCard[\"home\"] | PieceSeedSpec[\"home\"] | DieSeedSpec[\"home\"]>,\n { type: \"space\" | \"edge\" | \"vertex\" }\n> {\n return (\n home?.type === \"space\" || home?.type === \"edge\" || home?.type === \"vertex\"\n );\n}\n\nfunction validateBoardDuplicates(boards: readonly BoardSpec[]): string[] {\n return boards.flatMap((board, index) => [\n ...(board.layout === \"generic\"\n ? collectDuplicateIdIssues({\n entries: (board.spaces ?? []).map((space, i) => ({\n id: space.id,\n path: `manifest.boards[${index}].spaces[${i}].id`,\n })),\n label: \"space id\",\n })\n : []),\n ...collectDuplicateIdIssues({\n entries: (board.relations ?? []).map((relation, i) => ({\n id: relation.id,\n path: `manifest.boards[${index}].relations[${i}].id`,\n })),\n label: \"relation id\",\n }),\n ]);\n}\nfunction collectBoardRecordKeyIssues(manifest: GameTopologyManifest): string[] {\n const issues: string[] = [];\n for (const [i, board] of (manifest.boards ?? []).entries()) {\n const path = `manifest.boards[${i}]`;\n if (board.visibility === \"ownerOnly\" && board.scope === \"shared\")\n issues.push(`${path}.visibility: ownerOnly requires perPlayer scope.`);\n issues.push(\n ...collectKeyIssues([\n { value: board.id, path: `${path}.id` },\n { value: board.typeId, path: `${path}.typeId` },\n ]),\n ...fieldSchemaKeyIssues(\n board.boardFieldsSchema,\n `${path}.boardFieldsSchema`,\n ),\n ...fieldSchemaKeyIssues(\n board.relationFieldsSchema,\n `${path}.relationFieldsSchema`,\n ),\n );\n if (board.layout === \"generic\") {\n issues.push(\n ...fieldSchemaKeyIssues(\n board.spaceFieldsSchema,\n `${path}.spaceFieldsSchema`,\n ),\n );\n for (const [j, space] of (board.spaces ?? []).entries())\n issues.push(\n ...collectKeyIssues([\n { value: space.id, path: `${path}.spaces[${j}].id` },\n { value: space.typeId, path: `${path}.spaces[${j}].typeId` },\n ]),\n );\n }\n for (const [j, relation] of (board.relations ?? []).entries())\n issues.push(\n ...collectKeyIssues([\n { value: relation.id, path: `${path}.relations[${j}].id` },\n { value: relation.typeId, path: `${path}.relations[${j}].typeId` },\n ]),\n );\n }\n return issues;\n}\nfunction collectManifestRecordKeyIssues(\n manifest: GameTopologyManifest,\n): string[] {\n const cardSets = manifest.cardSets;\n const cards = cardSets.flatMap((cardSet, cardSetIndex) =>\n cardSet.cards.flatMap((card, cardIndex) =>\n renderCardInstanceIds(card).map((cardId) => ({\n card,\n cardId,\n cardIndex,\n cardSetIndex,\n })),\n ),\n );\n\n return [\n ...collectKeyIssues([\n ...cardSets.map((cardSet, index) => ({\n value: cardSet.id,\n path: `manifest.cardSets[${index}].id`,\n })),\n ...cards.flatMap(({ card, cardId, cardIndex, cardSetIndex }) => [\n {\n value: card.id,\n path: `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].id`,\n },\n {\n value: card.cardType,\n path: `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].cardType`,\n },\n {\n value: cardId,\n path: `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].runtimeId`,\n },\n ]),\n ...(manifest.zones ?? []).map((zone, index) => ({\n value: zone.id,\n path: `manifest.zones[${index}].id`,\n })),\n ...(manifest.resources ?? []).map((resource, index) => ({\n value: resource.id,\n path: `manifest.resources[${index}].id`,\n })),\n ...(manifest.pieceTypes ?? []).flatMap((pieceType, typeIndex) => [\n {\n value: pieceType.id,\n path: `manifest.pieceTypes[${typeIndex}].id`,\n },\n ]),\n ...(manifest.dieTypes ?? []).flatMap((dieType, typeIndex) => [\n {\n value: dieType.id,\n path: `manifest.dieTypes[${typeIndex}].id`,\n },\n ]),\n ...expandSeedIds(manifest.pieceSeeds ?? []).map((pieceId, index) => ({\n value: pieceId,\n path: `manifest.pieceSeeds[*][${index}]`,\n })),\n ...expandSeedIds(manifest.dieSeeds ?? []).map((dieId, index) => ({\n value: dieId,\n path: `manifest.dieSeeds[*][${index}]`,\n })),\n ]),\n ...cardSets.flatMap((cardSet, cardSetIndex) =>\n collectCardSchemaKeyIssues(cardSet, `manifest.cardSets[${cardSetIndex}]`),\n ),\n ...(manifest.pieceTypes ?? []).flatMap((pieceType, typeIndex) =>\n fieldSchemaKeyIssues(\n pieceType.fieldsSchema,\n `manifest.pieceTypes[${typeIndex}].fieldsSchema`,\n ),\n ),\n ...(manifest.dieTypes ?? []).flatMap((dieType, typeIndex) =>\n fieldSchemaKeyIssues(\n dieType.fieldsSchema,\n `manifest.dieTypes[${typeIndex}].fieldsSchema`,\n ),\n ),\n ...collectBoardRecordKeyIssues(manifest),\n ];\n}\n\nfunction validateTileDefinitions(manifest: GameTopologyManifest): string[] {\n const errors: string[] = [];\n errors.push(\n ...collectDuplicateIdIssues({\n entries: (manifest.tileTypes ?? []).map((type, i) => ({\n id: type.id,\n path: `manifest.tileTypes[${i}].id`,\n })),\n label: \"tile type id\",\n }),\n );\n for (const [i, type] of (manifest.tileTypes ?? []).entries()) {\n const path = `manifest.tileTypes[${i}]`;\n const parsed = TileTypeSpecSchema.safeParse(type);\n if (!parsed.success)\n for (const issue of parsed.error.issues)\n errors.push(`${path}.${issue.path.join(\".\")}: ${issue.message}`);\n errors.push(...validateRecordKey(type.id, `${path}.id`));\n errors.push(\n ...collectDuplicateIdIssues({\n entries: type.cells.map((cell, j) => ({\n id: cell.id,\n path: `${path}.cells[${j}].id`,\n })),\n label: \"tile local cell id\",\n }),\n );\n const coordinates = new Set<string>();\n for (const [j, cell] of type.cells.entries()) {\n errors.push(...validateRecordKey(cell.id, `${path}.cells[${j}].id`));\n errors.push(\n ...validateRecordKey(cell.typeId, `${path}.cells[${j}].typeId`),\n );\n const key =\n \"q\" in cell.at\n ? JSON.stringify([cell.at.q, cell.at.r])\n : JSON.stringify([cell.at.col, cell.at.row]);\n if (coordinates.has(key))\n errors.push(`${path}.cells[${j}].at: Duplicate tile local coordinate.`);\n coordinates.add(key);\n }\n for (const kind of [\"edges\", \"vertices\"] as const) {\n const addresses = new Set<string>();\n for (const [j, annotation] of (type[kind] ?? []).entries()) {\n errors.push(\n ...validateRecordKey(\n annotation.typeId,\n `${path}.${kind}[${j}].typeId`,\n ),\n );\n if (!type.cells.some((cell) => cell.id === annotation.cellId))\n errors.push(\n `${path}.${kind}[${j}].cellId: Unknown tile cell '${annotation.cellId}'.`,\n );\n const address = JSON.stringify([\n annotation.cellId,\n \"side\" in annotation ? annotation.side : annotation.corner,\n ]);\n if (addresses.has(address))\n errors.push(\n `${path}.${kind}[${j}]: Duplicate tile annotation address.`,\n );\n addresses.add(address);\n }\n }\n if (\n type.frontImage !== undefined &&\n !ASSET_IMAGE_PATH.test(type.frontImage)\n )\n errors.push(`${path}.frontImage: Must be an image path under assets/.`);\n for (const key of [\n \"fieldsSchema\",\n \"propertiesSchema\",\n \"cellFieldsSchema\",\n \"edgeFieldsSchema\",\n \"vertexFieldsSchema\",\n ] as const)\n errors.push(...fieldSchemaKeyIssues(type[key], `${path}.${key}`));\n }\n for (const [i, seed] of (manifest.tileSeeds ?? []).entries()) {\n errors.push(...validateRecordKey(seed.id, `manifest.tileSeeds[${i}].id`));\n if (seed.disclosure !== undefined) {\n const disclosure = AuthoredTileDisclosureSchema.safeParse(\n seed.disclosure,\n );\n if (!disclosure.success)\n errors.push(\n `manifest.tileSeeds[${i}].disclosure: ${disclosure.error.message}`,\n );\n if (\n seed.disclosure.appearance?.backImage !== undefined &&\n !ASSET_IMAGE_PATH.test(seed.disclosure.appearance.backImage)\n )\n errors.push(\n `manifest.tileSeeds[${i}].disclosure.appearance.backImage: Must be an image path under assets/.`,\n );\n if (\n seed.home?.type === \"board\" &&\n seed.disclosure.appearance !== undefined &&\n seed.disclosure.appearance.layout !== seed.home.layout\n )\n errors.push(\n `manifest.tileSeeds[${i}].disclosure.appearance.layout: Must match board placement layout.`,\n );\n }\n for (const id of expandSeedIds([seed]))\n errors.push(...validateRecordKey(id, `manifest.tileSeeds[${i}].id`));\n if (seed.home?.type === \"zone\") {\n const zoneId = seed.home.zoneId;\n const zone = manifest.zones?.find((zone) => zone.id === zoneId);\n if (\n zone &&\n \"scope\" in zone &&\n zone.scope === \"perPlayer\" &&\n seed.scope !== \"perPlayer\"\n )\n errors.push(\n `manifest.tileSeeds[${i}].home: Shared tile inventory cannot infer a per-player host.`,\n );\n }\n }\n return errors;\n}\n\nfunction validateCounts(manifest: GameTopologyManifest): string[] {\n const errors: string[] = [];\n const check = (count: number, path: string) => {\n if (!Number.isSafeInteger(count) || count < 1) {\n errors.push(`${path}: Expected a positive safe integer.`);\n }\n };\n manifest.cardSets.forEach((set, setIndex) => {\n set.cards.forEach((card, index) =>\n check(card.count, `manifest.cardSets[${setIndex}].cards[${index}].count`),\n );\n });\n for (const family of [\"pieceSeeds\", \"dieSeeds\", \"tileSeeds\"] as const) {\n manifest[family]?.forEach((seed, index) => {\n if (seed.count !== undefined)\n check(seed.count, `manifest.${family}[${index}].count`);\n });\n }\n check(manifest.players.minPlayers, \"manifest.players.minPlayers\");\n check(manifest.players.maxPlayers, \"manifest.players.maxPlayers\");\n if (manifest.players.minPlayers > manifest.players.maxPlayers) {\n errors.push(\"manifest.players: minPlayers must not exceed maxPlayers.\");\n }\n if (manifest.players.optimalPlayers !== undefined) {\n check(manifest.players.optimalPlayers, \"manifest.players.optimalPlayers\");\n if (\n manifest.players.optimalPlayers < manifest.players.minPlayers ||\n manifest.players.optimalPlayers > manifest.players.maxPlayers\n )\n errors.push(\n \"manifest.players.optimalPlayers: Must be within minPlayers and maxPlayers.\",\n );\n }\n return errors;\n}\n\nexport function assertValidManifest(manifest: GameTopologyManifest): void {\n const validation = validateManifestAuthoring(manifest);\n if (validation.errors.length) {\n throw new Error(\n `Invalid topology manifest:\\n${validation.errors.join(\"\\n\")}`,\n );\n }\n}\n\nexport function validateManifestAuthoring(\n manifest: GameTopologyManifest,\n): ManifestAuthoringValidationResult {\n const errors = validateCounts(manifest);\n // Never expand invalid counts (including Infinity) into runtime ids.\n if (errors.length) return { errors, warnings: [] };\n\n for (const [index, zone] of (manifest.zones ?? []).entries()) {\n if (\n \"scope\" in zone &&\n zone.scope === \"shared\" &&\n zone.visibility === \"ownerOnly\"\n ) {\n errors.push(\n `manifest.zones[${index}].visibility: ownerOnly requires perPlayer scope; use hidden for concealed shared contents`,\n );\n }\n }\n\n const componentIds = [\n ...manifest.cardSets.flatMap((set) =>\n set.cards.flatMap(renderCardInstanceIds),\n ),\n ...expandSeedIds(manifest.pieceSeeds ?? []),\n ...expandSeedIds(manifest.dieSeeds ?? []),\n ...expandSeedIds(manifest.tileSeeds ?? []),\n ];\n for (const id of componentIds)\n if (isCardReferenceNamespace(id))\n errors.push(\n `Component id '${id}' uses the reserved concealed-id namespace '${CARD_REFERENCE_PREFIX}'.`,\n );\n errors.push(...collectManifestRecordKeyIssues(manifest));\n errors.push(\n ...collectDuplicateIdIssues({\n label: \"component runtime id\",\n entries: [\n ...manifest.cardSets.flatMap((set, setIndex) =>\n set.cards.flatMap((card, index) =>\n renderCardInstanceIds(card).map((id) => ({\n id,\n path: `manifest.cardSets[${setIndex}].cards[${index}]`,\n })),\n ),\n ),\n ...expandSeedIds(manifest.pieceSeeds ?? []).map((id, index) => ({\n id,\n path: `manifest.pieceSeeds.runtimeIds[${index}]`,\n })),\n ...expandSeedIds(manifest.tileSeeds ?? []).map((id, index) => ({\n id,\n path: `manifest.tileSeeds.runtimeIds[${index}]`,\n })),\n ...expandSeedIds(manifest.dieSeeds ?? []).map((id, index) => ({\n id,\n path: `manifest.dieSeeds.runtimeIds[${index}]`,\n })),\n ],\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: manifest.cardSets.map((cardSet, index) => ({\n id: cardSet.id,\n path: `manifest.cardSets[${index}].id`,\n })),\n label: \"card set id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: manifest.cardSets.flatMap((cardSet, cardSetIndex) =>\n cardSet.cards.flatMap((card, cardIndex) =>\n renderCardInstanceIds(card).map((cardId) => ({\n id: cardId,\n path: `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].id`,\n })),\n ),\n ),\n label: \"card runtime id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: (manifest.zones ?? []).map((zone: ZoneSpec, index) => ({\n id: zone.id,\n path: `manifest.zones[${index}].id`,\n })),\n label: \"zone id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: (manifest.boards ?? []).map((board, index) => ({\n id: board.id,\n path: `manifest.boards[${index}].id`,\n })),\n label: \"board id\",\n }),\n );\n errors.push(...validateBoardDuplicates(manifest.boards ?? []));\n errors.push(\n ...collectDuplicateIdIssues({\n entries: (manifest.pieceTypes ?? []).map((pieceType, index) => ({\n id: pieceType.id,\n path: `manifest.pieceTypes[${index}].id`,\n })),\n label: \"piece type id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: expandSeedIds(manifest.pieceSeeds ?? []).map(\n (pieceId, index) => ({\n id: pieceId,\n path: `manifest.pieceSeeds[*][${index}]`,\n }),\n ),\n label: \"piece runtime id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: (manifest.dieTypes ?? []).map((dieType, index) => ({\n id: dieType.id,\n path: `manifest.dieTypes[${index}].id`,\n })),\n label: \"die type id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: expandSeedIds(manifest.dieSeeds ?? []).map((dieId, index) => ({\n id: dieId,\n path: `manifest.dieSeeds[*][${index}]`,\n })),\n label: \"die runtime id\",\n }),\n );\n errors.push(\n ...collectDuplicateIdIssues({\n entries: (manifest.resources ?? []).map((resource, index) => ({\n id: resource.id,\n path: `manifest.resources[${index}].id`,\n })),\n label: \"resource id\",\n }),\n );\n errors.push(...validatePlayerScopedSeedHomes(manifest));\n errors.push(...validateCardHomes(manifest));\n errors.push(...validateTileDefinitions(manifest));\n for (const [kind, seeds, types] of [\n [\"pieceSeeds\", manifest.pieceSeeds ?? [], manifest.pieceTypes ?? []],\n [\"dieSeeds\", manifest.dieSeeds ?? [], manifest.dieTypes ?? []],\n [\"tileSeeds\", manifest.tileSeeds ?? [], manifest.tileTypes ?? []],\n ] as const)\n for (const [index, seed] of seeds.entries()) {\n if (!types.some((type) => type.id === seed.typeId))\n errors.push(\n `manifest.${kind}[${index}].typeId: Unknown component type '${seed.typeId}'.`,\n );\n }\n for (const [cardSetIndex, cardSet] of manifest.cardSets.entries()) {\n for (const [cardIndex, card] of cardSet.cards.entries()) {\n const path = `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}]`;\n if (typeof card.id !== \"string\" || card.id.length === 0) {\n errors.push(`${path}.id: Card definition id is required.`);\n } else if (isCardReferenceNamespace(card.id)) {\n errors.push(\n `${path}.id: The '${CARD_REFERENCE_PREFIX}' prefix is reserved for concealed card positions.`,\n );\n }\n if (typeof card.cardType !== \"string\" || card.cardType.length === 0) {\n errors.push(`${path}.cardType: Card category is required.`);\n } else if (\n cardSet.cardSchema.byCardType != null &&\n typeof cardSet.cardSchema.byCardType === \"object\" &&\n !Object.hasOwn(cardSet.cardSchema.byCardType, card.cardType)\n ) {\n errors.push(\n `${path}.cardType: Unknown card category '${card.cardType}' for card set '${cardSet.id}'.`,\n );\n }\n }\n }\n errors.push(...validateAnalyzedManifest(manifest));\n errors.push(...validateCardImages(manifest));\n\n return {\n errors,\n warnings: [],\n };\n}\n\nfunction validateAnalyzedManifest(manifest: GameTopologyManifest): string[] {\n let analysis: ReturnType<typeof analyzeManifestStructure>;\n try {\n analysis = analyzeManifestStructure(manifest);\n } catch (error) {\n return [\n `manifest: ${error instanceof Error ? error.message : String(error)}`,\n ];\n }\n const context = fieldReferenceContext(analysis, \"manifest\");\n const errors = validateHomeMembership(manifest, analysis);\n const resolve = createFieldValidatorResolver((boardId) =>\n boardId ? fieldReferenceContext(analysis, \"manifest\", boardId) : context,\n );\n function admit(\n schema: FieldSchemaJson,\n path: string,\n boardId?: string,\n ): void {\n try {\n resolve(schema, boardId);\n } catch (error) {\n errors.push(\n `${path}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const [i, set] of manifest.cardSets.entries()) {\n if (set.cardSchema.byCardType !== undefined) {\n const variants = z\n .record(z.string(), z.record(z.string(), z.json()))\n .parse(set.cardSchema.byCardType);\n for (const [id, schema] of Object.entries(variants))\n admit(schema, `manifest.cardSets[${i}].cardSchema.byCardType.${id}`);\n } else admit(set.cardSchema, `manifest.cardSets[${i}].cardSchema`);\n }\n for (const [i, board] of (manifest.boards ?? []).entries())\n for (const key of [\n \"boardFieldsSchema\",\n \"spaceFieldsSchema\",\n \"relationFieldsSchema\",\n \"edgeFieldsSchema\",\n \"vertexFieldsSchema\",\n ] as const)\n if (key in board) {\n const schema: unknown = Reflect.get(board, key);\n if (schema !== undefined)\n admit(\n z.record(z.string(), z.json()).parse(schema),\n `manifest.boards[${i}].${key}`,\n board.id,\n );\n }\n function check(\n schema: FieldSchemaJson | undefined,\n values: unknown,\n path: string,\n boardId?: string,\n ): void {\n if (!schema) return;\n try {\n const validator = resolve(schema, boardId);\n const result = validator.safeParse(values ?? {});\n if (!result.success)\n for (const issue of result.error.issues)\n errors.push(\n `${path}${issue.path.length ? \".\" + issue.path.join(\".\") : \"\"}: ${issue.message}`,\n );\n } catch (error) {\n errors.push(\n `${path}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const type of [\n ...(manifest.pieceTypes ?? []),\n ...(manifest.dieTypes ?? []),\n ])\n if (type.fieldsSchema) {\n try {\n resolve(type.fieldsSchema);\n } catch (error) {\n errors.push(\n `manifest.componentTypes.${type.id}.fieldsSchema: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const [i, type] of (manifest.tileTypes ?? []).entries()) {\n const path = `manifest.tileTypes[${i}]`;\n for (const key of [\n \"fieldsSchema\",\n \"propertiesSchema\",\n \"cellFieldsSchema\",\n \"edgeFieldsSchema\",\n \"vertexFieldsSchema\",\n ] as const)\n if (type[key]) {\n try {\n resolve(type[key]);\n } catch (error) {\n errors.push(\n `${path}.${key}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n check(type.fieldsSchema, type.fields, `${path}.fields`);\n for (const [j, cell] of type.cells.entries())\n check(type.cellFieldsSchema, cell.fields, `${path}.cells[${j}].fields`);\n for (const [j, edge] of (type.edges ?? []).entries())\n check(type.edgeFieldsSchema, edge.fields, `${path}.edges[${j}].fields`);\n for (const [j, vertex] of (type.vertices ?? []).entries())\n check(\n type.vertexFieldsSchema,\n vertex.fields,\n `${path}.vertices[${j}].fields`,\n );\n }\n for (const [i, seed] of (manifest.tileSeeds ?? []).entries())\n check(\n manifest.tileTypes?.find((type) => type.id === seed.typeId)\n ?.propertiesSchema,\n seed.properties,\n `manifest.tileSeeds[${i}].properties`,\n );\n for (const [si, set] of manifest.cardSets.entries())\n for (const [ci, card] of set.cards.entries()) {\n try {\n check(\n schemaForCardType(set.cardSchema, card.cardType),\n card.properties,\n `manifest.cardSets[${si}].cards[${ci}].properties`,\n );\n } catch (error) {\n errors.push(\n `manifest.cardSets[${si}].cards[${ci}].properties: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const [kind, seeds, types] of [\n [\"pieceSeeds\", manifest.pieceSeeds ?? [], manifest.pieceTypes ?? []],\n [\"dieSeeds\", manifest.dieSeeds ?? [], manifest.dieTypes ?? []],\n ] as const)\n for (const [i, seed] of seeds.entries())\n check(\n types.find((type) => type.id === seed.typeId)?.fieldsSchema,\n seed.fields,\n `manifest.${kind}[${i}].fields`,\n );\n for (const [i, board] of (manifest.boards ?? []).entries()) {\n const base = `manifest.boards[${i}]`;\n check(board.boardFieldsSchema, board.fields, `${base}.fields`, board.id);\n const spaces = board.layout === \"generic\" ? (board.spaces ?? []) : [];\n for (const [j, space] of spaces.entries())\n check(\n board.layout === \"generic\" ? board.spaceFieldsSchema : undefined,\n space.fields,\n `${base}.spaces[${j}].fields`,\n board.id,\n );\n {\n for (const [j, relation] of (board.relations ?? []).entries())\n check(\n board.relationFieldsSchema,\n relation.fields,\n `${base}.relations[${j}].fields`,\n board.id,\n );\n }\n }\n return errors;\n}\n\nfunction validateHomeMembership(\n manifest: GameTopologyManifest,\n analysis: ReturnType<typeof analyzeManifestStructure>,\n): string[] {\n const errors: string[] = [];\n function check(\n home: BoardCard[\"home\"] | TileSeedSpec[\"home\"],\n path: string,\n scope: \"shared\" | \"perPlayer\" = \"shared\",\n ): void {\n if (!home || home.type === \"detached\") return;\n if (home.type === \"zone\") {\n const zone = manifest.zones?.find((zone) => zone.id === home.zoneId);\n if (!zone) {\n errors.push(`${path}.zoneId: unknown zone '${home.zoneId}'.`);\n return;\n }\n if (\"scope\" in zone) {\n if (home.component !== undefined)\n errors.push(\n `${path}.component: This zone does not have a component host.`,\n );\n } else if (\"board\" in zone.attachedTo) {\n if (home.component !== undefined)\n errors.push(`${path}.component: This zone has a board host.`);\n const attachedBoard = zone.attachedTo.board;\n const board = manifest.boards?.find(\n (board) => board.id === attachedBoard,\n );\n if (scope !== \"perPlayer\" && board?.scope === \"perPlayer\")\n errors.push(\n `${path}: Shared inventory cannot infer a per-player board host.`,\n );\n } else {\n const attachment = zone.attachedTo;\n const type =\n \"pieceType\" in attachment\n ? attachment.pieceType\n : \"dieType\" in attachment\n ? attachment.dieType\n : attachment.tileType;\n const seeds =\n \"pieceType\" in attachment\n ? manifest.pieceSeeds\n : \"dieType\" in attachment\n ? manifest.dieSeeds\n : manifest.tileSeeds;\n const host = seeds?.find(\n (seed) =>\n seed.typeId === type &&\n expandSeedIds([seed]).includes(home.component ?? \"\"),\n );\n if (!host)\n errors.push(\n `${path}.component: Expected an expanded component base of type '${type}'.`,\n );\n else if (scope !== \"perPlayer\" && host.scope === \"perPlayer\")\n errors.push(\n `${path}: Shared inventory cannot infer a per-player component host.`,\n );\n }\n return;\n }\n const board = analysis.analyzedBoards.find(\n (board) => board.board.id === home.boardId,\n );\n if (!board) {\n errors.push(`${path}.boardId: unknown board '${home.boardId}'.`);\n return;\n }\n if (home.type === \"board\") {\n if (board.layout === \"generic\" || board.layout !== home.layout)\n errors.push(`${path}: Tile home requires matching tiled board layout.`);\n if (scope !== \"perPlayer\" && board.board.scope === \"perPlayer\")\n errors.push(`${path}: Shared tile cannot infer per-player board.`);\n return;\n }\n if (home.type === \"space\") {\n if (!board.spaces.some((space) => space.id === home.spaceId))\n errors.push(\n `${path}.spaceId: unknown space '${home.spaceId}' on board '${home.boardId}'.`,\n );\n } else {\n const matches = (ids: readonly string[]) =>\n ids.length === home.ref.spaces.length &&\n [...ids]\n .sort()\n .every((id, index) => id === [...home.ref.spaces].sort()[index]);\n const exists =\n board.layout !== \"generic\" &&\n (home.type === \"edge\"\n ? board.edges.some((edge) => matches(edge.spaceIds))\n : board.vertices.some((vertex) => matches(vertex.spaceIds)));\n if (!exists)\n errors.push(\n `${path}.ref: Unknown ${home.type} reference on board '${home.boardId}'.`,\n );\n }\n }\n for (const [index, zone] of (manifest.zones ?? []).entries()) {\n if (!(\"attachedTo\" in zone)) continue;\n const attachment = zone.attachedTo;\n const path = `manifest.zones[${index}].attachedTo`;\n if (\"board\" in attachment) {\n const board = analysis.analyzedBoards.find(\n (board) => board.board.id === attachment.board,\n );\n if (!board)\n errors.push(`${path}.board: Unknown board '${attachment.board}'.`);\n else {\n if (\n \"space\" in attachment &&\n (board.layout !== \"generic\" ||\n !board.spaces.some((space) => space.id === attachment.space))\n )\n errors.push(`${path}.space: Unknown space '${attachment.space}'.`);\n if (zone.visibility === \"ownerOnly\" && board.board.scope === \"shared\")\n errors.push(`${path}: ownerOnly requires an owned host.`);\n }\n } else if (\"pieceType\" in attachment) {\n if (!analysis.pieceTypeIds.includes(attachment.pieceType))\n errors.push(\n `${path}.pieceType: Unknown piece type '${attachment.pieceType}'.`,\n );\n } else if (\"dieType\" in attachment) {\n if (!analysis.dieTypeIds.includes(attachment.dieType))\n errors.push(\n `${path}.dieType: Unknown die type '${attachment.dieType}'.`,\n );\n } else {\n const type = manifest.tileTypes?.find(\n (type) => type.id === attachment.tileType,\n );\n if (!type || !type.cells.some((cell) => cell.id === attachment.cell))\n errors.push(`${path}: Unknown tile type or local cell.`);\n }\n }\n for (const [si, set] of manifest.cardSets.entries()) {\n check(set.defaultHome, `manifest.cardSets[${si}].defaultHome`, \"perPlayer\");\n for (const [ci, card] of set.cards.entries())\n check(\n card.home ?? set.defaultHome,\n `manifest.cardSets[${si}].cards[${ci}].home`,\n card.scope,\n );\n }\n for (const [kind, seeds] of [\n [\"pieceSeeds\", manifest.pieceSeeds ?? []],\n [\"dieSeeds\", manifest.dieSeeds ?? []],\n [\"tileSeeds\", manifest.tileSeeds ?? []],\n ] as const)\n for (const [i, seed] of seeds.entries())\n check(seed.home, `manifest.${kind}[${i}].home`, seed.scope);\n return errors;\n}\n","import { tileSpaceId } from \"../../shared/domain/tile-space.js\";\nimport {\n deriveBoardTopology,\n type BoardEdge,\n type BoardVertex,\n type BoardTopology,\n type TilePlacement,\n} from \"../../shared/board-topology.js\";\nimport type {\n TopologyDefinitions,\n BoardDefinition,\n TileDefinition,\n} from \"../../shared/domain/topology-definitions.js\";\nimport { RuntimeJsonSchema } from \"../../shared/runtime-json.js\";\nimport { boardSpaceHostId } from \"../../shared/domain/board-space-host.js\";\nimport {\n enumerateZoneHosts,\n assertContainmentAcyclic,\n assertZoneConsistency,\n type ZoneTable,\n} from \"../table/zones.js\";\nimport type {\n RuntimeComponentLocation,\n RuntimeBoardInstance,\n ZoneDefinition,\n} from \"../model\";\nimport {\n PlayerRosterSchema,\n isPlayerIdValue,\n} from \"../../shared/domain/player-identity.js\";\nimport {\n renderCardInstanceIds,\n expandSeedIds,\n scopedInstances,\n initialCardMetadata,\n createInstanceDeclaration,\n createSpaceDeclaration,\n createBoardElementDeclaration,\n} from \"./identity-runtime.js\";\nimport { perPlayerInstanceId } from \"../../shared/domain/per-player-instance.js\";\nimport * as z from \"zod\";\nimport {\n createFieldValidatorResolver,\n schemaForCardType,\n type FieldReferenceContext,\n} from \"./field-schemas\";\nimport type {\n BoardCard,\n BoardRelationSpec,\n BoardSpec,\n BoardSpaceSpec,\n CardSetDefinition,\n FieldSchemaJson,\n PieceSeedSpec,\n ZoneSpec,\n} from \"../../shared/domain/contracts.js\";\nimport type { GameTopologyManifest } from \"../../shared/domain/manifest.js\";\n\nimport { assertValidManifest } from \"./manifest-validation.js\";\n\ninterface AnalyzedBoard {\n layout: \"generic\" | \"hex\" | \"square\";\n board: BoardSpec;\n boardTypeId?: string | null;\n runtimeBoardIds: string[];\n topologies: Map<string, BoardTopology>;\n boardFieldsSchema?: FieldSchemaJson;\n spaceFieldsSchema?: FieldSchemaJson;\n relationFieldsSchema?: FieldSchemaJson;\n spaces: BoardSpaceSpec[];\n relations: BoardRelationSpec[];\n edges: readonly BoardEdge[];\n vertices: readonly BoardVertex[];\n}\ninterface ManifestAnalysis {\n manifest: GameTopologyManifest;\n playerIds: string[];\n sharedZones: ZoneSpec[];\n playerZones: ZoneSpec[];\n zoneIds: string[];\n cardSets: CardSetDefinition[];\n cardSetIds: string[];\n cardTypes: string[];\n cardIds: string[];\n cardSetIdByCardId: Map<string, string>;\n cardTypeByCardId: Map<string, string>;\n sharedZoneCardSetIds: Map<string, string[]>;\n sharedZoneIdsByCardSetId: Map<string, string[]>;\n homeSharedZoneIdsByCardType: Map<string, string[]>;\n homeSharedZoneIdByCardType: Map<string, string>;\n playerZoneCardSetIds: Map<string, string[]>;\n zoneCardSetIdsById: Map<string, string[]>;\n zoneVisibilityById: Map<string, NonNullable<ZoneSpec[\"visibility\"]>>;\n resourceIds: string[];\n resourcePresentationById: Record<\n string,\n { label: string; icon?: string | null }\n >;\n pieceTypeIds: string[];\n pieceIds: string[];\n pieceTypeIdByPieceId: Map<string, string>;\n dieTypeIds: string[];\n dieIds: string[];\n tileTypeIds: string[];\n tileIds: string[];\n tileTypeIdByTileId: Map<string, string>;\n tilePropertiesSchemasById: Map<string, FieldSchemaJson | undefined>;\n dieTypeIdByDieId: Map<string, string>;\n boardBaseIds: string[];\n boardIds: string[];\n boardTypeIds: string[];\n boardLayoutById: Map<string, string>;\n boardIdsByLayout: Map<string, string[]>;\n boardBaseIdsByLayout: Map<string, string[]>;\n boardIdsByBaseId: Map<string, string[]>;\n boardIdsByTypeId: Map<string, string[]>;\n spaceIdsByBoardId: Map<string, string[]>;\n spaceTypeIdByBoardId: Map<string, Record<string, string | null>>;\n spaceIdsByTypeId: Map<string, string[]>;\n relationTypeIds: string[];\n relationTypeIdsByBoardId: Map<string, string[]>;\n edgeIds: string[];\n edgeTypeIds: string[];\n edgeIdsByTypeId: Map<string, string[]>;\n edgeIdsByBoardIdAndTypeId: Map<string, Record<string, string[]>>;\n vertexIds: string[];\n vertexTypeIds: string[];\n vertexIdsByTypeId: Map<string, string[]>;\n vertexIdsByBoardIdAndTypeId: Map<string, Record<string, string[]>>;\n spaceIds: string[];\n spaceTypeIds: string[];\n analyzedBoards: AnalyzedBoard[];\n pieceTypeSchemasById: Map<string, FieldSchemaJson | null | undefined>;\n dieTypeSchemasById: Map<string, FieldSchemaJson | null | undefined>;\n}\n\nfunction dedupeSorted(values: Iterable<string>): string[] {\n return Array.from(new Set(values)).sort();\n}\n\nfunction sortedObject<Value>(\n entries: Iterable<readonly [string, Value]>,\n): Record<string, Value> {\n return Object.fromEntries(\n Array.from(entries).sort(([left], [right]) => left.localeCompare(right)),\n );\n}\n\nfunction createRecord<Value>(): Record<string, Value> {\n return Object.create(null) as Record<string, Value>;\n}\n\nfunction seededTopologyInventory(\n manifest: GameTopologyManifest,\n playerIds: readonly string[],\n) {\n const boards: Record<string, RuntimeBoardInstance> = {};\n for (const board of manifest.boards ?? [])\n for (const { id } of scopedInstances(\n \"board\",\n [board.id],\n board.scope,\n playerIds,\n ))\n boards[id] = {\n baseId: board.id,\n visibility: board.visibility ?? \"public\",\n relations: [],\n };\n const tiles: Record<\n string,\n { id: string; tileTypeId: string; ownerId: string | null }\n > = {};\n const componentLocations: Record<\n string,\n TilePlacement | { type: \"Detached\" }\n > = {};\n for (const seed of manifest.tileSeeds ?? [])\n for (const { id, playerId: origin } of scopedInstances(\n \"tile\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n )) {\n tiles[id] = { id, tileTypeId: seed.typeId, ownerId: origin };\n const home = seed.home;\n if (home?.type === \"board\") {\n const board = manifest.boards?.find(\n (board) => board.id === home.boardId,\n );\n if (!board)\n throw new Error(`Tile home names unknown board '${home.boardId}'.`);\n const boardId =\n board.scope === \"perPlayer\" && origin !== null\n ? perPlayerInstanceId(\"board\", board.id, origin)\n : board.id;\n componentLocations[id] = { ...home, type: \"OnBoard\", boardId };\n } else componentLocations[id] = { type: \"Detached\" };\n }\n return { boards, tiles, componentLocations };\n}\nfunction analyzeBoards(manifest: GameTopologyManifest, playerIds: string[]) {\n const inventory = seededTopologyInventory(manifest, playerIds);\n const declarations = buildTopologyDefinitions(manifest, (_schema, values) =>\n z.record(z.string(), RuntimeJsonSchema).parse(values ?? {}),\n );\n return (manifest.boards ?? []).map((board): AnalyzedBoard => {\n const runtimeBoardIds = Object.entries(inventory.boards)\n .filter(([, instance]) => instance.baseId === board.id)\n .map(([id]) => id);\n const topologies = new Map(\n runtimeBoardIds.map((id) => [\n id,\n deriveBoardTopology(inventory, declarations, id),\n ]),\n );\n const values = [...topologies.values()];\n return {\n layout: board.layout,\n board,\n boardTypeId: board.typeId,\n runtimeBoardIds,\n topologies,\n boardFieldsSchema: board.boardFieldsSchema,\n spaceFieldsSchema:\n board.layout === \"generic\" ? board.spaceFieldsSchema : undefined,\n relationFieldsSchema: board.relationFieldsSchema,\n spaces: values.length\n ? values.flatMap((topology) =>\n Object.values(topology.spaces).map((space) => ({\n id: space.id,\n ...(space.typeId == null ? {} : { typeId: space.typeId }),\n })),\n )\n : board.layout === \"generic\"\n ? [...(board.spaces ?? [])]\n : [],\n relations: [...(board.relations ?? [])],\n edges: values.flatMap((topology) =>\n topology.layout === \"generic\" ? [] : topology.edges,\n ),\n vertices: values.flatMap((topology) =>\n topology.layout === \"generic\" ? [] : topology.vertices,\n ),\n };\n });\n}\n\nexport function analyzeManifest(\n manifest: GameTopologyManifest,\n runtimePlayerIds?: readonly string[],\n): ManifestAnalysis {\n assertValidManifest(manifest);\n return analyzeManifestStructure(manifest, runtimePlayerIds);\n}\n\n/** Structural analysis shared by semantic reference validation and runtime initialization. */\nexport function analyzeManifestStructure(\n manifest: GameTopologyManifest,\n runtimePlayerIds?: readonly string[],\n): ManifestAnalysis {\n const playerIds = [...(runtimePlayerIds ?? [])];\n const sharedZones = (manifest.zones ?? []).filter(\n (zone) => \"scope\" in zone && zone.scope === \"shared\",\n );\n const playerZones = (manifest.zones ?? []).filter(\n (zone) => \"scope\" in zone && zone.scope === \"perPlayer\",\n );\n const zoneIds = dedupeSorted((manifest.zones ?? []).map((zone) => zone.id));\n const cardSets = manifest.cardSets;\n const cardSetIds = dedupeSorted(cardSets.map((cardSet) => cardSet.id));\n const cardTypes = dedupeSorted(\n cardSets.flatMap((cardSet) => cardSet.cards.map((card) => card.cardType)),\n );\n const cardIds = dedupeSorted(\n cardSets.flatMap((cardSet) =>\n cardSet.cards.flatMap((card) =>\n scopedInstances(\n \"card\",\n renderCardInstanceIds(card),\n card.scope,\n playerIds,\n ).map((instance) => instance.id),\n ),\n ),\n );\n const cardSetIdByCardId = new Map<string, string>();\n const cardTypeByCardId = new Map<string, string>();\n for (const cardSet of cardSets) {\n for (const card of cardSet.cards) {\n for (const { id: cardId } of scopedInstances(\n \"card\",\n renderCardInstanceIds(card),\n card.scope,\n playerIds,\n )) {\n cardSetIdByCardId.set(cardId, cardSet.id);\n cardTypeByCardId.set(cardId, card.cardType);\n }\n }\n }\n\n const sharedZoneCardSetIds = new Map<string, string[]>();\n for (const zone of sharedZones) {\n sharedZoneCardSetIds.set(\n zone.id,\n dedupeSorted(zone.allowedCardSetIds ?? []),\n );\n }\n const playerZoneCardSetIds = new Map<string, string[]>();\n for (const zone of playerZones) {\n playerZoneCardSetIds.set(\n zone.id,\n dedupeSorted(zone.allowedCardSetIds ?? []),\n );\n }\n const zoneCardSetIdsById = new Map(\n (manifest.zones ?? []).map((zone) => [\n zone.id,\n dedupeSorted(zone.allowedCardSetIds ?? []),\n ]),\n );\n\n const sharedZoneIdsByCardSetId = new Map<string, string[]>(\n cardSetIds.map((cardSetId): [string, string[]] => [cardSetId, []]),\n );\n for (const [zoneId, allowedCardSetIds] of sharedZoneCardSetIds.entries()) {\n for (const cardSetId of allowedCardSetIds) {\n const zoneIds = sharedZoneIdsByCardSetId.get(cardSetId) ?? [];\n zoneIds.push(zoneId);\n sharedZoneIdsByCardSetId.set(cardSetId, zoneIds);\n }\n }\n for (const [cardSetId, zoneIds] of sharedZoneIdsByCardSetId.entries()) {\n sharedZoneIdsByCardSetId.set(cardSetId, dedupeSorted(zoneIds));\n }\n\n const sharedZoneIdSet = new Set(sharedZones.map((zone) => zone.id));\n const homeSharedZoneIdsByCardType = new Map<string, string[]>(\n cardTypes.map((cardType): [string, string[]] => [cardType, []]),\n );\n for (const cardSet of cardSets) {\n for (const card of cardSet.cards) {\n if (\n card.home?.type !== \"zone\" ||\n !sharedZoneIdSet.has(card.home.zoneId)\n ) {\n continue;\n }\n const cardType = card.cardType;\n const zoneIds = homeSharedZoneIdsByCardType.get(cardType) ?? [];\n zoneIds.push(card.home.zoneId);\n homeSharedZoneIdsByCardType.set(cardType, zoneIds);\n }\n }\n const homeSharedZoneIdByCardType = new Map<string, string>();\n for (const [cardType, zoneIds] of homeSharedZoneIdsByCardType.entries()) {\n const uniqueZoneIds = dedupeSorted(zoneIds);\n homeSharedZoneIdsByCardType.set(cardType, uniqueZoneIds);\n const [homeZoneId] = uniqueZoneIds;\n if (uniqueZoneIds.length === 1 && homeZoneId !== undefined) {\n homeSharedZoneIdByCardType.set(cardType, homeZoneId);\n }\n }\n\n const zoneVisibilityById = new Map<\n string,\n NonNullable<ZoneSpec[\"visibility\"]>\n >(\n (manifest.zones ?? []).map((zone) => [\n zone.id,\n zone.visibility ?? \"public\",\n ]),\n );\n const resourceIds = dedupeSorted(\n (manifest.resources ?? []).map((resource) => resource.id),\n );\n const resourcePresentationById = sortedObject(\n (manifest.resources ?? []).map((resource) => [\n resource.id,\n {\n label: resource.name,\n ...(resource.icon ? { icon: resource.icon } : {}),\n },\n ]),\n );\n const pieceTypeIds = dedupeSorted(\n (manifest.pieceTypes ?? []).map((pieceType) => pieceType.id),\n );\n const pieceTypeSchemasById = new Map(\n (manifest.pieceTypes ?? []).map((pieceType) => [\n pieceType.id,\n pieceType.fieldsSchema,\n ]),\n );\n const pieceTypeIdByPieceId = new Map<string, string>();\n for (const seed of manifest.pieceSeeds ?? []) {\n for (const { id: pieceId } of scopedInstances(\n \"piece\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n )) {\n pieceTypeIdByPieceId.set(pieceId, seed.typeId);\n }\n }\n const pieceIds = dedupeSorted(pieceTypeIdByPieceId.keys());\n const dieTypeIds = dedupeSorted(\n (manifest.dieTypes ?? []).map((dieType) => dieType.id),\n );\n const dieTypeSchemasById = new Map(\n (manifest.dieTypes ?? []).map((dieType) => [\n dieType.id,\n dieType.fieldsSchema,\n ]),\n );\n const dieTypeIdByDieId = new Map<string, string>();\n for (const seed of manifest.dieSeeds ?? []) {\n for (const { id: dieId } of scopedInstances(\n \"die\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n )) {\n dieTypeIdByDieId.set(dieId, seed.typeId);\n }\n }\n const dieIds = dedupeSorted(dieTypeIdByDieId.keys());\n const tileTypeIds = dedupeSorted(\n (manifest.tileTypes ?? []).map((type) => type.id),\n );\n const tilePropertiesSchemasById = new Map(\n (manifest.tileTypes ?? []).map((type) => [type.id, type.propertiesSchema]),\n );\n const tileTypeIdByTileId = new Map<string, string>();\n for (const seed of manifest.tileSeeds ?? [])\n for (const { id } of scopedInstances(\n \"tile\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n ))\n tileTypeIdByTileId.set(id, seed.typeId);\n const tileIds = dedupeSorted(tileTypeIdByTileId.keys());\n const analyzedBoards = analyzeBoards(manifest, playerIds);\n const boardBaseIds = dedupeSorted(\n analyzedBoards.map(({ board }) => board.id),\n );\n const boardIds = dedupeSorted(\n analyzedBoards.flatMap((entry) => entry.runtimeBoardIds),\n );\n const boardTypeIds = dedupeSorted(\n analyzedBoards\n .map((board) => board.boardTypeId)\n .filter((typeId): typeId is string => typeof typeId === \"string\"),\n );\n const boardLayoutById = new Map<string, string>();\n const boardIdsByLayout = new Map<string, string[]>();\n const boardBaseIdsByLayout = new Map<string, string[]>();\n const boardIdsByBaseId = new Map<string, string[]>();\n const boardIdsByTypeId = new Map<string, string[]>();\n const spaceIdsByBoardId = new Map<string, string[]>();\n const spaceTypeIdByBoardId = new Map<string, Record<string, string | null>>();\n const spaceIdsByTypeId = new Map<string, string[]>();\n const relationTypeIdsByBoardId = new Map<string, string[]>();\n const edgeIdsByTypeId = new Map<string, string[]>();\n const edgeIdsByBoardIdAndTypeId = new Map<string, Record<string, string[]>>();\n const vertexIdsByTypeId = new Map<string, string[]>();\n const vertexIdsByBoardIdAndTypeId = new Map<\n string,\n Record<string, string[]>\n >();\n for (const analyzedBoard of analyzedBoards) {\n boardIdsByBaseId.set(analyzedBoard.board.id, analyzedBoard.runtimeBoardIds);\n boardIdsByLayout.set(\n analyzedBoard.board.layout,\n dedupeSorted([\n ...(boardIdsByLayout.get(analyzedBoard.board.layout) ?? []),\n ...analyzedBoard.runtimeBoardIds,\n ]),\n );\n boardBaseIdsByLayout.set(\n analyzedBoard.board.layout,\n dedupeSorted([\n ...(boardBaseIdsByLayout.get(analyzedBoard.board.layout) ?? []),\n analyzedBoard.board.id,\n ]),\n );\n const runtimeRelationTypeIds = dedupeSorted(\n analyzedBoard.relations.map((relation) => relation.typeId),\n );\n for (const runtimeBoardId of analyzedBoard.runtimeBoardIds) {\n boardLayoutById.set(runtimeBoardId, analyzedBoard.board.layout);\n spaceIdsByBoardId.set(\n runtimeBoardId,\n Object.keys(analyzedBoard.topologies.get(runtimeBoardId)?.spaces ?? {}),\n );\n spaceTypeIdByBoardId.set(\n runtimeBoardId,\n Object.fromEntries(\n Object.values(\n analyzedBoard.topologies.get(runtimeBoardId)?.spaces ?? {},\n ).map((space) => [space.id, space.typeId ?? null]),\n ),\n );\n relationTypeIdsByBoardId.set(runtimeBoardId, runtimeRelationTypeIds);\n }\n if (analyzedBoard.boardTypeId) {\n boardIdsByTypeId.set(\n analyzedBoard.boardTypeId,\n dedupeSorted([\n ...(boardIdsByTypeId.get(analyzedBoard.boardTypeId) ?? []),\n ...analyzedBoard.runtimeBoardIds,\n ]),\n );\n }\n for (const space of analyzedBoard.spaces) {\n if (!space.typeId) {\n continue;\n }\n spaceIdsByTypeId.set(\n space.typeId,\n dedupeSorted([...(spaceIdsByTypeId.get(space.typeId) ?? []), space.id]),\n );\n }\n if (analyzedBoard.layout !== \"generic\") {\n const edgeIdsForBoardByType: Record<string, string[]> = {};\n for (const edge of analyzedBoard.edges) {\n if (!edge.typeId) {\n continue;\n }\n edgeIdsByTypeId.set(\n edge.typeId,\n dedupeSorted([...(edgeIdsByTypeId.get(edge.typeId) ?? []), edge.id]),\n );\n edgeIdsForBoardByType[edge.typeId] = dedupeSorted([\n ...(edgeIdsForBoardByType[edge.typeId] ?? []),\n edge.id,\n ]);\n }\n const vertexIdsForBoardByType: Record<string, string[]> = {};\n for (const vertex of analyzedBoard.vertices) {\n if (!vertex.typeId) {\n continue;\n }\n vertexIdsByTypeId.set(\n vertex.typeId,\n dedupeSorted([\n ...(vertexIdsByTypeId.get(vertex.typeId) ?? []),\n vertex.id,\n ]),\n );\n vertexIdsForBoardByType[vertex.typeId] = dedupeSorted([\n ...(vertexIdsForBoardByType[vertex.typeId] ?? []),\n vertex.id,\n ]);\n }\n for (const runtimeBoardId of analyzedBoard.runtimeBoardIds) {\n const topology = analyzedBoard.topologies.get(runtimeBoardId);\n const byType = (\n elements: readonly { id: string; typeId?: string | null }[],\n ) => {\n const result: Record<string, string[]> = {};\n for (const element of elements)\n if (element.typeId)\n result[element.typeId] = [\n ...(result[element.typeId] ?? []),\n element.id,\n ];\n return result;\n };\n edgeIdsByBoardIdAndTypeId.set(\n runtimeBoardId,\n byType(\n topology && topology.layout !== \"generic\" ? topology.edges : [],\n ),\n );\n vertexIdsByBoardIdAndTypeId.set(\n runtimeBoardId,\n byType(\n topology && topology.layout !== \"generic\" ? topology.vertices : [],\n ),\n );\n }\n }\n }\n const relationTypeIds = dedupeSorted(\n Array.from(relationTypeIdsByBoardId.values()).flat(),\n );\n const edgeIds = dedupeSorted(\n analyzedBoards.flatMap((board) =>\n board.layout === \"generic\" ? [] : board.edges.map((edge) => edge.id),\n ),\n );\n const edgeTypeIds = dedupeSorted(edgeIdsByTypeId.keys());\n const vertexIds = dedupeSorted(\n analyzedBoards.flatMap((board) =>\n board.layout === \"generic\"\n ? []\n : board.vertices.map((vertex) => vertex.id),\n ),\n );\n const vertexTypeIds = dedupeSorted(vertexIdsByTypeId.keys());\n const spaceIds = dedupeSorted(\n analyzedBoards.flatMap((board) => board.spaces.map((space) => space.id)),\n );\n const spaceTypeIds = dedupeSorted(\n analyzedBoards.flatMap((board) =>\n board.spaces\n .map((space) => space.typeId)\n .filter((typeId): typeId is string => typeof typeId === \"string\"),\n ),\n );\n\n return {\n manifest,\n playerIds,\n sharedZones,\n playerZones,\n zoneIds,\n cardSets,\n cardSetIds,\n cardTypes,\n cardIds,\n cardSetIdByCardId,\n cardTypeByCardId,\n sharedZoneCardSetIds,\n sharedZoneIdsByCardSetId,\n homeSharedZoneIdsByCardType,\n homeSharedZoneIdByCardType,\n playerZoneCardSetIds,\n zoneCardSetIdsById,\n zoneVisibilityById,\n resourceIds,\n resourcePresentationById,\n pieceTypeIds,\n pieceIds,\n pieceTypeIdByPieceId,\n dieTypeIds,\n dieIds,\n dieTypeIdByDieId,\n tileTypeIds,\n tileIds,\n tileTypeIdByTileId,\n tilePropertiesSchemasById,\n boardBaseIds,\n boardIds,\n boardTypeIds,\n boardLayoutById,\n boardIdsByLayout,\n boardBaseIdsByLayout,\n boardIdsByBaseId,\n boardIdsByTypeId,\n spaceIdsByBoardId,\n spaceTypeIdByBoardId,\n spaceIdsByTypeId,\n relationTypeIds,\n relationTypeIdsByBoardId,\n edgeIds,\n edgeTypeIds,\n edgeIdsByTypeId,\n edgeIdsByBoardIdAndTypeId,\n vertexIds,\n vertexTypeIds,\n vertexIdsByTypeId,\n vertexIdsByBoardIdAndTypeId,\n spaceIds,\n spaceTypeIds,\n analyzedBoards,\n pieceTypeSchemasById,\n dieTypeSchemasById,\n };\n}\n\nfunction cloneJson<Value>(value: Value): Value {\n return JSON.parse(JSON.stringify(value)) as Value;\n}\n\nfunction boardSpaceRefKey(spaceIds: readonly string[]): string {\n return [...spaceIds]\n .sort((left, right) => left.localeCompare(right))\n .join(\"$$\");\n}\n\nexport function fieldReferenceContext(\n analysis: ManifestAnalysis,\n stage: \"manifest\" | \"session\" = \"session\",\n boardId?: string,\n): FieldReferenceContext {\n const board = boardId\n ? analysis.analyzedBoards.find(\n (item) =>\n item.board.id === boardId || item.runtimeBoardIds.includes(boardId),\n )\n : undefined;\n const runtimeTopology = boardId ? board?.topologies.get(boardId) : undefined;\n const runtimeEdges =\n runtimeTopology && runtimeTopology.layout !== \"generic\"\n ? runtimeTopology.edges\n : (board?.edges ?? []);\n const runtimeVertices =\n runtimeTopology && runtimeTopology.layout !== \"generic\"\n ? runtimeTopology.vertices\n : (board?.vertices ?? []);\n return {\n stage,\n deferred:\n stage === \"manifest\"\n ? [\n \"playerId\",\n \"boardId\",\n \"spaceId\",\n \"edgeId\",\n \"vertexId\",\n ...(analysis.cardSets.some((set) =>\n set.cards.some((card) => card.scope === \"perPlayer\"),\n )\n ? [\"cardId\" as const]\n : []),\n ...(analysis.manifest.pieceSeeds?.some(\n (seed) => seed.scope === \"perPlayer\",\n )\n ? [\"pieceId\" as const]\n : []),\n ...(analysis.manifest.tileSeeds?.some(\n (seed) => seed.scope === \"perPlayer\",\n )\n ? [\"tileId\" as const]\n : []),\n ...(analysis.manifest.dieSeeds?.some(\n (seed) => seed.scope === \"perPlayer\",\n )\n ? [\"dieId\" as const]\n : []),\n ]\n : undefined,\n accepts:\n stage === \"manifest\"\n ? {\n playerId: isPlayerIdValue,\n edgeId: createBoardElementDeclaration(\n analysis.manifest,\n \"edge\",\n board?.board.id,\n ).accepts,\n vertexId: createBoardElementDeclaration(\n analysis.manifest,\n \"vertex\",\n board?.board.id,\n ).accepts,\n spaceId: createSpaceDeclaration(analysis.manifest, board?.board.id)\n .accepts,\n boardId: createInstanceDeclaration(\n \"board\",\n (analysis.manifest.boards ?? []).map((board) => ({\n baseIds: [board.id],\n scope: board.scope,\n })),\n ).accepts,\n cardId: createInstanceDeclaration(\n \"card\",\n analysis.cardSets.flatMap((set) =>\n set.cards.map((card) => ({\n baseIds: renderCardInstanceIds(card),\n scope: card.scope,\n })),\n ),\n ).accepts,\n pieceId: createInstanceDeclaration(\n \"piece\",\n (analysis.manifest.pieceSeeds ?? []).map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ).accepts,\n tileId: createInstanceDeclaration(\n \"tile\",\n (analysis.manifest.tileSeeds ?? []).map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ).accepts,\n dieId: createInstanceDeclaration(\n \"die\",\n (analysis.manifest.dieSeeds ?? []).map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ).accepts,\n }\n : undefined,\n ids: {\n cardId: analysis.cardIds,\n zoneId: analysis.zoneIds,\n playerId: analysis.playerIds,\n boardId: analysis.boardIds,\n spaceId:\n boardId && analysis.spaceIdsByBoardId.has(boardId)\n ? (analysis.spaceIdsByBoardId.get(boardId) ?? [])\n : board\n ? board.spaces.map((space) => space.id)\n : analysis.spaceIds,\n edgeId:\n board && board.layout !== \"generic\"\n ? runtimeEdges.map((edge) => edge.id)\n : analysis.edgeIds,\n vertexId:\n board && board.layout !== \"generic\"\n ? runtimeVertices.map((vertex) => vertex.id)\n : analysis.vertexIds,\n pieceId: analysis.pieceIds,\n dieId: analysis.dieIds,\n tileId: analysis.tileIds,\n resourceId: analysis.resourceIds,\n },\n };\n}\n\nconst fieldResolvers = new WeakMap<\n ManifestAnalysis,\n Map<\"manifest\" | \"session\", ReturnType<typeof createFieldValidatorResolver>>\n>();\nfunction materializeFields(\n schema: FieldSchemaJson | null | undefined,\n analysis: ManifestAnalysis,\n values: unknown,\n boardId?: string,\n stage: \"manifest\" | \"session\" = \"session\",\n): Record<string, unknown> {\n if (!schema) return z.record(z.string(), z.unknown()).parse(values ?? {});\n let stages = fieldResolvers.get(analysis);\n if (!stages) {\n stages = new Map();\n fieldResolvers.set(analysis, stages);\n }\n let resolve = stages.get(stage);\n if (!resolve) {\n resolve = createFieldValidatorResolver((board) =>\n fieldReferenceContext(analysis, stage, board),\n );\n stages.set(stage, resolve);\n }\n return z\n .record(z.string(), z.unknown())\n .parse(resolve(schema, boardId).parse(values ?? {}));\n}\n\ntype MaterializeOptions = {\n manifest: GameTopologyManifest;\n playerIds: readonly string[];\n shuffleItems: <Value>(values: readonly Value[]) => Value[];\n};\n/** Enumerate empty zones from the structural instance inventory, without fields or homes. */\nexport function materializeEmptyZones(\n analysis: ManifestAnalysis,\n): Record<string, Record<string, string[]>> {\n const hosts = {\n playerOrder: analysis.playerIds,\n pieces: Object.fromEntries(\n [...analysis.pieceTypeIdByPieceId].map(([id, pieceTypeId]) => [\n id,\n { id, pieceTypeId },\n ]),\n ),\n dice: Object.fromEntries(\n [...analysis.dieTypeIdByDieId].map(([id, dieTypeId]) => [\n id,\n { id, dieTypeId },\n ]),\n ),\n ...seededTopologyInventory(analysis.manifest, analysis.playerIds),\n };\n const definitions = buildTopologyDefinitions(\n analysis.manifest,\n (_schema, values) =>\n z.record(z.string(), RuntimeJsonSchema).parse(values ?? {}),\n );\n return Object.fromEntries(\n (analysis.manifest.zones ?? []).map((zone) => [\n zone.id,\n Object.fromEntries(\n enumerateZoneHosts(hosts, definitions, {\n ...(\"scope\" in zone\n ? { scope: zone.scope }\n : { attachedTo: zone.attachedTo }),\n visibility: zone.visibility ?? \"public\",\n allowedCardSetIds: zone.allowedCardSetIds ?? [],\n }).map((hostId) => [hostId, []]),\n ),\n ]),\n );\n}\n\n/** Construct actual session inventory; references use the supplied live roster. */\nexport function materializeManifestTable(\n options: MaterializeOptions,\n): Record<string, unknown> {\n return materializeManifest(\n { ...options, playerIds: PlayerRosterSchema.parse(options.playerIds) },\n \"session\",\n );\n}\nfunction freezeDefinition<T>(value: T): T {\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value)) freezeDefinition(child);\n Object.freeze(value);\n }\n return value;\n}\n/** Normalize immutable rules without manufacturing session instances. */\nexport function materializeTopologyDefinitions(\n analysis: ManifestAnalysis,\n stage: \"manifest\" | \"session\" = \"manifest\",\n): TopologyDefinitions {\n const definitions = buildTopologyDefinitions(\n analysis.manifest,\n (schema, value, boardId) =>\n z\n .record(z.string(), RuntimeJsonSchema)\n .parse(materializeFields(schema, analysis, value, boardId, stage)),\n );\n const inventory = seededTopologyInventory(\n analysis.manifest,\n analysis.playerIds,\n );\n for (const boardId of Object.keys(inventory.boards))\n deriveBoardTopology(inventory, definitions, boardId);\n return definitions;\n}\n\nfunction buildTopologyDefinitions(\n manifest: GameTopologyManifest,\n fields: (\n schema: FieldSchemaJson | undefined,\n value: unknown,\n boardId?: string,\n ) => Record<string, z.infer<typeof RuntimeJsonSchema>>,\n): TopologyDefinitions {\n const boardDefinitions: Record<string, BoardDefinition> = {};\n for (const board of manifest.boards ?? []) {\n const base = {\n id: board.id,\n name: board.name,\n scope: board.scope,\n ...(board.typeId === undefined ? {} : { typeId: board.typeId }),\n fields: fields(board.boardFieldsSchema, board.fields, board.id),\n };\n boardDefinitions[board.id] =\n board.layout === \"generic\"\n ? {\n ...base,\n layout: \"generic\",\n spaces: Object.fromEntries(\n (board.spaces ?? []).map((space) => [\n space.id,\n {\n ...space,\n fields: fields(\n board.spaceFieldsSchema,\n space.fields,\n board.id,\n ),\n },\n ]),\n ),\n }\n : board.layout === \"hex\"\n ? {\n ...base,\n layout: \"hex\",\n orientation: board.orientation ?? \"pointy\",\n }\n : { ...base, layout: \"square\" };\n }\n const tileDefinitions: Record<string, TileDefinition> = {};\n for (const type of manifest.tileTypes ?? []) {\n const {\n fieldsSchema,\n // Strip the mutable instance schema from immutable rule definitions.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Mutable instance schema must not enter immutable definitions.\n propertiesSchema,\n cellFieldsSchema,\n edgeFieldsSchema,\n vertexFieldsSchema,\n ...definition\n } = type;\n const normalized = {\n ...definition,\n fields: fields(fieldsSchema, type.fields),\n };\n if (type.layout === \"hex\")\n tileDefinitions[type.id] = {\n ...normalized,\n layout: \"hex\",\n cells: type.cells.map((cell) => ({\n ...cell,\n fields: fields(cellFieldsSchema, cell.fields),\n })),\n edges: (type.edges ?? []).map((edge) => ({\n ...edge,\n fields: fields(edgeFieldsSchema, edge.fields),\n })),\n vertices: (type.vertices ?? []).map((vertex) => ({\n ...vertex,\n fields: fields(vertexFieldsSchema, vertex.fields),\n })),\n };\n else\n tileDefinitions[type.id] = {\n ...normalized,\n layout: \"square\",\n cells: type.cells.map((cell) => ({\n ...cell,\n fields: fields(cellFieldsSchema, cell.fields),\n })),\n edges: (type.edges ?? []).map((edge) => ({\n ...edge,\n fields: fields(edgeFieldsSchema, edge.fields),\n })),\n vertices: (type.vertices ?? []).map((vertex) => ({\n ...vertex,\n fields: fields(vertexFieldsSchema, vertex.fields),\n })),\n };\n }\n return freezeDefinition(\n structuredClone({ boardDefinitions, tileDefinitions }),\n );\n}\nfunction materializeManifest(\n options: MaterializeOptions,\n stage: \"manifest\" | \"session\",\n): Record<string, unknown> {\n const analysis = analyzeManifest(options.manifest, options.playerIds);\n const fields = (\n schema: FieldSchemaJson | null | undefined,\n analysis: ManifestAnalysis,\n values: unknown,\n boardId?: string,\n ) => materializeFields(schema, analysis, values, boardId, stage);\n const manifest = analysis.manifest;\n const playerIds = [...options.playerIds];\n\n for (const type of manifest.tileTypes ?? []) {\n fields(type.fieldsSchema, analysis, type.fields);\n for (const cell of type.cells)\n fields(type.cellFieldsSchema, analysis, cell.fields);\n for (const edge of type.edges ?? [])\n fields(type.edgeFieldsSchema, analysis, edge.fields);\n for (const vertex of type.vertices ?? [])\n fields(type.vertexFieldsSchema, analysis, vertex.fields);\n }\n\n const cards = createRecord<\n ZoneTable[\"cards\"][string] & Record<string, unknown>\n >();\n const pieces = createRecord<\n ZoneTable[\"pieces\"][string] & Record<string, unknown>\n >();\n const tiles = createRecord<\n ZoneTable[\"tiles\"][string] & Record<string, unknown>\n >();\n const dice = createRecord<\n ZoneTable[\"dice\"][string] & Record<string, unknown>\n >();\n const componentLocations = createRecord<RuntimeComponentLocation>();\n const locationOrder = new Map<string, number>();\n\n const boardAnalysisByBaseId = new Map(\n analysis.analyzedBoards.map((board) => [board.board.id, board] as const),\n );\n const edgeIdByBoardBaseIdAndSpaces = new Map<string, Map<string, string>>();\n const vertexIdByBoardBaseIdAndSpaces = new Map<string, Map<string, string>>();\n\n for (const analyzedBoard of analysis.analyzedBoards) {\n for (const [boardId, topology] of analyzedBoard.topologies) {\n if (topology.layout === \"generic\") continue;\n edgeIdByBoardBaseIdAndSpaces.set(\n boardId,\n new Map(\n topology.edges.map((edge) => [\n boardSpaceRefKey(edge.spaceIds),\n edge.id,\n ]),\n ),\n );\n vertexIdByBoardBaseIdAndSpaces.set(\n boardId,\n new Map(\n topology.vertices.map((vertex) => [\n boardSpaceRefKey(vertex.spaceIds),\n vertex.id,\n ]),\n ),\n );\n }\n }\n\n const nextLocationPosition = (location: Record<string, unknown>): number => {\n const key = JSON.stringify(location);\n const position = locationOrder.get(key) ?? 0;\n locationOrder.set(key, position + 1);\n return position;\n };\n const zoneDefinitions: Record<string, ZoneDefinition> = Object.fromEntries(\n (manifest.zones ?? []).map((zone) => [\n zone.id,\n {\n ...(\"scope\" in zone\n ? { scope: zone.scope }\n : { attachedTo: zone.attachedTo }),\n visibility: zone.visibility ?? \"public\",\n allowedCardSetIds: zone.allowedCardSetIds ?? [],\n },\n ]),\n );\n const pendingHomes: (() => void)[] = [];\n const resolveRuntimeBoardId = (\n boardBaseId: string,\n origin: string | null | undefined,\n context?: string,\n ) => {\n const analyzedBoard = boardAnalysisByBaseId.get(boardBaseId);\n if (!analyzedBoard) {\n throw new Error(\n `${context ?? \"Component home\"}.boardId: Unknown board '${boardBaseId}'.`,\n );\n }\n if (analyzedBoard?.board.scope === \"perPlayer\") {\n if (!origin) {\n throw new Error(\n `${context ?? `Home on board '${boardBaseId}'`} requires perPlayer scope because board '${boardBaseId}' has scope 'perPlayer'. Use perPlayer scope to resolve the player-scoped destination.`,\n );\n }\n return perPlayerInstanceId(\"board\", boardBaseId, origin);\n }\n return boardBaseId;\n };\n\n const resolveBoardEdgeId = (\n boardBaseId: string,\n spaceIds: readonly string[],\n ) => {\n const edgeId = edgeIdByBoardBaseIdAndSpaces\n .get(boardBaseId)\n ?.get(boardSpaceRefKey(spaceIds));\n if (!edgeId) {\n throw new Error(\n `Unknown edge on board '${boardBaseId}' for spaces [${spaceIds.join(\", \")}].`,\n );\n }\n return edgeId;\n };\n\n const resolveBoardVertexId = (\n boardBaseId: string,\n spaceIds: readonly string[],\n ) => {\n const vertexId = vertexIdByBoardBaseIdAndSpaces\n .get(boardBaseId)\n ?.get(boardSpaceRefKey(spaceIds));\n if (!vertexId) {\n throw new Error(\n `Unknown vertex on board '${boardBaseId}' for spaces [${spaceIds.join(\", \")}].`,\n );\n }\n return vertexId;\n };\n\n const materializeComponentLocation = (\n home: NonNullable<BoardCard[\"home\"]>,\n origin: string | null,\n context: {\n path: string;\n label: string;\n },\n ): RuntimeComponentLocation => {\n if (home.type === \"detached\") {\n return { type: \"Detached\" };\n }\n\n if (home.type === \"zone\") {\n const definition = zoneDefinitions[home.zoneId];\n if (!definition)\n throw new Error(`${context.path}: Unknown zone '${home.zoneId}'.`);\n let hostId: string;\n if (\"scope\" in definition) {\n if (definition.scope === \"shared\") hostId = \"table\";\n else {\n if (!origin)\n throw new Error(\n `${context.path}: Per-player zone requires a replication origin.`,\n );\n hostId = origin;\n }\n } else if (\"board\" in definition.attachedTo) {\n const boardId = resolveRuntimeBoardId(\n definition.attachedTo.board,\n origin,\n context.path,\n );\n hostId =\n definition.attachedTo.space !== undefined\n ? boardSpaceHostId(boardId, definition.attachedTo.space)\n : boardId;\n } else {\n if (!home.component)\n throw new Error(\n `${context.path}.component: Component-attached zone requires a host base id.`,\n );\n const family =\n \"pieceType\" in definition.attachedTo\n ? \"piece\"\n : \"dieType\" in definition.attachedTo\n ? \"die\"\n : \"tile\";\n const seeds =\n family === \"piece\"\n ? manifest.pieceSeeds\n : family === \"die\"\n ? manifest.dieSeeds\n : manifest.tileSeeds;\n const seed = seeds?.find((seed) =>\n expandSeedIds([seed]).includes(home.component ?? \"\"),\n );\n if (!seed)\n throw new Error(\n `${context.path}.component: Unknown host base '${home.component}'.`,\n );\n if (seed.scope === \"perPlayer\") {\n if (!origin)\n throw new Error(\n `${context.path}: Replicated host requires a replication origin.`,\n );\n hostId = perPlayerInstanceId(family, home.component, origin);\n } else hostId = home.component;\n if (\"tileType\" in definition.attachedTo)\n hostId = tileSpaceId(hostId, definition.attachedTo.cell);\n }\n return { type: \"InZone\", zoneId: home.zoneId, hostId, playedBy: null };\n }\n\n if (home.type === \"space\") {\n const boardId = resolveRuntimeBoardId(\n home.boardId,\n origin,\n `${context.path}.boardId: ${context.label}`,\n );\n if (!analysis.spaceIdsByBoardId.get(boardId)?.includes(home.spaceId)) {\n throw new Error(\n `${context.path}.spaceId: ${context.label} targets unknown space '${home.spaceId}' on board '${home.boardId}'.`,\n );\n }\n return {\n type: \"OnSpace\",\n boardId,\n spaceId: home.spaceId,\n position: nextLocationPosition({\n type: \"OnSpace\",\n boardId,\n spaceId: home.spaceId,\n }),\n };\n }\n\n if (home.type === \"edge\") {\n const boardId = resolveRuntimeBoardId(\n home.boardId,\n origin,\n `${context.path}.boardId: ${context.label}`,\n );\n const edgeId = resolveBoardEdgeId(boardId, home.ref.spaces);\n return {\n type: \"OnEdge\",\n boardId,\n edgeId,\n position: nextLocationPosition({\n type: \"OnEdge\",\n boardId,\n edgeId,\n }),\n };\n }\n\n if (home.type === \"vertex\") {\n const boardId = resolveRuntimeBoardId(\n home.boardId,\n origin,\n `${context.path}.boardId: ${context.label}`,\n );\n const vertexId = resolveBoardVertexId(boardId, home.ref.spaces);\n return {\n type: \"OnVertex\",\n boardId,\n vertexId,\n position: nextLocationPosition({\n type: \"OnVertex\",\n boardId,\n vertexId,\n }),\n };\n }\n\n const exhaustive: never = home;\n throw new Error(\n `Unsupported component home: ${JSON.stringify(exhaustive)}`,\n );\n };\n\n for (const [cardSetIndex, cardSet] of manifest.cardSets.entries()) {\n for (const [cardIndex, card] of cardSet.cards.entries()) {\n const cardInstanceIds = scopedInstances(\n \"card\",\n renderCardInstanceIds(card),\n card.scope,\n playerIds,\n );\n for (const [\n instanceIndex,\n { id: cardId, playerId: origin },\n ] of cardInstanceIds.entries()) {\n cards[cardId] = {\n id: cardId,\n cardSetId: cardSet.id,\n cardType: card.cardType,\n name: card.name,\n text: card.text,\n frontImage: card.frontImage,\n backImage: card.backImage,\n properties: fields(\n schemaForCardType(cardSet.cardSchema, card.cardType),\n analysis,\n card.properties,\n ),\n };\n const resolvedHome = card.home ?? cardSet.defaultHome;\n const path =\n card.home === undefined\n ? `manifest.cardSets[${cardSetIndex}].defaultHome`\n : `manifest.cardSets[${cardSetIndex}].cards[${cardIndex}].home`;\n componentLocations[cardId] = { type: \"Detached\" };\n pendingHomes.push(() => {\n componentLocations[cardId] = materializeComponentLocation(\n resolvedHome,\n origin,\n {\n path,\n label: `Card '${card.id}' instance ${instanceIndex + 1}`,\n },\n );\n });\n }\n }\n }\n\n if (Object.keys(cards).length !== analysis.cardIds.length) {\n throw new Error(\n \"Materialized card record cardinality drifted from analysis.\",\n );\n }\n if (Object.keys(componentLocations).length !== analysis.cardIds.length) {\n throw new Error(\n \"Materialized card locations drifted from analysis before seed placement.\",\n );\n }\n\n const pieceTypesById = new Map(\n (manifest.pieceTypes ?? []).map((pieceType) => [pieceType.id, pieceType]),\n );\n const dieTypesById = new Map(\n (manifest.dieTypes ?? []).map((dieType) => [dieType.id, dieType]),\n );\n\n const assignSeedLocation = (\n componentId: string,\n origin: string | null | undefined,\n home:\n | PieceSeedSpec[\"home\"]\n | import(\"../../shared/domain/contracts.js\").TileSeedSpec[\"home\"]\n | undefined,\n context: { path: string; label: string },\n ) => {\n componentLocations[componentId] = { type: \"Detached\" };\n if (home?.type === \"board\") {\n componentLocations[componentId] = {\n ...home,\n type: \"OnBoard\",\n boardId: resolveRuntimeBoardId(home.boardId, origin, context.path),\n };\n return;\n }\n if (home)\n pendingHomes.push(() => {\n componentLocations[componentId] = materializeComponentLocation(\n home,\n origin ?? null,\n context,\n );\n });\n };\n\n for (const [seedIndex, seed] of (manifest.pieceSeeds ?? []).entries()) {\n const pieceType = pieceTypesById.get(seed.typeId);\n for (const { id: componentId, playerId: origin } of scopedInstances(\n \"piece\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n )) {\n pieces[componentId] = {\n componentType: \"piece\",\n id: componentId,\n pieceTypeId: seed.typeId,\n pieceName: pieceType?.name ?? seed.typeId,\n ownerId: origin,\n properties: fields(\n analysis.pieceTypeSchemasById.get(seed.typeId),\n analysis,\n seed.fields,\n ),\n };\n assignSeedLocation(componentId, origin, seed.home, {\n path: `manifest.pieceSeeds[${seedIndex}].home`,\n label: `Piece seed '${seed.id ?? seed.typeId}'`,\n });\n }\n }\n\n for (const [seedIndex, seed] of (manifest.dieSeeds ?? []).entries()) {\n const dieType = dieTypesById.get(seed.typeId);\n for (const { id: componentId, playerId: origin } of scopedInstances(\n \"die\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n )) {\n dice[componentId] = {\n componentType: \"die\",\n id: componentId,\n dieTypeId: seed.typeId,\n dieName: dieType?.name ?? seed.typeId,\n ownerId: origin,\n sides: dieType?.sides ?? 6,\n value: null,\n properties: fields(\n analysis.dieTypeSchemasById.get(seed.typeId),\n analysis,\n seed.fields,\n ),\n };\n assignSeedLocation(componentId, origin, seed.home, {\n path: `manifest.dieSeeds[${seedIndex}].home`,\n label: `Die seed '${seed.id ?? seed.typeId}'`,\n });\n }\n }\n\n for (const [index, seed] of (manifest.tileSeeds ?? []).entries()) {\n for (const { id, playerId: origin } of scopedInstances(\n \"tile\",\n expandSeedIds([seed]),\n seed.scope,\n playerIds,\n )) {\n tiles[id] = {\n componentType: \"tile\",\n disclosure: structuredClone(\n seed.disclosure ?? { face: { audience: \"public\" } },\n ),\n id,\n tileTypeId: seed.typeId,\n ownerId: origin,\n properties: fields(\n analysis.tilePropertiesSchemasById.get(seed.typeId),\n analysis,\n seed.properties,\n ),\n };\n assignSeedLocation(id, origin, seed.home, {\n path: `manifest.tileSeeds[${index}].home`,\n label: `Tile seed '${seed.id}'`,\n });\n }\n }\n const topologyDefinitions = materializeTopologyDefinitions(\n analysis,\n \"session\",\n );\n const boardStatesById: Record<string, RuntimeBoardInstance> = {};\n for (const board of analysis.analyzedBoards)\n for (const id of board.runtimeBoardIds)\n boardStatesById[id] = {\n baseId: board.board.id,\n visibility: board.board.visibility ?? \"public\",\n relations: board.relations.map((relation) => ({\n id: relation.id,\n typeId: relation.typeId,\n fromSpaceId: relation.fromSpaceId,\n toSpaceId: relation.toSpaceId,\n directed: relation.directed ?? false,\n fields: z\n .record(z.string(), RuntimeJsonSchema)\n .parse(\n fields(board.relationFieldsSchema, analysis, relation.fields, id),\n ),\n })),\n };\n const zones = materializeEmptyZones(analysis);\n const zoneTable: ZoneTable = {\n playerOrder: playerIds,\n zones,\n cards,\n pieces,\n dice,\n tiles,\n componentLocations,\n boards: boardStatesById,\n };\n for (const boardId of Object.keys(boardStatesById))\n deriveBoardTopology(zoneTable, topologyDefinitions, boardId);\n for (const resolveHome of pendingHomes) resolveHome();\n assertContainmentAcyclic(zoneTable, {\n zoneDefinitions,\n ...topologyDefinitions,\n });\n for (const [componentId, location] of Object.entries(componentLocations)) {\n if (location.type !== \"InZone\") continue;\n const ids = zones[String(location.zoneId)]?.[String(location.hostId)];\n if (!ids) throw new Error(`Missing zone host for '${componentId}'.`);\n ids.push(componentId);\n }\n assertZoneConsistency(zoneTable, { zoneDefinitions, ...topologyDefinitions });\n const { ownerOfCard, visibility } = initialCardMetadata(\n manifest.cardSets,\n playerIds,\n );\n const resourcesByPlayer = Object.fromEntries(\n playerIds.map((playerId) => [\n playerId,\n Object.fromEntries(\n analysis.resourceIds.map((resourceId) => [resourceId, 0]),\n ),\n ]),\n );\n return cloneJson({\n playerOrder: playerIds,\n zones,\n cards,\n pieces,\n componentLocations,\n ownerOfCard,\n visibility,\n resources: resourcesByPlayer,\n boards: boardStatesById,\n dice,\n tiles,\n });\n}\n","import type { ReadonlyRuntimeData } from \"../../shared/runtime-json.js\";\nimport type { PerPlayerInstanceId } from \"../../shared/domain/per-player-instance.js\";\nimport * as z from \"zod\";\nimport type {\n FieldSchemaJson,\n JsonValue,\n} from \"../../shared/domain/contracts.js\";\nimport type { ManifestIdsOf, TileSpaceIds } from \"./types.js\";\nimport type {\n BoardEdgeId,\n BoardVertexId,\n} from \"../../shared/domain/board-identities.js\";\n\nexport const FIELD_REF_KEY = \"x-dreamboard-ref\";\nconst OBJECT_MODE_KEY = \"x-dreamboard-object-mode\";\nexport const FIELD_REF_FAMILIES = [\n \"cardId\",\n \"zoneId\",\n \"playerId\",\n \"boardId\",\n \"spaceId\",\n \"edgeId\",\n \"vertexId\",\n \"pieceId\",\n \"dieId\",\n \"tileId\",\n \"resourceId\",\n] as const;\nexport type FieldRefFamily = (typeof FIELD_REF_FAMILIES)[number];\nconst marker = <F extends FieldRefFamily>(family: F) =>\n z\n .string()\n .meta({ [FIELD_REF_KEY]: family })\n .brand<`dreamboard:${F}`, \"inout\">();\nexport const ref = {\n cardId: () => marker(\"cardId\"),\n zoneId: () => marker(\"zoneId\"),\n playerId: () => marker(\"playerId\"),\n boardId: () => marker(\"boardId\"),\n spaceId: () => marker(\"spaceId\"),\n edgeId: () => marker(\"edgeId\"),\n vertexId: () => marker(\"vertexId\"),\n pieceId: () => marker(\"pieceId\"),\n dieId: () => marker(\"dieId\"),\n tileId: () => marker(\"tileId\"),\n resourceId: () => marker(\"resourceId\"),\n};\nexport type FieldSchema = z.ZodObject<\n z.core.$ZodShape,\n z.core.$ZodObjectConfig\n>;\nexport type CardSchema =\n FieldSchema | { readonly byCardType: Readonly<Record<string, FieldSchema>> };\n\ntype RefFamily<T> = {\n [F in FieldRefFamily]: T extends z.core.$brand<`dreamboard:${F}`> ? F : never;\n}[FieldRefFamily];\ntype BoardSpaceId<M, B> = B extends { layout: \"hex\" | \"square\" }\n ? TileSpaceIds<M, B[\"layout\"]>\n : B extends { spaces: readonly (infer S)[] }\n ? S extends { id: infer I extends string }\n ? I\n : never\n : never;\ntype RuntimeBoardIdentity<B> = B extends { id: infer I extends string }\n ? B extends { scope: \"perPlayer\" }\n ? PerPlayerInstanceId<\"board\", I>\n : I\n : never;\ntype ScopedBoardEdgeId<B> = B extends { layout: \"hex\" | \"square\" }\n ? BoardEdgeId<RuntimeBoardIdentity<B>>\n : never;\ntype ScopedBoardVertexId<B> = B extends { layout: \"hex\" | \"square\" }\n ? BoardVertexId<RuntimeBoardIdentity<B>>\n : never;\ntype ReferenceId<F extends FieldRefFamily, M, B> = F extends \"spaceId\"\n ? [B] extends [never]\n ? ManifestIdsOf<M>[\"spaceId\"]\n : BoardSpaceId<M, B>\n : F extends \"edgeId\"\n ? [B] extends [never]\n ? ManifestIdsOf<M>[\"edgeId\"]\n : ScopedBoardEdgeId<B>\n : F extends \"vertexId\"\n ? [B] extends [never]\n ? ManifestIdsOf<M>[\"vertexId\"]\n : ScopedBoardVertexId<B>\n : ManifestIdsOf<M>[F];\nexport type ResolveFields<T, M, B = never> = T extends unknown\n ? [RefFamily<T>] extends [never]\n ? T extends string | number | boolean | null | undefined\n ? T\n : T extends readonly unknown[]\n ? { [K in keyof T]: ResolveFields<T[K], M, B> }\n : T extends object\n ? { [K in keyof T]: ResolveFields<T[K], M, B> }\n : JsonValue\n : ReferenceId<RefFamily<T>, M, B>\n : never;\nexport type FieldsInput<S, M, B = never> = [S] extends [never]\n ? Record<string, JsonValue>\n : S extends FieldSchema\n ? {\n [K in keyof z.input<S>]: ReadonlyRuntimeData<\n ResolveFields<z.input<S>[K], M, B>\n >;\n }\n : Record<string, JsonValue>;\nexport type FieldsOutput<S, M, B = never> = [S] extends [never]\n ? Record<string, JsonValue>\n : S extends FieldSchema\n ? {\n [K in keyof z.output<S>]: Exclude<\n ResolveFields<z.output<S>[K], M, B>,\n undefined\n >;\n }\n : Record<string, JsonValue>;\n\n/** Reject checks whose meaning cannot survive a JSON round trip. */\nfunction assertPortable(\n schema: z.core.$ZodType,\n path: string,\n seen: Set<z.core.$ZodType>,\n active = new Set<z.core.$ZodType>(),\n objectSentinel = false,\n): void {\n if (\n !objectSentinel &&\n (schema instanceof z.ZodUnknown || schema instanceof z.ZodNever)\n )\n throw new Error(\n `${path}: unsupported field schema '${schema._zod.def.type}'`,\n );\n if (active.has(schema))\n throw new Error(`${path}: recursive field schemas are not portable`);\n if (seen.has(schema)) return;\n seen.add(schema);\n active.add(schema);\n const metadata = z.globalRegistry.get(schema);\n if (metadata)\n for (const key of Object.keys(metadata))\n if (![\"title\", \"description\", \"examples\", FIELD_REF_KEY].includes(key))\n throw new Error(`${path}: unsupported behavioral metadata '${key}'`);\n if (\n metadata?.[FIELD_REF_KEY] !== undefined &&\n (!(schema instanceof z.ZodString) ||\n !FIELD_REF_FAMILIES.some((family) => family === metadata[FIELD_REF_KEY]))\n )\n throw new Error(`${path}: invalid field reference metadata`);\n for (const check of schema._zod.def.checks ?? []) {\n if (\n ![\n \"greater_than\",\n \"less_than\",\n \"multiple_of\",\n \"number_format\",\n \"min_length\",\n \"max_length\",\n \"length_equals\",\n \"string_format\",\n ].includes(check._zod.def.check)\n )\n throw new Error(\n `${path}: unsupported portable check '${check._zod.def.check}'`,\n );\n if (\n check._zod.def.check === \"string_format\" &&\n (!(\"format\" in check._zod.def) || check._zod.def.format !== \"regex\")\n )\n throw new Error(`${path}: string formats are not portable`);\n if (\n \"pattern\" in check._zod.def &&\n check._zod.def.pattern instanceof RegExp &&\n check._zod.def.pattern.flags\n )\n throw new Error(`${path}: regex flags are not portable`);\n }\n if (schema instanceof z.ZodObject) {\n for (const [key, child] of Object.entries<unknown>(schema.shape)) {\n if (!(child instanceof z.ZodType))\n throw new Error(`${path}.${key}: invalid field schema`);\n assertPortable(child, `${path}.${key}`, seen, active);\n }\n if (schema._zod.def.catchall)\n assertPortable(schema._zod.def.catchall, `${path}.*`, seen, active, true);\n } else if (schema instanceof z.ZodArray)\n assertPortable(schema.element, `${path}[]`, seen, active);\n else if (schema instanceof z.ZodRecord) {\n if (\n !(schema.keyType instanceof z.ZodString) ||\n schema.keyType._zod.def.checks?.length\n )\n throw new Error(\n `${path}: records require an unconstrained string key schema`,\n );\n assertPortable(schema.keyType, `${path}.key`, seen, active);\n assertPortable(schema.valueType, `${path}.*`, seen, active);\n } else if (\n schema instanceof z.ZodOptional ||\n schema instanceof z.ZodNullable ||\n schema instanceof z.ZodDefault\n )\n assertPortable(schema.unwrap(), path, seen, active);\n else if (!(\n schema instanceof z.ZodString ||\n schema instanceof z.ZodNumber ||\n schema instanceof z.ZodBoolean ||\n schema instanceof z.ZodEnum ||\n schema instanceof z.ZodLiteral ||\n schema instanceof z.ZodNull ||\n (objectSentinel &&\n (schema instanceof z.ZodUnknown || schema instanceof z.ZodNever))\n ))\n throw new Error(\n `${path}: unsupported field schema '${schema._zod.def.type}'`,\n );\n if (\"coerce\" in schema._zod.def && schema._zod.def.coerce)\n throw new Error(`${path}: coercion is not portable`);\n active.delete(schema);\n}\nfunction sampleDefaults(\n schema: z.core.$ZodType,\n copies = new Map<z.core.$ZodType, z.core.$ZodType>(),\n): z.core.$ZodType {\n const existing = copies.get(schema);\n if (existing) return existing;\n let copy = schema;\n if (schema instanceof z.ZodDefault) {\n const definition = { ...schema._zod.def };\n assertPlainData(definition.defaultValue);\n const value = z.json().parse(definition.defaultValue);\n copy = z.core.clone(\n schema,\n {\n ...definition,\n innerType: sampleDefaults(definition.innerType, copies),\n defaultValue: value,\n },\n { parent: false },\n );\n } else if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable)\n copy = z.core.clone(\n schema,\n {\n ...schema._zod.def,\n innerType: sampleDefaults(schema._zod.def.innerType, copies),\n },\n { parent: false },\n );\n else if (schema instanceof z.ZodObject) {\n const shape = Object.fromEntries(\n Object.entries<unknown>(schema.shape).map(([key, child]) => {\n if (!(child instanceof z.ZodType))\n throw new Error(\"Invalid field schema\");\n return [key, sampleDefaults(child, copies)];\n }),\n );\n copy = z.core.clone(\n schema,\n {\n ...schema._zod.def,\n shape,\n catchall: schema._zod.def.catchall\n ? sampleDefaults(schema._zod.def.catchall, copies)\n : undefined,\n },\n { parent: false },\n );\n } else if (schema instanceof z.ZodArray)\n copy = z.core.clone(\n schema,\n {\n ...schema._zod.def,\n element: sampleDefaults(schema.element, copies),\n },\n { parent: false },\n );\n else if (schema instanceof z.ZodRecord)\n copy = z.core.clone(\n schema,\n {\n ...schema._zod.def,\n valueType: sampleDefaults(schema.valueType, copies),\n },\n { parent: false },\n );\n const metadata = z.globalRegistry.get(schema);\n if (copy !== schema && metadata) z.globalRegistry.add(copy, metadata);\n copies.set(schema, copy);\n return copy;\n}\nfunction assertPlainData(value: unknown): void {\n if (value === null || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const child of value) assertPlainData(child);\n return;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null)\n throw new Error(\"Manifest data must contain plain JSON objects\");\n for (const child of Object.values(value)) assertPlainData(child);\n}\n\nexport function toFieldSchemaJson(schema: FieldSchema): FieldSchemaJson {\n assertPortable(schema, \"fields\", new Set());\n return z.record(z.string(), z.json()).parse(\n z.toJSONSchema(sampleDefaults(schema), {\n io: \"input\",\n unrepresentable: \"throw\",\n reused: \"inline\",\n override: ({ zodSchema, jsonSchema }) => {\n if (\n zodSchema._zod.def.type === \"object\" &&\n zodSchema._zod.def.catchall === undefined\n )\n jsonSchema[OBJECT_MODE_KEY] = \"strip\";\n },\n }),\n );\n}\n\nexport type FieldReferenceContext = {\n /** Manifest checks validate static references and defer session-dependent families. */\n stage: \"manifest\" | \"session\";\n ids: Readonly<Partial<Record<FieldRefFamily, readonly string[]>>>;\n deferred?: readonly FieldRefFamily[];\n /** Static declaration membership for families whose seats are not known yet. */\n accepts?: Readonly<\n Partial<Record<FieldRefFamily, (value: string) => boolean>>\n >;\n};\nexport function fieldValidator(\n schema: FieldSchemaJson,\n context: FieldReferenceContext,\n): z.ZodType {\n if (schema.type !== \"object\")\n throw new Error(\"Field schemas must describe an object\");\n function resolve(value: JsonValue): JsonValue {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n return value;\n const resolved: FieldSchemaJson = { ...value };\n for (const key of [\"properties\", \"patternProperties\", \"$defs\"]) {\n const children = value[key];\n if (\n children !== null &&\n typeof children === \"object\" &&\n !Array.isArray(children)\n )\n resolved[key] = Object.fromEntries(\n Object.entries(children).map(([name, child]) => [\n name,\n resolve(child),\n ]),\n );\n }\n for (const key of [\"items\", \"additionalProperties\", \"propertyNames\", \"not\"])\n if (value[key] !== undefined) resolved[key] = resolve(value[key]);\n for (const key of [\"anyOf\", \"allOf\", \"oneOf\", \"prefixItems\"])\n if (Array.isArray(value[key])) resolved[key] = value[key].map(resolve);\n const family = value[FIELD_REF_KEY];\n if (family !== undefined) {\n const known = FIELD_REF_FAMILIES.find(\n (candidate) => candidate === family,\n );\n if (!known)\n throw new Error(`Unknown field reference family '${String(family)}'`);\n delete resolved[FIELD_REF_KEY];\n if (context.deferred?.includes(known)) return resolved;\n const ids = context.ids[known];\n if (!ids)\n throw new Error(\n `Missing ${context.stage} reference resolver for ${known}`,\n );\n if (ids.length === 0) return { ...resolved, not: {} };\n const declared = value.enum;\n const allowed = Array.isArray(declared)\n ? ids.filter((id) => declared.includes(id))\n : [...ids];\n return allowed.length\n ? { ...resolved, enum: allowed }\n : { ...resolved, not: {} };\n }\n return resolved;\n }\n assertFieldSchemaJson(schema);\n const json = z.record(z.string(), z.json()).parse(resolve(schema));\n validateDefaults(json);\n const normalize = createOutputNormalizer(json);\n const referenceChecks = createDeferredReferenceChecks(schema, context);\n function checkDefaults(node: FieldSchemaJson): void {\n if (Object.hasOwn(node, \"default\")) {\n const issues = createDeferredReferenceChecks(node, context)(node.default);\n if (issues.length)\n throw new Error(\n `Invalid field reference default: ${issues.map((issue) => issue.message).join(\"; \")}`,\n );\n }\n for (const child of schemaChildren(node)) checkDefaults(child);\n }\n checkDefaults(schema);\n return validatorFromJson(json)\n .superRefine((value, ctx) => {\n for (const issue of referenceChecks(value))\n ctx.addIssue({ code: \"custom\", ...issue });\n })\n .transform(normalize);\n}\n\n/** Compile only deferred reference membership, alongside the JSON constraint owner. */\nfunction createDeferredReferenceChecks(\n schema: FieldSchemaJson,\n context: FieldReferenceContext,\n) {\n type Issue = { path: PropertyKey[]; message: string };\n type Check = (value: unknown, path: PropertyKey[], issues: Issue[]) => void;\n function build(node: FieldSchemaJson): Check {\n const family = FIELD_REF_FAMILIES.find(\n (family) => node[FIELD_REF_KEY] === family,\n );\n const admit =\n family && context.deferred?.includes(family)\n ? context.accepts?.[family]\n : undefined;\n const properties =\n node.properties === undefined\n ? new Map<string, Check>()\n : new Map(\n Object.entries(jsonObject(node.properties)).map(([key, child]) => [\n key,\n build(jsonObject(child)),\n ]),\n );\n const items =\n node.items === undefined ? undefined : build(jsonObject(node.items));\n const additional =\n node.additionalProperties && typeof node.additionalProperties === \"object\"\n ? build(jsonObject(node.additionalProperties))\n : undefined;\n const nullable = Array.isArray(node.anyOf)\n ? node.anyOf\n .filter((child) => jsonObject(child).type !== \"null\")\n .map((child) => build(jsonObject(child)))\n : [];\n return (value, path, issues) => {\n if (typeof value === \"string\" && admit && !admit(value))\n issues.push({\n path,\n message: `Unknown declared ${family} reference '${value}'`,\n });\n if (Array.isArray(value) && items)\n value.forEach((child, i) => items(child, [...path, i], issues));\n else if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n )\n for (const [key, child] of Object.entries(value))\n (properties.get(key) ?? additional)?.(child, [...path, key], issues);\n if (value !== null)\n for (const check of nullable) check(value, path, issues);\n };\n }\n const check = build(schema);\n return (value: unknown): Issue[] => {\n const issues: Issue[] = [];\n check(value, [], issues);\n return issues;\n };\n}\n\n/** Zod's JSON reader prioritizes enum/const over sibling constraints. */\nfunction validatorFromJson(schema: FieldSchemaJson): z.ZodType {\n function lower(node: FieldSchemaJson): FieldSchemaJson {\n const lowered = { ...node };\n if (node.properties !== undefined)\n lowered.properties = Object.fromEntries(\n Object.entries(jsonObject(node.properties)).map(([key, child]) => [\n key,\n lower(jsonObject(child)),\n ]),\n );\n for (const key of [\"items\", \"additionalProperties\", \"propertyNames\", \"not\"])\n if (node[key] !== undefined && typeof node[key] !== \"boolean\")\n lowered[key] = lower(jsonObject(node[key]));\n if (Array.isArray(node.anyOf))\n lowered.anyOf = node.anyOf.map((child) => lower(jsonObject(child)));\n if (node.enum === undefined && node.const === undefined) return lowered;\n const {\n enum: values,\n const: constant,\n default: fallback,\n ...constraints\n } = lowered;\n const predicates: FieldSchemaJson[] = [constraints];\n if (values !== undefined) predicates.push({ enum: values });\n if (constant !== undefined) predicates.push({ const: constant });\n return {\n allOf: predicates,\n ...(Object.hasOwn(lowered, \"default\") ? { default: fallback } : {}),\n };\n }\n return z.fromJSONSchema(lower(schema));\n}\n\nconst SCHEMA_KEYS = new Set([\n \"$schema\",\n \"type\",\n \"properties\",\n \"additionalProperties\",\n \"propertyNames\",\n \"items\",\n \"anyOf\",\n \"not\",\n \"required\",\n \"enum\",\n \"const\",\n \"default\",\n \"description\",\n \"title\",\n \"examples\",\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"minItems\",\n \"maxItems\",\n FIELD_REF_KEY,\n OBJECT_MODE_KEY,\n]);\nfunction jsonObject(value: JsonValue): FieldSchemaJson {\n if (value === null || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(\"Expected a field schema object\");\n return value;\n}\nfunction schemaChildren(schema: FieldSchemaJson): FieldSchemaJson[] {\n const children: FieldSchemaJson[] = [];\n if (schema.properties !== undefined)\n for (const child of Object.values(jsonObject(schema.properties)))\n children.push(jsonObject(child));\n for (const key of [\"items\", \"additionalProperties\", \"propertyNames\", \"not\"])\n if (schema[key] !== undefined && typeof schema[key] !== \"boolean\")\n children.push(jsonObject(schema[key]));\n for (const key of [\"anyOf\"])\n if (schema[key] !== undefined) {\n const nodes = schema[key];\n if (!Array.isArray(nodes))\n throw new Error(`Expected ${key} schema array`);\n for (const child of nodes) children.push(jsonObject(child));\n }\n return children;\n}\nexport function assertFieldSchemaJson(schema: FieldSchemaJson): void {\n z.record(z.string(), z.json()).parse(schema);\n if (\n schema.type !== undefined &&\n !(Array.isArray(schema.type) ? schema.type : [schema.type]).every((type) =>\n [\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n ].includes(String(type)),\n )\n )\n throw new Error(\"Unsupported field JSON Schema type\");\n for (const key of Object.keys(schema))\n if (!SCHEMA_KEYS.has(key))\n throw new Error(`Unsupported field JSON Schema keyword '${key}'`);\n for (const value of [\n ...(Array.isArray(schema.enum) ? schema.enum : []),\n ...(Object.hasOwn(schema, \"const\") ? [schema.const] : []),\n ])\n if (\n value !== null &&\n ![\"string\", \"number\", \"boolean\"].includes(typeof value)\n )\n throw new Error(\"Field enum/const values must be primitive JSON values\");\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n if (\n Array.isArray(schema.type) &&\n (schema.type.length !== 2 ||\n !schema.type.includes(\"null\") ||\n !schema.type.some((type) =>\n [\"string\", \"number\", \"integer\", \"boolean\"].includes(String(type)),\n ))\n )\n throw new Error(\"Portable type arrays require a primitive and null\");\n for (const key of [\"minLength\", \"maxLength\", \"minItems\", \"maxItems\"])\n if (\n schema[key] !== undefined &&\n (typeof schema[key] !== \"number\" ||\n !Number.isSafeInteger(schema[key]) ||\n schema[key] < 0)\n )\n throw new Error(`${key} requires a nonnegative safe integer`);\n for (const key of [\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n ])\n if (\n schema[key] !== undefined &&\n (typeof schema[key] !== \"number\" ||\n !Number.isFinite(schema[key]) ||\n (key === \"multipleOf\" && schema[key] <= 0))\n )\n throw new Error(\n `${key} requires a finite${key === \"multipleOf\" ? \" positive\" : \"\"} number`,\n );\n for (const key of [\"pattern\", \"title\", \"description\"])\n if (schema[key] !== undefined && typeof schema[key] !== \"string\")\n throw new Error(`${key} requires a string`);\n if (typeof schema.pattern === \"string\") new RegExp(schema.pattern);\n if (\n schema.enum !== undefined &&\n (!Array.isArray(schema.enum) || schema.enum.length === 0)\n )\n throw new Error(\"enum requires a nonempty array\");\n if (schema.examples !== undefined && !Array.isArray(schema.examples))\n throw new Error(\"examples requires an array\");\n if (schema.required !== undefined) {\n if (\n !Array.isArray(schema.required) ||\n schema.required.some((key) => typeof key !== \"string\") ||\n new Set(schema.required).size !== schema.required.length\n )\n throw new Error(\"required requires unique declared property names\");\n const properties =\n schema.properties === undefined ? {} : jsonObject(schema.properties);\n if (schema.required.some((key) => !Object.hasOwn(properties, String(key))))\n throw new Error(\"required requires unique declared property names\");\n }\n if (\n schema.not !== undefined &&\n Object.keys(jsonObject(schema.not)).length !== 0\n )\n throw new Error(\"Portable not supports the empty schema only\");\n if (\n schema.propertyNames !== undefined &&\n !sameJson(schema.propertyNames, { type: \"string\" })\n )\n throw new Error(\"Portable records require unconstrained string keys\");\n if (\n schema.anyOf !== undefined &&\n (!Array.isArray(schema.anyOf) || schema.anyOf.length !== 2)\n )\n throw new Error(\"Portable anyOf supports nullable schemas only\");\n if (schema[FIELD_REF_KEY] !== undefined && schema.type !== \"string\")\n throw new Error(\"Field reference metadata requires a string schema\");\n for (const [keywords, compatible] of [\n [[\"minLength\", \"maxLength\", \"pattern\"], [\"string\"]],\n [\n [\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n ],\n [\"number\", \"integer\"],\n ],\n [[\"minItems\", \"maxItems\", \"items\"], [\"array\"]],\n [[\"properties\", \"required\", \"additionalProperties\"], [\"object\"]],\n ])\n if (\n keywords.some((key) => schema[key] !== undefined) &&\n !types.some((type) => compatible.some((candidate) => candidate === type))\n )\n throw new Error(\n \"Field schema constraints require a compatible explicit type\",\n );\n if (\n schema.$schema !== undefined &&\n schema.$schema !== \"https://json-schema.org/draft/2020-12/schema\"\n )\n throw new Error(\"Field schemas require JSON Schema draft 2020-12\");\n if (\n schema[OBJECT_MODE_KEY] !== undefined &&\n (schema[OBJECT_MODE_KEY] !== \"strip\" || schema.type !== \"object\")\n )\n throw new Error(\n \"Object-mode metadata requires an object schema and strip mode\",\n );\n if (Array.isArray(schema.anyOf)) {\n const branches = schema.anyOf;\n const meaningful = branches.filter(\n (branch) =>\n !(\n branch !== null &&\n typeof branch === \"object\" &&\n !Array.isArray(branch) &&\n branch.type === \"null\"\n ),\n );\n if (meaningful.length !== 1)\n throw new Error(\"Portable anyOf supports nullable schemas only\");\n }\n for (const child of schemaChildren(schema)) assertFieldSchemaJson(child);\n}\nfunction sameJson(left: JsonValue, right: JsonValue): boolean {\n if (left === right) return true;\n if (Array.isArray(left))\n return (\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((child, index) => sameJson(child, right[index]))\n );\n if (\n left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\" ||\n Array.isArray(right)\n )\n return false;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(\n (key) => Object.hasOwn(right, key) && sameJson(left[key], right[key]),\n )\n );\n}\nfunction validateDefaults(schema: FieldSchemaJson): void {\n for (const child of schemaChildren(schema)) validateDefaults(child);\n if (Object.hasOwn(schema, \"default\")) {\n const { default: value, ...validation } = schema;\n const concrete = z\n .json()\n .parse(\n createOutputNormalizer(validation)(\n validatorFromJson(validation).parse(value),\n ),\n );\n if (!sameJson(value, concrete))\n throw new Error(\n \"Concrete field defaults must already conform to their output shape\",\n );\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n/** Compile object output policy once alongside the validator. */\nfunction createOutputNormalizer(\n schema: FieldSchemaJson,\n): (value: unknown) => unknown {\n if (Array.isArray(schema.anyOf)) {\n const branch = schema.anyOf.find(\n (child) =>\n child !== null &&\n typeof child === \"object\" &&\n !Array.isArray(child) &&\n child.type !== \"null\",\n );\n if (branch !== undefined) {\n const normalize = createOutputNormalizer(jsonObject(branch));\n return (value) => (value === null ? null : normalize(value));\n }\n }\n if (schema.type === \"array\" && schema.items !== undefined) {\n const normalize = createOutputNormalizer(jsonObject(schema.items));\n return (value) => (Array.isArray(value) ? value.map(normalize) : value);\n }\n if (schema.type !== \"object\") return (value) => value;\n const properties =\n schema.properties === undefined ? {} : jsonObject(schema.properties);\n const fields = new Map(\n Object.entries(properties).map(([key, child]) => [\n key,\n createOutputNormalizer(jsonObject(child)),\n ]),\n );\n const additional =\n schema.additionalProperties !== undefined &&\n typeof schema.additionalProperties !== \"boolean\"\n ? createOutputNormalizer(jsonObject(schema.additionalProperties))\n : undefined;\n const strip = schema[OBJECT_MODE_KEY] === \"strip\";\n return (value) => {\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value).flatMap(([key, child]) => {\n const normalize = fields.get(key);\n if (normalize) return [[key, normalize(child)]];\n if (strip) return [];\n return [[key, additional ? additional(child) : child]];\n }),\n );\n };\n}\n\nexport function schemaForCardType(\n schema: import(\"../../shared/domain/contracts.js\").CardSchemaJson,\n cardType: string,\n): FieldSchemaJson {\n const variants = schema.byCardType;\n if (\n variants !== undefined &&\n variants !== null &&\n typeof variants === \"object\" &&\n !Array.isArray(variants)\n ) {\n const variant = variants[cardType];\n if (\n variant === null ||\n typeof variant !== \"object\" ||\n Array.isArray(variant)\n )\n throw new Error(`Missing field schema for card type '${cardType}'`);\n return variant;\n }\n return schema;\n}\n\nexport function fieldSchemaKeyIssues(\n schema: FieldSchemaJson | null | undefined,\n path: string,\n): string[] {\n if (!schema) return [];\n if (schema.byCardType !== undefined) {\n try {\n if (Object.keys(schema).length !== 1)\n throw new Error(\"Card variant schemas require only byCardType\");\n const variants = z\n .record(z.string().min(1), z.record(z.string(), z.json()))\n .parse(schema.byCardType);\n return Object.entries(variants).flatMap(([type, variant]) => [\n ...([\"__proto__\", \"prototype\", \"constructor\"].includes(type)\n ? [\n `${path}.byCardType.${type}: '${type}' is reserved and cannot be used as a generated record key.`,\n ]\n : []),\n ...(variant.type !== \"object\"\n ? [\n `${path}.byCardType.${type}: Field schemas must describe an object`,\n ]\n : fieldSchemaKeyIssues(variant, `${path}.byCardType.${type}`)),\n ]);\n } catch (error) {\n return [\n `${path}: ${error instanceof Error ? error.message : String(error)}`,\n ];\n }\n }\n try {\n if (schema.type !== \"object\")\n throw new Error(\"Field schemas must describe an object\");\n assertFieldSchemaJson(schema);\n } catch (error) {\n return [\n `${path}: ${error instanceof Error ? error.message : String(error)}`,\n ];\n }\n const issues: string[] = [];\n function walk(value: JsonValue, at: string): void {\n if (Array.isArray(value)) {\n value.forEach((child, i) => walk(child, `${at}[${i}]`));\n return;\n }\n if (value === null || typeof value !== \"object\") return;\n const properties = value.properties;\n if (\n properties &&\n typeof properties === \"object\" &&\n !Array.isArray(properties)\n )\n for (const key of Object.keys(properties)) {\n if ([\"__proto__\", \"prototype\", \"constructor\"].includes(key))\n issues.push(\n `${at}.properties.${key}: '${key}' is reserved and cannot be used as a generated record key.`,\n );\n }\n for (const key of [\"properties\", \"patternProperties\", \"$defs\"]) {\n const children = value[key];\n if (\n children !== null &&\n typeof children === \"object\" &&\n !Array.isArray(children)\n )\n for (const [name, child] of Object.entries(children))\n walk(child, `${at}.${key}.${name}`);\n }\n for (const key of [\"items\", \"additionalProperties\", \"propertyNames\", \"not\"])\n if (value[key] !== undefined) walk(value[key], `${at}.${key}`);\n for (const key of [\"anyOf\", \"allOf\", \"oneOf\", \"prefixItems\"])\n if (Array.isArray(value[key]))\n value[key].forEach((child, i) => walk(child, `${at}.${key}[${i}]`));\n }\n walk(schema, path);\n return issues;\n}\n\n/** Authoring conversion walks data, replacing only declared schema fields. */\nexport function toManifestJson(value: unknown): unknown {\n function cloneData(input: unknown): unknown {\n if (input instanceof z.ZodType)\n throw new Error(\n \"Zod schemas belong only in declared manifest schema fields\",\n );\n if (Array.isArray(input)) return input.map(cloneData);\n if (isRecord(input)) {\n const prototype: unknown = Object.getPrototypeOf(input);\n if (prototype !== Object.prototype && prototype !== null)\n throw new Error(\"Manifest data must contain plain JSON objects\");\n return Object.fromEntries(\n Object.entries(input).map(([key, child]) => [key, cloneData(child)]),\n );\n }\n return input;\n }\n function convertSchema(input: unknown, card = false): unknown {\n if (input instanceof z.ZodObject) return toFieldSchemaJson(input);\n if (card && isRecord(input) && Object.hasOwn(input, \"byCardType\")) {\n if (Object.keys(input).length !== 1 || !isRecord(input.byCardType))\n throw new Error(\"Card variant schemas require only byCardType\");\n return {\n byCardType: Object.fromEntries(\n Object.entries(input.byCardType).map(([type, schema]) => [\n type,\n convertSchema(schema),\n ]),\n ),\n };\n }\n return cloneData(input);\n }\n function entries(input: unknown, keys: readonly string[]): unknown {\n if (!Array.isArray(input)) return cloneData(input);\n return input.map((entry) =>\n isRecord(entry)\n ? Object.fromEntries(\n Object.entries(entry).map(([key, child]) => [\n key,\n keys.includes(key)\n ? convertSchema(child, key === \"cardSchema\")\n : cloneData(child),\n ]),\n )\n : cloneData(entry),\n );\n }\n if (!isRecord(value)) return cloneData(value);\n const json = Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n key === \"cardSets\"\n ? entries(child, [\"cardSchema\"])\n : key === \"boards\"\n ? entries(child, [\n \"boardFieldsSchema\",\n \"spaceFieldsSchema\",\n \"relationFieldsSchema\",\n \"edgeFieldsSchema\",\n \"vertexFieldsSchema\",\n ])\n : key === \"tileTypes\"\n ? entries(child, [\n \"fieldsSchema\",\n \"propertiesSchema\",\n \"cellFieldsSchema\",\n \"edgeFieldsSchema\",\n \"vertexFieldsSchema\",\n ])\n : key === \"pieceTypes\" || key === \"dieTypes\"\n ? entries(child, [\"fieldsSchema\"])\n : cloneData(child),\n ]),\n );\n return json;\n}\n\n/** One converter per schema and board scope for one immutable reference context. */\nexport function createFieldValidatorResolver(\n contextForBoard: (boardId?: string) => FieldReferenceContext,\n) {\n const validators = new Map<FieldSchemaJson, Map<string, z.ZodType>>();\n return (schema: FieldSchemaJson, boardId?: string): z.ZodType => {\n let scoped = validators.get(schema);\n if (!scoped) {\n scoped = new Map();\n validators.set(schema, scoped);\n }\n const key = boardId ?? \"\";\n let validator = scoped.get(key);\n if (!validator) {\n validator = fieldValidator(schema, contextForBoard(boardId));\n scoped.set(key, validator);\n }\n return validator;\n };\n}\n","import type { GameTopologyManifest } from \"../../shared/domain/manifest\";\nimport { GameTopologyManifestSchema } from \"../../shared/domain/manifest-schema.js\";\nimport { assertValidManifest } from \"./manifest-validation\";\n\n/** Admit an external JSON document using the SDK's structural and semantic contract. */\nexport function parseTopologyManifestJson(\n value: unknown,\n): GameTopologyManifest {\n const result = GameTopologyManifestSchema.safeParse(value);\n if (!result.success) {\n throw new Error(\n `Invalid topology manifest:\\n${result.error.issues\n .map((issue) => {\n const path = issue.path\n .map((segment) =>\n typeof segment === \"number\"\n ? `[${segment}]`\n : `.${String(segment)}`,\n )\n .join(\"\");\n return `manifest${path}: ${issue.message}`;\n })\n .join(\"\\n\")}`,\n );\n }\n const manifest = result.data;\n assertValidManifest(manifest);\n return manifest;\n}\n","import type { ReadonlyRuntimeData } from \"../../shared/runtime-json.js\";\nimport { BoardRelationSchema } from \"../../shared/board-topology-schema.js\";\nimport { BoardTopologyError } from \"../../shared/board-topology.js\";\nimport {\n PlayerIdSchema,\n PlayerRosterSchema,\n} from \"../../shared/domain/player-identity.js\";\nimport {\n expandSeedIds,\n renderCardInstanceIds,\n initialCardMetadata,\n createInstanceDeclaration,\n createSpaceDeclaration,\n createBoardElementDeclaration,\n} from \"./identity-runtime.js\";\nimport { parseTopologyManifestJson } from \"./parse-json\";\nimport type { TypedTopologyManifest } from \"./authoring\";\nimport { toManifestJson } from \"./field-schemas\";\nimport type { ManifestCountValidation } from \"./identity-types\";\nimport * as z from \"zod\";\nimport { buildTypedRecord } from \"./generated-helpers.js\";\nimport { type GameTopologyManifest } from \"../../shared/domain/manifest.js\";\nimport {\n analyzeManifest,\n analyzeManifestStructure,\n materializeManifestTable,\n materializeTopologyDefinitions,\n materializeEmptyZones,\n} from \"./materialize\";\nimport { createTableSchema, type RuntimeManifestIds } from \"./schema\";\nimport { asPlayerId } from \"../per-player\";\nimport {\n assumeManifestSchema,\n createManifestStringLiteralSchema,\n markManifestScopedSchema,\n} from \"../model/manifest\";\nimport type { ReducerManifestContract, RuntimeTableRecord } from \"../model\";\nimport type {\n AuthoredManifest,\n AuthoredOf,\n ValidatedManifest,\n CompiledManifest,\n} from \"./types\";\n\ntype JsonManifestInput = ReadonlyRuntimeData<GameTopologyManifest>;\nexport type ManifestDocumentInput =\n AuthoredManifest | ValidatedManifest | JsonManifestInput;\ntype ManifestAdmission<M> = [M] extends [ValidatedManifest<unknown>]\n ? unknown\n : [M] extends [ManifestDocumentInput]\n ? AuthoredManifest extends M\n ? unknown\n : M extends AuthoredManifest\n ? TypedTopologyManifest<M>\n : unknown\n : ManifestDocumentInput;\nexport type ManifestInput<M> = M &\n ManifestCountValidation<NoInfer<M>> &\n ManifestAdmission<NoInfer<M>>;\n\n/** Compile authored topology once, in memory, with the same validation used by initialization. */\nexport function compileManifest<const M>(\n manifest: ManifestInput<M>,\n): CompiledManifest<AuthoredOf<M>> {\n // Runtime admission establishes the facade; this boundary preserves its authored input witness.\n // eslint-disable-next-line no-restricted-syntax -- Validated compilation correlates inferred IDs and portable fields with this exact authored source.\n return compileManifestRuntime(manifest) as unknown as CompiledManifest<\n AuthoredOf<M>\n >;\n}\n/** Internal erased entry for already type-checked authoring factories; admission still runs once. */\nfunction compileManifestRuntime(\n manifest: unknown,\n): CompiledManifest<AuthoredManifest> {\n const source = parseTopologyManifestJson(toManifestJson(manifest));\n const analysis = analyzeManifest(source);\n const topologyDefinitions = materializeTopologyDefinitions(analysis);\n const literals = {\n cardSetIds: analysis.cardSetIds,\n cardTypes: analysis.cardTypes,\n cardIds: analysis.cardIds,\n zoneIds: analysis.zoneIds,\n resourceIds: analysis.resourceIds,\n pieceTypeIds: analysis.pieceTypeIds,\n pieceIds: analysis.pieceIds,\n dieTypeIds: analysis.dieTypeIds,\n dieIds: analysis.dieIds,\n tileTypeIds: analysis.tileTypeIds,\n tileIds: analysis.tileIds,\n boardTypeIds: analysis.boardTypeIds,\n boardBaseIds: analysis.boardBaseIds,\n boardIds: analysis.boardIds,\n relationTypeIds: analysis.relationTypeIds,\n edgeIds: analysis.edgeIds,\n edgeTypeIds: analysis.edgeTypeIds,\n vertexIds: analysis.vertexIds,\n vertexTypeIds: analysis.vertexTypeIds,\n spaceIds: analysis.spaceIds,\n spaceTypeIds: analysis.spaceTypeIds,\n playerIds: analysis.playerIds.map(asPlayerId),\n phaseNames: [],\n boardLayouts: [\"generic\", \"hex\", \"square\"],\n resourcePresentationById: analysis.resourcePresentationById,\n ownerResourceIds: (source.resources ?? [])\n .filter((resource) => resource.visibility === \"owner\")\n .map((resource) => resource.id)\n .sort(),\n cardSetIdByCardId: Object.fromEntries(analysis.cardSetIdByCardId),\n cardTypeByCardId: Object.fromEntries(analysis.cardTypeByCardId),\n } satisfies ReducerManifestContract<\n RuntimeTableRecord,\n string,\n string,\n string,\n string\n >[\"literals\"];\n const families = [\n \"phaseName\",\n \"boardLayout\",\n \"cardSetId\",\n \"cardType\",\n \"cardId\",\n \"zoneId\",\n \"resourceId\",\n \"pieceTypeId\",\n \"pieceId\",\n \"dieTypeId\",\n \"dieId\",\n \"tileTypeId\",\n \"tileId\",\n \"boardTypeId\",\n \"boardBaseId\",\n \"boardId\",\n \"relationTypeId\",\n \"edgeId\",\n \"edgeTypeId\",\n \"vertexId\",\n \"vertexTypeId\",\n \"spaceId\",\n \"spaceTypeId\",\n ] as const;\n // eslint-disable-next-line no-restricted-syntax -- The complete families list constructs each ID schema from its matching literals; playerId is added explicitly; relation tags use their open schema.\n const ids = {\n ...Object.fromEntries(\n families.map((family) => {\n const values = literals[`${family}s`];\n return [\n family,\n family === \"relationTypeId\"\n ? BoardRelationSchema.shape.typeId\n : family === \"phaseName\"\n ? markManifestScopedSchema(z.string(), family)\n : values.length\n ? createManifestStringLiteralSchema(values, family)\n : markManifestScopedSchema(z.never(), family),\n ];\n }),\n ),\n playerId: markManifestScopedSchema(\n PlayerIdSchema.transform(asPlayerId),\n \"playerId\",\n ),\n } as unknown as RuntimeManifestIds;\n ids.edgeId = markManifestScopedSchema(\n createBoardElementDeclaration(source, \"edge\").schema,\n \"edgeId\",\n );\n ids.vertexId = markManifestScopedSchema(\n createBoardElementDeclaration(source, \"vertex\").schema,\n \"vertexId\",\n );\n ids.spaceId = markManifestScopedSchema(\n createSpaceDeclaration(source).schema,\n \"spaceId\",\n );\n ids.boardId = markManifestScopedSchema(\n createInstanceDeclaration(\n \"board\",\n (source.boards ?? []).map((board) => ({\n baseIds: [board.id],\n scope: board.scope,\n })),\n ).schema,\n \"boardId\",\n );\n ids.cardId = markManifestScopedSchema(\n createInstanceDeclaration(\n \"card\",\n source.cardSets.flatMap((set) =>\n set.cards.map((card) => ({\n baseIds: renderCardInstanceIds(card),\n scope: card.scope,\n })),\n ),\n ).schema,\n \"cardId\",\n );\n ids.pieceId = markManifestScopedSchema(\n createInstanceDeclaration(\n \"piece\",\n (source.pieceSeeds ?? []).map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ).schema,\n \"pieceId\",\n );\n ids.dieId = markManifestScopedSchema(\n createInstanceDeclaration(\n \"die\",\n (source.dieSeeds ?? []).map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ).schema,\n \"dieId\",\n );\n ids.tileId = markManifestScopedSchema(\n createInstanceDeclaration(\n \"tile\",\n (source.tileSeeds ?? []).map((seed) => ({\n baseIds: expandSeedIds([seed]),\n scope: seed.scope,\n })),\n ).schema,\n \"tileId\",\n );\n const zoneDefinitions = Object.freeze(\n Object.fromEntries(\n (source.zones ?? []).map((zone) => [\n zone.id,\n Object.freeze({\n ...(\"scope\" in zone\n ? { scope: zone.scope }\n : { attachedTo: zone.attachedTo }),\n visibility: zone.visibility ?? \"public\",\n allowedCardSetIds: Object.freeze([\n ...(analysis.zoneCardSetIdsById.get(zone.id) ?? []),\n ]),\n }),\n ]),\n ),\n );\n let rosterKey = \"\";\n let rosterSchema: z.ZodType | undefined;\n const tableSchema = assumeManifestSchema<RuntimeTableRecord>(\n z.unknown().transform((table, context) => {\n const header = z\n .object({\n playerOrder: PlayerRosterSchema,\n })\n .safeParse(table);\n if (!header.success) {\n for (const issue of header.error.issues)\n context.addIssue({\n code: \"custom\",\n path: issue.path,\n message: issue.message,\n });\n return z.NEVER;\n }\n const key = JSON.stringify(header.data.playerOrder);\n if (!rosterSchema || key !== rosterKey) {\n // Source was admitted once; runtime roster analysis is structural only.\n try {\n const nextSchema = createTableSchema(\n analyzeManifestStructure(source, header.data.playerOrder),\n ids,\n { zoneDefinitions, ...topologyDefinitions },\n );\n rosterSchema = nextSchema;\n rosterKey = key;\n } catch (error) {\n if (!(error instanceof BoardTopologyError)) throw error;\n context.addIssue({\n code: \"custom\",\n path: [\"boards\"],\n message: error.message,\n });\n return z.NEVER;\n }\n }\n const parsed = rosterSchema.safeParse(table);\n if (!parsed.success) {\n for (const issue of parsed.error.issues)\n context.addIssue({\n code: \"custom\",\n path: issue.path,\n message: issue.message,\n });\n return z.NEVER;\n }\n return parsed.data;\n }),\n );\n const resolvePlayers = (players: readonly string[] = analysis.playerIds) =>\n PlayerRosterSchema.parse(players).map(asPlayerId);\n const defaults = {\n zones: (players?: readonly string[]) =>\n materializeEmptyZones(\n analyzeManifestStructure(\n source,\n PlayerRosterSchema.parse(players ?? []),\n ),\n ),\n ownerOfCard: (players?: readonly string[]) =>\n initialCardMetadata(\n source.cardSets,\n PlayerRosterSchema.parse(players ?? []),\n ).ownerOfCard,\n visibility: (players?: readonly string[]) =>\n initialCardMetadata(\n source.cardSets,\n PlayerRosterSchema.parse(players ?? []),\n ).visibility,\n resources: (players?: readonly string[]) =>\n Object.fromEntries(\n resolvePlayers(players).map((id) => [\n id,\n Object.fromEntries(analysis.resourceIds.map((id) => [id, 0])),\n ]),\n ),\n };\n const createInitialTable = (options: {\n playerIds: readonly string[];\n shuffleItems?: <V>(values: readonly V[]) => V[];\n }) => {\n const playerIds = PlayerRosterSchema.parse(options.playerIds);\n return tableSchema.parse(\n materializeManifestTable({\n manifest: source,\n playerIds,\n shuffleItems: options.shuffleItems ?? ((values) => [...values]),\n }),\n );\n };\n // eslint-disable-next-line no-restricted-syntax -- Runtime admission supplies every literal, schema, record, and setup factory; this internal boundary binds those results to the erased compiled facade.\n return {\n zoneDefinitions,\n literals,\n ids,\n defaults,\n records: Object.fromEntries(\n families.map((family) => [\n `${family}s`,\n <V>(\n initial: V | ((id: string) => V),\n options?: { playerIds: readonly string[] },\n ) => {\n const dynamic =\n family === \"cardId\" ||\n family === \"pieceId\" ||\n family === \"dieId\" ||\n family === \"tileId\" ||\n family === \"boardId\";\n if (dynamic && !options)\n throw new Error(\n \"Instance record factories require explicit playerIds.\",\n );\n const keys =\n dynamic && options\n ? analyzeManifestStructure(\n source,\n PlayerRosterSchema.parse(options.playerIds),\n )[`${family}s`]\n : literals[`${family}s`];\n return buildTypedRecord(keys, initial);\n },\n ]),\n ),\n tableSchema,\n ...topologyDefinitions,\n createInitialTable,\n normalSetup: {\n minPlayers: source.players.minPlayers,\n maxPlayers: source.players.maxPlayers,\n createInitialTable,\n },\n } as unknown as CompiledManifest<AuthoredManifest>;\n}\n","type RecordInitializer<Id extends string, Value> = Value | ((id: Id) => Value);\n\nexport function buildTypedRecord<Id extends string, Value>(\n ids: readonly Id[],\n initial: RecordInitializer<Id, Value>,\n): Record<Id, Value> {\n const createValue =\n typeof initial === \"function\"\n ? (initial as (id: Id) => Value)\n : () => initial;\n\n return Object.fromEntries(ids.map((id) => [id, createValue(id)])) as Record<\n Id,\n Value\n >;\n}\n\nexport function isTypedId<Id extends string>(\n ids: readonly Id[],\n value: string,\n): value is Id {\n return (ids as readonly string[]).includes(value);\n}\n\nexport function expectTypedId<Id extends string>(\n ids: readonly Id[],\n value: string,\n description: string,\n): Id {\n if (isTypedId(ids, value)) {\n return value;\n }\n\n throw new Error(`Unknown ${description} '${value}'.`);\n}\n","import { getPublicTileFootprint } from \"../../shared/tile-appearance.js\";\nimport { TileDisclosureSchema } from \"../../shared/domain/tile-disclosure.js\";\nimport { ZoneVisibilitySchema } from \"../../shared/domain/manifest-schema.js\";\nimport { BoardRelationSchema } from \"../../shared/board-topology-schema.js\";\nimport { RuntimeJsonSchema } from \"../../shared/runtime-json.js\";\nimport { deriveBoardTopology } from \"../../shared/board-topology.js\";\nimport { TilePlacementSchema } from \"../../shared/domain/tile-placement.js\";\nimport { asPlayerId } from \"../per-player.js\";\nimport * as z from \"zod\";\nimport type { FieldSchemaJson } from \"../../shared/domain/contracts.js\";\nimport {\n createFieldValidatorResolver,\n schemaForCardType,\n} from \"./field-schemas\";\nimport { fieldReferenceContext } from \"./materialize\";\nimport { assertZoneConsistency } from \"../table/zones\";\nimport type { ZoneDefinitions } from \"../model\";\nimport type { ManifestIds } from \"../model\";\n\nimport type { analyzeManifest } from \"./materialize\";\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction property(value: unknown, key: string): unknown {\n return isRecord(value) ? value[key] : undefined;\n}\nfunction recordEntries(value: unknown): [string, unknown][] {\n return isRecord(value) ? Object.entries(value) : [];\n}\ntype Analysis = ReturnType<typeof analyzeManifest>;\nexport type RuntimeManifestIds = {\n [K in keyof ManifestIds<string, string, string, string>]: z.ZodType<string>;\n};\ntype Ids = RuntimeManifestIds;\nexport function createTableSchema(\n analysis: Analysis,\n ids: Ids,\n definitions: ZoneDefinitions,\n) {\n const membership = (values: readonly string[]): z.ZodType<string> =>\n values.length ? z.enum(values) : z.never();\n const activeBoardId = membership(analysis.boardIds);\n const activeCardId = membership(analysis.cardIds);\n const activePlayerId = membership(analysis.playerIds).transform(asPlayerId);\n const unknownRecordSchema = z.record(z.string(), RuntimeJsonSchema);\n const resolveStatic = createFieldValidatorResolver((boardId) =>\n fieldReferenceContext(analysis, \"manifest\", boardId),\n );\n const objectSchema = (\n schema: FieldSchemaJson | null | undefined,\n boardId?: string,\n ) =>\n schema\n ? resolveStatic(schema, boardId).pipe(unknownRecordSchema)\n : unknownRecordSchema;\n const shape = <T, S extends z.ZodType>(\n items: readonly T[],\n getKey: (item: T) => string,\n getSchema: (item: T) => S,\n ) =>\n z.object(\n Object.fromEntries(items.map((item) => [getKey(item), getSchema(item)])),\n );\n const cardStateByIdSchema = shape(\n analysis.cardIds,\n (id) => id,\n (id) => {\n const setId = analysis.cardSetIdByCardId.get(id)!;\n const type = analysis.cardTypeByCardId.get(id)!;\n const schema = analysis.cardSets.find(\n (set) => set.id === setId,\n )!.cardSchema;\n const properties = objectSchema(schemaForCardType(schema, type));\n return z.object({\n componentType: z.string().optional(),\n id: z.literal(id),\n cardSetId: z.literal(setId),\n cardType: z.literal(type),\n name: z.string().optional(),\n text: z.string().optional(),\n frontImage: z.string().optional(),\n backImage: z.string().optional(),\n properties,\n });\n },\n ).strict();\n const pieceStateByIdSchema = shape(\n analysis.pieceIds,\n (id) => id,\n (id) => {\n const type = analysis.pieceTypeIdByPieceId.get(id)!;\n return z.object({\n componentType: z.string().optional(),\n id: z.literal(id),\n pieceTypeId: z.literal(type),\n pieceName: z.string().nullish(),\n ownerId: activePlayerId.nullish(),\n properties: objectSchema(analysis.pieceTypeSchemasById.get(type)),\n });\n },\n ).strict();\n const dieStateByIdSchema = shape(\n analysis.dieIds,\n (id) => id,\n (id) => {\n const type = analysis.dieTypeIdByDieId.get(id)!;\n return z.object({\n componentType: z.string().optional(),\n id: z.literal(id),\n dieTypeId: z.literal(type),\n dieName: z.string().nullish(),\n ownerId: activePlayerId.nullish(),\n sides: z.literal(\n analysis.manifest.dieTypes?.find((die) => die.id === type)?.sides ??\n 6,\n ),\n value: z.number().int().nullish(),\n properties: objectSchema(analysis.dieTypeSchemasById.get(type)),\n });\n },\n ).strict();\n const tileStateByIdSchema = shape(\n analysis.tileIds,\n (id) => id,\n (id) => {\n const type = analysis.tileTypeIdByTileId.get(id)!;\n return z.strictObject({\n disclosure: TileDisclosureSchema.superRefine((disclosure, context) => {\n if (disclosure.face.audience === \"seats\")\n for (const playerId of disclosure.face.playerIds)\n if (!activePlayerId.safeParse(playerId).success)\n context.addIssue({\n code: \"custom\",\n path: [\"face\", \"playerIds\"],\n message:\n \"Tile face audience must name active roster players.\",\n });\n }),\n componentType: z.literal(\"tile\"),\n id: z.literal(id),\n tileTypeId: z.literal(type),\n ownerId: activePlayerId.nullable(),\n properties: objectSchema(analysis.tilePropertiesSchemasById.get(type)),\n });\n },\n ).strict();\n const boards = analysis.analyzedBoards.flatMap((board) =>\n board.runtimeBoardIds.map((id) => ({\n id,\n schema: z.strictObject({\n baseId: z.literal(board.board.id),\n visibility:\n board.board.scope === \"shared\"\n ? z.enum([\"public\", \"hidden\"])\n : ZoneVisibilitySchema,\n relations: z.array(\n BoardRelationSchema.extend({\n fields: objectSchema(board.relationFieldsSchema),\n }),\n ),\n }),\n })),\n );\n const boardStateByIdSchema = shape(\n boards,\n (board) => board.id,\n (board) => board.schema,\n ).strict();\n const tilePlacement = z.discriminatedUnion(\"layout\", [\n TilePlacementSchema.options[0].extend({ boardId: activeBoardId }),\n TilePlacementSchema.options[1].extend({ boardId: activeBoardId }),\n ]);\n let sessionKey = \"\";\n let resolveSession:\n ReturnType<typeof createFieldValidatorResolver> | undefined;\n return z\n .object({\n playerOrder: z.array(activePlayerId),\n zones: z.record(z.string(), z.record(z.string(), z.array(z.string()))),\n cards: cardStateByIdSchema,\n pieces: pieceStateByIdSchema,\n componentLocations: z.record(\n z.string(),\n z.union([\n tilePlacement,\n z.strictObject({ type: z.literal(\"Detached\") }),\n z\n .object({\n type: z.literal(\"InZone\"),\n zoneId: ids.zoneId,\n hostId: z.string(),\n playedBy: activePlayerId.nullable(),\n })\n .strict(),\n z.strictObject({\n type: z.literal(\"OnSpace\"),\n boardId: activeBoardId,\n spaceId: z.string().min(1),\n position: z.number().int().nullable().optional(),\n }),\n z.strictObject({\n type: z.literal(\"OnEdge\"),\n boardId: activeBoardId,\n edgeId: z.string().min(1),\n position: z.number().int().nullable().optional(),\n }),\n z.strictObject({\n type: z.literal(\"OnVertex\"),\n boardId: activeBoardId,\n vertexId: z.string().min(1),\n position: z.number().int().nullable().optional(),\n }),\n ]),\n ),\n ownerOfCard: z.record(activeCardId, activePlayerId.nullable()),\n visibility: z.record(\n activeCardId,\n z.object({\n faceUp: z.boolean(),\n visibleTo: z.array(activePlayerId).nullable().optional(),\n }),\n ),\n resources: z.record(\n activePlayerId,\n z.record(ids.resourceId, z.number().int()),\n ),\n boards: boardStateByIdSchema,\n dice: dieStateByIdSchema,\n tiles: tileStateByIdSchema,\n })\n .strict()\n .superRefine((table, context) => {\n const players = new Set<string>(table.playerOrder);\n if (players.size !== table.playerOrder.length) {\n context.addIssue({\n code: \"custom\",\n path: [\"playerOrder\"],\n message: \"Duplicate player id\",\n });\n }\n const checkPlayers = (\n record: Record<string, unknown>,\n path: string[],\n ) => {\n for (const playerId of table.playerOrder) {\n if (!Object.hasOwn(record, playerId))\n context.addIssue({\n code: \"custom\",\n path: [...path, playerId],\n message: \"Missing active player\",\n });\n }\n for (const playerId of Object.keys(record)) {\n if (!players.has(playerId))\n context.addIssue({\n code: \"custom\",\n path: [...path, playerId],\n message: \"Unknown active player\",\n });\n }\n };\n const playerIds = [...table.playerOrder];\n const boardEntries = Object.entries(table.boards).map(\n ([id, board]) => [id, property(board, \"baseId\")] as const,\n );\n const boardIds = boardEntries.map(([id]) => id);\n const referenceContext = fieldReferenceContext(analysis);\n const topologyIds = new Map<\n string,\n { spaceId: string[]; edgeId: string[]; vertexId: string[] }\n >();\n try {\n for (const id of boardIds) {\n const topology = deriveBoardTopology(table, definitions, id);\n topologyIds.set(id, {\n spaceId: Object.keys(topology.spaces),\n edgeId:\n topology.layout === \"generic\"\n ? []\n : topology.edges.map((edge) => edge.id),\n vertexId:\n topology.layout === \"generic\"\n ? []\n : topology.vertices.map((vertex) => vertex.id),\n });\n }\n } catch (error) {\n context.addIssue({\n code: \"custom\",\n path: [\"boards\"],\n message: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n const geometryIds = {\n spaceId: [\n ...new Set([...topologyIds.values()].flatMap((ids) => ids.spaceId)),\n ],\n edgeId: [\n ...new Set([...topologyIds.values()].flatMap((ids) => ids.edgeId)),\n ],\n vertexId: [\n ...new Set([...topologyIds.values()].flatMap((ids) => ids.vertexId)),\n ],\n };\n const fieldContext = {\n ...referenceContext,\n ids: {\n ...referenceContext.ids,\n ...geometryIds,\n playerId: playerIds,\n boardId: boardIds,\n },\n };\n const key = JSON.stringify([\n playerIds,\n [...boardEntries].sort(([a], [b]) => a.localeCompare(b)),\n [...topologyIds].sort(([a], [b]) => a.localeCompare(b)),\n ]);\n if (!resolveSession || key !== sessionKey) {\n const nextResolver = createFieldValidatorResolver((boardId) => ({\n ...fieldContext,\n ids: {\n ...fieldContext.ids,\n ...(boardId ? topologyIds.get(boardId) : geometryIds),\n },\n }));\n sessionKey = key;\n resolveSession = nextResolver;\n }\n const sessionResolver = resolveSession;\n const validateFields = (\n schema: FieldSchemaJson | null | undefined,\n value: unknown,\n path: PropertyKey[],\n boardId?: string,\n ) => {\n if (!schema) return;\n try {\n const result = sessionResolver(schema, boardId).safeParse(value);\n if (!result.success)\n for (const issue of result.error.issues)\n context.addIssue({\n code: \"custom\",\n path: [...path, ...issue.path],\n message: issue.message,\n });\n } catch (error) {\n context.addIssue({\n code: \"custom\",\n path,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n };\n for (const [id, card] of recordEntries(table.cards)) {\n const set = analysis.cardSets.find(\n (set) => set.id === analysis.cardSetIdByCardId.get(id),\n );\n if (set)\n validateFields(\n schemaForCardType(\n set.cardSchema,\n analysis.cardTypeByCardId.get(id)!,\n ),\n property(card, \"properties\"),\n [\"cards\", id, \"properties\"],\n );\n }\n for (const [id, piece] of recordEntries(table.pieces))\n validateFields(\n analysis.pieceTypeSchemasById.get(\n analysis.pieceTypeIdByPieceId.get(id)!,\n ),\n property(piece, \"properties\"),\n [\"pieces\", id, \"properties\"],\n );\n for (const [id, die] of recordEntries(table.dice))\n validateFields(\n analysis.dieTypeSchemasById.get(analysis.dieTypeIdByDieId.get(id)!),\n property(die, \"properties\"),\n [\"dice\", id, \"properties\"],\n );\n for (const [i, authored] of (analysis.manifest.boards ?? []).entries()) {\n for (const [runtimeId, baseId] of boardEntries) {\n if (baseId !== authored.id) continue;\n const definition = definitions.boardDefinitions[authored.id];\n validateFields(\n authored.boardFieldsSchema,\n definition.fields,\n [\"manifest\", \"boards\", i, \"fields\"],\n runtimeId,\n );\n if (\n authored.layout === \"generic\" &&\n definition.layout === \"generic\"\n ) {\n for (const [spaceId, space] of Object.entries(definition.spaces))\n validateFields(\n authored.spaceFieldsSchema,\n space.fields,\n [\"manifest\", \"boards\", i, \"spaces\", spaceId, \"fields\"],\n runtimeId,\n );\n }\n }\n }\n for (const [i, type] of (analysis.manifest.tileTypes ?? []).entries()) {\n validateFields(type.fieldsSchema, type.fields ?? {}, [\n \"manifest\",\n \"tileTypes\",\n i,\n \"fields\",\n ]);\n for (const [j, cell] of type.cells.entries())\n validateFields(type.cellFieldsSchema, cell.fields ?? {}, [\n \"manifest\",\n \"tileTypes\",\n i,\n \"cells\",\n j,\n \"fields\",\n ]);\n for (const [j, edge] of (type.edges ?? []).entries())\n validateFields(type.edgeFieldsSchema, edge.fields ?? {}, [\n \"manifest\",\n \"tileTypes\",\n i,\n \"edges\",\n j,\n \"fields\",\n ]);\n for (const [j, vertex] of (type.vertices ?? []).entries())\n validateFields(type.vertexFieldsSchema, vertex.fields ?? {}, [\n \"manifest\",\n \"tileTypes\",\n i,\n \"vertices\",\n j,\n \"fields\",\n ]);\n }\n for (const [id, tile] of recordEntries(table.tiles))\n validateFields(\n analysis.tilePropertiesSchemasById.get(\n analysis.tileTypeIdByTileId.get(id)!,\n ),\n property(tile, \"properties\"),\n [\"tiles\", id, \"properties\"],\n );\n for (const [id, board] of Object.entries(table.boards)) {\n const declaration = analysis.analyzedBoards.find(\n (item) => item.board.id === board.baseId,\n );\n if (declaration)\n for (const [index, relation] of board.relations.entries())\n validateFields(\n declaration.relationFieldsSchema,\n relation.fields,\n [\"boards\", id, \"relations\", index, \"fields\"],\n id,\n );\n }\n for (const [id, location] of Object.entries(table.componentLocations)) {\n if (location.type !== \"OnBoard\") continue;\n const tile = Object.hasOwn(table.tiles, id)\n ? table.tiles[id]\n : undefined;\n const board = Object.hasOwn(table.boards, location.boardId)\n ? table.boards[location.boardId]\n : undefined;\n const tileDefinition =\n tile && Object.hasOwn(definitions.tileDefinitions, tile.tileTypeId)\n ? definitions.tileDefinitions[tile.tileTypeId]\n : undefined;\n const boardDefinition =\n board && Object.hasOwn(definitions.boardDefinitions, board.baseId)\n ? definitions.boardDefinitions[board.baseId]\n : undefined;\n if (\n !tile ||\n !tileDefinition ||\n !boardDefinition ||\n boardDefinition.layout === \"generic\" ||\n (tile?.disclosure.appearance !== undefined &&\n tile.disclosure.appearance.layout !== location.layout) ||\n tileDefinition.layout !== location.layout ||\n boardDefinition.layout !== location.layout\n )\n context.addIssue({\n code: \"custom\",\n path: [\"componentLocations\", id],\n message: \"OnBoard requires a tile and matching tiled board layout.\",\n });\n }\n for (const [id, tile] of Object.entries(table.tiles)) {\n const location = table.componentLocations[id];\n if (location?.type !== \"OnBoard\" || !tile.disclosure.appearance)\n continue;\n try {\n getPublicTileFootprint(tile.disclosure.appearance, location);\n } catch (error) {\n context.addIssue({\n code: \"custom\",\n path: [\"tiles\", id, \"disclosure\", \"appearance\"],\n message: error instanceof Error ? error.message : String(error),\n });\n }\n }\n checkPlayers(table.resources, [\"resources\"]);\n try {\n assertZoneConsistency(table, definitions);\n } catch (error) {\n context.addIssue({\n code: \"custom\",\n path: [\"zones\"],\n message: error instanceof Error ? error.message : String(error),\n });\n }\n });\n}\n","import * as z from \"zod\";\nimport {\n defineHex,\n Grid,\n ring as ringTraversal,\n rectangle as rectangleTraversal,\n spiral as spiralTraversal,\n} from \"honeycomb-grid\";\nimport { MAXIMUM_BOARD_COORDINATE } from \"../../shared/domain/board-coordinates.js\";\n\ntype Coordinate = { readonly q: number; readonly r: number };\ntype TileIdentity = {\n readonly boardId: string;\n readonly tileTypeId: string;\n readonly tileId: string;\n readonly name?: string;\n};\ntype CoordinateCell<C extends Coordinate> = C extends Coordinate\n ? { id: `${C[\"q\"]},${C[\"r\"]}`; at: { q: C[\"q\"]; r: C[\"r\"] } }\n : never;\nconst coordinate = z.strictObject({\n q: z.int().min(-MAXIMUM_BOARD_COORDINATE).max(MAXIMUM_BOARD_COORDINATE),\n r: z.int().min(-MAXIMUM_BOARD_COORDINATE).max(MAXIMUM_BOARD_COORDINATE),\n});\nconst radius = z.int().nonnegative().max(MAXIMUM_BOARD_COORDINATE);\nconst dimension = z.int().positive().max(MAXIMUM_BOARD_COORDINATE);\n/** Fixed boards use the same definitions and seeded placements as movable inventory. */\nexport function fromCoordinates<\n const Options extends TileIdentity & {\n readonly coordinates: readonly Coordinate[];\n },\n>(options: Options) {\n z.array(coordinate).nonempty().parse(options.coordinates);\n const tileTypeId: Options[\"tileTypeId\"] = options.tileTypeId;\n const tileId: Options[\"tileId\"] = options.tileId;\n const boardId: Options[\"boardId\"] = options.boardId;\n return {\n tileTypes: [\n {\n id: tileTypeId,\n name: options.name ?? tileTypeId,\n layout: \"hex\" as const,\n // Array.map loses the correlation between each coordinate pair and its ID.\n // Every result is built from that same validated pair, preserving the witness.\n cells: options.coordinates.map((at) => ({\n id: `${at.q},${at.r}` as const,\n at: { q: at.q, r: at.r },\n })) as CoordinateCell<Options[\"coordinates\"][number]>[],\n },\n ],\n tileSeeds: [\n {\n id: tileId,\n typeId: tileTypeId,\n home: {\n type: \"board\" as const,\n boardId,\n layout: \"hex\" as const,\n q: 0,\n r: 0,\n rotation: 0 as const,\n },\n },\n ],\n };\n}\nconst Hex = defineHex();\ntype RadiusOptions = TileIdentity & {\n readonly radius: number;\n readonly center?: Coordinate;\n};\nfunction checkedRadius(options: RadiusOptions) {\n radius.parse(options.radius);\n const center = coordinate.parse(options.center ?? { q: 0, r: 0 });\n for (const axis of [center.q, center.r]) {\n coordinate.shape.q.parse(axis + options.radius);\n coordinate.shape.q.parse(axis - options.radius);\n }\n return center;\n}\nexport function hexagon<const Options extends RadiusOptions>(options: Options) {\n const center = checkedRadius(options);\n const coordinates = Array.from(\n new Grid(Hex, spiralTraversal({ radius: options.radius, start: center })),\n (hex) => ({ q: hex.q, r: hex.r }),\n );\n return fromCoordinates({ ...options, coordinates });\n}\nexport function spiral<const Options extends RadiusOptions>(options: Options) {\n return hexagon(options);\n}\nexport function ring<const Options extends RadiusOptions>(options: Options) {\n const center = checkedRadius(options);\n const coordinates = Array.from(\n new Grid(Hex, ringTraversal({ radius: options.radius, center })),\n (hex) => ({ q: hex.q, r: hex.r }),\n );\n return fromCoordinates({ ...options, coordinates });\n}\nexport function rectangle<\n const Options extends TileIdentity & {\n readonly width: number;\n readonly height: number;\n readonly start?: Coordinate;\n },\n>(options: Options) {\n dimension.parse(options.width);\n dimension.parse(options.height);\n const start = coordinate.parse(options.start ?? { q: 0, r: 0 });\n coordinate.shape.q.parse(start.q + options.width + options.height);\n coordinate.shape.r.parse(start.r + options.height);\n const coordinates = Array.from(\n new Grid(\n Hex,\n rectangleTraversal({\n width: options.width,\n height: options.height,\n start,\n }),\n ),\n (hex) => ({ q: hex.q, r: hex.r }),\n );\n return fromCoordinates({ ...options, coordinates });\n}\n","import type { AuthoredTileDisclosure } from \"../../shared/domain/tile-disclosure.js\";\nimport type { SchemaAuthoring, TileSpaceIds } from \"./types\";\nimport { toManifestJson, type FieldsInput } from \"./field-schemas\";\nimport { parseTopologyManifestJson } from \"./parse-json\";\nimport type { ValidatedManifest } from \"./types\";\nimport type {\n ManifestCountValidation,\n RuntimeIdsFromCount,\n} from \"./identity-types\";\nimport type {\n BoardEdgeRef,\n BoardVertexRef,\n GameTopologyManifest as ApiGameTopologyManifest,\n} from \"../../shared/domain/contracts.js\";\n\ntype GameTopologyManifest = SchemaAuthoring<ApiGameTopologyManifest>;\n\ntype ArrayItem<T> = T extends readonly (infer Item)[] ? Item : never;\ntype EntryId<T> = T extends { id: infer Id extends string } ? Id : never;\ntype IdsOf<T> = EntryId<ArrayItem<NonNullable<T>>>;\n\ntype CardSetId<Manifest extends GameTopologyManifest> = IdsOf<\n Manifest[\"cardSets\"]\n>;\ntype BoardId<Manifest extends GameTopologyManifest> = IdsOf<Manifest[\"boards\"]>;\ntype PerPlayerBoardId<Manifest extends GameTopologyManifest> = EntryId<\n Extract<ArrayItem<NonNullable<Manifest[\"boards\"]>>, { scope: \"perPlayer\" }>\n>;\ntype SharedBoardId<Manifest extends GameTopologyManifest> = Exclude<\n BoardId<Manifest>,\n PerPlayerBoardId<Manifest>\n>;\ntype PieceTypeId<Manifest extends GameTopologyManifest> = IdsOf<\n Manifest[\"pieceTypes\"]\n>;\ntype DieTypeId<Manifest extends GameTopologyManifest> = IdsOf<\n Manifest[\"dieTypes\"]\n>;\ntype PieceSeedOf<Manifest extends GameTopologyManifest> = ArrayItem<\n NonNullable<Manifest[\"pieceSeeds\"]>\n>;\ntype DieSeedOf<Manifest extends GameTopologyManifest> = ArrayItem<\n NonNullable<Manifest[\"dieSeeds\"]>\n>;\ntype BoardOf<\n Manifest extends GameTopologyManifest,\n CurrentBoardId extends BoardId<Manifest>,\n> = Extract<ArrayItem<NonNullable<Manifest[\"boards\"]>>, { id: CurrentBoardId }>;\ntype SpaceIdOf<BoardLike, Manifest> = BoardLike extends {\n layout: \"hex\" | \"square\";\n}\n ? TileSpaceIds<Manifest, BoardLike[\"layout\"]>\n : IdsOf<BoardLike extends { spaces?: infer Spaces } ? Spaces : never>;\ntype SpaceIdForBoard<\n Manifest extends GameTopologyManifest,\n CurrentBoardId extends BoardId<Manifest>,\n> = SpaceIdOf<BoardOf<Manifest, CurrentBoardId>, Manifest>;\ntype PieceTypeOf<\n Manifest extends GameTopologyManifest,\n T extends PieceTypeId<Manifest>,\n> = Extract<ArrayItem<NonNullable<Manifest[\"pieceTypes\"]>>, { id: T }>;\ntype DieTypeOf<\n Manifest extends GameTopologyManifest,\n T extends DieTypeId<Manifest>,\n> = Extract<ArrayItem<NonNullable<Manifest[\"dieTypes\"]>>, { id: T }>;\n\ntype TypedSharedSpaceHomeSpec<Manifest extends GameTopologyManifest> = {\n [CurrentBoardId in SharedBoardId<Manifest>]: {\n type: \"space\";\n boardId: CurrentBoardId;\n spaceId: SpaceIdForBoard<Manifest, CurrentBoardId>;\n };\n}[SharedBoardId<Manifest>];\n\ntype TypedPerPlayerSpaceHomeSpec<Manifest extends GameTopologyManifest> = {\n [CurrentBoardId in PerPlayerBoardId<Manifest>]: {\n type: \"space\";\n boardId: CurrentBoardId;\n spaceId: SpaceIdForBoard<Manifest, CurrentBoardId>;\n };\n}[PerPlayerBoardId<Manifest>];\n\ntype TypedSharedEdgeHomeSpec<Manifest extends GameTopologyManifest> = {\n [CurrentBoardId in SharedBoardId<Manifest>]: {\n type: \"edge\";\n boardId: CurrentBoardId;\n ref: SchemaAuthoring<BoardEdgeRef>;\n };\n}[SharedBoardId<Manifest>];\n\ntype TypedPerPlayerEdgeHomeSpec<Manifest extends GameTopologyManifest> = {\n [CurrentBoardId in PerPlayerBoardId<Manifest>]: {\n type: \"edge\";\n boardId: CurrentBoardId;\n ref: SchemaAuthoring<BoardEdgeRef>;\n };\n}[PerPlayerBoardId<Manifest>];\n\ntype TypedSharedVertexHomeSpec<Manifest extends GameTopologyManifest> = {\n [CurrentBoardId in SharedBoardId<Manifest>]: {\n type: \"vertex\";\n boardId: CurrentBoardId;\n ref: SchemaAuthoring<BoardVertexRef>;\n };\n}[SharedBoardId<Manifest>];\n\ntype TypedPerPlayerVertexHomeSpec<Manifest extends GameTopologyManifest> = {\n [CurrentBoardId in PerPlayerBoardId<Manifest>]: {\n type: \"vertex\";\n boardId: CurrentBoardId;\n ref: SchemaAuthoring<BoardVertexRef>;\n };\n}[PerPlayerBoardId<Manifest>];\n\ntype ExpandedSeedId<Seed> = Seed extends { typeId: infer T extends string }\n ? RuntimeIdsFromCount<\n Seed extends { id: infer I extends string } ? I : T,\n Seed extends { count: infer C } ? C : never\n >\n : never;\ntype ZoneHomeFor<\n Zone,\n Manifest extends GameTopologyManifest,\n Shared extends boolean,\n> = Zone extends { id: infer Z extends string }\n ? Zone extends { scope: \"shared\" }\n ? { type: \"zone\"; zoneId: Z; component?: never }\n : Zone extends { scope: \"perPlayer\" }\n ? Shared extends true\n ? never\n : { type: \"zone\"; zoneId: Z; component?: never }\n : Zone extends { attachedTo: { board: infer B } }\n ? B extends SharedBoardId<Manifest>\n ? { type: \"zone\"; zoneId: Z; component?: never }\n : Shared extends true\n ? never\n : { type: \"zone\"; zoneId: Z; component?: never }\n : Zone extends { attachedTo: { pieceType: infer T } }\n ? ComponentZoneHome<\n Z,\n Extract<PieceSeedOf<Manifest>, { typeId: T }>,\n Shared\n >\n : Zone extends { attachedTo: { dieType: infer T } }\n ? ComponentZoneHome<\n Z,\n Extract<DieSeedOf<Manifest>, { typeId: T }>,\n Shared\n >\n : Zone extends { attachedTo: { tileType: infer T } }\n ? ComponentZoneHome<\n Z,\n Extract<ArrayItem<Manifest[\"tileSeeds\"]>, { typeId: T }>,\n Shared\n >\n : never\n : never;\ntype ComponentZoneHome<Z extends string, Seed, Shared extends boolean> = (\n Shared extends true ? Exclude<Seed, { scope: \"perPlayer\" }> : Seed\n) extends infer Host\n ? Host extends object\n ? { type: \"zone\"; zoneId: Z; component: ExpandedSeedId<Host> }\n : never\n : never;\ntype TypedSharedZoneHomeSpec<Manifest extends GameTopologyManifest> =\n ZoneHomeFor<ArrayItem<NonNullable<Manifest[\"zones\"]>>, Manifest, true>;\ntype TypedPerPlayerZoneHomeSpec<Manifest extends GameTopologyManifest> =\n ZoneHomeFor<ArrayItem<NonNullable<Manifest[\"zones\"]>>, Manifest, false>;\n\ntype TypedPlayerScopedComponentHomeSpec<Manifest extends GameTopologyManifest> =\n | TypedPerPlayerZoneHomeSpec<Manifest>\n | TypedPerPlayerSpaceHomeSpec<Manifest>\n | TypedPerPlayerEdgeHomeSpec<Manifest>\n | TypedPerPlayerVertexHomeSpec<Manifest>;\n\ntype TypedSharedComponentHomeSpec<Manifest extends GameTopologyManifest> =\n | { type: \"detached\" }\n | TypedSharedZoneHomeSpec<Manifest>\n | TypedSharedSpaceHomeSpec<Manifest>\n | TypedSharedEdgeHomeSpec<Manifest>\n | TypedSharedVertexHomeSpec<Manifest>;\n\ntype TypedComponentHomeSpec<Manifest extends GameTopologyManifest> =\n | TypedSharedComponentHomeSpec<Manifest>\n | TypedPlayerScopedComponentHomeSpec<Manifest>;\n\ntype TypedSeedLocationSpec<Seed, Manifest extends GameTopologyManifest> = Omit<\n Seed,\n \"home\"\n> & {\n home?: Seed extends { scope: \"perPlayer\" }\n ? TypedComponentHomeSpec<Manifest>\n : TypedSharedComponentHomeSpec<Manifest>;\n};\ntype AuthoredComponent<T> = Omit<T, \"ownerId\" | \"visibility\"> & {\n ownerId?: never;\n visibility?: { faceUp?: boolean; visibleTo?: never };\n};\ntype TypedFields<\n T,\n Schema,\n Manifest extends GameTopologyManifest,\n BoardLike = never,\n> = T extends { fields?: unknown }\n ? Omit<T, \"fields\"> & {\n fields?: FieldsInput<Schema, Manifest, BoardLike>;\n }\n : T;\ntype TypedBoardRelation<\n Relation,\n Manifest extends GameTopologyManifest,\n BoardLike,\n RelationSchema,\n> = Relation extends object\n ? Omit<\n TypedFields<Relation, RelationSchema, Manifest, BoardLike>,\n \"fromSpaceId\" | \"toSpaceId\"\n > & {\n fromSpaceId: SpaceIdOf<BoardLike, Manifest>;\n toSpaceId: SpaceIdOf<BoardLike, Manifest>;\n }\n : Relation;\ntype TypedOptionalArray<\n Base,\n Source,\n Key extends string,\n Item,\n> = Source extends { [Property in Key]?: readonly unknown[] }\n ? Base & {\n [Property in Key]?: ReadonlyArray<Item>;\n }\n : Base;\ntype SchemaForEntry<Entry, Key extends string> = Key extends keyof Entry\n ? Entry[Key]\n : undefined;\ntype TypedGenericBoardLike<\n Entry,\n Manifest extends GameTopologyManifest,\n BoardLike,\n> = TypedOptionalArray<\n TypedOptionalArray<\n TypedFields<\n Omit<Entry, \"spaces\" | \"relations\">,\n SchemaForEntry<Entry, \"boardFieldsSchema\">,\n Manifest,\n BoardLike\n >,\n Entry,\n \"spaces\",\n TypedFields<\n ArrayItem<NonNullable<Entry extends { spaces?: infer S } ? S : never>>,\n SchemaForEntry<Entry, \"spaceFieldsSchema\">,\n Manifest,\n BoardLike\n >\n >,\n Entry,\n \"relations\",\n TypedBoardRelation<\n ArrayItem<NonNullable<Entry extends { relations?: infer R } ? R : never>>,\n Manifest,\n BoardLike,\n SchemaForEntry<Entry, \"relationFieldsSchema\">\n >\n>;\ntype AuthoredKeys<T> = {\n [K in keyof T]-?: Record<never, never> extends Pick<T, K>\n ? [Exclude<T[K], undefined>] extends [never]\n ? never\n : K\n : K;\n}[keyof T];\ntype TypedBoardLikeEntry<Entry, Manifest extends GameTopologyManifest> =\n | \"containers\"\n | \"containerFieldsSchema\"\n | \"shape\"\n | \"exclude\"\n | \"edges\"\n | \"vertices\"\n | \"edgeFieldsSchema\"\n | \"vertexFieldsSchema\" extends infer Legacy\n ? Extract<Legacy, AuthoredKeys<Entry>> extends never\n ? Entry extends { layout: \"generic\" }\n ? TypedGenericBoardLike<Entry, Manifest, Entry>\n : \"spaces\" | \"spaceFieldsSchema\" extends infer Geometry\n ? Extract<Geometry, AuthoredKeys<Entry>> extends never\n ? TypedFields<\n Entry,\n SchemaForEntry<Entry, \"boardFieldsSchema\">,\n Manifest,\n Entry\n >\n : never\n : never\n : never\n : never;\n\ntype AuthoredCardType<Card> = Card extends {\n cardType: infer Category extends string;\n}\n ? Category\n : never;\ntype TypedCard<\n Card,\n Manifest extends GameTopologyManifest,\n CardSchema,\n> = Card extends { id: string; cardType: string }\n ? Omit<AuthoredComponent<Card>, \"home\" | \"properties\"> & {\n home?: Card extends { scope: \"perPlayer\" }\n ? TypedComponentHomeSpec<Manifest>\n : TypedSharedComponentHomeSpec<Manifest>;\n properties: CardSchema extends {\n byCardType: infer Variants extends Record<string, unknown>;\n }\n ? AuthoredCardType<Card> extends keyof Variants\n ? FieldsInput<Variants[AuthoredCardType<Card>], Manifest>\n : never\n : FieldsInput<CardSchema, Manifest>;\n }\n : Card;\n\ntype TypedCardSet<\n CardSet,\n Manifest extends GameTopologyManifest,\n> = CardSet extends {\n cardSchema: infer CardSchema;\n cards: infer Cards extends readonly unknown[];\n}\n ? Omit<CardSet, \"cards\" | \"defaultHome\"> & {\n defaultHome: TypedComponentHomeSpec<Manifest>;\n cards: ReadonlyArray<TypedCard<ArrayItem<Cards>, Manifest, CardSchema>>;\n }\n : CardSet;\n\ntype TypedAllowedCardSetIds<\n T,\n Manifest extends GameTopologyManifest,\n> = T extends object\n ? Omit<T, \"allowedCardSetIds\"> & {\n allowedCardSetIds?: readonly CardSetId<Manifest>[];\n }\n : T;\n\ntype TypedZone<\n Zone,\n Manifest extends GameTopologyManifest,\n> = TypedAllowedCardSetIds<Zone, Manifest> &\n (Zone extends { attachedTo: infer A }\n ? {\n attachedTo: A extends { board: infer B }\n ? B extends BoardId<Manifest>\n ? A extends { space: unknown }\n ? BoardOf<Manifest, B> extends { layout: \"generic\" }\n ? { board: B; space: SpaceIdForBoard<Manifest, B> }\n : never\n : { board: B }\n : never\n : A extends { pieceType: unknown }\n ? { pieceType: PieceTypeId<Manifest> }\n : A extends { dieType: unknown }\n ? { dieType: DieTypeId<Manifest> }\n : A extends { tileType: infer T }\n ? {\n tileType: T;\n cell: IdsOf<\n Extract<\n ArrayItem<Manifest[\"tileTypes\"]>,\n { id: T }\n >[\"cells\"]\n >;\n }\n : never;\n }\n : unknown);\n\ntype TypedPieceSeed<\n Seed,\n Manifest extends GameTopologyManifest,\n> = Seed extends { typeId: infer CurrentTypeId }\n ? CurrentTypeId extends PieceTypeId<Manifest>\n ? Omit<\n TypedSeedLocationSpec<AuthoredComponent<Seed>, Manifest>,\n \"typeId\" | \"home\" | \"fields\"\n > & {\n typeId: CurrentTypeId;\n fields?: FieldsInput<\n PieceTypeOf<Manifest, CurrentTypeId> extends {\n fieldsSchema?: infer FieldsSchema;\n }\n ? FieldsSchema\n : undefined,\n Manifest\n >;\n } & Pick<TypedSeedLocationSpec<AuthoredComponent<Seed>, Manifest>, \"home\">\n : Omit<Seed, \"typeId\"> & {\n typeId: PieceTypeId<Manifest>;\n }\n : never;\n\ntype TypedDieSeed<Seed, Manifest extends GameTopologyManifest> = Seed extends {\n typeId: infer CurrentTypeId;\n}\n ? CurrentTypeId extends DieTypeId<Manifest>\n ? Omit<\n TypedSeedLocationSpec<AuthoredComponent<Seed>, Manifest>,\n \"typeId\" | \"home\" | \"fields\"\n > & {\n typeId: CurrentTypeId;\n fields?: FieldsInput<\n DieTypeOf<Manifest, CurrentTypeId> extends {\n fieldsSchema?: infer FieldsSchema;\n }\n ? FieldsSchema\n : undefined,\n Manifest\n >;\n } & Pick<TypedSeedLocationSpec<AuthoredComponent<Seed>, Manifest>, \"home\">\n : Omit<Seed, \"typeId\"> & {\n typeId: DieTypeId<Manifest>;\n }\n : never;\n\ntype TileTypeId<Manifest extends GameTopologyManifest> = IdsOf<\n Manifest[\"tileTypes\"]\n>;\ntype TypedTileType<T, Manifest extends GameTopologyManifest> = T extends object\n ? Omit<\n TypedFields<T, SchemaForEntry<T, \"fieldsSchema\">, Manifest>,\n \"cells\" | \"edges\" | \"vertices\"\n > & {\n cells: ReadonlyArray<\n TypedFields<\n ArrayItem<T extends { cells: infer C } ? C : never>,\n SchemaForEntry<T, \"cellFieldsSchema\">,\n Manifest\n >\n >;\n edges?: ReadonlyArray<\n TypedFields<\n ArrayItem<T extends { edges?: infer E } ? E : never>,\n SchemaForEntry<T, \"edgeFieldsSchema\">,\n Manifest\n > & { cellId: IdsOf<T extends { cells: infer C } ? C : never> }\n >;\n vertices?: ReadonlyArray<\n TypedFields<\n ArrayItem<T extends { vertices?: infer V } ? V : never>,\n SchemaForEntry<T, \"vertexFieldsSchema\">,\n Manifest\n > & { cellId: IdsOf<T extends { cells: infer C } ? C : never> }\n >;\n }\n : never;\ntype TileBoardHome<Seed, Manifest extends GameTopologyManifest, T> =\n ArrayItem<Manifest[\"boards\"]> extends infer B\n ? B extends { id: infer I; layout: infer L extends \"hex\" | \"square\" }\n ? Extract<ArrayItem<Manifest[\"tileTypes\"]>, { id: T }> extends {\n layout: L;\n }\n ? Seed extends { scope: \"perPlayer\" }\n ? TileBoardCoordinates<L> & { type: \"board\"; boardId: I; layout: L }\n : B extends { scope: \"shared\" }\n ? TileBoardCoordinates<L> & { type: \"board\"; boardId: I; layout: L }\n : never\n : never\n : never\n : never;\ntype TileBoardCoordinates<L> = L extends \"hex\"\n ? { q: number; r: number; rotation: 0 | 1 | 2 | 3 | 4 | 5 }\n : { col: number; row: number; rotation: 0 | 1 | 2 | 3 };\ntype TypedTileSeed<Seed, Manifest extends GameTopologyManifest> = Seed extends {\n typeId: infer T;\n}\n ? Omit<\n Seed,\n \"typeId\" | \"properties\" | \"home\" | \"ownerId\" | \"visibility\" | \"disclosure\"\n > & {\n ownerId?: never;\n visibility?: never;\n disclosure?: SchemaAuthoring<AuthoredTileDisclosure>;\n typeId: TileTypeId<Manifest>;\n properties?: FieldsInput<\n SchemaForEntry<\n Extract<ArrayItem<Manifest[\"tileTypes\"]>, { id: T }>,\n \"propertiesSchema\"\n >,\n Manifest\n >;\n home?:\n | { type: \"detached\" }\n | TileBoardHome<Seed, Manifest, T>\n | ZoneHomeFor<\n ArrayItem<NonNullable<Manifest[\"zones\"]>>,\n Manifest,\n Seed extends { scope: \"perPlayer\" } ? false : true\n >;\n }\n : never;\n\nexport type TypedTopologyManifest<Manifest extends GameTopologyManifest> = Omit<\n Manifest,\n | \"cardSets\"\n | \"zones\"\n | \"boards\"\n | \"pieceTypes\"\n | \"dieTypes\"\n | \"pieceSeeds\"\n | \"dieSeeds\"\n | \"tileTypes\"\n | \"tileSeeds\"\n> & {\n tileTypes?: ReadonlyArray<\n TypedTileType<ArrayItem<Manifest[\"tileTypes\"]>, Manifest>\n >;\n tileSeeds?: ReadonlyArray<\n TypedTileSeed<ArrayItem<Manifest[\"tileSeeds\"]>, Manifest>\n >;\n pieceTypes?: ReadonlyArray<\n ArrayItem<Manifest[\"pieceTypes\"]> extends infer T\n ? \"slots\" extends keyof T\n ? never\n : T\n : never\n >;\n dieTypes?: ReadonlyArray<\n ArrayItem<Manifest[\"dieTypes\"]> extends infer T\n ? \"slots\" extends keyof T\n ? never\n : T\n : never\n >;\n cardSets: ReadonlyArray<\n TypedCardSet<ArrayItem<Manifest[\"cardSets\"]>, Manifest>\n >;\n zones?: Manifest[\"zones\"] extends readonly unknown[]\n ? ReadonlyArray<TypedZone<ArrayItem<Manifest[\"zones\"]>, Manifest>>\n : Manifest[\"zones\"];\n boards?: Manifest[\"boards\"] extends readonly unknown[]\n ? ReadonlyArray<\n TypedBoardLikeEntry<ArrayItem<Manifest[\"boards\"]>, Manifest>\n >\n : Manifest[\"boards\"];\n pieceSeeds?: Manifest[\"pieceSeeds\"] extends readonly unknown[]\n ? ReadonlyArray<TypedPieceSeed<ArrayItem<Manifest[\"pieceSeeds\"]>, Manifest>>\n : Manifest[\"pieceSeeds\"];\n dieSeeds?: Manifest[\"dieSeeds\"] extends readonly unknown[]\n ? ReadonlyArray<TypedDieSeed<ArrayItem<Manifest[\"dieSeeds\"]>, Manifest>>\n : Manifest[\"dieSeeds\"];\n};\n\nexport type TopologyManifestValidation<Manifest> =\n Manifest extends GameTopologyManifest\n ? TypedTopologyManifest<Manifest>\n : GameTopologyManifest;\n\nexport function defineTopologyManifest<const Manifest>(\n manifest: Manifest &\n TopologyManifestValidation<NoInfer<Manifest>> &\n ManifestCountValidation<NoInfer<Manifest>>,\n): ValidatedManifest<Manifest> {\n const validated = parseTopologyManifestJson(toManifestJson(manifest));\n // eslint-disable-next-line no-restricted-syntax -- Semantic validation establishes the JSON boundary and its authored-type witness.\n return validated as unknown as ValidatedManifest<Manifest>;\n}\n","export {\n type BoundInputBuilders,\n type BoundTargetPredicate,\n type ContractTypes,\n type GameAuthoring,\n type PhaseAuthoring,\n type PhaseTypes,\n} from \"./reducer/authoring/contract-authoring\";\nexport { createGame } from \"./reducer/authoring/game\";\nexport type {\n ReducerGameDefinition,\n ReducerGameDefinitionInput,\n} from \"./reducer/model\";\nexport { gameEvent } from \"./reducer/game-event\";\nexport type {\n GameEvent,\n GameEventDetail,\n InteractionRule,\n ReducerValidationResult,\n SystemActionEvent,\n ValidationIssue,\n} from \"./reducer/model\";\nexport {\n many,\n type BoardTargetPredicate,\n type CardTargetPredicate,\n type TileTargetPredicate,\n type ChoiceOptionsFactory,\n type ChoiceTargetOption,\n type ChoiceTargetPredicate,\n type ManyOptions,\n type BoardSpaceTarget,\n type PositionTarget,\n type TargetContext,\n type TargetPredicate,\n type TargetPredicateArgs,\n} from \"./reducer/inputs\";\nexport {\n normalizeCommandParams,\n sparseCounts,\n sparseMap,\n type SparseCounts,\n type SparseMap,\n} from \"./reducer/schema-helpers\";\nexport { FrameworkErrorCodes } from \"./reducer/model\";\nexport { createReducerBundle } from \"./reducer/bundle\";\nexport type { ReducerBundle, ReducerBundleOptions } from \"./reducer/bundle\";\nexport { noopDiagnosticsSink } from \"./reducer/diagnostics\";\nexport type {\n DispatchTraceSummaryEntry,\n ReducerDiagnosticEvent,\n ReducerDiagnosticsSink,\n} from \"./reducer/diagnostics\";\nexport type {\n ReducerTransaction,\n ReducerTransactionOutcome,\n RotateZoneArgs,\n} from \"./reducer/transaction\";\nexport { asPlayerId, isPlayerId, type PlayerId } from \"./reducer/per-player\";\nexport { memoize } from \"./reducer/memoize\";\n// Flat `getX` table helpers were removed from the public surface in favour\n// of the opinionated `q.*` namespace returned by `createTableQueries` /\n// `createStateQueries` (also injected into every reducer callback as `q`).\nexport {\n createTableQueries,\n createStateQueries,\n} from \"./reducer/table-queries\";\nexport type {\n TableQueries,\n TableQueriesOfState,\n GameOutcome,\n OutcomeResult,\n OutcomeScoreComponent,\n OutcomeStanding,\n OutcomeTieBreak,\n} from \"./reducer/model\";\n\nexport { compileManifest } from \"./reducer/manifest/compiler\";\nexport { parseTopologyManifestJson } from \"./reducer/manifest/parse-json\";\nexport type {\n AuthoredManifest,\n ValidatedManifest,\n CompiledManifest,\n ManifestIdsOf,\n ManifestTable,\n} from \"./reducer/manifest/types\";\n\nexport {\n hexagon,\n rectangle,\n ring,\n spiral,\n fromCoordinates,\n} from \"./reducer/manifest/hex-tiles\";\n\n/** Public worker ABI and wire schemas. */\nexport {\n assertReducerBundleContract,\n REDUCER_CONTRACT_VERSION,\n} from \"./shared/worker-contract\";\nexport type {\n MaybePromise,\n ReducerBundleContract,\n} from \"./shared/worker-contract\";\nexport type * as ReducerWire from \"./shared/runtime-types\";\nexport * as ReducerWireZod from \"./shared/runtime-schema\";\nexport { materializeManifestTable } from \"./reducer/manifest/materialize\";\n\nexport {\n defineTopologyManifest,\n type TypedTopologyManifest,\n} from \"./reducer/manifest/authoring.js\";\n\nexport type { GameTopologyManifest } from \"./shared/domain/manifest.js\";\nexport type {\n SquareBoardSpec,\n TileTypeSpec,\n TileSeedSpec,\n PublicTileAppearance,\n TileFaceAudience,\n AuthoredTileFaceAudience,\n TileDisclosure,\n AuthoredTileDisclosure,\n} from \"./shared/domain/contracts.js\";\n\nexport type {\n SeatTileRef,\n SeatSpaceRef,\n} from \"./shared/domain/seat-reference.js\";\n\nexport * as z from \"zod\";\nexport { ref } from \"./reducer/manifest/field-schemas\";\nexport type {\n FieldSchema,\n FieldsInput,\n FieldsOutput,\n} from \"./reducer/manifest/field-schemas\";\n\nexport {\n perPlayerInstanceId,\n parsePerPlayerInstanceId,\n type PerPlayerInstanceId,\n type PerPlayerInstanceFamily,\n} from \"./shared/domain/per-player-instance.js\";\n\nexport {\n boardSpaceHostId,\n parseBoardSpaceHostId,\n type BoardSpaceHostId,\n} from \"./shared/domain/board-space-host.js\";\n\nexport {\n tileSpaceId,\n parseTileSpaceId,\n type TileSpaceId,\n} from \"./shared/domain/tile-space.js\";\nexport {\n boardEdgeId,\n boardVertexId,\n parseBoardElementId,\n} from \"./shared/domain/board-element.js\";\nexport type {\n BoardEdgeId,\n BoardVertexId,\n} from \"./shared/domain/board-identities.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,2BAA2B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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gB,EAAE,GAAG,SAAS,YAAY,CAAC;AACpD;;;ACgbO,SAAS,uBACd,UAG6B;AAC7B,QAAM,YAAY,0BAA0B,eAAe,QAAQ,CAAC;AAEpE,SAAO;AACT;;;ACjbA,YAAYC,SAAO;","names":["z","z","z","z","z","z","z","z","z","json","family","check","board","zoneIds","analysis","seed","zone","board","type","z","z","isRecord","record","ids","set","id","z","z"]}