viborm 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-namespace-BpMbLKpL.mjs → adapter-namespace-B8XWzCev.mjs} +1 -1
- package/dist/{adapter-namespace-BpMbLKpL.mjs.map → adapter-namespace-B8XWzCev.mjs.map} +1 -1
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/{batch-refs-B4zn-FAu.mjs → batch-refs-DoWlPD2h.mjs} +1 -1
- package/dist/{batch-refs-B4zn-FAu.mjs.map → batch-refs-DoWlPD2h.mjs.map} +1 -1
- package/dist/{builder-Df24l2Bd.mjs → builder-DhxaVYP2.mjs} +2 -2
- package/dist/{builder-Df24l2Bd.mjs.map → builder-DhxaVYP2.mjs.map} +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/cloudflare-kv.mjs +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache/memory.mjs +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cache.mjs +1 -1
- package/dist/cache.mjs.map +1 -1
- package/dist/chain-BjJ_M7EE.mjs +2 -0
- package/dist/chain-BjJ_M7EE.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/client-BCgMXn6N.mjs +2 -0
- package/dist/client-BCgMXn6N.mjs.map +1 -0
- package/dist/{client-70MrTq1E.d.mts → client-Df81J4oB.d.mts} +1 -1
- package/dist/{client-DM1UHfYG.mjs → client-q6ccRgdO.mjs} +2 -2
- package/dist/{client-DM1UHfYG.mjs.map → client-q6ccRgdO.mjs.map} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{clock-C24RcpwO.mjs → clock-YTLtjLFS.mjs} +1 -1
- package/dist/{clock-C24RcpwO.mjs.map → clock-YTLtjLFS.mjs.map} +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/{driver-CPD0Xxw2.mjs → driver-D6_Ik58x.mjs} +2 -2
- package/dist/{driver-CPD0Xxw2.mjs.map → driver-D6_Ik58x.mjs.map} +1 -1
- package/dist/{driver-B9fIori_.mjs → driver-Ddt147dK.mjs} +2 -2
- package/dist/{driver-B9fIori_.mjs.map → driver-Ddt147dK.mjs.map} +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/driver.mjs +1 -1
- package/dist/every-dpzVDwzu.mjs +2 -0
- package/dist/{every-1pKZteeB.mjs.map → every-dpzVDwzu.mjs.map} +1 -1
- package/dist/{fs-estate-i8Zlr1OQ.mjs → fs-estate-azK36i9V.mjs} +2 -2
- package/dist/{fs-estate-i8Zlr1OQ.mjs.map → fs-estate-azK36i9V.mjs.map} +1 -1
- package/dist/{hydration-DsyHNSDS.mjs → hydration-C2uXmJy6.mjs} +2 -2
- package/dist/{hydration-DsyHNSDS.mjs.map → hydration-C2uXmJy6.mjs.map} +1 -1
- package/dist/{identifier-conversion-DaZ9yNpv.mjs → identifier-conversion-C2pwwFOS.mjs} +2 -2
- package/dist/{identifier-conversion-DaZ9yNpv.mjs.map → identifier-conversion-C2pwwFOS.mjs.map} +1 -1
- package/dist/identity-Bj2EN6Ss.mjs +2 -0
- package/dist/identity-Bj2EN6Ss.mjs.map +1 -0
- package/dist/{index-VsM29vYN.d.mts → index-D4O0Twvs.d.mts} +16 -8
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{key-D_kagnFv.mjs → key-B7vuAYPG.mjs} +2 -2
- package/dist/{key-D_kagnFv.mjs.map → key-B7vuAYPG.mjs.map} +1 -1
- package/dist/{libsql-DFAoHXrI.mjs → libsql-DUO6vHad.mjs} +2 -2
- package/dist/{libsql-DFAoHXrI.mjs.map → libsql-DUO6vHad.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-GTWgeDNY.mjs → memory-BApsTkt1.mjs} +2 -2
- package/dist/{memory-GTWgeDNY.mjs.map → memory-BApsTkt1.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/storage/durable-object.mjs +1 -1
- package/dist/migrations/storage/fs.mjs +1 -1
- package/dist/migrations/storage/r2.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-xChEivOe.mjs → mysql-D1GlcktG.mjs} +2 -2
- package/dist/{mysql-xChEivOe.mjs.map → mysql-D1GlcktG.mjs.map} +1 -1
- package/dist/{mysql-adapter-C6c5govr.mjs → mysql-adapter-ClOoHKpn.mjs} +2 -2
- package/dist/{mysql-adapter-C6c5govr.mjs.map → mysql-adapter-ClOoHKpn.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-D9mvOHP4.d.mts → object-store-BN64q8Zn.d.mts} +3 -3
- package/dist/{object-store-ChYHlOMD.mjs → object-store-CZADAv4c.mjs} +2 -2
- package/dist/{object-store-ChYHlOMD.mjs.map → object-store-CZADAv4c.mjs.map} +1 -1
- package/dist/permissions.d.mts +2 -2
- package/dist/permissions.mjs +1 -1
- package/dist/permissions.mjs.map +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/{pinned-session-BTplL3iZ.mjs → pinned-session-CjvR0Ge2.mjs} +2 -2
- package/dist/{pinned-session-BTplL3iZ.mjs.map → pinned-session-CjvR0Ge2.mjs.map} +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C1NzLBge.d.mts → planner-8smxUOt9.d.mts} +1 -1
- package/dist/{postgres-BqAxDWTQ.mjs → postgres-Be0jMJWI.mjs} +2 -2
- package/dist/{postgres-BqAxDWTQ.mjs.map → postgres-Be0jMJWI.mjs.map} +1 -1
- package/dist/{postgres-adapter-CxEit2-v.mjs → postgres-adapter-BoQ4RRwr.mjs} +2 -2
- package/dist/{postgres-adapter-CxEit2-v.mjs.map → postgres-adapter-BoQ4RRwr.mjs.map} +1 -1
- package/dist/{postgres-adapter-CGthb5yh.mjs → postgres-adapter-C_Mt8lVC.mjs} +2 -2
- package/dist/{postgres-adapter-CGthb5yh.mjs.map → postgres-adapter-C_Mt8lVC.mjs.map} +1 -1
- package/dist/{postgres-result-KyBKBNJr.mjs → postgres-result-CYu1dyI_.mjs} +1 -1
- package/dist/{postgres-result-KyBKBNJr.mjs.map → postgres-result-CYu1dyI_.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/result-shape-DQc-tDJ5.mjs +2 -0
- package/dist/{result-shape-CDgX_vzn.mjs.map → result-shape-DQc-tDJ5.mjs.map} +1 -1
- package/dist/rows-JXjhWwyb.mjs +2 -0
- package/dist/rows-JXjhWwyb.mjs.map +1 -0
- package/dist/{scalar-S8yMvdmx.mjs → scalar-CqqZ6jWd.mjs} +2 -2
- package/dist/{scalar-S8yMvdmx.mjs.map → scalar-CqqZ6jWd.mjs.map} +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema/json.mjs +1 -1
- package/dist/{schema-9N9jQlVL.mjs → schema-Cv-hhpl5.mjs} +2 -2
- package/dist/{schema-9N9jQlVL.mjs.map → schema-Cv-hhpl5.mjs.map} +1 -1
- package/dist/{schema-introspection-CyXKReK1.mjs → schema-introspection-B2Rvqgut.mjs} +3 -3
- package/dist/{schema-introspection-CyXKReK1.mjs.map → schema-introspection-B2Rvqgut.mjs.map} +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/schema.mjs +1 -1
- package/dist/{select-assembly-CkGe2ABs.mjs → select-assembly-BxtETbG9.mjs} +1 -1
- package/dist/{select-assembly-CkGe2ABs.mjs.map → select-assembly-BxtETbG9.mjs.map} +1 -1
- package/dist/{settle-CS_k6Ztm.mjs → settle-etgtP1WM.mjs} +2 -2
- package/dist/{settle-CS_k6Ztm.mjs.map → settle-etgtP1WM.mjs.map} +1 -1
- package/dist/sha256-CEYo7k7R.mjs +2 -0
- package/dist/sha256-CEYo7k7R.mjs.map +1 -0
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sql-statement-tokens-CFi1y3bK.mjs → sql-statement-tokens-BW7Q-rF-.mjs} +1 -1
- package/dist/{sql-statement-tokens-CFi1y3bK.mjs.map → sql-statement-tokens-BW7Q-rF-.mjs.map} +1 -1
- package/dist/{sqlite-adapter-BXAJy3mI.mjs → sqlite-adapter-B_LNxPA0.mjs} +2 -2
- package/dist/{sqlite-adapter-BXAJy3mI.mjs.map → sqlite-adapter-B_LNxPA0.mjs.map} +1 -1
- package/dist/{sqlite-utils-D_cypcyW.mjs → sqlite-utils-DIOll4P7.mjs} +1 -1
- package/dist/{sqlite-utils-D_cypcyW.mjs.map → sqlite-utils-DIOll4P7.mjs.map} +1 -1
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/{standard-sql-CoGqv-iX.mjs → standard-sql-mJt0RHHE.mjs} +1 -1
- package/dist/{standard-sql-CoGqv-iX.mjs.map → standard-sql-mJt0RHHE.mjs.map} +1 -1
- package/dist/{to-many-C1PuFIpf.mjs → to-many-BSipkSbK.mjs} +2 -2
- package/dist/{to-many-C1PuFIpf.mjs.map → to-many-BSipkSbK.mjs.map} +1 -1
- package/dist/{utils-CtFUE8UN.mjs → utils-DjXObbUK.mjs} +2 -2
- package/dist/{utils-CtFUE8UN.mjs.map → utils-DjXObbUK.mjs.map} +1 -1
- package/dist/v-CrJYqdzu.mjs +2 -0
- package/dist/v-CrJYqdzu.mjs.map +1 -0
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/{validator-DgffZq9C.mjs → validator-BqzpyNmt.mjs} +2 -2
- package/dist/{validator-DgffZq9C.mjs.map → validator-BqzpyNmt.mjs.map} +1 -1
- package/dist/version-Dus3if78.mjs +2 -0
- package/dist/{version-CXuJzC-q.mjs.map → version-Dus3if78.mjs.map} +1 -1
- package/package.json +16 -15
- package/dist/chain-C7c1YTXD.mjs +0 -2
- package/dist/chain-C7c1YTXD.mjs.map +0 -1
- package/dist/client-_WKrPNmm.mjs +0 -2
- package/dist/client-_WKrPNmm.mjs.map +0 -1
- package/dist/controls-Da-efekX.mjs +0 -2
- package/dist/controls-Da-efekX.mjs.map +0 -1
- package/dist/every-1pKZteeB.mjs +0 -2
- package/dist/identity-oQvIe7u8.mjs +0 -2
- package/dist/identity-oQvIe7u8.mjs.map +0 -1
- package/dist/result-shape-CDgX_vzn.mjs +0 -2
- package/dist/v-CYTUI0H5.mjs +0 -2
- package/dist/v-CYTUI0H5.mjs.map +0 -1
- package/dist/version-CXuJzC-q.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validator-DgffZq9C.mjs","names":["marker","scalar","validateSchema","isDecimalList","#schema","#resolution","issue"],"sources":["../src/schema/model/keys.ts","../src/schema/relation/helpers.ts","../src/schema/relation/junction-topology.ts","../src/schema/validation/id-domains.ts","../src/schema/validation/rules/fk.ts","../src/schema/validation/rules/model-members.ts","../src/schema/validation/rules/polymorphic.ts","../src/schema/validation/relation-resolution.ts","../src/schema/validation/rules/model.ts","../src/schema/validation/rules/relation.ts","../src/schema/validation/rules/index.ts","../src/schema/validation/validator.ts"],"sourcesContent":["/**\n * The ordered model-key catalog — the one owner of how a row can be addressed.\n *\n * A model's key facts have exactly three shapes, and this module stores each\n * once, grouped and ordered, in TS-field-name space:\n *\n * - `rowKey` — the complete primary key in constraint order (the array given to\n * `.id([...])`, or the one `.id()` scalar). Optional: a model may declare no\n * primary key.\n * - `addressableKeys` — the exact keys a public unique selector can name. A key\n * with a `name` is a grouped constraint whose selector is that name and whose\n * value is an object of members (`where: { region_slug: { region, slug } }`);\n * a key without one is a bare scalar selector (`where: { email }`). That\n * spelling difference is a real addressing fact — `.id([\"a\"])` and a scalar\n * `.id()` on `a` accept different selectors — so it is stored, not inferred.\n * - `referenceableKeys` — every complete ordered key a foreign key may target:\n * the addressable keys above plus total unique indexes. This is deliberately\n * wider than the public selector grammar and is the one physical-key catalog\n * consumed by schema validation and relation topology.\n * - `uniqueOverlapFields` — the conservative flattened view, used only to ask\n * whether two selectors MAY overlap. Never a substitute for a grouped key.\n *\n * Public addressability and physical referenceability remain distinct views:\n * a foreign key may target a total unique INDEX no selector can address.\n *\n * A second deliberate survivor: the validation whereUnique factories\n * (`validation/model/core/filter.ts` / `where.ts`) keep reading the constraint\n * slots directly, because they need the member `VibSchema` VALUES to build the\n * parser and its inferred type — something a field-name catalog structurally\n * cannot supply. That is the preserved type/runtime-projection distinction,\n * not a missed migration.\n *\n * The catalog's arrays are cached for the model's lifetime and handed out\n * uncopied; every consumer treats them as the `readonly` types say. A consumer\n * that needs to mutate must copy first, as `getPrimaryKeyFields` does.\n *\n * Field-name space only: hydration binds column names after model construction,\n * so caching resolved columns here would freeze pre-hydration names. Every\n * column resolution is a downstream projection through `getColumnName`.\n */\n\nimport { isTotalIndex, type Model } from \"./model\";\n\nexport interface OrderedModelKey {\n // No \"uniqueIndex\" kind, deliberately departing from the plan's §4.1 sketch:\n // an index is never addressable, and an inhabited kind for it would invite\n // someone to push index-derived keys into `addressableKeys`, silently making\n // `where: { <indexed column> }` a unique discriminator.\n readonly kind: \"primary\" | \"unique\" | \"compoundUnique\";\n /**\n * The grouped-constraint selector name. Present exactly when the public\n * selector is the constraint name wrapping an object of members; absent for\n * a bare single-scalar selector.\n */\n readonly name?: string;\n /** Ordered members. Compound keys stay grouped; never flatten them. */\n readonly fields: readonly string[];\n}\n\nexport interface ModelKeyCatalog {\n readonly rowKey?: OrderedModelKey;\n readonly addressableKeys: readonly OrderedModelKey[];\n readonly referenceableKeys: readonly (readonly string[])[];\n readonly uniqueOverlapFields: readonly string[];\n}\n\n/**\n * One catalog per model instance. Models are immutable after construction\n * except name hydration, which binds COLUMN names only — key membership and\n * order never change, and the catalog stores no columns.\n */\nconst catalogCache = new WeakMap<object, ModelKeyCatalog>();\n\nexport function getModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const cached = catalogCache.get(model);\n if (cached) {\n return cached;\n }\n const catalog = buildModelKeyCatalog(model);\n catalogCache.set(model, catalog);\n return catalog;\n}\n\n/**\n * Resolve one public unique-selector key to its addressable key.\n *\n * Definition validation guarantees that one model-local public selector name\n * identifies at most one key. The catalog therefore resolves one exact match;\n * it does not own a scalar/compound or primary/unique precedence policy.\n */\nexport function findAddressableKey(\n model: Model<any>,\n selectorKey: string\n): OrderedModelKey | undefined {\n for (const key of getModelKeyCatalog(model).addressableKeys) {\n const selector = key.name ?? key.fields[0];\n if (selector === selectorKey) {\n return key;\n }\n }\n return undefined;\n}\n\nconst LOGICAL_FILTER_NAMES = [\"AND\", \"OR\", \"NOT\"] as const;\n\n/**\n * Find compound selectors that collide in the actual public unique-where\n * namespace. Extended unique selectors merge every model field and the three\n * logical filters with compound discriminators, so those names are occupied\n * before compound IDs and uniques are added. The namespace is model-local and\n * stays in TypeScript/query spelling; mapped columns and physical constraint\n * names are separate adapter/driver facts.\n */\nexport function getAmbiguousPublicSelectorNames(\n model: Model<any>\n): readonly string[] {\n const state = model[\"~\"].state;\n const occupied = new Set<string>([\n ...Object.keys(state.shape),\n ...LOGICAL_FILTER_NAMES,\n ]);\n const ambiguous = new Set<string>();\n const compoundNames = [\n ...Object.keys(state.compoundId ?? {}),\n ...Object.keys(state.compoundUniques ?? {}),\n ];\n for (const name of compoundNames) {\n if (occupied.has(name)) ambiguous.add(name);\n occupied.add(name);\n }\n return [...ambiguous];\n}\n\n/**\n * Resolve one complete referenced tuple to the target key's own order.\n *\n * Membership is order-insensitive, but the answer is ordered because MySQL\n * requires composite referenced columns to follow an index left-prefix. An\n * exactly-spelled key wins; otherwise catalog order supplies the stable answer.\n */\nexport function findReferenceableKey(\n model: Model<any>,\n fields: readonly string[]\n): readonly string[] | undefined {\n let setMatch: readonly string[] | undefined;\n for (const candidate of getModelKeyCatalog(model).referenceableKeys) {\n if (\n candidate.length !== fields.length ||\n !candidate.every((field) => fields.includes(field))\n ) {\n continue;\n }\n if (candidate.every((field, position) => field === fields[position])) {\n return candidate;\n }\n setMatch ??= candidate;\n }\n return setMatch;\n}\n\nfunction buildModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const state = model[\"~\"].state;\n const addressableKeys: OrderedModelKey[] = [];\n\n // Bare scalar selectors, in shape-declaration order. `state.uniques` carries\n // `.id()` scalars beside `.unique()` ones (`extractUniqueScalarMap` keys on\n // `isUnique || isId`), so the scalar primary key is addressable here too.\n let scalarRowKey: OrderedModelKey | undefined;\n for (const field of Object.keys(state.uniques)) {\n const isId = state.scalars[field]?.[\"~\"].state.isId === true;\n const key: OrderedModelKey = isId\n ? { kind: \"primary\", fields: [field] }\n : { kind: \"unique\", fields: [field] };\n if (isId && !scalarRowKey) {\n scalarRowKey = key;\n }\n addressableKeys.push(key);\n }\n\n // EVERY declared compound-id constraint is addressable by its name — the\n // selector grammar has always resolved any of them (a second `.id([...])` is\n // representable; F002 refuses it at PUSH time only, never at `createClient`),\n // and empty ones stay addressable so their established \"must include at least\n // one field\" refusal keeps firing. The ROW key below is narrower: first\n // non-empty constraint only.\n const compoundIds: Record<string, { entries: Record<string, unknown> }> =\n state.compoundId ?? {};\n let compoundRowKey: OrderedModelKey | undefined;\n let firstCompoundId = true;\n for (const [name, constraint] of Object.entries(compoundIds)) {\n const key: OrderedModelKey = {\n kind: \"primary\",\n name,\n fields: Object.keys(constraint.entries),\n };\n // The row key is the FIRST declared constraint only, and only when it has a\n // name and members — a later non-empty constraint does not promote, exactly\n // as `getCompoundIdConstraint` has always read the record.\n if (firstCompoundId) {\n firstCompoundId = false;\n if (name && key.fields.length > 0) {\n compoundRowKey = key;\n }\n }\n addressableKeys.push(key);\n }\n\n // Named compound uniques, in declaration order.\n const compoundUniques: Record<string, { entries: Record<string, unknown> }> =\n state.compoundUniques ?? {};\n for (const [name, constraint] of Object.entries(compoundUniques)) {\n addressableKeys.push({\n kind: \"compoundUnique\",\n name,\n fields: Object.keys(constraint.entries),\n });\n }\n\n // The conservative flattened overlap view, in its established construction\n // order: scalar unique/id fields, then every compound-id member, then every\n // compound-unique member.\n const overlap = new Set<string>(Object.keys(state.uniques));\n for (const constraint of Object.values(compoundIds)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n for (const constraint of Object.values(compoundUniques)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n\n const referenceableKeys: readonly (readonly string[])[] = [\n ...addressableKeys.map((key) => key.fields),\n ...state.indexes\n .filter((index) => index.options.unique && isTotalIndex(index.options))\n .map((index) => index.fields),\n ];\n\n return {\n // The row key prefers the compound constraint: `getPrimaryKeyFields` has\n // always answered compound-first, and the projection contract pins that\n // reading (`target-projection.core.test.ts`, \"schema order is the KEY's\n // order\"). A model spelling both is refused by F002 at PUSH time only —\n // `createClient` never runs that rule — so the cursor deliberately keeps\n // its own scalar-first projection (`getCursorIdentityFields`).\n rowKey: compoundRowKey ?? scalarRowKey,\n addressableKeys,\n referenceableKeys,\n uniqueOverlapFields: [...overlap],\n };\n}\n","// Relation physical naming — stored-reference indexes plus junction tables,\n// side tokens, expanded columns, and constraint names.\n//\n// Nothing here discovers a pair. The full-schema relation resolver decides which\n// two slots share a junction and which single endpoint owns the overrides, then\n// hands this owner the already-oriented facts. That is why no function below\n// reads a relation object or a second endpoint's declaration.\n\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport type { JunctionSideActions } from \"./types\";\n\n// =============================================================================\n// DEFAULT NAMES\n// =============================================================================\n\n/**\n * Generate a junction table name from two model names\n * Names are sorted alphabetically and joined with underscore\n *\n * @example\n * generateJunctionTableName(\"post\", \"tag\") // \"post_tag\"\n * generateJunctionTableName(\"user\", \"role\") // \"role_user\"\n */\nexport function generateJunctionTableName(\n model1: string,\n model2: string\n): string {\n const names = [model1.toLowerCase(), model2.toLowerCase()].sort();\n return `${names[0]}_${names[1]}`;\n}\n\n/**\n * Generate a junction column name from a model name\n *\n * @example\n * generateJunctionFieldName(\"post\") // \"postId\"\n * generateJunctionFieldName(\"User\") // \"userId\"\n */\nexport function generateJunctionFieldName(modelName: string): string {\n return `${modelName.toLowerCase()}Id`;\n}\n\nexport interface JunctionFieldGroup {\n /** The declared side token, or its generated equivalent. */\n readonly token: string;\n /** Complete ordered junction columns for this endpoint's row key. */\n readonly fields: readonly string[];\n}\n\nexport interface JunctionFieldGroups {\n readonly source: JunctionFieldGroup;\n readonly target: JunctionFieldGroup;\n}\n\nexport type JunctionConstraintKind = \"fkey\" | \"idx\" | \"key\";\n\nexport class JunctionPhysicalNameError extends Error {\n readonly kind: \"collision\" | \"invalidIdentifier\";\n\n constructor(kind: \"collision\" | \"invalidIdentifier\", message: string) {\n super(message);\n this.name = \"JunctionPhysicalNameError\";\n this.kind = kind;\n }\n}\n\n/**\n * The automatic index name backing a non-unique stored reference, or\n * `undefined` when the schema has already spent both spellings on its own\n * declared indexes — the index is a read optimization, so it yields to the\n * names the schema declared.\n *\n * ONE owner for the rule: the migration serializer emits this name and the\n * schema-validation variant-storage reservation refuses names that would\n * collide with it. Both call here over the normalized stored-reference column\n * order, so the emitted name and the reserved name cannot diverge.\n */\nexport function automaticForeignKeyIndexName(\n tableName: string,\n foreignKeyColumns: readonly string[],\n declaredNames: ReadonlySet<string>\n): string | undefined {\n const preferred = `${tableName}_${foreignKeyColumns.join(\"_\")}_idx`;\n const name = declaredNames.has(preferred)\n ? `${tableName}_${foreignKeyColumns.join(\"_\")}_fkey_idx`\n : preferred;\n return declaredNames.has(name) ? undefined : name;\n}\n\n/** Derive one portable junction constraint name from the side naming token. */\nexport function getJunctionConstraintName(\n table: string,\n side: JunctionFieldGroup,\n kind: JunctionConstraintKind\n): string {\n const name = `${table}_${side.token}_${kind}`;\n if (!isValidSchemaIdentifier(name)) {\n throw new JunctionPhysicalNameError(\n \"invalidIdentifier\",\n `Generated junction ${kind} name '${name}' is not a valid SQL identifier.`\n );\n }\n return name;\n}\n\n/**\n * Expand the two side naming tokens over their complete row keys. The four\n * guards live HERE and only here — row-key emptiness per side, token identifier\n * validity, expanded field identifier validity, and the cross-side field\n * collision — so the ordinary pair path and the variant member path share one\n * refusal set.\n */\nexport function expandJunctionFieldGroups(\n sourceModelName: string,\n targetModelName: string,\n sourceToken: string,\n targetToken: string,\n sourceRowKeyFields: readonly string[],\n targetRowKeyFields: readonly string[]\n): JunctionFieldGroups {\n if (sourceRowKeyFields.length === 0) {\n throw new Error(\n `Model '${sourceModelName}' has no primary key; a junction side requires a complete row key.`\n );\n }\n if (targetRowKeyFields.length === 0) {\n throw new Error(\n `Model '${targetModelName}' has no primary key; a junction side requires a complete row key.`\n );\n }\n for (const token of [sourceToken, targetToken]) {\n if (!isValidSchemaIdentifier(token)) {\n throw new JunctionPhysicalNameError(\n \"invalidIdentifier\",\n `Junction side prefix '${token}' is not a valid SQL identifier.`\n );\n }\n }\n const source = junctionFieldGroup(sourceToken, sourceRowKeyFields.length);\n const target = junctionFieldGroup(targetToken, targetRowKeyFields.length);\n const occupied = new Map<string, string>();\n for (const field of [...source.fields, ...target.fields]) {\n if (!isValidSchemaIdentifier(field)) {\n throw new JunctionPhysicalNameError(\n \"invalidIdentifier\",\n `Expanded junction field '${field}' is not a valid SQL identifier.`\n );\n }\n const portableName = field.toLowerCase();\n const previous = occupied.get(portableName);\n if (previous !== undefined) {\n throw new JunctionPhysicalNameError(\n \"collision\",\n `Junction fields '${previous}' and '${field}' collide after compound-prefix expansion.`\n );\n }\n occupied.set(portableName, field);\n }\n return { source, target };\n}\n\n/** Canonical physical side order shared by snapshots and bound membership. */\nexport function junctionSourceSideIsFirst(\n sourceModelName: string,\n sourceFields: readonly string[],\n targetModelName: string,\n targetFields: readonly string[]\n): boolean {\n const sourceModel = sourceModelName.toLowerCase();\n const targetModel = targetModelName.toLowerCase();\n if (sourceModel !== targetModel) return sourceModel < targetModel;\n return sourceFields.join(\"\\0\") <= targetFields.join(\"\\0\");\n}\n\nfunction junctionFieldGroup(\n token: string,\n rowKeyArity: number\n): JunctionFieldGroup {\n return {\n token,\n fields:\n rowKeyArity === 1\n ? [token]\n : Array.from(\n { length: rowKeyArity },\n (_, index) => `${token}_${index + 1}`\n ),\n };\n}\n\n// =============================================================================\n// ORDINARY PAIR NAMES\n// =============================================================================\n\n/**\n * One resolved ordinary junction pair, oriented source → target by the caller.\n * `overrides` are the SINGLE owning endpoint's, already mirrored into this\n * orientation; a pair whose two endpoints both configure the junction never\n * reaches here.\n */\nexport interface OrdinaryJunctionNameInput {\n readonly sourceModelName: string;\n readonly targetModelName: string;\n /** Field keys of the two paired slots — the self-junction token defaults. */\n readonly sourceField: string;\n readonly targetField: string;\n readonly sourceRowKeyIsCompound: boolean;\n readonly targetRowKeyIsCompound: boolean;\n /** The agreed relation-name claim, which suffixes a generated table name. */\n readonly pairName: string | undefined;\n readonly overrides: JunctionOverrideView | undefined;\n}\n\n/**\n * One endpoint's declared junction overrides, seen from the SOURCE side of the\n * resolved pair. The declaration type refuses an empty object; this resolved\n * view does not, because mirroring the owner's facts onto the other side is a\n * derivation, not a declaration.\n */\nexport interface JunctionOverrideView {\n readonly table?: string;\n readonly source?: string;\n readonly target?: string;\n readonly onDelete?: JunctionSideActions;\n readonly onUpdate?: JunctionSideActions;\n}\n\nexport interface OrdinaryJunctionNames {\n readonly table: string;\n readonly sourceToken: string;\n readonly targetToken: string;\n}\n\n/**\n * The ONE owner of an ordinary junction's default names.\n *\n * A self junction takes its side tokens from the two FIELD keys, because the\n * model name is the same on both sides and cannot separate them. A non-self\n * junction keeps the model-name derivation its stored bytes were generated\n * from. A compound row key turns the token into a positional prefix, so it\n * drops the scalar `Id` suffix.\n */\nexport function resolveOrdinaryJunctionNames(\n input: OrdinaryJunctionNameInput\n): OrdinaryJunctionNames {\n const overrides = input.overrides;\n const isSelf = input.sourceModelName === input.targetModelName;\n const base = generateJunctionTableName(\n input.sourceModelName,\n input.targetModelName\n );\n return {\n table:\n overrides?.table ?? (input.pairName ? `${base}_${input.pairName}` : base),\n sourceToken:\n overrides?.source ??\n defaultSideToken(\n isSelf,\n input.sourceField,\n input.sourceModelName,\n input.sourceRowKeyIsCompound\n ),\n targetToken:\n overrides?.target ??\n defaultSideToken(\n isSelf,\n input.targetField,\n input.targetModelName,\n input.targetRowKeyIsCompound\n ),\n };\n}\n\nfunction defaultSideToken(\n isSelf: boolean,\n field: string,\n modelName: string,\n isCompound: boolean\n): string {\n if (isSelf) return isCompound ? field : `${field}Id`;\n return isCompound\n ? modelName.toLowerCase()\n : generateJunctionFieldName(modelName);\n}\n","/**\n * Resolved junction topology — the one owner of a junction's physical facts:\n * the table, both complete ordered sides, the canonical side order, the pair\n * identity, and the derived constraint names.\n *\n * DELIBERATELY NOT exported from the relation barrel (`./index.ts`): the public\n * API of `viborm/schema` stays frozen, and every consumer deep-imports this\n * module.\n *\n * ONE ENTRY, ONE CALLER. The full-schema relation resolver hands this owner an\n * already-paired, already-oriented junction and stores the result on the\n * resolved edge; engine binder and migration serializer read that stored value\n * instead of expanding a second time. Ordinary pairs and variant member\n * junctions differ only in where their tokens come from, so they share one\n * derivation rather than two entry points with two refusal orders.\n *\n * Constraint names stay lazy memoized METHODS. The gate asks all four during\n * resolution, so a published edge carries them settled; laziness is what keeps\n * the equal-token refusal attached to the first ask rather than to construction.\n */\n\nimport type { Model } from \"../model\";\nimport {\n expandJunctionFieldGroups,\n generateJunctionFieldName,\n getJunctionConstraintName,\n type JunctionFieldGroup,\n JunctionPhysicalNameError,\n junctionSourceSideIsFirst,\n} from \"./helpers\";\nimport type {\n JunctionReferentialAction,\n VariantJunctionOverride,\n} from \"./types\";\n\nexport interface JunctionEndpointInput {\n /** Carried opaquely; the owner never dereferences it (the engine projects it into its `JunctionSide`). */\n readonly model: Model<any>;\n /**\n * The CALLER's established name spelling: the engine passes\n * `names.ts ?? \"unknown\"`, the resolver passes schema keys — identical only\n * because hydration sets `names.ts` to the key. The owner must not re-derive\n * names.\n */\n readonly modelName: string;\n /**\n * Complete ordered row key, resolved by the CALLER. May be empty — the owner\n * forwards it so `expandJunctionFieldGroups` stays the SINGLE emptiness\n * guard.\n */\n readonly rowKey: readonly string[];\n /** The side naming token, resolved by the caller from overrides or defaults. */\n readonly token: string;\n /**\n * This side's foreign-key actions, already oriented onto this side by the\n * caller. Absent (omitted, never `undefined`: the owner copies the side\n * through) means the junction default; only an ordinary pair's owner states\n * them.\n */\n readonly onDelete?: JunctionReferentialAction;\n readonly onUpdate?: JunctionReferentialAction;\n}\n\nexport interface JunctionTopologyInput {\n readonly table: string;\n readonly source: JunctionEndpointInput;\n readonly target: JunctionEndpointInput;\n readonly pairName: string | undefined;\n}\n\n/** One junction column paired with the endpoint field it references. */\nexport interface ResolvedJunctionMember {\n readonly junctionField: string;\n readonly referencedField: string;\n}\n\nexport interface ResolvedJunctionSide {\n readonly model: Model<any>;\n readonly modelName: string;\n /** The declared side token or its generated equivalent — the constraint-name input. */\n readonly token: string;\n /** Complete ordered stored reference, model-key-catalog order (index-aligned with the input rowKey). */\n readonly members: readonly ResolvedJunctionMember[];\n /**\n * The actions of the foreign key from the junction to THIS side's model.\n * They travel with the side, so reordering the two sides into canonical\n * physical order moves each action with its own table and columns.\n */\n readonly onDelete?: JunctionReferentialAction;\n readonly onUpdate?: JunctionReferentialAction;\n}\n\nexport interface ResolvedJunctionTopology {\n readonly table: string;\n readonly source: ResolvedJunctionSide;\n readonly target: ResolvedJunctionSide;\n /**\n * Canonical physical side order — `junctionSourceSideIsFirst` over the\n * token-expanded junction fields. A plain fact for the serializer; the\n * engine's `BoundJunctionMembership` does NOT gain this field and\n * membership-scope equality stays orientation-erased.\n */\n readonly sourceIsFirst: boolean;\n /** The agreed relation-name claim — pair-identity input for the serializer's dedupe key. */\n readonly pairName: string | undefined;\n /** `${table}_${sideToken}_fkey` via `getJunctionConstraintName`. Memoized per side. */\n foreignKeyName(side: \"source\" | \"target\"): string;\n /** `${table}_${secondToken}_idx` over the canonical SECOND side. Memoized. */\n reverseIndexName(): string;\n /**\n * `${table}_${targetToken}_key` over the complete TARGET side — the\n * singular-inverse unique-constraint name.\n */\n uniqueTargetName(): string;\n}\n\n/**\n * Resolve one junction's complete physical topology.\n *\n * Throws exactly what `expandJunctionFieldGroups` throws (row-key emptiness,\n * token identifier, expanded-field identifier, cross-side collision) and adds\n * no guard of its own beyond the equal-token refusal on the first fkey ask.\n */\nexport function resolveJunctionTopology(\n input: JunctionTopologyInput\n): ResolvedJunctionTopology {\n const groups = expandJunctionFieldGroups(\n input.source.modelName,\n input.target.modelName,\n input.source.token,\n input.target.token,\n input.source.rowKey,\n input.target.rowKey\n );\n return deriveJunctionTopology({\n table: input.table,\n source: sideFacts(input.source, groups.source),\n target: sideFacts(input.target, groups.target),\n pairName: input.pairName,\n });\n}\n\nexport interface VariantMemberNames {\n readonly table: string;\n readonly sourceToken: string;\n readonly targetToken: string;\n}\n\n/**\n * The ONE owner of a variant collection member's junction names.\n *\n * Defaults: the table is `${ownerTable}_${relationField}_${publicType}`\n * (declaration-shaped, NOT the sorted-alphabetical ordinary generator — a\n * member junction has an owner side and a variant side, not two peers); the\n * source token follows the ordinary convention (compound row key → lowercased\n * owner schema key as a positional prefix, scalar →\n * `<lowercasedOwnerSchemaKey>Id`); the target token is\n * VARIANT-derived (`publicType` rather than the target model's name), which\n * keeps same-model duplicate variants and self targets naturally distinct — a\n * self target whose variant spells the owner's own name collides and is refused\n * through the one cross-side collision guard, escaped via `.through()`. An\n * explicit `.through()` entry overrides all three names.\n *\n * The owner RETURNS NAMES ONLY. Identifier and length refusals fire where each\n * name is consumed.\n */\nexport function resolveVariantMemberNames(input: {\n readonly ownerTableName: string;\n readonly ownerModelName: string;\n readonly relationField: string;\n readonly publicType: string;\n readonly ownerRowKeyIsCompound: boolean;\n readonly targetRowKeyIsCompound: boolean;\n readonly junction: VariantJunctionOverride | undefined;\n}): VariantMemberNames {\n if (input.junction) {\n return {\n table: input.junction.table,\n sourceToken: input.junction.source,\n targetToken: input.junction.target,\n };\n }\n return {\n table: `${input.ownerTableName}_${input.relationField}_${input.publicType}`,\n sourceToken: input.ownerRowKeyIsCompound\n ? input.ownerModelName.toLowerCase()\n : generateJunctionFieldName(input.ownerModelName),\n targetToken: input.targetRowKeyIsCompound\n ? input.publicType.toLowerCase()\n : generateJunctionFieldName(input.publicType),\n };\n}\n\n/** Per-side facts the relation-free derivation consumes. */\ninterface JunctionSideFacts {\n readonly model: Model<any>;\n readonly modelName: string;\n readonly token: string;\n readonly fields: readonly string[];\n readonly rowKey: readonly string[];\n readonly onDelete?: JunctionReferentialAction;\n readonly onUpdate?: JunctionReferentialAction;\n}\n\ninterface JunctionTopologyFacts {\n readonly table: string;\n readonly source: JunctionSideFacts;\n readonly target: JunctionSideFacts;\n readonly pairName: string | undefined;\n}\n\n/**\n * The endpoint's facts travel through as the caller stated them: its actions\n * are already oriented onto this side, and an unstated one is already absent.\n */\nfunction sideFacts(\n endpoint: JunctionEndpointInput,\n group: JunctionFieldGroup\n): JunctionSideFacts {\n return { ...endpoint, token: group.token, fields: group.fields };\n}\n\n/** Relation-free half of the resolution: member zip, canonical order, names. */\nfunction deriveJunctionTopology(\n facts: JunctionTopologyFacts\n): ResolvedJunctionTopology {\n const { table, source, target, pairName } = facts;\n const sourceIsFirst = junctionSourceSideIsFirst(\n source.modelName,\n source.fields,\n target.modelName,\n target.fields\n );\n const canonicalSecond = sourceIsFirst ? target : source;\n let sourceForeignKey: string | undefined;\n let targetForeignKey: string | undefined;\n let reverseIndex: string | undefined;\n let uniqueTarget: string | undefined;\n return {\n table,\n source: resolveSide(source),\n target: resolveSide(target),\n sourceIsFirst,\n pairName,\n foreignKeyName(side: \"source\" | \"target\"): string {\n // The SOLE guard against duplicate `${table}_${token}_fkey` names from\n // equal side tokens whose EXPANSIONS differ in arity (explicit scalar\n // token vs generated compound prefix): the expanded-field collision guard\n // never sees them.\n if (source.token === target.token) {\n throw new JunctionPhysicalNameError(\n \"collision\",\n `Junction sides of '${table}' share naming token '${source.token}' and would derive the same foreign-key constraint name.`\n );\n }\n if (side === \"source\") {\n sourceForeignKey ??= getJunctionConstraintName(table, source, \"fkey\");\n return sourceForeignKey;\n }\n targetForeignKey ??= getJunctionConstraintName(table, target, \"fkey\");\n return targetForeignKey;\n },\n reverseIndexName(): string {\n reverseIndex ??= getJunctionConstraintName(table, canonicalSecond, \"idx\");\n return reverseIndex;\n },\n uniqueTargetName(): string {\n uniqueTarget ??= getJunctionConstraintName(table, target, \"key\");\n return uniqueTarget;\n },\n };\n}\n\nfunction resolveSide({\n fields,\n rowKey,\n ...side\n}: JunctionSideFacts): ResolvedJunctionSide {\n return {\n ...side,\n members: rowKey.map((referencedField, index) => ({\n // `junctionFieldGroup` (helpers.ts) returns exactly `rowKeyArity` fields\n // for the same row-key list zipped here, so this lookup cannot miss.\n junctionField: fields[index]!,\n referencedField,\n })),\n };\n}\n","/**\n * Where a FOREIGN KEY gets its identifier domain.\n *\n * A key declares its format; the columns that reference it do not repeat the\n * declaration. `post.authorId` referencing `user.id` — a `.uuid(\"usr\")` — holds\n * exactly the values `user.id` holds, so it admits them, normalizes them and\n * stores them the same way, and it does so without a generator of its own and\n * without a single character of its own declaration. That is the whole rule:\n * DERIVED, never re-declared.\n *\n * It is a fact of the SCHEMA, not of a scalar, which is why it lives at L5\n * beside the resolution that already knows which field references which. The\n * FK scalar's state is never touched: no default is installed on it, and two\n * models sharing one `s.string()` instance stay independent, because the answer\n * is keyed by (model, field) and not by the scalar.\n *\n * Derivation is a FIXPOINT because a referenced key may itself be a foreign\n * key — a one-to-one child whose primary key is its parent reference is the\n * ordinary case, and a chain of them is not unusual. A reference CYCLE is\n * one answer, not several: every field on it holds every other's values, so\n * it holds the one domain its declarations and the keys it reaches outside\n * itself agree on, whatever order the schema lists its models in. A cycle with\n * no declaration anywhere on it simply has no domain; it is not an error, it\n * is a schema of plain strings.\n *\n * Two things make it fail, and both are the same failure: DISAGREEMENT. A field\n * reached through several references (a shared foreign key, a compound member,\n * a polymorphic variant row) must find one domain at the end of every one of\n * them, and a field that declares a domain must declare the one its target\n * already has. There is no first-target fallback and no \"closest\" rule: two\n * answers to \"what does this column hold\" is not something a default can fix.\n */\n\nimport {\n describeIdDomain,\n type IdDomain,\n sameIdDomain,\n} from \"@validation/primitives/id-codec\";\nimport type { Model } from \"../model\";\nimport {\n NATIVE_DIALECTS,\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"../scalars/native-types\";\nimport {\n describeIdNativeTypes,\n idDomainOfState,\n idStorageOf,\n} from \"../scalars/string/id-domain\";\nimport type { ResolvedRelationIndex } from \"./relation-resolution\";\nimport { resolvedEdges } from \"./relation-resolution\";\nimport type { SchemaValidationIssue, ValidationContext } from \"./types\";\n\n/** Per model, the domain of each field that has one — declared or derived. */\nexport type IdDomainIndex = ReadonlyMap<\n Model<any>,\n ReadonlyMap<string, IdDomain>\n>;\n\n/** The derived domains, plus everything disagreement had to say. */\nexport interface IdDomainDerivation {\n readonly domains: IdDomainIndex;\n readonly issues: readonly SchemaValidationIssue[];\n}\n\n/** One end of a reference: the key a foreign-key member points at. */\ninterface ReferenceTarget {\n readonly model: Model<any>;\n readonly field: string;\n}\n\ntype ReferenceGraph = Map<Model<any>, Map<string, ReferenceTarget[]>>;\n\nconst MEMO = new WeakMap<ResolvedRelationIndex, IdDomainIndex>();\n\n/** Every `(owner.field) → (target.field)` edge the resolved index states. */\nfunction buildReferenceGraph(index: ResolvedRelationIndex): ReferenceGraph {\n const graph: ReferenceGraph = new Map();\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const owner = edge.owner;\n const other =\n edge.endpoints[0] === owner ? edge.endpoints[1] : edge.endpoints[0];\n let byField = graph.get(owner.source);\n if (byField === undefined) {\n byField = new Map();\n graph.set(owner.source, byField);\n }\n for (const member of edge.reference.members) {\n let targets = byField.get(member.foreignField);\n if (targets === undefined) {\n targets = [];\n byField.set(member.foreignField, targets);\n }\n targets.push({\n model: other.source,\n field: member.referencedField,\n });\n }\n }\n return graph;\n}\n\n/** The domain a field DECLARES, read through the one declaration owner. */\nfunction declaredDomainOf(\n model: Model<any>,\n field: string\n): IdDomain | undefined {\n return idDomainOfState(model[\"~\"].state.scalars[field]?.[\"~\"].state);\n}\n\nfunction nameOf(ctx: ValidationContext | undefined, model: Model<any>): string {\n return ctx?.modelToName.get(model) ?? model[\"~\"].names.ts ?? \"model\";\n}\n\n/**\n * Derive every foreign key's domain, and say where two answers met.\n *\n * The unit of derivation is a STRONGLY CONNECTED COMPONENT of the reference\n * graph, not a field. Every field on a reference cycle holds every other's\n * values, so the component holds one domain: the one every declaration on it\n * and every key it references outside itself agree on. Tarjan's walk settles a\n * component only once every component it references is settled, so the answer\n * is a function of the graph and never of the order the schema registered it\n * in — a field is never asked about while it is still being answered.\n */\nexport function deriveIdDomains(\n index: ResolvedRelationIndex,\n ctx?: ValidationContext\n): IdDomainDerivation {\n const domains = new Map<Model<any>, Map<string, IdDomain>>();\n const issues: SchemaValidationIssue[] = [];\n let hasDeclaredDomain = false;\n for (const model of index.keys()) {\n for (const field of Object.keys(model[\"~\"].state.scalars)) {\n if (declaredDomainOf(model, field) !== undefined) {\n hasDeclaredDomain = true;\n break;\n }\n }\n if (hasDeclaredDomain) break;\n }\n // Every inherited domain originates at a declaration. Without one, neither\n // propagation nor a domain/native-storage disagreement is possible.\n if (!hasDeclaredDomain) {\n MEMO.set(index, domains);\n return { domains, issues };\n }\n return deriveDeclaredIdDomains(index, ctx, domains, issues);\n}\n\n/**\n * The propagation itself, apart from {@link deriveIdDomains} so that a schema\n * declaring no identifier domain never compiles it.\n */\nfunction deriveDeclaredIdDomains(\n index: ResolvedRelationIndex,\n ctx: ValidationContext | undefined,\n domains: Map<Model<any>, Map<string, IdDomain>>,\n issues: SchemaValidationIssue[]\n): IdDomainDerivation {\n const graph = buildReferenceGraph(index);\n const settled = new Map<Model<any>, Map<string, IdDomain | undefined>>();\n // Tarjan's discovery index per field. Keyed by model IDENTITY, not by name:\n // a name is for the message, and two models that happen to render the same\n // one must not share a node.\n const discovered = new Map<Model<any>, Map<string, number>>();\n const open: ReferenceTarget[] = [];\n let discoveries = 0;\n\n const marker = (node: ReferenceTarget): string =>\n `${nameOf(ctx, node.model)}.${node.field}`;\n\n const publish = (node: ReferenceTarget, domain: IdDomain | undefined) => {\n let bySettled = settled.get(node.model);\n if (bySettled === undefined) {\n bySettled = new Map();\n settled.set(node.model, bySettled);\n }\n bySettled.set(node.field, domain);\n if (domain !== undefined) {\n let byField = domains.get(node.model);\n if (byField === undefined) {\n byField = new Map();\n domains.set(node.model, byField);\n }\n byField.set(node.field, domain);\n }\n };\n\n /**\n * One component's domain: its members' declarations and the settled keys it\n * references outside itself, which must all be one. A target not yet settled\n * is a member — Tarjan pops a component only when every edge leaving it\n * reaches a settled one.\n */\n const settleComponent = (members: readonly ReferenceTarget[]) => {\n let agreed: IdDomain | undefined;\n let agreedFrom: string | undefined;\n let conflicted = false;\n for (const member of members) {\n const own = marker(member);\n const declared = declaredDomainOf(member.model, member.field);\n const answers: { domain: IdDomain | undefined; from: string }[] =\n declared === undefined ? [] : [{ domain: declared, from: own }];\n for (const target of graph.get(member.model)?.get(member.field) ?? []) {\n const outside = settled.get(target.model);\n if (outside?.has(target.field) !== true) continue;\n answers.push({\n domain: outside.get(target.field),\n from: marker(target),\n });\n }\n for (const answer of answers) {\n if (agreedFrom === undefined) {\n agreed = answer.domain;\n agreedFrom = answer.from;\n continue;\n }\n if (sameIdDomain(agreed, answer.domain)) continue;\n conflicted = true;\n const other = answer.from === own ? agreedFrom : answer.from;\n issues.push({\n code: \"FK012\",\n message:\n `'${own}' would hold ${describeIdDomain2(agreed)} through '${agreedFrom}' ` +\n `and ${describeIdDomain2(answer.domain)} through '${answer.from}'. ` +\n \"A column stores one identifier domain.\",\n severity: \"error\",\n model: nameOf(ctx, member.model),\n field: member.field,\n candidates: [agreedFrom, answer.from],\n repair:\n declared === undefined\n ? `Give every key '${own}' references the same identifier format, prefix and length`\n : `Declare '${own}' with the same identifier format, prefix and length as '${other}', or declare nothing and let it derive`,\n });\n }\n }\n for (const member of members) {\n publish(member, conflicted ? undefined : agreed);\n }\n };\n\n /** Tarjan's walk from one field; answers the lowest discovery it reaches. */\n const connect = (node: ReferenceTarget): number => {\n const discovery = discoveries;\n discoveries += 1;\n let byField = discovered.get(node.model);\n if (byField === undefined) {\n byField = new Map();\n discovered.set(node.model, byField);\n }\n byField.set(node.field, discovery);\n open.push(node);\n let lowest = discovery;\n for (const target of graph.get(node.model)?.get(node.field) ?? []) {\n const seen = discovered.get(target.model)?.get(target.field);\n if (seen === undefined) {\n lowest = Math.min(lowest, connect(target));\n } else if (settled.get(target.model)?.has(target.field) !== true) {\n // Discovered and not settled: still open, so on this component.\n lowest = Math.min(lowest, seen);\n }\n }\n // The root of a component: everything opened since it is the component.\n if (lowest === discovery) settleComponent(open.splice(open.indexOf(node)));\n return lowest;\n };\n\n const resolve = (model: Model<any>, field: string): IdDomain | undefined => {\n const cached = settled.get(model);\n if (cached?.has(field) !== true) connect({ model, field });\n return settled.get(model)?.get(field);\n };\n\n for (const [model, byField] of graph) {\n for (const field of byField.keys()) resolve(model, field);\n }\n\n // The same question asked of the COLUMN rather than the values: a foreign\n // key holds its key's values, so it must hold them in the key's physical\n // form too. Storage is read off each column's OWN native type (`idStorageOf`),\n // so a key kept text by an override beside a foreign key that declares no\n // override is a `uuid`/byte column referencing a text one — PostgreSQL and\n // MySQL refuse the constraint, SQLite accepts it and the engine binds a\n // payload the key never holds. Only a dialect one of the two declarations\n // selects a native type on can disagree: with neither, both take the same\n // automatic column.\n for (const [model, byField] of graph) {\n for (const [field, targets] of byField) {\n const domain = resolve(model, field);\n if (domain === undefined) continue;\n const own = model[\"~\"].state.scalars[field]?.[\"~\"].nativeType;\n for (const target of targets) {\n const theirs =\n target.model[\"~\"].state.scalars[target.field]?.[\"~\"].nativeType;\n const split = storageDisagreement(domain, own, theirs);\n if (split === undefined) continue;\n const marker = `${nameOf(ctx, model)}.${field}`;\n const targetMarker = `${nameOf(ctx, target.model)}.${target.field}`;\n issues.push({\n code: \"FK012\",\n message:\n `'${marker}' would store ${describeIdDomain(domain)} as ${split.own} on ${split.dialect} ` +\n `and the key it references, '${targetMarker}', as ${split.theirs}. ` +\n \"A foreign key stores its key's values in the key's own physical form.\",\n severity: \"error\",\n model: nameOf(ctx, model),\n field,\n candidates: [marker, targetMarker],\n repair: `Give '${marker}' the same ${split.dialect} native type as '${targetMarker}' (${split.theirs})`,\n });\n }\n }\n }\n\n // The polymorphic row carrier's ONE private id column stores every variant's\n // key, so every variant's key must hold one domain — the same DISAGREEMENT\n // rule the shared-foreign-key case above states, over a column that is not a\n // field and therefore has no (model, field) of its own to key an issue by.\n //\n // It is checked HERE and not beside the rest of P002 because the answer may\n // be DERIVED: a variant whose primary key is its parent foreign key declares\n // nothing and still holds uuids, and the storage rule runs while the index it\n // would have to ask is still being built. Comparing declarations there\n // refused two variants that hold the same domain and admitted two that hold\n // different ones — the second of which is what types the carrier column from\n // one variant and writes another variant's key through it.\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"variantRowCarrier\") continue;\n const carrier = `${nameOf(ctx, edge.carrier.source)}.${edge.carrier.field}`;\n // A published carrier has at least one member — the edge type says so.\n const [head, ...rest] = edge.members;\n const agreed = resolve(head.targetModel, head.referencedField);\n let agreedFrom = `${nameOf(ctx, head.targetModel)}.${head.referencedField}`;\n for (const member of rest) {\n const domain = resolve(member.targetModel, member.referencedField);\n if (sameIdDomain(agreed, domain)) continue;\n const marker = `${nameOf(ctx, member.targetModel)}.${member.referencedField}`;\n issues.push({\n code: \"P002\",\n message:\n `The one id column of '${carrier}' would hold ${describeIdDomain2(agreed)} ` +\n `through '${agreedFrom}' and ${describeIdDomain2(domain)} through '${marker}'. ` +\n \"A column stores one identifier domain.\",\n severity: \"error\",\n model: nameOf(ctx, edge.carrier.source),\n relation: edge.carrier.field,\n candidates: [agreedFrom, marker],\n repair: `Give every variant target of '${carrier}' the same identifier format, prefix and length`,\n });\n agreedFrom = marker;\n }\n }\n\n // Every model the index registers, so a declared domain on a relationless\n // model is checked too. The resolved index holds one slot map per registered\n // model, including an empty one.\n for (const model of index.keys()) {\n const scalars = model[\"~\"].state.scalars;\n for (const field of Object.keys(scalars)) {\n const domain = resolve(model, field);\n if (domain === undefined) continue;\n refuseUnusableNativeType(\n model,\n field,\n scalars[field]?.[\"~\"].nativeType,\n domain,\n ctx,\n issues\n );\n }\n }\n\n // The topology gate already pays for this derivation. Publish its successful\n // answer on the same index so the first operation consumes it directly.\n if (issues.length === 0) MEMO.set(index, domains);\n return { domains, issues };\n}\n\n/**\n * Refuse a native type override the declared domain cannot live in.\n *\n * The override says what the COLUMN is; the domain says what the column holds.\n * `varchar(26)` holds a ULID as text, `BINARY(16)` holds its bytes, and\n * `INTEGER` holds neither — and nothing downstream can repair that choice: the\n * migration would emit the column the override named and the engine would bind\n * the value the domain named, which is a table that refuses every row.\n *\n * Asked of EVERY dialect the declaration selects a native type on — one\n * dialect for the tagged shorthand, each entry of a map — because no dialect is\n * bound yet and each of them is a column some migration will create. It is\n * checked HERE rather than in the advisory rule list because `skipValidation`\n * may drop advice and must not be able to drop this.\n */\nfunction refuseUnusableNativeType(\n model: Model<any>,\n field: string,\n declaration: NativeTypeDeclaration | undefined,\n domain: IdDomain,\n ctx: ValidationContext | undefined,\n issues: SchemaValidationIssue[]\n): void {\n for (const dialect of NATIVE_DIALECTS) {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) continue;\n if (idStorageOf(domain, declaration, dialect) !== undefined) continue;\n const marker = `${nameOf(ctx, model)}.${field}`;\n issues.push({\n code: \"F013\",\n message: `'${marker}' holds ${describeIdDomain(domain)}, which cannot live in the ${dialect} column '${nativeType.type}'.`,\n severity: \"error\",\n model: nameOf(ctx, model),\n field,\n repair: `Declare '${marker}' with one of: ${describeIdNativeTypes(domain.format, dialect)} — or drop the native type and take the automatic column.`,\n });\n }\n}\n\n/**\n * The first dialect on which two columns holding one domain store it\n * differently, with each column's spelling there; `undefined` when they agree.\n *\n * Compared by REPRESENTATION, the one physical fact the engine binds by: two\n * text spellings (`varchar(40)` beside `text`) hold the same public strings.\n * An override this domain cannot live in answers nothing here — `F013` refuses\n * it by name.\n */\nfunction storageDisagreement(\n domain: IdDomain,\n own: NativeTypeDeclaration | undefined,\n theirs: NativeTypeDeclaration | undefined\n):\n | { readonly dialect: string; readonly own: string; readonly theirs: string }\n | undefined {\n // Every dialect: one neither declaration selects gives both columns the same\n // automatic storage, so asking it too costs nothing and cannot disagree.\n for (const dialect of NATIVE_DIALECTS) {\n const ownStorage = idStorageOf(domain, own, dialect);\n const theirStorage = idStorageOf(domain, theirs, dialect);\n if (ownStorage === undefined || theirStorage === undefined) continue;\n if (ownStorage.representation === theirStorage.representation) continue;\n return {\n dialect,\n own: ownStorage.columnType,\n theirs: theirStorage.columnType,\n };\n }\n return undefined;\n}\n\n/** `describeIdDomain`, extended to the absence of one. */\nfunction describeIdDomain2(domain: IdDomain | undefined): string {\n return domain === undefined\n ? \"no identifier domain\"\n : describeIdDomain(domain);\n}\n\n/**\n * The derived domains of one resolved index, computed once per index identity.\n *\n * Every consumer that already threads the index reads this — the write path's\n * parameter encoding, the read projection, the result decode, the operation\n * schemas and the migration serializer — so there is one derivation per schema\n * and not one per query. The issues are dropped here: a schema whose domains\n * disagree never becomes an index (the gate refuses it), so by the time anyone\n * asks this question there is nothing left to report.\n */\nexport function idDomainsOf(index: ResolvedRelationIndex): IdDomainIndex {\n const existing = MEMO.get(index);\n if (existing) return existing;\n return deriveIdDomains(index).domains;\n}\n\n/**\n * The identifier domain of one model field: the ONE lookup every consumer uses.\n *\n * Declared first, derived second — and never both, because a declaration that\n * disagrees with what it references is refused before an index exists. Reads\n * the index only when the field declares nothing, so a schema with no relations\n * pays nothing.\n */\nexport function idDomainOf(\n model: Model<any>,\n field: string,\n index: ResolvedRelationIndex | undefined\n): IdDomain | undefined {\n const declared = declaredDomainOf(model, field);\n if (declared !== undefined || index === undefined) return declared;\n return idDomainsOf(index).get(model)?.get(field);\n}\n","// The stored-reference subowner.\n//\n// It proves that a declared `.fields(...).references(...)` pair is physically\n// legal — every member exists, aligns by position with its counterpart, matches\n// scalar types, and references a key the target can be addressed by — and\n// returns the one `ResolvedStoredReference` the trusted edge carries. The\n// mandatory relation-definition gate is its only caller; no consumer repeats\n// these checks and none receives the untrusted declaration.\n//\n// Arity is not checked here: `.references(...)` accepts only an equal-arity\n// tuple, so an unequal pair cannot be constructed.\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { findReferenceableKey, type Model } from \"../../model\";\nimport type { ForeignKeyDeclaration } from \"../../relation\";\nimport { sqliteDateTimePhysicalForm } from \"../../scalars/datetime/physical\";\nimport type { ResolvedStoredReference } from \"../relation-resolution\";\nimport type { SchemaValidationIssue } from \"../types\";\n\nexport interface StoredReferenceInput {\n readonly modelName: string;\n readonly model: Model<any>;\n readonly relationName: string;\n readonly targetName: string;\n readonly target: Model<any>;\n readonly foreignKey: ForeignKeyDeclaration;\n}\n\nexport interface StoredReferenceCheck {\n /** Present only when every structural fact above held. */\n readonly reference: ResolvedStoredReference | undefined;\n readonly issues: readonly SchemaValidationIssue[];\n /** Ordered local members whose scalar accepts NULL. */\n readonly nullableForeignFields: readonly string[];\n}\n\nexport function checkStoredReference(\n input: StoredReferenceInput\n): StoredReferenceCheck {\n const { modelName, model, relationName, targetName, target } = input;\n const { fields, references, onDelete, onUpdate } = input.foreignKey;\n const issues: SchemaValidationIssue[] = [];\n const localScalars = model[\"~\"].state.scalars;\n const targetScalars = target[\"~\"].state.scalars;\n const nullableForeignFields: string[] = [];\n let legal = true;\n\n for (const [position, foreignField] of fields.entries()) {\n const local = localScalars[foreignField];\n if (!local) {\n legal = false;\n issues.push(fk001(modelName, relationName, foreignField));\n continue;\n }\n if (isDecimalList(local)) {\n legal = false;\n issues.push(fk010(modelName, relationName, foreignField));\n continue;\n }\n if (local[\"~\"].state.type === \"point\") {\n // Only the local member belongs here. A referenced GeoPoint cannot be an\n // addressable key, which is already owned by I005 and FK005.\n legal = false;\n issues.push(fk011(modelName, relationName, foreignField));\n }\n if (local[\"~\"].state.nullable) nullableForeignFields.push(foreignField);\n const referencedField = references[position]!;\n const remote = targetScalars[referencedField];\n if (!remote) {\n legal = false;\n issues.push(fk002(modelName, relationName, targetName, referencedField));\n continue;\n }\n const localState = local[\"~\"].state;\n const remoteState = remote[\"~\"].state;\n const localType = localState.type;\n const remoteType = remoteState.type;\n const localIsArray = localState.array === true;\n const remoteIsArray = remoteState.array === true;\n const localDecimal = localState.decimal;\n const remoteDecimal = remoteState.decimal;\n const arrayShapeMismatch =\n localType === remoteType && localIsArray !== remoteIsArray;\n const decimalDomainMismatch =\n localType === \"decimal\" &&\n remoteType === \"decimal\" &&\n !sameDecimalDescriptor(localDecimal, remoteDecimal);\n const localDateTimeForm =\n localType === \"datetime\" && !localIsArray\n ? sqliteDateTimePhysicalForm(local[\"~\"].nativeType)\n : undefined;\n const remoteDateTimeForm =\n remoteType === \"datetime\" && !remoteIsArray\n ? sqliteDateTimePhysicalForm(remote[\"~\"].nativeType)\n : undefined;\n const dateTimeDomainMismatch =\n localDateTimeForm !== undefined &&\n remoteDateTimeForm !== undefined &&\n localDateTimeForm !== remoteDateTimeForm;\n if (\n localType !== remoteType ||\n arrayShapeMismatch ||\n decimalDomainMismatch ||\n dateTimeDomainMismatch\n ) {\n legal = false;\n issues.push(\n fk003({\n modelName,\n relationName,\n targetName,\n foreignField,\n referencedField,\n localState,\n remoteState,\n localDateTimeForm,\n remoteDateTimeForm,\n arrayShapeMismatch,\n decimalDomainMismatch,\n dateTimeDomainMismatch,\n })\n );\n }\n }\n\n const targetKey = findReferenceableKey(target, references);\n if (!targetKey) {\n legal = false;\n issues.push(fk005(modelName, relationName, targetName, references));\n }\n\n if (onDelete === \"setNull\" || onUpdate === \"setNull\") {\n for (const foreignField of fields) {\n const local = localScalars[foreignField];\n if (local && !local[\"~\"].state.nullable) {\n legal = false;\n issues.push(ra004(modelName, relationName, foreignField));\n }\n }\n }\n\n if (onDelete === \"cascade\" && nullableForeignFields.length === 0) {\n issues.push(ra003(modelName, relationName));\n }\n\n // Published in the MATCHED KEY's order, not the declaration's. Each pair\n // travels whole, so the pairing the author wrote is untouched and both DDL\n // sides permute together. `static-membership.ts` reads the DECLARATION, so\n // its compile-time foreign-key tuple can be ordered differently; every shape\n // either side publishes is name-keyed, so the two orders never meet.\n const members = fields.map((foreignField, position) => ({\n foreignField,\n referencedField: references[position]!,\n }));\n if (targetKey) {\n members.sort(\n (left, right) =>\n targetKey.indexOf(left.referencedField) -\n targetKey.indexOf(right.referencedField)\n );\n }\n const [head, ...rest] = members;\n return {\n reference:\n legal && head\n ? {\n members: [head, ...rest],\n ...(onDelete ? { onDelete } : {}),\n ...(onUpdate ? { onUpdate } : {}),\n }\n : undefined,\n issues,\n nullableForeignFields,\n };\n}\n\n/**\n * A fixed-decimal LIST, which plan 2.1 excludes from every key position.\n *\n * Only the LOCAL member is asked here, and that is the whole exclusion for a\n * stored reference: the REFERENCED tuple has to be a key the target can be\n * addressed by (FK005), and a decimal list can be no part of one — the scalar\n * builder refuses `.id()` and `.unique()` on it and I004 refuses it inside a\n * compound key or a unique index. So the referenced side is already closed, by\n * the owners of the positions it would have to occupy.\n */\nfunction isDecimalList(\n scalar: Model<any>[\"~\"][\"state\"][\"scalars\"][string]\n): boolean {\n const state = scalar[\"~\"].state;\n return state.type === \"decimal\" && state.array === true;\n}\n\n// The issues below are built only for an invalid declaration; keeping them out\n// of `checkStoredReference` means a valid schema never compiles them.\n\ntype Issue = SchemaValidationIssue;\ntype ScalarState = Model<any>[\"~\"][\"state\"][\"scalars\"][string][\"~\"][\"state\"];\n\nfunction fk001(model: string, relation: string, field: string): Issue {\n return {\n code: \"FK001\",\n message: `FK '${field}' in '${relation}' not in '${model}'`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Declare a scalar '${field}' on '${model}' or name an existing one in .fields(...)`,\n };\n}\n\nfunction fk010(model: string, relation: string, field: string): Issue {\n return {\n code: \"FK010\",\n message: `FK '${field}' in '${relation}' is a fixed-decimal list, which cannot be a foreign-key member`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Store the reference in a scalar decimal (or another scalar type) on '${model}'`,\n };\n}\n\nfunction fk011(model: string, relation: string, field: string): Issue {\n return {\n code: \"FK011\",\n message: `FK '${field}' in '${relation}' is a GeoPoint, which cannot be a foreign-key member`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Store relation identity in a portable scalar key on '${model}'`,\n };\n}\n\nfunction fk002(\n model: string,\n relation: string,\n targetName: string,\n field: string\n): Issue {\n return {\n code: \"FK002\",\n message: `Reference '${field}' not in '${targetName}'`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Reference a scalar declared on '${targetName}'`,\n };\n}\n\nfunction describeMember(\n state: ScalarState,\n dateTimeForm: string | undefined\n): string {\n if (state.array === true) return `${state.type}[]`;\n if (state.type === \"decimal\" && state.decimal)\n return `decimal(${state.decimal.precision},${state.decimal.scale})`;\n return dateTimeForm ? `datetime(${dateTimeForm})` : state.type;\n}\n\nfunction fk003(mismatch: {\n modelName: string;\n relationName: string;\n targetName: string;\n foreignField: string;\n referencedField: string;\n localState: ScalarState;\n remoteState: ScalarState;\n localDateTimeForm: string | undefined;\n remoteDateTimeForm: string | undefined;\n arrayShapeMismatch: boolean;\n decimalDomainMismatch: boolean;\n dateTimeDomainMismatch: boolean;\n}): Issue {\n const { foreignField, referencedField, targetName } = mismatch;\n const local = describeMember(mismatch.localState, mismatch.localDateTimeForm);\n const remote = describeMember(\n mismatch.remoteState,\n mismatch.remoteDateTimeForm\n );\n const same = mismatch.decimalDomainMismatch\n ? \"decimal precision and scale\"\n : mismatch.arrayShapeMismatch\n ? \"scalar/list shape\"\n : mismatch.dateTimeDomainMismatch\n ? \"SQLite DateTime physical form\"\n : \"scalar type\";\n return {\n code: \"FK003\",\n message: `Type mismatch: '${foreignField}' (${local}) → '${referencedField}' (${remote}) in ${targetName}`,\n severity: \"error\",\n model: mismatch.modelName,\n relation: mismatch.relationName,\n repair: `Give '${foreignField}' the same ${same} as '${targetName}.${referencedField}'`,\n };\n}\n\nfunction fk005(\n model: string,\n relation: string,\n targetName: string,\n references: readonly string[]\n): Issue {\n return {\n code: \"FK005\",\n message: `[${references.join(\", \")}] in '${targetName}' should be unique/ID`,\n severity: \"error\",\n model,\n relation,\n repair: `Declare the referenced tuple on '${targetName}' with .id(), .unique(), or a compound key`,\n };\n}\n\nfunction ra004(model: string, relation: string, field: string): Issue {\n return {\n code: \"RA004\",\n message: `SET NULL on '${relation}' but '${field}' not nullable`,\n severity: \"error\",\n model,\n relation,\n repair: `Make '${field}' .nullable() or choose another referential action`,\n };\n}\n\nfunction ra003(model: string, relation: string): Issue {\n return {\n code: \"RA003\",\n message: `CASCADE on required '${relation}' may cause data loss`,\n severity: \"warning\",\n model,\n relation,\n };\n}\n","import type { Model } from \"../../model\";\nimport type { AnyRelation } from \"../../relation\";\nimport type { Scalar } from \"../../scalars/base\";\n\nexport function getRelationValues(model: Model<any>): AnyRelation[] {\n return Object.values(model[\"~\"].state.relations) as AnyRelation[];\n}\n\nexport function getScalars(model: Model<any>): [string, Scalar][] {\n return Object.entries(model[\"~\"].state.scalars) as [string, Scalar][];\n}\n","// The variant-storage subowner.\n//\n// It owns the PHYSICAL half of a variant carrier: the row-held `(type, id)`\n// column pair and its portable-identity restriction, the per-variant member\n// junction names and topologies, and the schema-wide reservation set every\n// generated name is checked against. Pairing, inverse cardinality, and\n// uniqueness are the relation resolver's; this module never discovers an\n// inverse and never decides a topology.\n//\n// The mandatory relation-definition gate is its only caller.\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { isValidSchemaIdentifier } from \"../../identifier\";\nimport { getModelKeyCatalog, type Model } from \"../../model\";\nimport { automaticForeignKeyIndexName } from \"../../relation/helpers\";\nimport {\n type ResolvedJunctionTopology,\n resolveJunctionTopology,\n resolveVariantMemberNames,\n type VariantMemberNames,\n} from \"../../relation/junction-topology\";\nimport type { VariantJunctionOverride } from \"../../relation/types\";\nimport { string } from \"../../scalars\";\nimport type { Scalar } from \"../../scalars/base\";\nimport { thrownAsError } from \"../error\";\nimport type { ResolvedVariantRowStorage } from \"../relation-resolution\";\nimport type {\n Schema,\n SchemaValidationIssue,\n ValidationContext,\n} from \"../types\";\nimport { getScalars } from \"./model-members\";\n\nconst PORTABLE_ID_TYPES = new Set([\"string\", \"int\", \"bigint\", \"decimal\"]);\n\nfunction issue(\n code: string,\n message: string,\n model: string,\n relation: string,\n repair: string\n): SchemaValidationIssue {\n return { code, message, severity: \"error\", model, relation, repair };\n}\n\n// =============================================================================\n// SCHEMA-WIDE PHYSICAL NAME RESERVATIONS\n// =============================================================================\n\n/** One resolved row foreign key, as the serializer's index derivation sees it. */\nexport interface StoredReferenceFact {\n readonly owner: Model<any>;\n readonly fields: readonly string[];\n /** A unique tuple is already covered and gets no automatic index. */\n readonly unique: boolean;\n}\n\nexport interface ReservationInput {\n readonly schema: Schema;\n readonly ctx: ValidationContext;\n /** Table and canonical reverse-index name of every resolved ordinary junction. */\n readonly junctionNames: readonly string[];\n readonly storedReferences: readonly StoredReferenceFact[];\n}\n\n/**\n * Every physical name the schema already claims, in the spelling the migration\n * serializer emits: table names, declared and generated indexes, primary-key and\n * unique constraint names, automatic foreign-key indexes, and ordinary junction\n * tables with their reverse indexes. A generated variant storage name that lands\n * in this set is refused rather than silently shadowing an existing object.\n */\nexport function collectReservedPhysicalNames(\n input: ReservationInput\n): Set<string> {\n const reserved = new Set<string>();\n for (const [candidateName, candidate] of input.schema) {\n const tableName = candidate[\"~\"].state.tableName ?? candidateName;\n for (const index of candidate[\"~\"].state.indexes) {\n reserved.add(\n index.options.name ?? `${tableName}_${index.fields.join(\"_\")}_idx`\n );\n }\n const scalars = getScalars(candidate);\n if (\n scalars.some(([, scalar]) => scalar[\"~\"].state.isId) ||\n candidate[\"~\"].state.compoundId\n ) {\n reserved.add(`${tableName}_pkey`);\n }\n for (const [field, scalar] of scalars) {\n if (scalar[\"~\"].state.isUnique && !scalar[\"~\"].state.isId) {\n const column = scalar[\"~\"].state.columnName ?? field;\n reserved.add(`${tableName}_${column}_key`);\n }\n }\n for (const constraint of Object.keys(\n candidate[\"~\"].state.compoundUniques ?? {}\n )) {\n reserved.add(`${tableName}_${constraint}_key`);\n }\n for (const indexName of automaticForeignKeyIndexNames(\n candidate,\n tableName,\n input.storedReferences\n )) {\n reserved.add(indexName);\n }\n }\n for (const tableName of input.ctx.tableToModels.keys())\n reserved.add(tableName);\n for (const junctionName of input.junctionNames) reserved.add(junctionName);\n return reserved;\n}\n\n/**\n * The index names the serializer generates for foreign keys that no declared\n * key or index already covers — reserved so a variant member junction cannot\n * claim one of them.\n */\nfunction automaticForeignKeyIndexNames(\n model: Model<any>,\n tableName: string,\n storedReferences: readonly StoredReferenceFact[]\n): readonly string[] {\n const state = model[\"~\"].state;\n const columnName = (field: string) =>\n state.scalars[field]?.[\"~\"].state.columnName ?? field;\n const primaryKeyColumns = getScalars(model)\n .filter(([, scalar]) => scalar[\"~\"].state.isId)\n .map(([field]) => columnName(field));\n // The FIRST declared compound id, read the way the key catalog reads it: a\n // second `.id([...])` is representable but F002 refuses it at push, so one\n // lookup answers and an absent record is simply no compound columns.\n const compoundIds: Record<string, { entries: Record<string, unknown> }> =\n state.compoundId ?? {};\n const [compoundId] = Object.values(compoundIds);\n if (compoundId) {\n primaryKeyColumns.push(...Object.keys(compoundId.entries).map(columnName));\n }\n const uniqueColumns = getScalars(model)\n .filter(([, scalar]) => scalar[\"~\"].state.isUnique)\n .map(([field]) => [columnName(field)]);\n if (state.compoundUniques) {\n for (const constraintName of Object.keys(state.compoundUniques)) {\n const constraint = state.compoundUniques[constraintName];\n if (constraint?.entries) {\n uniqueColumns.push(Object.keys(constraint.entries).map(columnName));\n }\n }\n }\n const declaredIndexes = state.indexes.map((index) => {\n const declaredName = index.options.name;\n return {\n name:\n typeof declaredName === \"string\"\n ? declaredName\n : `${tableName}_${index.fields.join(\"_\")}_idx`,\n columns: index.fields.map(columnName),\n where: index.options.where,\n };\n });\n const own = storedReferences.filter((fact) => fact.owner === model);\n const coveringColumns = [\n primaryKeyColumns,\n ...uniqueColumns,\n ...own\n .filter((fact) => fact.unique)\n .map((fact) => fact.fields.map(columnName)),\n ...declaredIndexes\n .filter((index) => !index.where)\n .map((index) => index.columns),\n ];\n const emittedNames = new Set<string>(\n declaredIndexes.map((index) => index.name)\n );\n const automaticNames: string[] = [];\n for (const fact of own) {\n if (fact.unique) continue;\n const foreignKeyColumns = fact.fields.map(columnName);\n const alreadyIndexed = coveringColumns.some((columns) =>\n foreignKeyColumns.every(\n (column, position) => columns[position] === column\n )\n );\n if (alreadyIndexed) continue;\n const name = automaticForeignKeyIndexName(\n tableName,\n foreignKeyColumns,\n emittedNames\n );\n if (name === undefined) continue;\n emittedNames.add(name);\n automaticNames.push(name);\n }\n return automaticNames;\n}\n\n// =============================================================================\n// ROW-HELD VARIANT STORAGE\n// =============================================================================\n\nexport interface VariantRowMemberInput {\n readonly variant: string;\n readonly target: Model<any>;\n}\n\nexport interface VariantRowStorageInput {\n readonly modelName: string;\n readonly ownerTable: string;\n readonly relationName: string;\n /** `.optional()` on the carrier — the nullability of both private columns. */\n readonly optional: boolean;\n readonly members: readonly VariantRowMemberInput[];\n /** The owner's own column names; mutated as each carrier claims its pair. */\n readonly reservedColumns: Set<string>;\n /** Schema-wide index names; mutated as each carrier claims its index. */\n readonly reservedIndexes: Set<string>;\n /** How many carriers in the whole schema generate each poly index name. */\n readonly indexNameCounts: ReadonlyMap<string, number>;\n}\n\nexport interface VariantRowStorageResult {\n /** Present only when every member resolved and the names are legal. */\n readonly storage: ResolvedVariantRowStorage | undefined;\n /** Variant key → the target's single scalar primary-key field. */\n readonly referencedFields: ReadonlyMap<string, string>;\n readonly issues: readonly SchemaValidationIssue[];\n}\n\n/**\n * The row-held `(type, id)` pair: one shared private column pair and one\n * composite index for the whole carrier, so every variant must expose the same\n * portable single-scalar identity.\n */\nexport function checkVariantRowStorage(\n input: VariantRowStorageInput\n): VariantRowStorageResult {\n const { modelName, relationName } = input;\n const issues: SchemaValidationIssue[] = [];\n const typeColumnName = `${relationName}_type`;\n const idColumnName = `${relationName}_id`;\n const indexName = `${input.ownerTable}_${relationName}_poly_idx`;\n const namesValid =\n isValidSchemaIdentifier(typeColumnName) &&\n isValidSchemaIdentifier(idColumnName) &&\n isValidSchemaIdentifier(indexName) &&\n !input.reservedColumns.has(typeColumnName) &&\n !input.reservedColumns.has(idColumnName) &&\n !input.reservedIndexes.has(indexName) &&\n // The prepass counted this exact name for every row carrier, so the entry\n // is there to read and a second default would be a second owner for it.\n input.indexNameCounts.get(indexName)! === 1;\n if (!namesValid) {\n issues.push(\n issue(\n \"P008\",\n `Variant relation '${relationName}' in '${modelName}' has invalid or colliding generated storage names`,\n modelName,\n relationName,\n `Rename the relation field or .map() the owner table so '${typeColumnName}', '${idColumnName}' and '${indexName}' are free`\n )\n );\n }\n input.reservedColumns.add(typeColumnName);\n input.reservedColumns.add(idColumnName);\n input.reservedIndexes.add(indexName);\n\n const referencedFields = new Map<string, string>();\n /**\n * Every variant's key, with the model that owns it.\n *\n * The FIRST is the carrier's own: its scalar types the private id column and\n * its (model, field) is what that column names as the key whose domain its\n * values carry. Every variant agrees on both or the carrier is refused — on\n * the representation below, and on the identifier domain in the derivation,\n * which is the one pass that can see a domain a variant DERIVES rather than\n * declares.\n */\n const keys: {\n readonly model: Model<any>;\n readonly field: string;\n readonly scalar: Scalar;\n }[] = [];\n for (const member of input.members) {\n const primaryKey = singlePrimaryKey(member.target);\n if (!primaryKey) {\n issues.push(\n issue(\n \"P009\",\n `Variant '${member.variant}' in '${modelName}.${relationName}' requires one scalar primary key`,\n modelName,\n relationName,\n `Give the '${member.variant}' target a single scalar .id() field`\n )\n );\n continue;\n }\n referencedFields.set(member.variant, primaryKey.field);\n keys.push({\n model: member.target,\n field: primaryKey.field,\n scalar: primaryKey.scalar,\n });\n }\n\n const carrierKey = keys[0];\n const portable =\n carrierKey !== undefined &&\n keys.every((key) =>\n hasCompatibleVariantIdentity(carrierKey.scalar, key.scalar)\n );\n if (keys.length > 0 && !portable) {\n issues.push(\n issue(\n \"P002\",\n `Variant targets in '${modelName}.${relationName}' require one compatible portable primary-key representation`,\n modelName,\n relationName,\n \"Give every variant target the same portable scalar id representation: one shared string, int, or bigint type, or decimal IDs with identical precision and scale\"\n )\n );\n }\n\n const complete =\n namesValid && portable && referencedFields.size === input.members.length;\n const nullable = input.optional;\n return {\n storage:\n complete && carrierKey\n ? {\n typeColumn: {\n name: typeColumnName,\n scalar: string(),\n nullable,\n },\n idColumn: {\n name: idColumnName,\n // The scalar and the pair are ONE key read two ways, never two\n // answers: the scalar types the column, the pair names the key\n // whose domain its values carry.\n scalar: carrierKey.scalar,\n nullable,\n reference: { model: carrierKey.model, field: carrierKey.field },\n },\n indexName,\n }\n : undefined,\n referencedFields,\n issues,\n };\n}\n\nfunction hasCompatibleVariantIdentity(\n first: Scalar,\n candidate: Scalar\n): boolean {\n const firstState = first[\"~\"].state;\n const candidateState = candidate[\"~\"].state;\n if (\n !PORTABLE_ID_TYPES.has(candidateState.type) ||\n candidateState.array === true ||\n candidate[\"~\"].nativeType !== undefined ||\n candidateState.type !== firstState.type\n ) {\n return false;\n }\n // The identifier DOMAIN is part of the representation too, and it is checked\n // where the DERIVED answer exists — in the identifier-domain derivation, over\n // the resolved index this rule runs before. A variant key may hold a domain\n // it never declared (the one-to-one child whose primary key is its parent\n // foreign key), and comparing declarations here refused those pairs while\n // admitting two derived domains that differ.\n if (candidateState.type !== \"decimal\") return true;\n const firstDescriptor = firstState.decimal;\n const candidateDescriptor = candidateState.decimal;\n return (\n firstDescriptor !== undefined &&\n candidateDescriptor !== undefined &&\n sameDecimalDescriptor(candidateDescriptor, firstDescriptor)\n );\n}\n\n/** The generated composite index name of one row-held carrier. */\nexport function variantRowIndexName(\n ownerTable: string,\n relationName: string\n): string {\n return `${ownerTable}_${relationName}_poly_idx`;\n}\n\nfunction singlePrimaryKey(\n model: Model<any>\n): { readonly field: string; readonly scalar: Scalar } | undefined {\n if (\n model[\"~\"].state.compoundId &&\n Object.keys(model[\"~\"].state.compoundId).length > 0\n ) {\n return undefined;\n }\n const primaryKeys = getScalars(model).filter(\n ([, scalar]) => scalar[\"~\"].state.isId\n );\n if (primaryKeys.length !== 1) return undefined;\n const [field, scalar] = primaryKeys[0]!;\n return { field, scalar };\n}\n\n// =============================================================================\n// MEMBER JUNCTION STORAGE\n// =============================================================================\n\nexport interface VariantMemberInput {\n readonly variant: string;\n readonly target: Model<any>;\n readonly targetName: string;\n readonly junction: VariantJunctionOverride | undefined;\n}\n\nexport interface VariantMemberJunctionInput {\n readonly modelName: string;\n readonly model: Model<any>;\n readonly ownerTable: string;\n readonly relationName: string;\n readonly members: readonly VariantMemberInput[];\n readonly reservedColumns: ReadonlySet<string>;\n /** Mutated: a refused member still claims its names, so a later flip cannot collide. */\n readonly reservedIndexes: Set<string>;\n /** Schema-wide claim counts, so a member can tell its own claim from a rival's. */\n readonly memberNameCounts: ReadonlyMap<string, number>;\n}\n\nexport interface VariantMemberJunctionResult {\n readonly topologies: ReadonlyMap<string, ResolvedJunctionTopology>;\n readonly issues: readonly SchemaValidationIssue[];\n}\n\n/** Per-variant member junctions: one fixed-target junction per variant. */\nexport function checkVariantMemberJunctions(\n input: VariantMemberJunctionInput\n): VariantMemberJunctionResult {\n const { modelName, relationName } = input;\n const issues: SchemaValidationIssue[] = [];\n const topologies = new Map<string, ResolvedJunctionTopology>();\n const ownerRowKey = getModelKeyCatalog(input.model).rowKey?.fields;\n if (!ownerRowKey?.length) {\n issues.push(\n issue(\n \"P018\",\n `Variant relation '${relationName}' in '${modelName}' requires a complete owner row key for its member junctions`,\n modelName,\n relationName,\n `Declare a primary key on '${modelName}'`\n )\n );\n return { topologies, issues };\n }\n\n for (const member of input.members) {\n const targetRowKey = getModelKeyCatalog(member.target).rowKey?.fields;\n if (!targetRowKey?.length) {\n issues.push(\n issue(\n \"P009\",\n `Variant '${member.variant}' in '${modelName}.${relationName}' requires a complete row key`,\n modelName,\n relationName,\n `Declare a primary key on '${member.targetName}'`\n )\n );\n continue;\n }\n const names = resolveVariantMemberNames({\n ownerTableName: input.ownerTable,\n ownerModelName: modelName,\n relationField: relationName,\n publicType: member.variant,\n ownerRowKeyIsCompound: ownerRowKey.length > 1,\n targetRowKeyIsCompound: targetRowKey.length > 1,\n junction: member.junction,\n });\n try {\n const topology = resolveJunctionTopology({\n table: names.table,\n source: {\n model: input.model,\n modelName,\n rowKey: ownerRowKey,\n token: names.sourceToken,\n },\n target: {\n model: member.target,\n modelName: member.targetName,\n rowKey: targetRowKey,\n token: names.targetToken,\n },\n pairName: `${modelName}.${relationName}.${member.variant}`,\n });\n const sourceForeignKey = topology.foreignKeyName(\"source\");\n const targetForeignKey = topology.foreignKeyName(\"target\");\n const reverseIndex = topology.reverseIndexName();\n const uniqueTarget = topology.uniqueTargetName();\n const collision = [names.table, reverseIndex].find(\n (physicalName) =>\n !isValidSchemaIdentifier(physicalName) ||\n input.reservedColumns.has(physicalName) ||\n input.reservedIndexes.has(physicalName) ||\n // Counted for every member the prepass planned, this one included.\n input.memberNameCounts.get(physicalName)! > 1\n );\n // Reserved even when refused: a refused member still claims its physical\n // names, so an inverse flip elsewhere cannot newly collide a schema that\n // was already valid.\n input.reservedIndexes.add(names.table);\n input.reservedIndexes.add(sourceForeignKey);\n input.reservedIndexes.add(targetForeignKey);\n input.reservedIndexes.add(reverseIndex);\n input.reservedIndexes.add(uniqueTarget);\n if (collision !== undefined) {\n issues.push(\n issue(\n \"P019\",\n `Variant '${member.variant}' in '${modelName}.${relationName}' has an invalid or colliding junction name '${collision}'`,\n modelName,\n relationName,\n `Give this variant an explicit .through({ ${member.variant}: { table, source, target } }) entry`\n )\n );\n continue;\n }\n topologies.set(member.variant, topology);\n } catch (error) {\n // Every throw on this path is a physical-name refusal: both row keys are\n // proven non-empty above, and no other guard exists on the member path.\n input.reservedIndexes.add(names.table);\n issues.push(\n issue(\n \"P019\",\n thrownAsError(error).message,\n modelName,\n relationName,\n `Give this variant an explicit .through({ ${member.variant}: { table, source, target } }) entry`\n )\n );\n }\n }\n return { topologies, issues };\n}\n\n/**\n * The names one member junction WOULD claim — the counting prepass's input, so\n * a member can tell \"someone else claims this name\" from its own single claim.\n * `undefined` when the member has no complete row key to expand.\n */\nexport function planVariantMemberNames(input: {\n readonly model: Model<any>;\n readonly modelName: string;\n readonly ownerTable: string;\n readonly relationName: string;\n readonly member: VariantMemberInput;\n}):\n | { readonly names: VariantMemberNames; readonly claims: readonly string[] }\n | undefined {\n const ownerRowKey = getModelKeyCatalog(input.model).rowKey?.fields;\n const targetRowKey = getModelKeyCatalog(input.member.target).rowKey?.fields;\n if (!(ownerRowKey?.length && targetRowKey?.length)) return undefined;\n const names = resolveVariantMemberNames({\n ownerTableName: input.ownerTable,\n ownerModelName: input.modelName,\n relationField: input.relationName,\n publicType: input.member.variant,\n ownerRowKeyIsCompound: ownerRowKey.length > 1,\n targetRowKeyIsCompound: targetRowKey.length > 1,\n junction: input.member.junction,\n });\n try {\n const topology = resolveJunctionTopology({\n table: names.table,\n source: {\n model: input.model,\n modelName: input.modelName,\n rowKey: ownerRowKey,\n token: names.sourceToken,\n },\n target: {\n model: input.member.target,\n modelName: input.member.targetName,\n rowKey: targetRowKey,\n token: names.targetToken,\n },\n pairName: undefined,\n });\n return {\n names,\n claims: [\n names.table,\n topology.foreignKeyName(\"source\"),\n topology.foreignKeyName(\"target\"),\n topology.reverseIndexName(),\n ],\n };\n } catch {\n // A member whose names cannot even be expanded claims only its table; the\n // per-member pass reports the refusal.\n return { names, claims: [names.table] };\n }\n}\n","/**\n * The one schema-wide relation topology owner (plan §6).\n *\n * A declaration states two facts: the slot cardinality its factory was spelled\n * with, and the target domain its argument names. Everything else about an edge\n * — who its partner is, which endpoint owns the foreign key, whether storage is\n * a row reference or a junction, whether that storage is unique, whether a\n * singular slot may be empty — is derived HERE, once per schema, from the whole\n * graph. Nothing downstream rescans for an inverse.\n *\n * The gate publishes a complete trusted index or a list of\n * `SchemaValidationIssue`s. There is no partial index and no `unresolved` arm: a\n * consumer holding an index holds a graph whose every physical fact the FK,\n * variant-storage and junction subowners invoked here have already proven.\n *\n * PAIRING IS A GRAPH, NOT A LADDER. Candidates are collected structurally, then\n * partitioned by the exact relation-name claim, then counted. No candidate wins\n * by being ordinary, variant, first, or sole.\n */\n\nimport { findReferenceableKey, getModelKeyCatalog, type Model } from \"../model\";\nimport {\n type JunctionOverrideView,\n JunctionPhysicalNameError,\n resolveOrdinaryJunctionNames,\n} from \"../relation/helpers\";\nimport {\n type ResolvedJunctionTopology,\n resolveJunctionTopology,\n} from \"../relation/junction-topology\";\nimport type { PolymorphicStorageColumn } from \"../relation/polymorphic\";\nimport type {\n AnyRelation,\n JunctionSideActions,\n ReferentialAction,\n RelationCardinality,\n RelationSlot,\n RelationState,\n VariantManyEntry,\n VariantOneEntry,\n} from \"../relation/types\";\nimport { thrownAsError } from \"./error\";\nimport { deriveIdDomains } from \"./id-domains\";\nimport { checkStoredReference } from \"./rules/fk\";\nimport { getScalars } from \"./rules/model-members\";\nimport {\n checkVariantMemberJunctions,\n checkVariantRowStorage,\n collectReservedPhysicalNames,\n planVariantMemberNames,\n type StoredReferenceFact,\n variantRowIndexName,\n} from \"./rules/polymorphic\";\nimport type { Schema, SchemaValidationIssue, ValidationContext } from \"./types\";\n\n// =============================================================================\n// TRUSTED FORMS (§6.6)\n// =============================================================================\n\nexport type ResolvedVariantRowStorage = {\n readonly typeColumn: PolymorphicStorageColumn;\n readonly idColumn: PolymorphicStorageColumn;\n readonly indexName: string;\n};\n\n/** The exact normalized entry, narrowed to what physical storage may read. */\nexport type ResolvedVariantStorageIdentity = {\n readonly storedValue: string;\n};\n\nexport type ResolvedVariantRowMember = {\n readonly variant: string;\n readonly entry: ResolvedVariantStorageIdentity;\n readonly targetModel: Model<any>;\n readonly referencedField: string;\n readonly inverse?: RelationSlot;\n};\n\nexport type ResolvedVariantJunctionMember = {\n readonly variant: string;\n readonly entry: ResolvedVariantStorageIdentity;\n readonly inverse?: RelationSlot;\n /** A singular bound inverse makes this member's target side unique. */\n readonly uniqueTarget: boolean;\n readonly topology: ResolvedJunctionTopology;\n};\n\nexport type ResolvedStoredReference = {\n readonly members: readonly [\n {\n readonly foreignField: string;\n readonly referencedField: string;\n },\n ...{\n readonly foreignField: string;\n readonly referencedField: string;\n }[],\n ];\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\nexport type ResolvedRelationEdge =\n | {\n readonly kind: \"foreignKey\";\n readonly endpoints: readonly [RelationSlot, RelationSlot];\n readonly owner: RelationSlot;\n readonly reference: ResolvedStoredReference;\n readonly unique: boolean;\n }\n | {\n readonly kind: \"junction\";\n readonly endpoints: readonly [RelationSlot, RelationSlot];\n /** Each side's foreign-key actions travel on that side. */\n readonly topology: ResolvedJunctionTopology;\n }\n | {\n readonly kind: \"variantRowCarrier\";\n readonly carrier: RelationSlot;\n readonly members: readonly [\n ResolvedVariantRowMember,\n ...ResolvedVariantRowMember[],\n ];\n readonly uniqueTarget: boolean;\n readonly storage: ResolvedVariantRowStorage;\n }\n | {\n readonly kind: \"variantJunctionCarrier\";\n readonly carrier: RelationSlot;\n readonly members: readonly [\n ResolvedVariantJunctionMember,\n ...ResolvedVariantJunctionMember[],\n ];\n };\n\nexport type ResolvedVariantRowEdge = Extract<\n ResolvedRelationEdge,\n { readonly kind: \"variantRowCarrier\" }\n>;\n\nexport type ResolvedVariantJunctionEdge = Extract<\n ResolvedRelationEdge,\n { readonly kind: \"variantJunctionCarrier\" }\n>;\n\nexport type ResolvedVariantEdge =\n | ResolvedVariantRowEdge\n | ResolvedVariantJunctionEdge;\n\n/** The two model-target edge forms, the only ones an ordinary slot resolves to. */\nexport type ResolvedOrdinaryEdge = Exclude<\n ResolvedRelationEdge,\n ResolvedVariantEdge\n>;\n\nexport type ResolvedSlot =\n | {\n readonly slot: RelationSlot;\n readonly edge: Exclude<ResolvedRelationEdge, ResolvedVariantEdge>;\n readonly member?: never;\n }\n | {\n /** The public carrier slot spans the edge's complete member collection. */\n readonly slot: RelationSlot;\n readonly edge: ResolvedVariantEdge;\n readonly member?: never;\n }\n | {\n /** An ordinary inverse is a view of exactly one existing member record. */\n readonly slot: RelationSlot;\n readonly edge: ResolvedVariantRowEdge;\n readonly member: ResolvedVariantRowEdge[\"members\"][number];\n }\n | {\n readonly slot: RelationSlot;\n readonly edge: ResolvedVariantJunctionEdge;\n readonly member: ResolvedVariantJunctionEdge[\"members\"][number];\n };\n\nexport type ResolvedRelationIndex = ReadonlyMap<\n Model<any>,\n ReadonlyMap<string, ResolvedSlot>\n>;\n\n/**\n * The trusted index XOR the reasons there is none.\n *\n * `issues` is present on BOTH arms and means the same thing on each: everything\n * the gate has to say about this schema. On the successful arm it can only hold\n * WARNINGS — one error is what makes the arm unsuccessful — and dropping them\n * there would silently lose every advisory the subowners produce about a schema\n * that happens to be valid, which is most of them.\n */\nexport type RelationResolution =\n | {\n readonly ok: true;\n readonly index: ResolvedRelationIndex;\n readonly issues: readonly SchemaValidationIssue[];\n }\n | {\n readonly ok: false;\n readonly issues: readonly SchemaValidationIssue[];\n readonly cause?: Error;\n };\n\n/**\n * The ON DELETE action a stored reference's constraint carries: the declared\n * one, else Prisma's default — SET NULL when every local member is nullable,\n * RESTRICT otherwise. TOTAL nullability, not the nullable subset the write side\n * clears: one referential action governs the whole constraint. The migration\n * serializer spells the constraint from this answer and the engine reads it to\n * know which deletes the database refuses, so the two cannot disagree.\n */\nexport function foreignKeyOnDelete(\n edge: Extract<ResolvedRelationEdge, { readonly kind: \"foreignKey\" }>\n): ReferentialAction {\n if (edge.reference.onDelete !== undefined) return edge.reference.onDelete;\n const scalars = edge.owner.source[\"~\"].state.scalars;\n return edge.reference.members.every(\n (member) => scalars[member.foreignField]?.[\"~\"].state.nullable === true\n )\n ? \"setNull\"\n : \"restrict\";\n}\n\n/** A junction side's ON DELETE action: the declared one, else CASCADE (Prisma parity). */\nexport function junctionOnDelete(\n side: Pick<ResolvedJunctionTopology[\"source\"], \"onDelete\">\n): ReferentialAction {\n return side.onDelete ?? \"cascade\";\n}\n\n/**\n * Stable unique edge enumeration, derived from the index rather than stored\n * beside it. Walk named schema/model/field order and yield an edge only at its\n * canonical anchor — a foreign key at its owner, a junction at `endpoints[0]`,\n * either variant family at its carrier — so carrier storage keeps its\n * historical serializer position even when an inverse model sorts earlier.\n */\nexport function* resolvedEdges(\n index: ResolvedRelationIndex\n): Generator<ResolvedRelationEdge> {\n for (const [model, slots] of index) {\n for (const [field, resolved] of slots) {\n if (resolved.member) continue;\n const edge = resolved.edge;\n const anchor =\n edge.kind === \"foreignKey\"\n ? edge.owner\n : edge.kind === \"junction\"\n ? edge.endpoints[0]\n : edge.carrier;\n if (anchor.source === model && anchor.field === field) yield edge;\n }\n }\n}\n\n// =============================================================================\n// CONTEXTUAL GRAPH NODES\n// =============================================================================\n\ninterface RegisteredModel {\n readonly model: Model<any>;\n readonly name: string;\n}\n\ninterface SlotNode {\n readonly slot: RelationSlot;\n readonly modelName: string;\n readonly field: string;\n readonly order: number;\n readonly state: RelationState;\n readonly relation: AnyRelation;\n}\n\n/** An ordinary slot, or one variant of a carrier: the two pairable things. */\ninterface Endpoint {\n readonly node: SlotNode;\n /** The variant key when this endpoint is one member of a carrier. */\n readonly variant: string | undefined;\n readonly target: Model<any>;\n readonly targetName: string;\n /** Members inherit the carrier's optional relation-name claim. */\n readonly name: string | undefined;\n readonly cardinality: RelationCardinality;\n /** Canonical position: model order, then field order, then variant order. */\n readonly order: number;\n}\n\n/**\n * An endpoint that IS one member of a carrier, so its variant key is settled.\n *\n * Carrier resolution asks each member for its key many times — for the name\n * prepass, the storage columns, the bound inverse, the junction override. That\n * key is settled exactly once, HERE, by the partition that selects members;\n * every later reader takes it as a fact rather than re-defaulting it.\n */\ntype VariantMember = Endpoint & { readonly variant: string };\n\nconst isVariantMember = (endpoint: Endpoint): endpoint is VariantMember =>\n endpoint.variant !== undefined;\n\ntype Verdict =\n | { readonly kind: \"paired\"; readonly partner: Endpoint }\n | { readonly kind: \"missing\" }\n | { readonly kind: \"nameMismatch\" }\n | { readonly kind: \"ambiguous\" };\n\ntype VariantMapEntry = VariantOneEntry | VariantManyEntry;\n\n// =============================================================================\n// THE GATE\n// =============================================================================\n\nexport function resolveSchemaRelations(\n schema: Schema,\n context: ValidationContext,\n // A schema `viborm check` validated skips the passes that only report\n // (required cycles, junction claims); everything the topology needs runs.\n checked = false\n): RelationResolution {\n const issues: SchemaValidationIssue[] = [];\n const registration = registerModels(schema);\n\n const nodes = collectSlotNodes(registration.models);\n const settlement = settleTargets(nodes, registration.byIdentity, issues);\n if (settlement.cause) {\n return { ok: false, issues, cause: settlement.cause };\n }\n\n const endpoints = settlement.endpoints;\n const byHolder = new Map<Model<any>, Endpoint[]>();\n for (const endpoint of endpoints) {\n const held = byHolder.get(endpoint.node.slot.source);\n if (held) held.push(endpoint);\n else byHolder.set(endpoint.node.slot.source, [endpoint]);\n }\n\n const structural = new Map<Endpoint, Endpoint[]>();\n const verdicts = new Map<Endpoint, Verdict>();\n for (const endpoint of endpoints) {\n const candidates = (byHolder.get(endpoint.target) ?? []).filter(\n (candidate) =>\n candidate.target === endpoint.node.slot.source &&\n // The asking slot itself is never a candidate; a self edge needs two\n // distinct fields.\n candidate.node !== endpoint.node &&\n // Two direct variant carriers never pair: neither owns the other's\n // storage, and a carrier-wide name cannot choose a member.\n !(candidate.variant !== undefined && endpoint.variant !== undefined)\n );\n structural.set(endpoint, candidates);\n verdicts.set(endpoint, decide(endpoint, candidates));\n }\n\n reportPairingIssues(endpoints, structural, verdicts, issues);\n\n const publication: Publication = {\n edges: [],\n slots: [],\n storedReferences: [],\n junctionTables: new Map(),\n junctionNames: [],\n issues,\n };\n\n for (const endpoint of endpoints) {\n const verdict = verdicts.get(endpoint);\n if (verdict?.kind !== \"paired\") continue;\n const partner = verdict.partner;\n if (endpoint.variant !== undefined || partner.variant !== undefined) {\n continue;\n }\n // Both endpoints of an ordinary pair must select each other, and the pair\n // is resolved once, from its canonically first endpoint.\n if (verdicts.get(partner)?.kind !== \"paired\") continue;\n if (endpoint.order > partner.order) continue;\n const edge = resolveOrdinaryPair(endpoint, partner, publication);\n if (!edge) continue;\n publication.edges.push(edge);\n publication.slots.push(\n { slot: endpoint.node.slot, edge },\n { slot: partner.node.slot, edge }\n );\n }\n reportJunctionTableClaims(publication, context, checked);\n if (!checked) {\n reportRequiredCycles(publication, registration.byIdentity);\n }\n\n resolveVariantCarriers(\n { schema, context, nodes, endpoints, verdicts },\n publication\n );\n\n if (issues.some((entry) => entry.severity === \"error\")) {\n return { ok: false, issues };\n }\n const index = buildIndex(registration.models, publication.slots);\n // Identifier domains are DERIVED from the edges just published, so they are\n // derived here and not by a rule beside the gate: every consumer that threads\n // the index reads them, and a schema whose foreign keys cannot agree on what\n // a column holds must not become an index at all.\n const identifiers = deriveIdDomains(index, context);\n if (identifiers.issues.length > 0) {\n return { ok: false, issues: [...issues, ...identifiers.issues] };\n }\n return { ok: true, index, issues };\n}\n\ninterface Publication {\n readonly edges: ResolvedRelationEdge[];\n readonly slots: ResolvedSlot[];\n readonly storedReferences: StoredReferenceFact[];\n /** Junction table name → the endpoint paths that claim it. */\n readonly junctionTables: Map<string, string[]>;\n /** Table and reverse-index names every ordinary junction reserves. */\n readonly junctionNames: string[];\n readonly issues: SchemaValidationIssue[];\n}\n\n// =============================================================================\n// REGISTRATION\n// =============================================================================\n\ninterface Registration {\n /** Schema key → model, first claim only. */\n readonly models: ReadonlyMap<string, Model<any>>;\n /** Identity lookup from a settled target value to the model it is. */\n readonly byIdentity: ReadonlyMap<unknown, RegisteredModel>;\n}\n\n/**\n * Index the schema by key and by model identity.\n *\n * There is no duplicate-registration check HERE. \"One model object binds one\n * schema key\" is proved by the registration preflight before hydration writes\n * anything (§7.1), which every effect-capable boundary runs before it reaches\n * this gate — so a second check would be a second guard for one invariant, and a\n * later one, after the names it protects were already written.\n */\nfunction registerModels(schema: Schema): Registration {\n const models = new Map<string, Model<any>>();\n const byIdentity = new Map<unknown, RegisteredModel>();\n for (const [name, model] of schema) {\n models.set(name, model);\n byIdentity.set(model, { model, name });\n }\n return { models, byIdentity };\n}\n\n// =============================================================================\n// SLOT NODES AND TARGET SETTLEMENT\n// =============================================================================\n\nfunction collectSlotNodes(models: ReadonlyMap<string, Model<any>>): SlotNode[] {\n const nodes: SlotNode[] = [];\n let order = 0;\n for (const [modelName, model] of models) {\n const relations: Record<string, AnyRelation> = model[\"~\"].state.relations;\n for (const [field, relation] of Object.entries(relations)) {\n nodes.push({\n slot: { source: model, field },\n modelName,\n field,\n order: order++,\n state: relation[\"~\"].state,\n relation,\n });\n }\n }\n return nodes;\n}\n\ninterface Settlement {\n readonly endpoints: Endpoint[];\n readonly cause: Error | undefined;\n}\n\n/**\n * Consume each terminal's lazy once-cell exactly once per slot, in canonical\n * order, and prove the settled value is a registered model.\n *\n * A thrown getter stops resolution: the first failure in canonical order emits\n * its contextual issue and returns the terminal's own settled `Error`, so every\n * schema context observes the same object and later getters stay uninvoked.\n */\nfunction settleTargets(\n nodes: readonly SlotNode[],\n byIdentity: ReadonlyMap<unknown, RegisteredModel>,\n issues: SchemaValidationIssue[]\n): Settlement {\n const endpoints: Endpoint[] = [];\n let order = 0;\n for (const node of nodes) {\n const target = node.state.target;\n if (target.kind === \"model\") {\n let settled: unknown;\n try {\n settled = node.relation[\"~\"].settleTarget();\n } catch (thrown) {\n issues.push(thrownTargetIssue(\"R006\", node, undefined, thrown));\n return { endpoints, cause: thrownAsError(thrown) };\n }\n const registered = byIdentity.get(settled);\n if (!registered) {\n issues.push(unregisteredTargetIssue(node));\n continue;\n }\n endpoints.push(makeEndpoint(node, undefined, registered, order++));\n continue;\n }\n const cause = settleVariantTargets(node, byIdentity, issues, endpoints);\n if (cause) return { endpoints, cause };\n order = endpoints.length;\n }\n return { endpoints, cause: undefined };\n}\n\n/** A polymorphic slot's variants, apart so ordinary schemas never compile it. */\nfunction settleVariantTargets(\n node: SlotNode,\n byIdentity: ReadonlyMap<unknown, RegisteredModel>,\n issues: SchemaValidationIssue[],\n endpoints: Endpoint[]\n): Error | undefined {\n // The caller settles `kind: \"model\"` targets itself.\n const target = node.state.target as Exclude<\n SlotNode[\"state\"][\"target\"],\n { kind: \"model\" }\n >;\n let order = endpoints.length;\n for (const variant of Object.keys(target.entries)) {\n let settled: unknown;\n try {\n settled = node.relation[\"~\"].settleTarget(variant);\n } catch (thrown) {\n issues.push(thrownTargetIssue(\"P001\", node, variant, thrown));\n return thrownAsError(thrown);\n }\n const registered = byIdentity.get(settled);\n if (!registered) {\n issues.push({\n code: \"P001\",\n message: `Variant '${variant}' in '${node.modelName}.${node.field}' is not registered in the schema`,\n severity: \"error\",\n model: node.modelName,\n relation: node.field,\n repair: `Register the '${variant}' target model in the schema`,\n });\n continue;\n }\n endpoints.push(makeEndpoint(node, variant, registered, order++));\n }\n}\n\nfunction unregisteredTargetIssue(node: SlotNode): SchemaValidationIssue {\n return {\n code: \"R006\",\n message: `'${node.field}' in '${node.modelName}' targets a model that is not registered in the schema`,\n severity: \"error\",\n model: node.modelName,\n relation: node.field,\n repair: \"Register the target model in the schema passed to the client\",\n };\n}\n\nfunction makeEndpoint(\n node: SlotNode,\n variant: string | undefined,\n registered: RegisteredModel,\n order: number\n): Endpoint {\n return {\n node,\n variant,\n target: registered.model,\n targetName: registered.name,\n name: node.state.name,\n cardinality: node.state.cardinality,\n order,\n };\n}\n\nfunction thrownTargetIssue(\n code: string,\n node: SlotNode,\n variant: string | undefined,\n thrown: unknown\n): SchemaValidationIssue {\n const where = variant ? `variant '${variant}' of ` : \"\";\n return {\n code,\n message: `Target getter for ${where}'${node.modelName}.${node.field}' threw: ${thrownAsError(thrown).message}`,\n severity: \"error\",\n model: node.modelName,\n relation: node.field,\n repair: \"Make the target getter return a registered model without throwing\",\n };\n}\n\n// =============================================================================\n// THE CANDIDATE GRAPH (§6.2)\n// =============================================================================\n\nfunction decide(endpoint: Endpoint, candidates: readonly Endpoint[]): Verdict {\n const exact = matching(endpoint, candidates);\n const [only] = exact;\n if (only && exact.length === 1) return { kind: \"paired\", partner: only };\n if (exact.length > 1) return { kind: \"ambiguous\" };\n // §6.2 rule 4 reads the candidate count AFTER the label partition, so a\n // variant member left with no same-named candidate has zero candidates and\n // stays a valid direct-only member. The differently named candidate is always\n // an ordinary slot — carriers never pair with carriers — and it must itself\n // pair, so the mistake this could hide still reports exactly one diagnostic,\n // at that slot.\n if (candidates.length === 0 || endpoint.variant !== undefined) {\n return { kind: \"missing\" };\n }\n return { kind: \"nameMismatch\" };\n}\n\nfunction matching(\n endpoint: Endpoint,\n candidates: readonly Endpoint[]\n): Endpoint[] {\n return candidates.filter((candidate) => candidate.name === endpoint.name);\n}\n\nfunction reportPairingIssues(\n endpoints: readonly Endpoint[],\n structural: ReadonlyMap<Endpoint, Endpoint[]>,\n verdicts: ReadonlyMap<Endpoint, Verdict>,\n issues: SchemaValidationIssue[]\n): void {\n for (const endpoint of endpoints) {\n const verdict = verdicts.get(endpoint);\n // Both maps were filled from this same endpoint list, one entry each.\n const candidates = structural.get(endpoint)!;\n if (verdict?.kind === \"missing\") {\n // A variant member with no candidate is a valid direct-only member.\n if (endpoint.variant !== undefined) continue;\n issues.push(missingInverseIssue(endpoint));\n continue;\n }\n if (verdict?.kind === \"ambiguous\") {\n const competing = matching(endpoint, candidates);\n issues.push(competingInverseIssue(endpoint, competing));\n continue;\n }\n if (verdict?.kind !== \"nameMismatch\") continue;\n // A mismatch is a fact about the PAIR, so it is reported once, at the\n // canonically first of the endpoints that disagree.\n const disagreeing = candidates.filter(\n (candidate) => verdicts.get(candidate)?.kind === \"nameMismatch\"\n );\n if (disagreeing.some((partner) => partner.order < endpoint.order)) continue;\n issues.push(nameMismatchIssue(endpoint, candidates));\n }\n}\n\nfunction describe(endpoint: Endpoint): string {\n return endpoint.variant === undefined\n ? `'${endpoint.node.modelName}.${endpoint.node.field}'`\n : `Variant '${endpoint.variant}' of '${endpoint.node.modelName}.${endpoint.node.field}'`;\n}\n\nfunction path(endpoint: Endpoint): string {\n return endpoint.variant === undefined\n ? `${endpoint.node.modelName}.${endpoint.node.field}`\n : `${endpoint.node.modelName}.${endpoint.node.field}.${endpoint.variant}`;\n}\n\nfunction label(name: string | undefined): string {\n return name === undefined ? \"no name\" : `'${name}'`;\n}\n\n// =============================================================================\n// ORDINARY TOPOLOGY (§6.3, §6.4)\n// =============================================================================\n\nfunction resolveOrdinaryPair(\n first: Endpoint,\n second: Endpoint,\n publication: Publication\n): ResolvedOrdinaryEdge | undefined {\n const issues = publication.issues;\n const endpoints: readonly [RelationSlot, RelationSlot] = [\n first.node.slot,\n second.node.slot,\n ];\n if (first.cardinality === \"many\" && second.cardinality === \"many\") {\n return resolveJunctionEdge(first, second, endpoints, publication);\n }\n\n for (const endpoint of [first, second]) {\n if (endpoint.node.state.junction === undefined) continue;\n issues.push(\n misplaced(endpoint, \"junction configuration\", \"an ordinary junction pair\")\n );\n return undefined;\n }\n\n const owners = [first, second].filter(\n (endpoint) => endpoint.node.state.foreignKey !== undefined\n );\n if (owners.length === 2) {\n issues.push(doubleOwnerIssue(first, second));\n return undefined;\n }\n const owner = owners[0];\n if (!owner) {\n // Name the ONE singular endpoint when exactly one is singular — that is\n // the end whose slot cannot be empty and so the one that must store the\n // key. Otherwise the canonically first endpoint carries the refusal.\n const [onlySingular, alsoSingular] = [first, second].filter(\n (endpoint) => endpoint.cardinality === \"one\"\n );\n const required = onlySingular && !alsoSingular ? onlySingular : first;\n issues.push(missingForeignKeyIssue(required));\n return undefined;\n }\n\n const partner = owner === first ? second : first;\n // `owners` IS the endpoints whose foreign key is defined, so re-asking here\n // would be a second owner for the fact that filter already decided.\n const foreignKey = owner.node.state.foreignKey!;\n const check = checkStoredReference({\n modelName: owner.node.modelName,\n model: owner.node.slot.source,\n relationName: owner.node.field,\n targetName: partner.node.modelName,\n target: partner.node.slot.source,\n foreignKey,\n });\n issues.push(...check.issues);\n\n const unique = first.cardinality === \"one\" && second.cardinality === \"one\";\n if (!unique && declaresUniqueKey(owner.node.slot.source, foreignKey.fields)) {\n issues.push(uniqueCollectionKeyIssue(owner, partner, foreignKey));\n return undefined;\n }\n if (!check.reference) return undefined;\n // The published local columns follow the NORMALIZED member order (a permuted\n // referenced tuple is reordered to its matched target key by\n // `checkStoredReference`), so the automatic-index name this fact reserves is\n // the same one the serializer derives from the members.\n publication.storedReferences.push({\n owner: owner.node.slot.source,\n fields: check.reference.members.map((member) => member.foreignField),\n unique,\n });\n return {\n kind: \"foreignKey\",\n endpoints,\n owner: owner.node.slot,\n reference: check.reference,\n unique,\n };\n}\n\nfunction resolveJunctionEdge(\n first: Endpoint,\n second: Endpoint,\n endpoints: readonly [RelationSlot, RelationSlot],\n publication: Publication\n): ResolvedOrdinaryEdge | undefined {\n const issues = publication.issues;\n const configured = [first, second].filter(\n (endpoint) => endpoint.node.state.junction !== undefined\n );\n if (configured.length === 2) {\n issues.push({\n code: \"R011\",\n message: `'${first.node.modelName}.${first.node.field}' and '${second.node.modelName}.${second.node.field}' both configure this junction; exactly one endpoint owns every override`,\n severity: \"error\",\n model: first.node.modelName,\n relation: first.node.field,\n candidates: [path(first), path(second)],\n repair: \"Keep the junction configuration on one endpoint only\",\n });\n return undefined;\n }\n // `configured` holds the endpoints whose junction value is set, so the sole\n // configuring endpoint's overrides are there to read.\n const configuring = configured[0];\n const overrides =\n configuring === undefined\n ? undefined\n : configuring === first\n ? configuring.node.state.junction\n : mirrorOverrides(configuring.node.state.junction!);\n\n const sourceRowKey =\n getModelKeyCatalog(first.node.slot.source).rowKey?.fields ?? [];\n const targetRowKey =\n getModelKeyCatalog(second.node.slot.source).rowKey?.fields ?? [];\n const names = resolveOrdinaryJunctionNames({\n sourceModelName: first.node.modelName,\n targetModelName: second.node.modelName,\n sourceField: first.node.field,\n targetField: second.node.field,\n sourceRowKeyIsCompound: sourceRowKey.length > 1,\n targetRowKeyIsCompound: targetRowKey.length > 1,\n pairName: first.name,\n overrides,\n });\n claimJunctionTable(publication, names.table, first, second);\n try {\n const topology = resolveJunctionTopology({\n table: names.table,\n source: {\n model: first.node.slot.source,\n modelName: first.node.modelName,\n rowKey: sourceRowKey,\n token: names.sourceToken,\n ...sideActions(overrides, \"source\"),\n },\n target: {\n model: second.node.slot.source,\n modelName: second.node.modelName,\n rowKey: targetRowKey,\n token: names.targetToken,\n ...sideActions(overrides, \"target\"),\n },\n pairName: first.name,\n });\n topology.foreignKeyName(\"source\");\n topology.foreignKeyName(\"target\");\n publication.junctionNames.push(names.table, topology.reverseIndexName());\n return { kind: \"junction\", endpoints, topology };\n } catch (error) {\n issues.push({\n code:\n error instanceof JunctionPhysicalNameError && error.kind === \"collision\"\n ? \"JT003\"\n : \"JT002\",\n message: thrownAsError(error).message,\n severity: \"error\",\n model: first.node.modelName,\n relation: first.node.field,\n repair:\n \"Give this junction an explicit .through(...) table and distinct .source(...)/.target(...) tokens\",\n });\n return undefined;\n }\n}\n\nfunction claimJunctionTable(\n publication: Publication,\n table: string,\n first: Endpoint,\n second: Endpoint\n): void {\n const claims = publication.junctionTables.get(table);\n const claim = `${path(first)}, ${path(second)}`;\n if (claims) claims.push(claim);\n else publication.junctionTables.set(table, [claim]);\n}\n\n/** JT001: one physical junction table belongs to exactly one resolved pair. */\nfunction reportJunctionTableClaims(\n publication: Publication,\n context: ValidationContext,\n checked: boolean\n): void {\n for (const [table, claims] of publication.junctionTables) {\n const models = context.tableToModels.get(table);\n if (models) {\n publication.issues.push({\n code: \"JT003\",\n message: `Junction '${table}' for ${claims.join(\"; \")} collides with the table of registered model ${models.join(\", \")}`,\n severity: \"error\",\n candidates: models,\n repair:\n \"Choose an unoccupied .through(...) table or map the model to a distinct table\",\n });\n }\n if (checked || claims.length < 2) continue;\n publication.issues.push({\n code: \"JT001\",\n message: `Junction '${table}' is claimed by more than one relation pair: ${claims.join(\"; \")}`,\n severity: \"error\",\n candidates: claims,\n repair:\n \"Give each pair its own .through(...) table or a distinct .name(...)\",\n });\n }\n}\n\n/**\n * CM002: a cycle of required foreign keys can never be inserted.\n *\n * \"Required\" is derived, not declared: a foreign key whose every local member is\n * non-nullable makes its target an insert dependency of its owner.\n */\nfunction reportRequiredCycles(\n publication: Publication,\n byIdentity: ReadonlyMap<unknown, RegisteredModel>\n): void {\n const graph = new Map<string, string[]>();\n for (const registered of byIdentity.values()) graph.set(registered.name, []);\n for (const edge of publication.edges) {\n if (edge.kind !== \"foreignKey\") continue;\n const owner = edge.owner;\n const scalars = owner.source[\"~\"].state.scalars;\n const required = edge.reference.members.every(\n (member) => scalars[member.foreignField]?.[\"~\"].state.nullable !== true\n );\n if (!required) continue;\n const [first, second] = edge.endpoints;\n const partner = first === owner ? second : first;\n const from = byIdentity.get(owner.source)?.name;\n const to = byIdentity.get(partner.source)?.name;\n if (from !== undefined && to !== undefined) graph.get(from)?.push(to);\n }\n\n const visited = new Set<string>();\n const stack = new Set<string>();\n const reported = new Set<string>();\n const walk = (node: string, trail: string[]): void => {\n if (stack.has(node)) {\n const cycle = [...trail.slice(trail.indexOf(node)), node];\n const key = [...cycle].sort().join(\"->\");\n if (reported.has(key)) return;\n reported.add(key);\n publication.issues.push(requiredCycleIssue(cycle));\n return;\n }\n if (visited.has(node)) return;\n visited.add(node);\n stack.add(node);\n trail.push(node);\n // Seeded for every registered model, and a neighbour IS a registered name.\n for (const neighbor of graph.get(node)!) walk(neighbor, trail);\n stack.delete(node);\n trail.pop();\n };\n for (const node of graph.keys()) {\n if (!visited.has(node)) walk(node, []);\n }\n}\n\n/**\n * The other endpoint's view of one owner's overrides: the two sides swap —\n * the side tokens and, with them, each action pair's sides.\n */\nfunction mirrorOverrides(\n overrides: JunctionOverrideView\n): JunctionOverrideView {\n return {\n ...(overrides.table === undefined ? {} : { table: overrides.table }),\n ...(overrides.target === undefined ? {} : { source: overrides.target }),\n ...(overrides.source === undefined ? {} : { target: overrides.source }),\n ...(overrides.onDelete === undefined\n ? {}\n : { onDelete: swapSides(overrides.onDelete) }),\n ...(overrides.onUpdate === undefined\n ? {}\n : { onUpdate: swapSides(overrides.onUpdate) }),\n };\n}\n\nfunction swapSides(actions: JunctionSideActions): JunctionSideActions {\n return { source: actions.target, target: actions.source };\n}\n\n/** One oriented side's slice of the owner's actions, for the topology. */\nfunction sideActions(\n overrides: JunctionOverrideView | undefined,\n side: \"source\" | \"target\"\n) {\n const onDelete = overrides?.onDelete?.[side];\n const onUpdate = overrides?.onUpdate?.[side];\n return {\n ...(onDelete === undefined ? {} : { onDelete }),\n ...(onUpdate === undefined ? {} : { onUpdate }),\n };\n}\n\nfunction misplaced(\n endpoint: Endpoint,\n what: string,\n where: string\n): SchemaValidationIssue {\n return {\n code: \"R012\",\n message: `${describe(endpoint)} declares ${what}, which only ${where} may carry`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n repair: `Remove ${what} from '${endpoint.node.modelName}.${endpoint.node.field}'`,\n };\n}\n\nfunction declaresUniqueKey(\n model: Model<any>,\n fields: readonly string[]\n): boolean {\n return findReferenceableKey(model, fields) !== undefined;\n}\n\n// =============================================================================\n// VARIANT TOPOLOGY (§6.5)\n// =============================================================================\n\ninterface GraphView {\n readonly schema: Schema;\n readonly context: ValidationContext;\n readonly nodes: readonly SlotNode[];\n readonly endpoints: readonly Endpoint[];\n readonly verdicts: ReadonlyMap<Endpoint, Verdict>;\n}\n\nfunction resolveVariantCarriers(\n graph: GraphView,\n publication: Publication\n): void {\n // The variant map is read ONCE per carrier, here, where the partition that\n // selects carriers is the same expression that narrows the target. Every\n // later reader takes the entries as a fact instead of re-classifying a\n // declaration it already knows is a carrier's.\n const carriers: SlotNode[] = [];\n const entriesByCarrier = new Map<\n SlotNode,\n Readonly<Record<string, VariantMapEntry>>\n >();\n for (const node of graph.nodes) {\n const target = node.state.target;\n if (target.kind !== \"variants\") continue;\n carriers.push(node);\n entriesByCarrier.set(node, target.entries);\n }\n if (carriers.length === 0) return;\n resolveCarriers(graph, publication, carriers, entriesByCarrier);\n}\n\n/** The carriers found above, resolved; schemas without one never compile it. */\nfunction resolveCarriers(\n graph: GraphView,\n publication: Publication,\n carriers: SlotNode[],\n entriesByCarrier: Map<SlotNode, Readonly<Record<string, VariantMapEntry>>>\n): void {\n // Every carrier gets an entry, empty or not: a carrier whose targets were all\n // refused above contributed no member, and the two passes below then read one\n // settled list in carrier order instead of each re-deciding what an absent\n // carrier means. A member's node IS a carrier — the same\n // `target.kind === \"variants\"` partition selected both — so the seeded list\n // is always there to push into.\n const membersByCarrier = new Map<SlotNode, VariantMember[]>();\n for (const carrier of carriers) membersByCarrier.set(carrier, []);\n for (const endpoint of graph.endpoints) {\n if (!isVariantMember(endpoint)) continue;\n membersByCarrier.get(endpoint.node)!.push(endpoint);\n }\n\n const memberNameCounts = new Map<string, number>();\n const indexNameCounts = new Map<string, number>();\n for (const [carrier, members] of membersByCarrier) {\n if (carrier.state.cardinality === \"one\") {\n const indexName = variantRowIndexName(tableOf(carrier), carrier.field);\n indexNameCounts.set(indexName, (indexNameCounts.get(indexName) ?? 0) + 1);\n continue;\n }\n for (const member of members) {\n const plan = planVariantMemberNames({\n model: carrier.slot.source,\n modelName: carrier.modelName,\n ownerTable: tableOf(carrier),\n relationName: carrier.field,\n member: memberInput(entriesByCarrier.get(carrier)!, member),\n });\n for (const claim of plan?.claims ?? []) {\n memberNameCounts.set(claim, (memberNameCounts.get(claim) ?? 0) + 1);\n }\n }\n }\n\n const reservedIndexes = collectReservedPhysicalNames({\n schema: graph.schema,\n ctx: graph.context,\n junctionNames: publication.junctionNames,\n storedReferences: publication.storedReferences,\n });\n\n for (const [carrier, members] of membersByCarrier) {\n const reservedColumns = new Set(\n getScalars(carrier.slot.source).map(\n ([field, scalar]) => scalar[\"~\"].state.columnName ?? field\n )\n );\n const bound = bindMembers(members, graph, publication);\n const edge: ResolvedVariantEdge | undefined =\n carrier.state.cardinality === \"one\"\n ? resolveRowCarrier({\n carrier,\n entries: entriesByCarrier.get(carrier)!,\n members,\n bound,\n reservedColumns,\n reservedIndexes,\n indexNameCounts,\n publication,\n })\n : resolveMemberJunctionCarrier({\n carrier,\n entries: entriesByCarrier.get(carrier)!,\n members,\n bound,\n reservedColumns,\n reservedIndexes,\n memberNameCounts,\n publication,\n });\n if (!edge) continue;\n publication.edges.push(edge);\n publication.slots.push({ slot: carrier.slot, edge });\n // An inverse view points at the EXACT member object the carrier edge already\n // owns — `member.inverse` is the slot that member bound, so there is no\n // second lookup that could miss. The two storage families are walked\n // separately only because `ResolvedSlot` pairs each edge form with its own\n // member type; the bodies are one rule.\n if (edge.kind === \"variantRowCarrier\") {\n for (const member of edge.members) {\n if (member.inverse) {\n publication.slots.push({ slot: member.inverse, edge, member });\n }\n }\n continue;\n }\n for (const member of edge.members) {\n if (member.inverse) {\n publication.slots.push({ slot: member.inverse, edge, member });\n }\n }\n }\n}\n\n/**\n * Variant key → the ordinary slot resolved onto that member.\n *\n * A bound inverse is a VIEW over carrier-owned storage: it configures neither a\n * foreign key nor a junction, because the carrier already owns both.\n */\nfunction bindMembers(\n members: readonly VariantMember[],\n graph: GraphView,\n publication: Publication\n): Map<string, Endpoint> {\n const bound = new Map<string, Endpoint>();\n for (const member of members) {\n const verdict = graph.verdicts.get(member);\n if (verdict?.kind !== \"paired\") continue;\n const inverse = verdict.partner;\n if (graph.verdicts.get(inverse)?.kind !== \"paired\") continue;\n if (inverse.node.state.foreignKey !== undefined) {\n publication.issues.push(\n misplaced(inverse, \"a foreign key\", \"an ordinary edge's owner\")\n );\n continue;\n }\n if (inverse.node.state.junction !== undefined) {\n publication.issues.push(\n misplaced(\n inverse,\n \"junction configuration\",\n \"an ordinary junction pair\"\n )\n );\n continue;\n }\n bound.set(member.variant, inverse);\n }\n return bound;\n}\n\ninterface CarrierInput {\n readonly carrier: SlotNode;\n /** The carrier's normalized variant map, narrowed once at the partition. */\n readonly entries: Readonly<Record<string, VariantMapEntry>>;\n readonly members: readonly VariantMember[];\n readonly bound: ReadonlyMap<string, Endpoint>;\n readonly reservedColumns: Set<string>;\n readonly reservedIndexes: Set<string>;\n readonly publication: Publication;\n}\n\nfunction resolveRowCarrier(\n input: CarrierInput & {\n readonly indexNameCounts: ReadonlyMap<string, number>;\n }\n): ResolvedVariantRowEdge | undefined {\n const { carrier, members, bound, publication } = input;\n const cardinalities = new Set(\n [...bound.values()].map((inverse) => inverse.cardinality)\n );\n if (cardinalities.size > 1) {\n publication.issues.push({\n code: \"P012\",\n message: `Variant relation '${carrier.field}' in '${carrier.modelName}' cannot mix to-one and to-many inverses; one composite index serves the whole carrier`,\n severity: \"error\",\n model: carrier.modelName,\n relation: carrier.field,\n repair: \"Give every bound inverse of this carrier the same cardinality\",\n });\n return undefined;\n }\n const storage = checkVariantRowStorage({\n modelName: carrier.modelName,\n ownerTable: tableOf(carrier),\n relationName: carrier.field,\n optional: carrier.state.optional === true,\n members: members.map((member) => ({\n variant: member.variant,\n target: member.target,\n })),\n reservedColumns: input.reservedColumns,\n reservedIndexes: input.reservedIndexes,\n indexNameCounts: input.indexNameCounts,\n });\n publication.issues.push(...storage.issues);\n if (!storage.storage) return undefined;\n\n const entries = input.entries;\n const resolved: ResolvedVariantRowMember[] = [];\n for (const member of members) {\n const variant = member.variant;\n // Storage is published ONLY when every member resolved a referenced field,\n // and each member's key came from this same entry map — so both lookups are\n // reads of what the completeness check above already decided.\n const referencedField = storage.referencedFields.get(variant)!;\n const entry = entries[variant]!;\n const inverse = bound.get(variant);\n resolved.push({\n variant,\n entry,\n targetModel: member.target,\n referencedField,\n ...(inverse ? { inverse: inverse.node.slot } : {}),\n });\n }\n // Published storage requires one portable identity, so a carrier that reaches\n // here resolved at least one member.\n const [head, ...rest] = resolved;\n return {\n kind: \"variantRowCarrier\",\n carrier: carrier.slot,\n members: [head!, ...rest],\n uniqueTarget: cardinalities.has(\"one\"),\n storage: storage.storage,\n };\n}\n\nfunction resolveMemberJunctionCarrier(\n input: CarrierInput & {\n readonly memberNameCounts: ReadonlyMap<string, number>;\n }\n): ResolvedVariantJunctionEdge | undefined {\n const { carrier, members, bound, publication } = input;\n const junctions = checkVariantMemberJunctions({\n modelName: carrier.modelName,\n model: carrier.slot.source,\n ownerTable: tableOf(carrier),\n relationName: carrier.field,\n members: members.map((member) => memberInput(input.entries, member)),\n reservedColumns: input.reservedColumns,\n reservedIndexes: input.reservedIndexes,\n memberNameCounts: input.memberNameCounts,\n });\n publication.issues.push(...junctions.issues);\n\n const entries = input.entries;\n const resolved: ResolvedVariantJunctionMember[] = [];\n for (const member of members) {\n const variant = member.variant;\n const topology = junctions.topologies.get(variant);\n const entry = entries[variant];\n if (!(topology && entry)) return undefined;\n const inverse = bound.get(variant);\n resolved.push({\n variant,\n entry,\n uniqueTarget: inverse?.cardinality === \"one\",\n topology,\n ...(inverse ? { inverse: inverse.node.slot } : {}),\n });\n }\n const [head, ...rest] = resolved;\n if (!head) return undefined;\n return {\n kind: \"variantJunctionCarrier\",\n carrier: carrier.slot,\n members: [head, ...rest],\n };\n}\n\nfunction memberInput(\n entries: Readonly<Record<string, VariantMapEntry>>,\n member: VariantMember\n) {\n return {\n variant: member.variant,\n target: member.target,\n targetName: member.targetName,\n junction: entries[member.variant]?.junction,\n };\n}\n\nfunction tableOf(node: SlotNode): string {\n return node.slot.source[\"~\"].state.tableName ?? node.modelName;\n}\n\n// =============================================================================\n// PUBLICATION\n// =============================================================================\n\n/**\n * Publish the slots as a per-model map in DECLARATION order.\n *\n * Resolution order is edge order — ordinary pairs first, at their canonically\n * first endpoint, then every variant carrier — so inserting `slots` as they were\n * produced would put a model's variant carrier after an ordinary slot declared\n * later. `resolvedEdges` promises schema/model/field order and the migration\n * serializer emits from it, so the shape order the model already holds is what\n * decides the map's order; the resolved slots are only looked up by it.\n */\nfunction buildIndex(\n models: ReadonlyMap<string, Model<any>>,\n slots: readonly ResolvedSlot[]\n): ResolvedRelationIndex {\n const resolvedBySlot = new Map<Model<any>, Map<string, ResolvedSlot>>();\n for (const resolved of slots) {\n const held = resolvedBySlot.get(resolved.slot.source);\n if (held) held.set(resolved.slot.field, resolved);\n else\n resolvedBySlot.set(\n resolved.slot.source,\n new Map([[resolved.slot.field, resolved]])\n );\n }\n const index = new Map<Model<any>, Map<string, ResolvedSlot>>();\n for (const model of models.values()) {\n const declared = resolvedBySlot.get(model);\n const ordered = new Map<string, ResolvedSlot>();\n const relations: Record<string, AnyRelation> = model[\"~\"].state.relations;\n for (const field of Object.keys(relations)) {\n const resolved = declared?.get(field);\n if (resolved) ordered.set(field, resolved);\n }\n index.set(model, ordered);\n }\n return index;\n}\n\n// Issue builders, apart from the resolution so a valid schema never compiles\n// them.\n\nfunction missingInverseIssue(endpoint: Endpoint): SchemaValidationIssue {\n return {\n code: \"R002\",\n message: `'${endpoint.node.modelName}.${endpoint.node.field}' has no inverse relation in '${endpoint.targetName}'`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n repair: `Declare a slot on '${endpoint.targetName}' whose target is '${endpoint.node.modelName}'`,\n };\n}\n\nfunction competingInverseIssue(\n endpoint: Endpoint,\n competing: readonly Endpoint[]\n): SchemaValidationIssue {\n return {\n code: \"R009\",\n message: `${describe(endpoint)} has ${competing.length} competing inverse candidates in '${endpoint.targetName}'`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n candidates: competing.map(path),\n repair:\n \"Give each intended pair the same distinct .name(...) on both endpoints\",\n };\n}\n\nfunction nameMismatchIssue(\n endpoint: Endpoint,\n candidates: readonly Endpoint[]\n): SchemaValidationIssue {\n return {\n code: \"R010\",\n message: `${describe(endpoint)} claims relation name ${label(endpoint.name)}, but no candidate in '${endpoint.targetName}' claims the same name`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n candidates: candidates.map(path),\n repair: \"Spell the same .name(...) on both endpoints, or omit it on both\",\n };\n}\n\nfunction doubleOwnerIssue(\n first: Endpoint,\n second: Endpoint\n): SchemaValidationIssue {\n return {\n code: \"CM003\",\n message: `'${first.node.modelName}.${first.node.field}' and '${second.node.modelName}.${second.node.field}' both complete a foreign key; exactly one endpoint owns it`,\n severity: \"error\",\n model: first.node.modelName,\n relation: first.node.field,\n candidates: [path(first), path(second)],\n repair: \"Drop .fields(...).references(...) from one endpoint\",\n };\n}\n\nfunction missingForeignKeyIssue(required: Endpoint): SchemaValidationIssue {\n return {\n code: \"FK004\",\n message: `'${required.node.modelName}.${required.node.field}' stores no foreign key; one endpoint of this edge must complete .fields(...).references(...)`,\n severity: \"error\",\n model: required.node.modelName,\n relation: required.node.field,\n repair: `Complete .fields(...).references(...) on '${required.node.modelName}.${required.node.field}'`,\n };\n}\n\nfunction uniqueCollectionKeyIssue(\n owner: Endpoint,\n partner: Endpoint,\n foreignKey: NonNullable<Endpoint[\"node\"][\"state\"][\"foreignKey\"]>\n): SchemaValidationIssue {\n return {\n code: \"FK009\",\n message: `'${owner.node.modelName}.${owner.node.field}' stores a unique foreign key, which contradicts the collection '${partner.node.modelName}.${partner.node.field}' declares`,\n severity: \"error\",\n model: owner.node.modelName,\n relation: owner.node.field,\n repair: `Drop the unique key on [${foreignKey.fields.join(\", \")}], or declare '${partner.node.modelName}.${partner.node.field}' with s.toOne`,\n };\n}\n\nfunction requiredCycleIssue(cycle: readonly string[]): SchemaValidationIssue {\n return {\n code: \"CM002\",\n message: `Circular required relations: ${cycle.join(\" → \")}`,\n severity: \"error\",\n repair: \"Make one foreign key in the cycle nullable\",\n };\n}\n","// Model & Scalar Validation Rules\n\nimport { validateSchema } from \"../../../validation/primitives/helpers\";\nimport { isValidSchemaIdentifier } from \"../../identifier\";\nimport { jsonNullKindOf } from \"../../json-null\";\nimport type { Model, ModelState } from \"../../model\";\nimport { getAmbiguousPublicSelectorNames } from \"../../model/keys\";\nimport { isGeneratorDefault } from \"../../scalars/common\";\nimport type { Schema, SchemaValidationIssue } from \"../types\";\nimport { getScalars } from \"./model-members\";\n\nfunction validateFieldNames(\n modelName: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n for (const fieldName of Object.keys(model[\"~\"].state.shape)) {\n if (isValidSchemaIdentifier(fieldName)) continue;\n errors.push({\n code: \"F001\",\n message: `Field '${fieldName}' in '${modelName}' is invalid identifier`,\n severity: \"error\",\n model: modelName,\n field: fieldName,\n });\n }\n return errors;\n}\n\n// =============================================================================\n// MODEL RULES (M001-M006)\n// =============================================================================\n\n/** M002: Model must have at least one scalar field */\nexport function modelHasFields(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n if (Object.keys(model[\"~\"].state.scalars).length === 0) {\n return [\n {\n code: \"M002\",\n message: `'${name}' must have at least one field`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n/** M005: Model name must be valid identifier */\nexport function modelNameValid(\n _s: Schema,\n name: string,\n _m: Model<any>\n): SchemaValidationIssue[] {\n if (!isValidSchemaIdentifier(name)) {\n return [\n {\n code: \"M005\",\n message: `'${name}' is not a valid identifier`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n/** M007: Mapped table name (.map()) must be a valid identifier */\nexport function modelMappedNameValid(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const tableName = model[\"~\"].state.tableName;\n if (tableName !== undefined && !isValidSchemaIdentifier(tableName)) {\n return [\n {\n code: \"M007\",\n message: `Mapped table name '${String(tableName)}' on '${name}' is not a valid identifier`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n/** M006: A model must not occupy the client Promise-assimilation hook. */\nexport function modelNameNotReserved(\n _s: Schema,\n name: string,\n _m: Model<any>\n): SchemaValidationIssue[] {\n if (name === \"then\") {\n return [\n {\n code: \"M006\",\n message: `Model 'then' conflicts with the client's Promise-assimilation hook; rename the model key and use .map(\"then\") to retain the table name`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n// =============================================================================\n// FIELD RULES (F001-F008) - SINGLE PASS\n// =============================================================================\n\n/** Helper: Get compound ID field names from state */\nexport function getCompoundIdFields(model: Model<any>): string[] {\n const compoundId = model[\"~\"].state.compoundId;\n if (!compoundId) return [];\n const constraints: NonNullable<ModelState[\"compoundId\"]> = compoundId;\n return Object.keys(Object.values(constraints)[0]!.entries);\n}\n\n/** Helper: Get compound unique constraints from state */\nexport function getCompoundUniques(\n model: Model<any>\n): Array<{ name: string; fields: string[] }> {\n const compoundUniques: ModelState[\"compoundUniques\"] =\n model[\"~\"].state.compoundUniques;\n if (!compoundUniques) return [];\n return Object.entries(compoundUniques).map(([name, schema]) => ({\n name,\n fields: Object.keys(schema.entries),\n }));\n}\n\n/**\n * Single-pass field validation\n * Combines: F001, F002, F003, F004, F006, F007, F008\n * Iterates scalars once instead of 7 separate passes\n */\nexport function validateFieldsSinglePass(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors = validateFieldNames(name, model);\n\n // Accumulators for cross-scalar checks\n let idCount = 0;\n const columnToFields = new Map<string, string[]>();\n\n for (const [fname, scalar] of getScalars(model)) {\n const st = scalar[\"~\"].state;\n\n // F009: Mapped column name (.map()) valid\n if (\n st.columnName !== undefined &&\n !isValidSchemaIdentifier(st.columnName)\n ) {\n errors.push({\n code: \"F009\",\n message: `Mapped column name '${String(st.columnName)}' for '${fname}' in '${name}' is not a valid identifier`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n\n // F002: Count ID scalars\n if (st.isId) idCount++;\n\n // F003: Track column names\n const col = st.columnName ?? fname;\n if (!columnToFields.has(col)) columnToFields.set(col, []);\n columnToFields.get(col)!.push(fname);\n\n // F004: Default type match. A decimal literal crossed its complete field\n // codec when `.default()` retained it, so this downstream boundary trusts\n // that canonical output instead of applying a custom schema twice.\n if (\n st.hasDefault &&\n st.default !== undefined &&\n typeof st.default !== \"function\" &&\n st.type !== \"decimal\"\n ) {\n const jsonKind =\n st.type === \"json\" ? jsonNullKindOf(st.default) : undefined;\n const result =\n jsonKind === undefined\n ? validateSchema(scalar[\"~\"].state.base, st.default)\n : jsonKind === \"JsonNull\" || (jsonKind === \"DbNull\" && st.nullable)\n ? { value: st.default, issues: undefined }\n : {\n issues: [\n {\n message:\n \"JSON default names a null this column cannot store\",\n },\n ],\n };\n if (result.issues) {\n errors.push({\n code: \"F004\",\n message: `Default value for '${fname}' in '${name}' doesn't match type`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n }\n\n // F006: ID not nullable\n if (st.isId && st.nullable) {\n errors.push({\n code: \"F006\",\n message: `ID '${fname}' in '${name}' cannot be nullable`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n\n // F007: ID not array\n if (st.isId && st.array) {\n errors.push({\n code: \"F007\",\n message: `ID '${fname}' in '${name}' cannot be array`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n\n // F008: Surface actual generated defaults on non-key fields.\n if (\n !st.isId &&\n (st.autoGenerate?.kind === \"increment\" || isGeneratorDefault(st.default))\n ) {\n errors.push({\n code: \"F008\",\n message: `Generated default on non-key '${fname}' in '${name}'; verify generation is intended`,\n severity: \"warning\",\n model: name,\n field: fname,\n });\n }\n }\n\n // Check for compound ID\n const compoundIdCount = Object.keys(model[\"~\"].state.compoundId ?? {}).length;\n const hasCompoundId = compoundIdCount > 0;\n\n // M001: No ID field (allow if compound ID exists)\n if (idCount === 0 && !hasCompoundId) {\n errors.push({\n code: \"M001\",\n message: `'${name}' must have an ID field (or use .id() for compound key)`,\n severity: \"error\",\n model: name,\n });\n }\n\n // F002: Multiple single-field IDs, single + compound, or multiple .id() calls\n if (idCount > 1 || (idCount > 0 && hasCompoundId) || compoundIdCount > 1) {\n errors.push({\n code: \"F002\",\n message: `'${name}' has conflicting ID definitions (use either single field .id() or model .id())`,\n severity: \"error\",\n model: name,\n });\n }\n\n // F003: Duplicate columns\n for (const [col, fields] of columnToFields) {\n if (fields.length > 1) {\n errors.push({\n code: \"F003\",\n message: `Column '${col}' used by multiple fields in '${name}': ${fields.join(\n \", \"\n )}`,\n severity: \"error\",\n model: name,\n });\n }\n }\n\n return errors;\n}\n\n// =============================================================================\n// INDEX RULES (I001-I005)\n// =============================================================================\n\n/** I001: Index fields must exist */\nexport function indexFieldsExist(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n const fields = new Set(Object.keys(model[\"~\"].state.scalars));\n for (const idx of model[\"~\"].state.indexes) {\n for (const f of idx.fields) {\n if (!fields.has(f)) {\n errors.push({\n code: \"I001\",\n message: `Index field '${f}' not in '${name}'`,\n severity: \"error\",\n model: name,\n field: f,\n });\n }\n }\n }\n return errors;\n}\n\n/** I002: Index names must be unique */\nexport function indexNameUnique(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const names = new Map<string, number>();\n for (const idx of model[\"~\"].state.indexes) {\n if (idx.options.name) {\n names.set(idx.options.name, (names.get(idx.options.name) ?? 0) + 1);\n }\n }\n const errors: SchemaValidationIssue[] = [];\n for (const [iname, count] of names) {\n if (count > 1) {\n errors.push({\n code: \"I002\",\n message: `Index name '${iname}' duplicated in '${name}'`,\n severity: \"error\",\n model: name,\n });\n }\n }\n return errors;\n}\n\n/** I003: Compound unique/id constraints must contain at least one field. */\nexport function compoundConstraintsNonEmpty(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n\n const compoundIdFields = getCompoundIdFields(model);\n if (model[\"~\"].state.compoundId && compoundIdFields.length === 0) {\n errors.push({\n code: \"I003\",\n message: `Compound ID in '${name}' must contain at least one field`,\n severity: \"error\",\n model: name,\n });\n }\n const compoundUniques = getCompoundUniques(model);\n for (const constraint of compoundUniques) {\n if (constraint.fields.length === 0) {\n errors.push({\n code: \"I003\",\n message: `Compound unique '${constraint.name}' in '${name}' must contain at least one field`,\n severity: \"error\",\n model: name,\n });\n }\n }\n\n return errors;\n}\n\n/**\n * F010's reserved names, each with the output it is reserved for. Both are\n * keys a selection publishes on its own (owner rulings, 2026-09-26: \"_count is\n * a reserved word\", \"_distance is reserved too\"): `_count` in `select` and\n * `include` is the relation-count projection, and `_distance` is the key a\n * selected point or vector distance publishes under.\n */\nconst RESERVED_MEMBER_NAMES = {\n _count: \"relation counts\",\n _distance: \"distance results\",\n} as const;\n\n/**\n * F010: a model member never takes a reserved name.\n *\n * A member named `_count` or `_distance` — a scalar, a relation or a variant\n * slot — would give that output key two producers, and every reader of a\n * selection (admission, the engine's projection, the schema-only renderer,\n * the static types) then needs its own answer to which one wins. Refusing the\n * name here leaves each key one meaning everywhere downstream. The two names\n * share one sentence because they share the reason and the remedy: the column\n * name stays available, and a renamed scalar keeps it with `.map(...)`.\n *\n * TypeScript callers meet the refusal earlier: the shape parameter of\n * `s.model` and `.extends` forbids both keys (`DeclaredModelShape`). That is a\n * convenience for them only; a JavaScript caller, a cast or a computed key\n * reaches this rule, so F010 is the contract for every caller.\n */\nexport function memberNamesAreNotReserved(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const shape = model[\"~\"].state.shape;\n return Object.entries(RESERVED_MEMBER_NAMES)\n .filter(([reserved]) => Object.hasOwn(shape, reserved))\n .map(\n ([reserved, output]): SchemaValidationIssue => ({\n code: \"F010\",\n message: `Model '${name}' declares a member named '${reserved}'; '${reserved}' is reserved for ${output}. Rename it, and use .map(\"${reserved}\") on a renamed scalar to keep its column name.`,\n severity: \"error\",\n model: name,\n field: reserved,\n })\n );\n}\n\n/** I006: one model-local public unique-where name has one meaning. */\nexport function publicSelectorNamesAreUnambiguous(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n return getAmbiguousPublicSelectorNames(model).map((selector) => ({\n code: \"I006\",\n message: `Public selector name '${selector}' is ambiguous in '${name}'; a compound selector must not reuse a model field, logical filter, or another compound selector name`,\n severity: \"error\",\n model: name,\n }));\n}\n\n/**\n * I004: a fixed-decimal LIST is not a member of a key or an index (plan 2.1).\n *\n * The MODEL-level half of the exclusion. `.id()` and `.unique()` are refused on\n * the declaration itself, where the chain writes them, but a compound key, a\n * compound unique and an index name their members by string from the model, so\n * the declaration never sees them and this is the only place they exist.\n *\n * Why a decimal list in particular: on two of three providers the column holds\n * ONE JSON container, so an index or a key over it addresses a document by its\n * spelling rather than by its members — and `[\"1.2\"]` and `[\"1.20\"]` are the\n * same list. Other array scalars are not refused: PostgreSQL indexes native\n * arrays meaningfully, and this program speaks only for the fixed decimal.\n */\nexport function decimalListsAreNotKeyMembers(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const scalars = model[\"~\"].state.scalars;\n const isDecimalList = (field: string): boolean => {\n const state = scalars[field]?.[\"~\"].state;\n return state?.type === \"decimal\" && state.array === true;\n };\n\n const positions: Array<{ field: string; position: string }> = [];\n for (const index of model[\"~\"].state.indexes) {\n for (const field of index.fields) {\n positions.push({ field, position: \"an index\" });\n }\n }\n for (const field of getCompoundIdFields(model)) {\n positions.push({ field, position: \"a compound ID\" });\n }\n for (const constraint of getCompoundUniques(model)) {\n for (const field of constraint.fields) {\n positions.push({ field, position: `unique '${constraint.name}'` });\n }\n }\n\n const errors: SchemaValidationIssue[] = [];\n for (const { field, position } of positions) {\n if (!isDecimalList(field)) continue;\n errors.push({\n code: \"I004\",\n message: `'${field}' in '${name}' is a fixed-decimal list, which cannot be a member of ${position}`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n return errors;\n}\n\n/**\n * I005: GeoPoint has one portable physical index role and no key role.\n *\n * The scalar class has no `.id()`/`.unique()` methods and the typed model\n * surface excludes compound keys and ordinary indexes. This definition gate\n * owns hostile JavaScript and decoded schema values that bypass those types.\n */\nexport function geoPointRolesArePortable(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const state = model[\"~\"].state;\n const isPoint = (field: string): boolean =>\n state.scalars[field]?.[\"~\"].state.type === \"point\";\n const issues: SchemaValidationIssue[] = [];\n\n for (const [field, scalar] of getScalars(model)) {\n const scalarState = scalar[\"~\"].state;\n if (\n scalarState.type === \"point\" &&\n (scalarState.isId || scalarState.isUnique)\n ) {\n issues.push({\n code: \"I005\",\n message: `GeoPoint '${field}' in '${name}' cannot be an ID or unique field`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n }\n\n for (const field of getCompoundIdFields(model)) {\n if (!isPoint(field)) continue;\n issues.push({\n code: \"I005\",\n message: `GeoPoint '${field}' in '${name}' cannot be a compound ID member`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n for (const constraint of getCompoundUniques(model)) {\n for (const field of constraint.fields) {\n if (!isPoint(field)) continue;\n issues.push({\n code: \"I005\",\n message: `GeoPoint '${field}' in '${name}' cannot be a member of unique '${constraint.name}'`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n }\n\n for (const index of state.indexes) {\n const pointFields = index.fields.filter(isPoint);\n const point =\n pointFields.length === 1\n ? state.scalars[pointFields[0]!]?.[\"~\"].state\n : undefined;\n const valid =\n index.fields.length === 1 &&\n pointFields.length === 1 &&\n point?.nullable === false &&\n index.options.type === \"spatial\" &&\n index.options.unique === undefined &&\n index.options.where === undefined;\n if (valid) continue;\n if (pointFields.length === 0 && index.options.type !== \"spatial\") continue;\n const field = pointFields[0] ?? index.fields[0];\n issues.push({\n code: \"I005\",\n message: `A spatial index in '${name}' must contain exactly one non-null GeoPoint and cannot be unique or partial`,\n severity: \"error\",\n model: name,\n ...(field ? { field } : {}),\n });\n }\n\n return issues;\n}\n\nexport const modelRules = [\n // Model-level checks (don't iterate fields)\n modelHasFields,\n modelNameValid,\n modelNameNotReserved,\n modelMappedNameValid,\n // Single-pass field validation (M001, F001-F008)\n validateFieldsSinglePass,\n // Index checks (iterate indexes, not fields)\n indexFieldsExist,\n indexNameUnique,\n // Compound key checks\n compoundConstraintsNonEmpty,\n publicSelectorNamesAreUnambiguous,\n memberNamesAreNotReserved,\n decimalListsAreNotKeyMembers,\n geoPointRolesArePortable,\n];\n","// Advisory cross-model relation rules.\n//\n// Every structural relation invariant — pairing, ownership, uniqueness, modifier\n// placement, physical junction naming — belongs to the mandatory\n// relation-definition gate (`../relation-resolution`). What survives here is\n// advice about how a schema is SPELLED, which the gate has no opinion about:\n// scalars that look like foreign keys but are not, a required insert cycle, and\n// the hand-rolled `*_type` + `*_id` pattern a variant carrier replaces.\n\nimport type { Model } from \"../../model\";\nimport type { Schema, SchemaValidationIssue } from \"../types\";\nimport { getCompoundIdFields, getCompoundUniques } from \"./model\";\nimport { getRelationValues, getScalars } from \"./model-members\";\n\n/** CM001: FK fields should have corresponding relation (warning) */\nexport function noOrphanFkFields(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n const fkFields = new Set<string>();\n for (const rel of getRelationValues(model)) {\n for (const field of rel[\"~\"].state.foreignKey?.fields ?? []) {\n fkFields.add(field);\n }\n }\n // Compound key members (e.g. orgId in .id([\"orgId\", \"memberId\"])) are\n // legitimate non-relation fields\n const compoundFields = new Set(getCompoundIdFields(model));\n for (const cu of getCompoundUniques(model)) {\n for (const f of cu.fields) compoundFields.add(f);\n }\n for (const [fname, scalar] of getScalars(model)) {\n // Heuristic: scalar key ending in \"Id\" might be FK\n if (\n fname.endsWith(\"Id\") &&\n !fkFields.has(fname) &&\n !compoundFields.has(fname) &&\n !scalar[\"~\"].state.isId\n ) {\n errors.push({\n code: \"CM001\",\n message: `'${fname}' in '${name}' looks like FK but no relation uses it`,\n severity: \"warning\",\n model: name,\n field: fname,\n });\n }\n }\n return errors;\n}\n\n/**\n * CM004: the hand-rolled polymorphic pattern.\n *\n * A `*_type` + `*_id` scalar pair with no relation using the id column is the\n * shape `s.toOne({ ... })` owns natively, with a real discriminator, exact\n * result types and validated targets.\n */\nconst POLYMORPHIC_TYPE_REGEX = /_type$|Type$/;\nexport function polymorphicRelationWarning(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n const fieldNames = Object.keys(model[\"~\"].state.scalars);\n\n for (const fname of fieldNames) {\n if (!(fname.endsWith(\"_type\") || fname.endsWith(\"Type\"))) continue;\n\n // Extract base name: \"commentable_type\" -> \"commentable\"\n const base = fname.replace(POLYMORPHIC_TYPE_REGEX, \"\");\n const idField = fieldNames.find(\n (f) => f === `${base}_id` || f === `${base}Id`\n );\n\n if (!idField) continue;\n const hasRelation = getRelationValues(model).some((relation) =>\n relation[\"~\"].state.foreignKey?.fields.includes(idField)\n );\n if (hasRelation) continue;\n errors.push({\n code: \"CM004\",\n message: `'${fname}' + '${idField}' in '${name}' looks like polymorphic pattern (not type-safe)`,\n severity: \"warning\",\n model: name,\n field: fname,\n });\n }\n return errors;\n}\n\nexport const relationRules = [noOrphanFkFields, polymorphicRelationWarning];\n","// Advisory validation rules.\n//\n// Structural relation topology is not here: the mandatory gate\n// (`../relation-resolution`) owns it and runs at every effect-capable boundary,\n// including the ones that skip this list.\n\nexport * from \"./model\";\nexport * from \"./relation\";\n\nimport type { ValidationRule } from \"../types\";\nimport { modelRules } from \"./model\";\nimport { relationRules } from \"./relation\";\n\nexport const allRules: ValidationRule[] = [...modelRules, ...relationRules];\n","// Schema Validator\n//\n// TWO layers, one boundary. The mandatory relation-definition gate\n// (`./relation-resolution`) decides every structural topology fact and runs at\n// every effect-capable boundary; the rule list beside it carries advice about\n// how a schema is spelled. `skipValidation` may drop the advice. It cannot drop\n// the gate: no query or migration is allowed to guess an edge.\n\nimport type { Model } from \"../model\";\nimport { preflightModelRegistrationIdentity } from \"../registration-preflight\";\nimport { SchemaValidationError } from \"./error\";\nimport {\n type RelationResolution,\n type ResolvedRelationIndex,\n resolveSchemaRelations,\n} from \"./relation-resolution\";\nimport { allRules } from \"./rules\";\nimport {\n memberNamesAreNotReserved,\n publicSelectorNamesAreUnambiguous,\n} from \"./rules/model\";\nimport type {\n Schema,\n SchemaValidationIssue,\n ValidationContext,\n ValidationResult,\n ValidationRule,\n} from \"./types\";\n\n/** Build context once, use everywhere */\nfunction buildContext(schema: Schema): ValidationContext {\n const modelToName = new Map<Model<any>, string>();\n const tableToModels = new Map<string, string[]>();\n\n for (const [name, model] of schema) {\n modelToName.set(model, name);\n const tableName = model[\"~\"].state.tableName ?? name;\n if (!tableToModels.has(tableName)) {\n tableToModels.set(tableName, []);\n }\n tableToModels.get(tableName)!.push(name);\n }\n\n return { modelToName, tableToModels };\n}\n\n/**\n * The public validator: every advisory rule unless told otherwise. Client\n * construction does not use it; {@link resolveSchemaOrThrow} runs only the\n * selector rules, so a client bundle does not carry the advisory ones.\n */\nexport class SchemaValidator {\n readonly #schema: Schema = new Map();\n /** One resolution per validator lifecycle: the gate runs once per schema. */\n #resolution: RelationResolution | undefined;\n\n /** Register a model with a name */\n register(name: string, model: Model<any>): this {\n const registered = this.#schema.get(name);\n if (registered) {\n if (registered === model) {\n this.#resolution = undefined;\n return this;\n }\n throw validationError([\n {\n code: \"M003\",\n message: `Model name '${name}' is duplicated`,\n severity: \"error\",\n model: name,\n },\n ]);\n }\n this.#schema.set(name, model);\n this.#resolution = undefined;\n return this;\n }\n\n /** Register multiple models */\n registerAll(models: Record<string, Model<any>>): this {\n for (const [name, model] of Object.entries(models)) {\n this.register(name, model);\n }\n return this;\n }\n\n /**\n * Resolve the relation graph. The successful arm is the one trusted topology\n * view; the failure arm carries the issues and, for a thrown lazy getter, the\n * terminal's own settled `Error`.\n */\n resolve(): RelationResolution {\n this.#resolution ??= resolveRegistered(\n this.#schema,\n buildContext(this.#schema)\n );\n return this.#resolution;\n }\n\n /** Validate all registered models */\n validate(rules: ValidationRule[] = allRules): ValidationResult {\n const errors: SchemaValidationIssue[] = [];\n const warnings: SchemaValidationIssue[] = [];\n for (const issue of schemaIssues(\n this.#schema,\n buildContext(this.#schema),\n this.resolve(),\n rules\n )) {\n (issue.severity === \"error\" ? errors : warnings).push(issue);\n }\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n\n /**\n * Validate and throw if invalid; a valid schema publishes the one trusted\n * topology. `validate` already reports every resolution issue by severity,\n * so validity and a successful resolution are one fact stated here once.\n */\n validateOrThrow(rules: ValidationRule[] = allRules): ResolvedRelationIndex {\n const result = this.validate(rules);\n const resolution = this.resolve();\n if (result.valid && resolution.ok) return resolution.index;\n throw validationError(\n result.errors,\n resolution.ok ? undefined : resolution.cause\n );\n }\n}\n\n/** The identity preflight, then the relation gate. */\nfunction resolveRegistered(\n schema: Schema,\n ctx: ValidationContext\n): RelationResolution {\n const identityIssue = preflightModelRegistrationIdentity(schema);\n return identityIssue\n ? { ok: false, issues: [identityIssue] }\n : resolveSchemaRelations(schema, ctx);\n}\n\n/**\n * Every issue a schema carries, in report order: shared tables, then the gate's\n * own issues — it reports on every schema, valid or not, since a successful\n * resolution still carries the advisories its subowners produced — then every\n * rule on every model. A throwing rule is S001.\n */\nfunction schemaIssues(\n schema: Schema,\n ctx: ValidationContext,\n resolution: RelationResolution,\n rules: readonly ValidationRule[]\n): SchemaValidationIssue[] {\n const issues: SchemaValidationIssue[] = [];\n for (const [tableName, models] of ctx.tableToModels) {\n if (models.length > 1) issues.push(sharedTableIssue(tableName, models));\n }\n for (const issue of resolution.issues) issues.push(issue);\n for (const [modelName, model] of schema) {\n for (const rule of rules) {\n let results: SchemaValidationIssue[];\n try {\n results = rule(schema, modelName, model, ctx);\n } catch (cause) {\n throw ruleFailure(rule, modelName, cause);\n }\n for (const result of results) issues.push(result);\n }\n }\n return issues;\n}\n\n/** Validate a schema object directly */\nexport function validateSchema(\n models: Record<string, Model<any>>\n): ValidationResult {\n return new SchemaValidator().registerAll(models).validate();\n}\n\n/**\n * Validate or throw — the structural gate plus the advisory rules, resolved\n * exactly once. The resolved index is an internal execution capability, not a\n * public validation result.\n */\nexport function validateSchemaOrThrow(\n models: Record<string, Model<any>>\n): void {\n validateResolvedSchemaOrThrow(models, allRules);\n}\n\n/** Internal validation boundary that also publishes the trusted topology. */\nexport function validateResolvedSchemaOrThrow(\n models: Record<string, Model<any>>,\n rules: ValidationRule[]\n): ResolvedRelationIndex {\n return new SchemaValidator().registerAll(models).validateOrThrow(rules);\n}\n\n/**\n * The rules every effect-capable boundary runs beside the relation gate: each\n * gives one admitted selector one meaning — a compound selector never reuses a\n * member name (I006), and no member takes an output key a selection\n * reserves, `_count` or `_distance` (F010).\n */\nconst SELECTOR_RULES: ValidationRule[] = [\n publicSelectorNamesAreUnambiguous,\n memberNamesAreNotReserved,\n];\n\n/**\n * The mandatory structural gate, for every boundary that can produce effects:\n * client construction, standalone registry construction, and migration\n * serialization/generation/push — including `push({ skipValidation: true })`,\n * which may skip advice but never this.\n *\n * It validates the definition contracts every query client relies on: the\n * relation gate plus the schema-wide model-identity checks a client needs to\n * address a model at all (one schema key per model object, no shared table)\n * and the selector rules, resolved exactly once. Advisory rules about how a\n * schema is spelled — a missing id, a reserved model name, an index shape —\n * remain at the boundary that writes DDL. Public selector ambiguity is\n * structural: every client operation relies on one stable meaning for each\n * admitted selector. Only errors are collected: no caller of this gate reads\n * an advisory.\n *\n * Returns the one trusted index. The caller owns it for its own lifecycle and\n * passes it on by identity rather than copying it.\n */\nexport function resolveSchemaOrThrow(\n models: Record<string, Model<any>>\n): ResolvedRelationIndex {\n // `Object.entries` keys are unique, so no name can be registered twice.\n const schema: Schema = new Map(Object.entries(models));\n const ctx = buildContext(schema);\n const resolution = resolveRegistered(schema, ctx);\n const errors = schemaIssues(schema, ctx, resolution, SELECTOR_RULES).filter(\n (issue) => issue.severity === \"error\"\n );\n if (errors.length === 0 && resolution.ok) return resolution.index;\n throw validationError(errors, resolution.ok ? undefined : resolution.cause);\n}\n\n/**\n * The client gate for a schema `viborm check` already validated: relation\n * resolution only, because the engine needs its topology. The identity,\n * table-name, selector-name and cycle checks are the check command's.\n */\nexport function resolveCheckedSchemaOrThrow(\n models: Record<string, Model<any>>\n): ResolvedRelationIndex {\n const schema: Schema = new Map(Object.entries(models));\n const resolution = resolveSchemaRelations(schema, buildContext(schema), true);\n if (resolution.ok) return resolution.index;\n throw validationError(\n resolution.issues.filter((issue) => issue.severity === \"error\"),\n resolution.cause\n );\n}\n\n/** One construction path for every thrown schema-validation result. */\nfunction validationError(\n issues: readonly SchemaValidationIssue[],\n cause?: Error\n): SchemaValidationError {\n return new SchemaValidationError(issues, cause ? { cause } : undefined);\n}\n\n/** M004, built only when two models share a table. */\nfunction sharedTableIssue(\n tableName: string,\n models: readonly string[]\n): SchemaValidationIssue {\n return {\n code: \"M004\",\n message: `Table name '${tableName}' used by multiple models: ${models.join(\", \")}`,\n severity: \"error\",\n };\n}\n\n/** A rule that threw, reported as the schema error it is. */\nfunction ruleFailure(\n rule: ValidationRule,\n modelName: string,\n cause: unknown\n): SchemaValidationError {\n const message = cause instanceof Error ? cause.message : String(cause);\n return new SchemaValidationError(\n [\n {\n code: \"S001\",\n message: `Schema rule '${rule.name || \"anonymous\"}' failed for '${modelName}': ${message}`,\n severity: \"error\",\n model: modelName,\n },\n ],\n cause instanceof Error ? { cause } : undefined\n );\n}\n"],"mappings":"sWAuEA,MAAM,EAAe,IAAI,QAEzB,SAAgB,mBAAmB,EAAoC,CACrE,IAAM,EAAS,EAAa,IAAI,EAAM,CACtC,GAAI,EACF,OAAO,EAET,IAAM,EAAU,qBAAqB,EAA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AW,MACrC,MAAM,gBACJ,EAAW,OAAO,OAAQ,GAAUA,EAAM,WAAa,QAAQ,CAC/D,EAAW,MACZ,CAIH,SAAS,gBACP,EACA,EACuB,CACvB,OAAO,IAAI,EAAsB,EAAQ,EAAQ,CAAE,QAAO,CAAG,IAAA,GAAU,CAIzE,SAAS,iBACP,EACA,EACuB,CACvB,MAAO,CACL,KAAM,OACN,QAAS,eAAe,EAAU,6BAA6B,EAAO,KAAK,KAAK,GAChF,SAAU,QACX,CAIH,SAAS,YACP,EACA,EACA,EACuB,CACvB,IAAM,EAAU,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,CACtE,OAAO,IAAI,EACT,CACE,CACE,KAAM,OACN,QAAS,gBAAgB,EAAK,MAAQ,YAAY,gBAAgB,EAAU,KAAK,IACjF,SAAU,QACV,MAAO,EACR,CACF,CACD,aAAiB,MAAQ,CAAE,QAAO,CAAG,IAAA,GACtC"}
|
|
1
|
+
{"version":3,"file":"validator-BqzpyNmt.mjs","names":["marker","scalar","validateSchema","isDecimalList","#schema","#resolution","issue"],"sources":["../src/schema/model/keys.ts","../src/schema/relation/helpers.ts","../src/schema/relation/junction-topology.ts","../src/schema/validation/id-domains.ts","../src/schema/validation/rules/fk.ts","../src/schema/validation/rules/model-members.ts","../src/schema/validation/rules/polymorphic.ts","../src/schema/validation/relation-resolution.ts","../src/schema/validation/rules/model.ts","../src/schema/validation/rules/relation.ts","../src/schema/validation/rules/index.ts","../src/schema/validation/validator.ts"],"sourcesContent":["/**\n * The ordered model-key catalog — the one owner of how a row can be addressed.\n *\n * A model's key facts have exactly three shapes, and this module stores each\n * once, grouped and ordered, in TS-field-name space:\n *\n * - `rowKey` — the complete primary key in constraint order (the array given to\n * `.id([...])`, or the one `.id()` scalar). Optional: a model may declare no\n * primary key.\n * - `addressableKeys` — the exact keys a public unique selector can name. A key\n * with a `name` is a grouped constraint whose selector is that name and whose\n * value is an object of members (`where: { region_slug: { region, slug } }`);\n * a key without one is a bare scalar selector (`where: { email }`). That\n * spelling difference is a real addressing fact — `.id([\"a\"])` and a scalar\n * `.id()` on `a` accept different selectors — so it is stored, not inferred.\n * - `referenceableKeys` — every complete ordered key a foreign key may target:\n * the addressable keys above plus total unique indexes. This is deliberately\n * wider than the public selector grammar and is the one physical-key catalog\n * consumed by schema validation and relation topology.\n * - `uniqueOverlapFields` — the conservative flattened view, used only to ask\n * whether two selectors MAY overlap. Never a substitute for a grouped key.\n *\n * Public addressability and physical referenceability remain distinct views:\n * a foreign key may target a total unique INDEX no selector can address.\n *\n * A second deliberate survivor: the validation whereUnique factories\n * (`validation/model/core/filter.ts` / `where.ts`) keep reading the constraint\n * slots directly, because they need the member `VibSchema` VALUES to build the\n * parser and its inferred type — something a field-name catalog structurally\n * cannot supply. That is the preserved type/runtime-projection distinction,\n * not a missed migration.\n *\n * The catalog's arrays are cached for the model's lifetime and handed out\n * uncopied; every consumer treats them as the `readonly` types say. A consumer\n * that needs to mutate must copy first, as `getPrimaryKeyFields` does.\n *\n * Field-name space only: hydration binds column names after model construction,\n * so caching resolved columns here would freeze pre-hydration names. Every\n * column resolution is a downstream projection through `getColumnName`.\n */\n\nimport { isTotalIndex, type Model } from \"./model\";\n\nexport interface OrderedModelKey {\n // No \"uniqueIndex\" kind, deliberately departing from the plan's §4.1 sketch:\n // an index is never addressable, and an inhabited kind for it would invite\n // someone to push index-derived keys into `addressableKeys`, silently making\n // `where: { <indexed column> }` a unique discriminator.\n readonly kind: \"primary\" | \"unique\" | \"compoundUnique\";\n /**\n * The grouped-constraint selector name. Present exactly when the public\n * selector is the constraint name wrapping an object of members; absent for\n * a bare single-scalar selector.\n */\n readonly name?: string;\n /** Ordered members. Compound keys stay grouped; never flatten them. */\n readonly fields: readonly string[];\n}\n\nexport interface ModelKeyCatalog {\n readonly rowKey?: OrderedModelKey;\n readonly addressableKeys: readonly OrderedModelKey[];\n readonly referenceableKeys: readonly (readonly string[])[];\n readonly uniqueOverlapFields: readonly string[];\n}\n\n/**\n * One catalog per model instance. Models are immutable after construction\n * except name hydration, which binds COLUMN names only — key membership and\n * order never change, and the catalog stores no columns.\n */\nconst catalogCache = new WeakMap<object, ModelKeyCatalog>();\n\nexport function getModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const cached = catalogCache.get(model);\n if (cached) {\n return cached;\n }\n const catalog = buildModelKeyCatalog(model);\n catalogCache.set(model, catalog);\n return catalog;\n}\n\n/**\n * Resolve one public unique-selector key to its addressable key.\n *\n * Definition validation guarantees that one model-local public selector name\n * identifies at most one key. The catalog therefore resolves one exact match;\n * it does not own a scalar/compound or primary/unique precedence policy.\n */\nexport function findAddressableKey(\n model: Model<any>,\n selectorKey: string\n): OrderedModelKey | undefined {\n for (const key of getModelKeyCatalog(model).addressableKeys) {\n const selector = key.name ?? key.fields[0];\n if (selector === selectorKey) {\n return key;\n }\n }\n return undefined;\n}\n\nconst LOGICAL_FILTER_NAMES = [\"AND\", \"OR\", \"NOT\"] as const;\n\n/**\n * Find compound selectors that collide in the actual public unique-where\n * namespace. Extended unique selectors merge every model field and the three\n * logical filters with compound discriminators, so those names are occupied\n * before compound IDs and uniques are added. The namespace is model-local and\n * stays in TypeScript/query spelling; mapped columns and physical constraint\n * names are separate adapter/driver facts.\n */\nexport function getAmbiguousPublicSelectorNames(\n model: Model<any>\n): readonly string[] {\n const state = model[\"~\"].state;\n const occupied = new Set<string>([\n ...Object.keys(state.shape),\n ...LOGICAL_FILTER_NAMES,\n ]);\n const ambiguous = new Set<string>();\n const compoundNames = [\n ...Object.keys(state.compoundId ?? {}),\n ...Object.keys(state.compoundUniques ?? {}),\n ];\n for (const name of compoundNames) {\n if (occupied.has(name)) ambiguous.add(name);\n occupied.add(name);\n }\n return [...ambiguous];\n}\n\n/**\n * Resolve one complete referenced tuple to the target key's own order.\n *\n * Membership is order-insensitive, but the answer is ordered because MySQL\n * requires composite referenced columns to follow an index left-prefix. An\n * exactly-spelled key wins; otherwise catalog order supplies the stable answer.\n */\nexport function findReferenceableKey(\n model: Model<any>,\n fields: readonly string[]\n): readonly string[] | undefined {\n let setMatch: readonly string[] | undefined;\n for (const candidate of getModelKeyCatalog(model).referenceableKeys) {\n if (\n candidate.length !== fields.length ||\n !candidate.every((field) => fields.includes(field))\n ) {\n continue;\n }\n if (candidate.every((field, position) => field === fields[position])) {\n return candidate;\n }\n setMatch ??= candidate;\n }\n return setMatch;\n}\n\nfunction buildModelKeyCatalog(model: Model<any>): ModelKeyCatalog {\n const state = model[\"~\"].state;\n const addressableKeys: OrderedModelKey[] = [];\n\n // Bare scalar selectors, in shape-declaration order. `state.uniques` carries\n // `.id()` scalars beside `.unique()` ones (`extractUniqueScalarMap` keys on\n // `isUnique || isId`), so the scalar primary key is addressable here too.\n let scalarRowKey: OrderedModelKey | undefined;\n for (const field of Object.keys(state.uniques)) {\n const isId = state.scalars[field]?.[\"~\"].state.isId === true;\n const key: OrderedModelKey = isId\n ? { kind: \"primary\", fields: [field] }\n : { kind: \"unique\", fields: [field] };\n if (isId && !scalarRowKey) {\n scalarRowKey = key;\n }\n addressableKeys.push(key);\n }\n\n // EVERY declared compound-id constraint is addressable by its name — the\n // selector grammar has always resolved any of them (a second `.id([...])` is\n // representable; F002 refuses it at PUSH time only, never at `createClient`),\n // and empty ones stay addressable so their established \"must include at least\n // one field\" refusal keeps firing. The ROW key below is narrower: first\n // non-empty constraint only.\n const compoundIds: Record<string, { entries: Record<string, unknown> }> =\n state.compoundId ?? {};\n let compoundRowKey: OrderedModelKey | undefined;\n let firstCompoundId = true;\n for (const [name, constraint] of Object.entries(compoundIds)) {\n const key: OrderedModelKey = {\n kind: \"primary\",\n name,\n fields: Object.keys(constraint.entries),\n };\n // The row key is the FIRST declared constraint only, and only when it has a\n // name and members — a later non-empty constraint does not promote, exactly\n // as `getCompoundIdConstraint` has always read the record.\n if (firstCompoundId) {\n firstCompoundId = false;\n if (name && key.fields.length > 0) {\n compoundRowKey = key;\n }\n }\n addressableKeys.push(key);\n }\n\n // Named compound uniques, in declaration order.\n const compoundUniques: Record<string, { entries: Record<string, unknown> }> =\n state.compoundUniques ?? {};\n for (const [name, constraint] of Object.entries(compoundUniques)) {\n addressableKeys.push({\n kind: \"compoundUnique\",\n name,\n fields: Object.keys(constraint.entries),\n });\n }\n\n // The conservative flattened overlap view, in its established construction\n // order: scalar unique/id fields, then every compound-id member, then every\n // compound-unique member.\n const overlap = new Set<string>(Object.keys(state.uniques));\n for (const constraint of Object.values(compoundIds)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n for (const constraint of Object.values(compoundUniques)) {\n for (const field of Object.keys(constraint.entries)) {\n overlap.add(field);\n }\n }\n\n const referenceableKeys: readonly (readonly string[])[] = [\n ...addressableKeys.map((key) => key.fields),\n ...state.indexes\n .filter((index) => index.options.unique && isTotalIndex(index.options))\n .map((index) => index.fields),\n ];\n\n return {\n // The row key prefers the compound constraint: `getPrimaryKeyFields` has\n // always answered compound-first, and the projection contract pins that\n // reading (`target-projection.core.test.ts`, \"schema order is the KEY's\n // order\"). A model spelling both is refused by F002 at PUSH time only —\n // `createClient` never runs that rule — so the cursor deliberately keeps\n // its own scalar-first projection (`getCursorIdentityFields`).\n rowKey: compoundRowKey ?? scalarRowKey,\n addressableKeys,\n referenceableKeys,\n uniqueOverlapFields: [...overlap],\n };\n}\n","// Relation physical naming — stored-reference indexes plus junction tables,\n// side tokens, expanded columns, and constraint names.\n//\n// Nothing here discovers a pair. The full-schema relation resolver decides which\n// two slots share a junction and which single endpoint owns the overrides, then\n// hands this owner the already-oriented facts. That is why no function below\n// reads a relation object or a second endpoint's declaration.\n\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport type { JunctionSideActions } from \"./types\";\n\n// =============================================================================\n// DEFAULT NAMES\n// =============================================================================\n\n/**\n * Generate a junction table name from two model names\n * Names are sorted alphabetically and joined with underscore\n *\n * @example\n * generateJunctionTableName(\"post\", \"tag\") // \"post_tag\"\n * generateJunctionTableName(\"user\", \"role\") // \"role_user\"\n */\nexport function generateJunctionTableName(\n model1: string,\n model2: string\n): string {\n const names = [model1.toLowerCase(), model2.toLowerCase()].sort();\n return `${names[0]}_${names[1]}`;\n}\n\n/**\n * Generate a junction column name from a model name\n *\n * @example\n * generateJunctionFieldName(\"post\") // \"postId\"\n * generateJunctionFieldName(\"User\") // \"userId\"\n */\nexport function generateJunctionFieldName(modelName: string): string {\n return `${modelName.toLowerCase()}Id`;\n}\n\nexport interface JunctionFieldGroup {\n /** The declared side token, or its generated equivalent. */\n readonly token: string;\n /** Complete ordered junction columns for this endpoint's row key. */\n readonly fields: readonly string[];\n}\n\nexport interface JunctionFieldGroups {\n readonly source: JunctionFieldGroup;\n readonly target: JunctionFieldGroup;\n}\n\nexport type JunctionConstraintKind = \"fkey\" | \"idx\" | \"key\";\n\nexport class JunctionPhysicalNameError extends Error {\n readonly kind: \"collision\" | \"invalidIdentifier\";\n\n constructor(kind: \"collision\" | \"invalidIdentifier\", message: string) {\n super(message);\n this.name = \"JunctionPhysicalNameError\";\n this.kind = kind;\n }\n}\n\n/**\n * The automatic index name backing a non-unique stored reference, or\n * `undefined` when the schema has already spent both spellings on its own\n * declared indexes — the index is a read optimization, so it yields to the\n * names the schema declared.\n *\n * ONE owner for the rule: the migration serializer emits this name and the\n * schema-validation variant-storage reservation refuses names that would\n * collide with it. Both call here over the normalized stored-reference column\n * order, so the emitted name and the reserved name cannot diverge.\n */\nexport function automaticForeignKeyIndexName(\n tableName: string,\n foreignKeyColumns: readonly string[],\n declaredNames: ReadonlySet<string>\n): string | undefined {\n const preferred = `${tableName}_${foreignKeyColumns.join(\"_\")}_idx`;\n const name = declaredNames.has(preferred)\n ? `${tableName}_${foreignKeyColumns.join(\"_\")}_fkey_idx`\n : preferred;\n return declaredNames.has(name) ? undefined : name;\n}\n\n/** Derive one portable junction constraint name from the side naming token. */\nexport function getJunctionConstraintName(\n table: string,\n side: JunctionFieldGroup,\n kind: JunctionConstraintKind\n): string {\n const name = `${table}_${side.token}_${kind}`;\n if (!isValidSchemaIdentifier(name)) {\n throw new JunctionPhysicalNameError(\n \"invalidIdentifier\",\n `Generated junction ${kind} name '${name}' is not a valid SQL identifier.`\n );\n }\n return name;\n}\n\n/**\n * Expand the two side naming tokens over their complete row keys. The four\n * guards live HERE and only here — row-key emptiness per side, token identifier\n * validity, expanded field identifier validity, and the cross-side field\n * collision — so the ordinary pair path and the variant member path share one\n * refusal set.\n */\nexport function expandJunctionFieldGroups(\n sourceModelName: string,\n targetModelName: string,\n sourceToken: string,\n targetToken: string,\n sourceRowKeyFields: readonly string[],\n targetRowKeyFields: readonly string[]\n): JunctionFieldGroups {\n if (sourceRowKeyFields.length === 0) {\n throw new Error(\n `Model '${sourceModelName}' has no primary key; a junction side requires a complete row key.`\n );\n }\n if (targetRowKeyFields.length === 0) {\n throw new Error(\n `Model '${targetModelName}' has no primary key; a junction side requires a complete row key.`\n );\n }\n for (const token of [sourceToken, targetToken]) {\n if (!isValidSchemaIdentifier(token)) {\n throw new JunctionPhysicalNameError(\n \"invalidIdentifier\",\n `Junction side prefix '${token}' is not a valid SQL identifier.`\n );\n }\n }\n const source = junctionFieldGroup(sourceToken, sourceRowKeyFields.length);\n const target = junctionFieldGroup(targetToken, targetRowKeyFields.length);\n const occupied = new Map<string, string>();\n for (const field of [...source.fields, ...target.fields]) {\n if (!isValidSchemaIdentifier(field)) {\n throw new JunctionPhysicalNameError(\n \"invalidIdentifier\",\n `Expanded junction field '${field}' is not a valid SQL identifier.`\n );\n }\n const portableName = field.toLowerCase();\n const previous = occupied.get(portableName);\n if (previous !== undefined) {\n throw new JunctionPhysicalNameError(\n \"collision\",\n `Junction fields '${previous}' and '${field}' collide after compound-prefix expansion.`\n );\n }\n occupied.set(portableName, field);\n }\n return { source, target };\n}\n\n/** Canonical physical side order shared by snapshots and bound membership. */\nexport function junctionSourceSideIsFirst(\n sourceModelName: string,\n sourceFields: readonly string[],\n targetModelName: string,\n targetFields: readonly string[]\n): boolean {\n const sourceModel = sourceModelName.toLowerCase();\n const targetModel = targetModelName.toLowerCase();\n if (sourceModel !== targetModel) return sourceModel < targetModel;\n return sourceFields.join(\"\\0\") <= targetFields.join(\"\\0\");\n}\n\nfunction junctionFieldGroup(\n token: string,\n rowKeyArity: number\n): JunctionFieldGroup {\n return {\n token,\n fields:\n rowKeyArity === 1\n ? [token]\n : Array.from(\n { length: rowKeyArity },\n (_, index) => `${token}_${index + 1}`\n ),\n };\n}\n\n// =============================================================================\n// ORDINARY PAIR NAMES\n// =============================================================================\n\n/**\n * One resolved ordinary junction pair, oriented source → target by the caller.\n * `overrides` are the SINGLE owning endpoint's, already mirrored into this\n * orientation; a pair whose two endpoints both configure the junction never\n * reaches here.\n */\nexport interface OrdinaryJunctionNameInput {\n readonly sourceModelName: string;\n readonly targetModelName: string;\n /** Field keys of the two paired slots — the self-junction token defaults. */\n readonly sourceField: string;\n readonly targetField: string;\n readonly sourceRowKeyIsCompound: boolean;\n readonly targetRowKeyIsCompound: boolean;\n /** The agreed relation-name claim, which suffixes a generated table name. */\n readonly pairName: string | undefined;\n readonly overrides: JunctionOverrideView | undefined;\n}\n\n/**\n * One endpoint's declared junction overrides, seen from the SOURCE side of the\n * resolved pair. The declaration type refuses an empty object; this resolved\n * view does not, because mirroring the owner's facts onto the other side is a\n * derivation, not a declaration.\n */\nexport interface JunctionOverrideView {\n readonly table?: string;\n readonly source?: string;\n readonly target?: string;\n readonly onDelete?: JunctionSideActions;\n readonly onUpdate?: JunctionSideActions;\n}\n\nexport interface OrdinaryJunctionNames {\n readonly table: string;\n readonly sourceToken: string;\n readonly targetToken: string;\n}\n\n/**\n * The ONE owner of an ordinary junction's default names.\n *\n * A self junction takes its side tokens from the two FIELD keys, because the\n * model name is the same on both sides and cannot separate them. A non-self\n * junction keeps the model-name derivation its stored bytes were generated\n * from. A compound row key turns the token into a positional prefix, so it\n * drops the scalar `Id` suffix.\n */\nexport function resolveOrdinaryJunctionNames(\n input: OrdinaryJunctionNameInput\n): OrdinaryJunctionNames {\n const overrides = input.overrides;\n const isSelf = input.sourceModelName === input.targetModelName;\n const base = generateJunctionTableName(\n input.sourceModelName,\n input.targetModelName\n );\n return {\n table:\n overrides?.table ?? (input.pairName ? `${base}_${input.pairName}` : base),\n sourceToken:\n overrides?.source ??\n defaultSideToken(\n isSelf,\n input.sourceField,\n input.sourceModelName,\n input.sourceRowKeyIsCompound\n ),\n targetToken:\n overrides?.target ??\n defaultSideToken(\n isSelf,\n input.targetField,\n input.targetModelName,\n input.targetRowKeyIsCompound\n ),\n };\n}\n\nfunction defaultSideToken(\n isSelf: boolean,\n field: string,\n modelName: string,\n isCompound: boolean\n): string {\n if (isSelf) return isCompound ? field : `${field}Id`;\n return isCompound\n ? modelName.toLowerCase()\n : generateJunctionFieldName(modelName);\n}\n","/**\n * Resolved junction topology — the one owner of a junction's physical facts:\n * the table, both complete ordered sides, the canonical side order, the pair\n * identity, and the derived constraint names.\n *\n * DELIBERATELY NOT exported from the relation barrel (`./index.ts`): the public\n * API of `viborm/schema` stays frozen, and every consumer deep-imports this\n * module.\n *\n * ONE ENTRY, ONE CALLER. The full-schema relation resolver hands this owner an\n * already-paired, already-oriented junction and stores the result on the\n * resolved edge; engine binder and migration serializer read that stored value\n * instead of expanding a second time. Ordinary pairs and variant member\n * junctions differ only in where their tokens come from, so they share one\n * derivation rather than two entry points with two refusal orders.\n *\n * Constraint names stay lazy memoized METHODS. The gate asks all four during\n * resolution, so a published edge carries them settled; laziness is what keeps\n * the equal-token refusal attached to the first ask rather than to construction.\n */\n\nimport type { Model } from \"../model\";\nimport {\n expandJunctionFieldGroups,\n generateJunctionFieldName,\n getJunctionConstraintName,\n type JunctionFieldGroup,\n JunctionPhysicalNameError,\n junctionSourceSideIsFirst,\n} from \"./helpers\";\nimport type {\n JunctionReferentialAction,\n VariantJunctionOverride,\n} from \"./types\";\n\nexport interface JunctionEndpointInput {\n /** Carried opaquely; the owner never dereferences it (the engine projects it into its `JunctionSide`). */\n readonly model: Model<any>;\n /**\n * The CALLER's established name spelling: the engine passes\n * `names.ts ?? \"unknown\"`, the resolver passes schema keys — identical only\n * because hydration sets `names.ts` to the key. The owner must not re-derive\n * names.\n */\n readonly modelName: string;\n /**\n * Complete ordered row key, resolved by the CALLER. May be empty — the owner\n * forwards it so `expandJunctionFieldGroups` stays the SINGLE emptiness\n * guard.\n */\n readonly rowKey: readonly string[];\n /** The side naming token, resolved by the caller from overrides or defaults. */\n readonly token: string;\n /**\n * This side's foreign-key actions, already oriented onto this side by the\n * caller. Absent (omitted, never `undefined`: the owner copies the side\n * through) means the junction default; only an ordinary pair's owner states\n * them.\n */\n readonly onDelete?: JunctionReferentialAction;\n readonly onUpdate?: JunctionReferentialAction;\n}\n\nexport interface JunctionTopologyInput {\n readonly table: string;\n readonly source: JunctionEndpointInput;\n readonly target: JunctionEndpointInput;\n readonly pairName: string | undefined;\n}\n\n/** One junction column paired with the endpoint field it references. */\nexport interface ResolvedJunctionMember {\n readonly junctionField: string;\n readonly referencedField: string;\n}\n\nexport interface ResolvedJunctionSide {\n readonly model: Model<any>;\n readonly modelName: string;\n /** The declared side token or its generated equivalent — the constraint-name input. */\n readonly token: string;\n /** Complete ordered stored reference, model-key-catalog order (index-aligned with the input rowKey). */\n readonly members: readonly ResolvedJunctionMember[];\n /**\n * The actions of the foreign key from the junction to THIS side's model.\n * They travel with the side, so reordering the two sides into canonical\n * physical order moves each action with its own table and columns.\n */\n readonly onDelete?: JunctionReferentialAction;\n readonly onUpdate?: JunctionReferentialAction;\n}\n\nexport interface ResolvedJunctionTopology {\n readonly table: string;\n readonly source: ResolvedJunctionSide;\n readonly target: ResolvedJunctionSide;\n /**\n * Canonical physical side order — `junctionSourceSideIsFirst` over the\n * token-expanded junction fields. A plain fact for the serializer; the\n * engine's `BoundJunctionMembership` does NOT gain this field and\n * membership-scope equality stays orientation-erased.\n */\n readonly sourceIsFirst: boolean;\n /** The agreed relation-name claim — pair-identity input for the serializer's dedupe key. */\n readonly pairName: string | undefined;\n /** `${table}_${sideToken}_fkey` via `getJunctionConstraintName`. Memoized per side. */\n foreignKeyName(side: \"source\" | \"target\"): string;\n /** `${table}_${secondToken}_idx` over the canonical SECOND side. Memoized. */\n reverseIndexName(): string;\n /**\n * `${table}_${targetToken}_key` over the complete TARGET side — the\n * singular-inverse unique-constraint name.\n */\n uniqueTargetName(): string;\n}\n\n/**\n * Resolve one junction's complete physical topology.\n *\n * Throws exactly what `expandJunctionFieldGroups` throws (row-key emptiness,\n * token identifier, expanded-field identifier, cross-side collision) and adds\n * no guard of its own beyond the equal-token refusal on the first fkey ask.\n */\nexport function resolveJunctionTopology(\n input: JunctionTopologyInput\n): ResolvedJunctionTopology {\n const groups = expandJunctionFieldGroups(\n input.source.modelName,\n input.target.modelName,\n input.source.token,\n input.target.token,\n input.source.rowKey,\n input.target.rowKey\n );\n return deriveJunctionTopology({\n table: input.table,\n source: sideFacts(input.source, groups.source),\n target: sideFacts(input.target, groups.target),\n pairName: input.pairName,\n });\n}\n\nexport interface VariantMemberNames {\n readonly table: string;\n readonly sourceToken: string;\n readonly targetToken: string;\n}\n\n/**\n * The ONE owner of a variant collection member's junction names.\n *\n * Defaults: the table is `${ownerTable}_${relationField}_${publicType}`\n * (declaration-shaped, NOT the sorted-alphabetical ordinary generator — a\n * member junction has an owner side and a variant side, not two peers); the\n * source token follows the ordinary convention (compound row key → lowercased\n * owner schema key as a positional prefix, scalar →\n * `<lowercasedOwnerSchemaKey>Id`); the target token is\n * VARIANT-derived (`publicType` rather than the target model's name), which\n * keeps same-model duplicate variants and self targets naturally distinct — a\n * self target whose variant spells the owner's own name collides and is refused\n * through the one cross-side collision guard, escaped via `.through()`. An\n * explicit `.through()` entry overrides all three names.\n *\n * The owner RETURNS NAMES ONLY. Identifier and length refusals fire where each\n * name is consumed.\n */\nexport function resolveVariantMemberNames(input: {\n readonly ownerTableName: string;\n readonly ownerModelName: string;\n readonly relationField: string;\n readonly publicType: string;\n readonly ownerRowKeyIsCompound: boolean;\n readonly targetRowKeyIsCompound: boolean;\n readonly junction: VariantJunctionOverride | undefined;\n}): VariantMemberNames {\n if (input.junction) {\n return {\n table: input.junction.table,\n sourceToken: input.junction.source,\n targetToken: input.junction.target,\n };\n }\n return {\n table: `${input.ownerTableName}_${input.relationField}_${input.publicType}`,\n sourceToken: input.ownerRowKeyIsCompound\n ? input.ownerModelName.toLowerCase()\n : generateJunctionFieldName(input.ownerModelName),\n targetToken: input.targetRowKeyIsCompound\n ? input.publicType.toLowerCase()\n : generateJunctionFieldName(input.publicType),\n };\n}\n\n/** Per-side facts the relation-free derivation consumes. */\ninterface JunctionSideFacts {\n readonly model: Model<any>;\n readonly modelName: string;\n readonly token: string;\n readonly fields: readonly string[];\n readonly rowKey: readonly string[];\n readonly onDelete?: JunctionReferentialAction;\n readonly onUpdate?: JunctionReferentialAction;\n}\n\ninterface JunctionTopologyFacts {\n readonly table: string;\n readonly source: JunctionSideFacts;\n readonly target: JunctionSideFacts;\n readonly pairName: string | undefined;\n}\n\n/**\n * The endpoint's facts travel through as the caller stated them: its actions\n * are already oriented onto this side, and an unstated one is already absent.\n */\nfunction sideFacts(\n endpoint: JunctionEndpointInput,\n group: JunctionFieldGroup\n): JunctionSideFacts {\n return { ...endpoint, token: group.token, fields: group.fields };\n}\n\n/** Relation-free half of the resolution: member zip, canonical order, names. */\nfunction deriveJunctionTopology(\n facts: JunctionTopologyFacts\n): ResolvedJunctionTopology {\n const { table, source, target, pairName } = facts;\n const sourceIsFirst = junctionSourceSideIsFirst(\n source.modelName,\n source.fields,\n target.modelName,\n target.fields\n );\n const canonicalSecond = sourceIsFirst ? target : source;\n let sourceForeignKey: string | undefined;\n let targetForeignKey: string | undefined;\n let reverseIndex: string | undefined;\n let uniqueTarget: string | undefined;\n return {\n table,\n source: resolveSide(source),\n target: resolveSide(target),\n sourceIsFirst,\n pairName,\n foreignKeyName(side: \"source\" | \"target\"): string {\n // The SOLE guard against duplicate `${table}_${token}_fkey` names from\n // equal side tokens whose EXPANSIONS differ in arity (explicit scalar\n // token vs generated compound prefix): the expanded-field collision guard\n // never sees them.\n if (source.token === target.token) {\n throw new JunctionPhysicalNameError(\n \"collision\",\n `Junction sides of '${table}' share naming token '${source.token}' and would derive the same foreign-key constraint name.`\n );\n }\n if (side === \"source\") {\n sourceForeignKey ??= getJunctionConstraintName(table, source, \"fkey\");\n return sourceForeignKey;\n }\n targetForeignKey ??= getJunctionConstraintName(table, target, \"fkey\");\n return targetForeignKey;\n },\n reverseIndexName(): string {\n reverseIndex ??= getJunctionConstraintName(table, canonicalSecond, \"idx\");\n return reverseIndex;\n },\n uniqueTargetName(): string {\n uniqueTarget ??= getJunctionConstraintName(table, target, \"key\");\n return uniqueTarget;\n },\n };\n}\n\nfunction resolveSide({\n fields,\n rowKey,\n ...side\n}: JunctionSideFacts): ResolvedJunctionSide {\n return {\n ...side,\n members: rowKey.map((referencedField, index) => ({\n // `junctionFieldGroup` (helpers.ts) returns exactly `rowKeyArity` fields\n // for the same row-key list zipped here, so this lookup cannot miss.\n junctionField: fields[index]!,\n referencedField,\n })),\n };\n}\n","/**\n * Where a FOREIGN KEY gets its identifier domain.\n *\n * A key declares its format; the columns that reference it do not repeat the\n * declaration. `post.authorId` referencing `user.id` — a `.uuid(\"usr\")` — holds\n * exactly the values `user.id` holds, so it admits them, normalizes them and\n * stores them the same way, and it does so without a generator of its own and\n * without a single character of its own declaration. That is the whole rule:\n * DERIVED, never re-declared.\n *\n * It is a fact of the SCHEMA, not of a scalar, which is why it lives at L5\n * beside the resolution that already knows which field references which. The\n * FK scalar's state is never touched: no default is installed on it, and two\n * models sharing one `s.string()` instance stay independent, because the answer\n * is keyed by (model, field) and not by the scalar.\n *\n * Derivation is a FIXPOINT because a referenced key may itself be a foreign\n * key — a one-to-one child whose primary key is its parent reference is the\n * ordinary case, and a chain of them is not unusual. A reference CYCLE is\n * one answer, not several: every field on it holds every other's values, so\n * it holds the one domain its declarations and the keys it reaches outside\n * itself agree on, whatever order the schema lists its models in. A cycle with\n * no declaration anywhere on it simply has no domain; it is not an error, it\n * is a schema of plain strings.\n *\n * Two things make it fail, and both are the same failure: DISAGREEMENT. A field\n * reached through several references (a shared foreign key, a compound member,\n * a polymorphic variant row) must find one domain at the end of every one of\n * them, and a field that declares a domain must declare the one its target\n * already has. There is no first-target fallback and no \"closest\" rule: two\n * answers to \"what does this column hold\" is not something a default can fix.\n */\n\nimport {\n describeIdDomain,\n type IdDomain,\n sameIdDomain,\n} from \"@validation/primitives/id-codec\";\nimport type { Model } from \"../model\";\nimport {\n NATIVE_DIALECTS,\n type NativeTypeDeclaration,\n nativeTypeFor,\n} from \"../scalars/native-types\";\nimport {\n describeIdNativeTypes,\n idDomainOfState,\n idStorageOf,\n} from \"../scalars/string/id-domain\";\nimport type { ResolvedRelationIndex } from \"./relation-resolution\";\nimport { resolvedEdges } from \"./relation-resolution\";\nimport type { SchemaValidationIssue, ValidationContext } from \"./types\";\n\n/** Per model, the domain of each field that has one — declared or derived. */\nexport type IdDomainIndex = ReadonlyMap<\n Model<any>,\n ReadonlyMap<string, IdDomain>\n>;\n\n/** The derived domains, plus everything disagreement had to say. */\nexport interface IdDomainDerivation {\n readonly domains: IdDomainIndex;\n readonly issues: readonly SchemaValidationIssue[];\n}\n\n/** One end of a reference: the key a foreign-key member points at. */\ninterface ReferenceTarget {\n readonly model: Model<any>;\n readonly field: string;\n}\n\ntype ReferenceGraph = Map<Model<any>, Map<string, ReferenceTarget[]>>;\n\nconst MEMO = new WeakMap<ResolvedRelationIndex, IdDomainIndex>();\n\n/** Every `(owner.field) → (target.field)` edge the resolved index states. */\nfunction buildReferenceGraph(index: ResolvedRelationIndex): ReferenceGraph {\n const graph: ReferenceGraph = new Map();\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"foreignKey\") continue;\n const owner = edge.owner;\n const other =\n edge.endpoints[0] === owner ? edge.endpoints[1] : edge.endpoints[0];\n let byField = graph.get(owner.source);\n if (byField === undefined) {\n byField = new Map();\n graph.set(owner.source, byField);\n }\n for (const member of edge.reference.members) {\n let targets = byField.get(member.foreignField);\n if (targets === undefined) {\n targets = [];\n byField.set(member.foreignField, targets);\n }\n targets.push({\n model: other.source,\n field: member.referencedField,\n });\n }\n }\n return graph;\n}\n\n/** The domain a field DECLARES, read through the one declaration owner. */\nfunction declaredDomainOf(\n model: Model<any>,\n field: string\n): IdDomain | undefined {\n return idDomainOfState(model[\"~\"].state.scalars[field]?.[\"~\"].state);\n}\n\nfunction nameOf(ctx: ValidationContext | undefined, model: Model<any>): string {\n return ctx?.modelToName.get(model) ?? model[\"~\"].names.ts ?? \"model\";\n}\n\n/**\n * Derive every foreign key's domain, and say where two answers met.\n *\n * The unit of derivation is a STRONGLY CONNECTED COMPONENT of the reference\n * graph, not a field. Every field on a reference cycle holds every other's\n * values, so the component holds one domain: the one every declaration on it\n * and every key it references outside itself agree on. Tarjan's walk settles a\n * component only once every component it references is settled, so the answer\n * is a function of the graph and never of the order the schema registered it\n * in — a field is never asked about while it is still being answered.\n */\nexport function deriveIdDomains(\n index: ResolvedRelationIndex,\n ctx?: ValidationContext\n): IdDomainDerivation {\n const domains = new Map<Model<any>, Map<string, IdDomain>>();\n const issues: SchemaValidationIssue[] = [];\n let hasDeclaredDomain = false;\n for (const model of index.keys()) {\n for (const field of Object.keys(model[\"~\"].state.scalars)) {\n if (declaredDomainOf(model, field) !== undefined) {\n hasDeclaredDomain = true;\n break;\n }\n }\n if (hasDeclaredDomain) break;\n }\n // Every inherited domain originates at a declaration. Without one, neither\n // propagation nor a domain/native-storage disagreement is possible.\n if (!hasDeclaredDomain) {\n MEMO.set(index, domains);\n return { domains, issues };\n }\n return deriveDeclaredIdDomains(index, ctx, domains, issues);\n}\n\n/**\n * The propagation itself, apart from {@link deriveIdDomains} so that a schema\n * declaring no identifier domain never compiles it.\n */\nfunction deriveDeclaredIdDomains(\n index: ResolvedRelationIndex,\n ctx: ValidationContext | undefined,\n domains: Map<Model<any>, Map<string, IdDomain>>,\n issues: SchemaValidationIssue[]\n): IdDomainDerivation {\n const graph = buildReferenceGraph(index);\n const settled = new Map<Model<any>, Map<string, IdDomain | undefined>>();\n // Tarjan's discovery index per field. Keyed by model IDENTITY, not by name:\n // a name is for the message, and two models that happen to render the same\n // one must not share a node.\n const discovered = new Map<Model<any>, Map<string, number>>();\n const open: ReferenceTarget[] = [];\n let discoveries = 0;\n\n const marker = (node: ReferenceTarget): string =>\n `${nameOf(ctx, node.model)}.${node.field}`;\n\n const publish = (node: ReferenceTarget, domain: IdDomain | undefined) => {\n let bySettled = settled.get(node.model);\n if (bySettled === undefined) {\n bySettled = new Map();\n settled.set(node.model, bySettled);\n }\n bySettled.set(node.field, domain);\n if (domain !== undefined) {\n let byField = domains.get(node.model);\n if (byField === undefined) {\n byField = new Map();\n domains.set(node.model, byField);\n }\n byField.set(node.field, domain);\n }\n };\n\n /**\n * One component's domain: its members' declarations and the settled keys it\n * references outside itself, which must all be one. A target not yet settled\n * is a member — Tarjan pops a component only when every edge leaving it\n * reaches a settled one.\n */\n const settleComponent = (members: readonly ReferenceTarget[]) => {\n let agreed: IdDomain | undefined;\n let agreedFrom: string | undefined;\n let conflicted = false;\n for (const member of members) {\n const own = marker(member);\n const declared = declaredDomainOf(member.model, member.field);\n const answers: { domain: IdDomain | undefined; from: string }[] =\n declared === undefined ? [] : [{ domain: declared, from: own }];\n for (const target of graph.get(member.model)?.get(member.field) ?? []) {\n const outside = settled.get(target.model);\n if (outside?.has(target.field) !== true) continue;\n answers.push({\n domain: outside.get(target.field),\n from: marker(target),\n });\n }\n for (const answer of answers) {\n if (agreedFrom === undefined) {\n agreed = answer.domain;\n agreedFrom = answer.from;\n continue;\n }\n if (sameIdDomain(agreed, answer.domain)) continue;\n conflicted = true;\n const other = answer.from === own ? agreedFrom : answer.from;\n issues.push({\n code: \"FK012\",\n message:\n `'${own}' would hold ${describeIdDomain2(agreed)} through '${agreedFrom}' ` +\n `and ${describeIdDomain2(answer.domain)} through '${answer.from}'. ` +\n \"A column stores one identifier domain.\",\n severity: \"error\",\n model: nameOf(ctx, member.model),\n field: member.field,\n candidates: [agreedFrom, answer.from],\n repair:\n declared === undefined\n ? `Give every key '${own}' references the same identifier format, prefix and length`\n : `Declare '${own}' with the same identifier format, prefix and length as '${other}', or declare nothing and let it derive`,\n });\n }\n }\n for (const member of members) {\n publish(member, conflicted ? undefined : agreed);\n }\n };\n\n /** Tarjan's walk from one field; answers the lowest discovery it reaches. */\n const connect = (node: ReferenceTarget): number => {\n const discovery = discoveries;\n discoveries += 1;\n let byField = discovered.get(node.model);\n if (byField === undefined) {\n byField = new Map();\n discovered.set(node.model, byField);\n }\n byField.set(node.field, discovery);\n open.push(node);\n let lowest = discovery;\n for (const target of graph.get(node.model)?.get(node.field) ?? []) {\n const seen = discovered.get(target.model)?.get(target.field);\n if (seen === undefined) {\n lowest = Math.min(lowest, connect(target));\n } else if (settled.get(target.model)?.has(target.field) !== true) {\n // Discovered and not settled: still open, so on this component.\n lowest = Math.min(lowest, seen);\n }\n }\n // The root of a component: everything opened since it is the component.\n if (lowest === discovery) settleComponent(open.splice(open.indexOf(node)));\n return lowest;\n };\n\n const resolve = (model: Model<any>, field: string): IdDomain | undefined => {\n const cached = settled.get(model);\n if (cached?.has(field) !== true) connect({ model, field });\n return settled.get(model)?.get(field);\n };\n\n for (const [model, byField] of graph) {\n for (const field of byField.keys()) resolve(model, field);\n }\n\n // The same question asked of the COLUMN rather than the values: a foreign\n // key holds its key's values, so it must hold them in the key's physical\n // form too. Storage is read off each column's OWN native type (`idStorageOf`),\n // so a key kept text by an override beside a foreign key that declares no\n // override is a `uuid`/byte column referencing a text one — PostgreSQL and\n // MySQL refuse the constraint, SQLite accepts it and the engine binds a\n // payload the key never holds. Only a dialect one of the two declarations\n // selects a native type on can disagree: with neither, both take the same\n // automatic column.\n for (const [model, byField] of graph) {\n for (const [field, targets] of byField) {\n const domain = resolve(model, field);\n if (domain === undefined) continue;\n const own = model[\"~\"].state.scalars[field]?.[\"~\"].nativeType;\n for (const target of targets) {\n const theirs =\n target.model[\"~\"].state.scalars[target.field]?.[\"~\"].nativeType;\n const split = storageDisagreement(domain, own, theirs);\n if (split === undefined) continue;\n const marker = `${nameOf(ctx, model)}.${field}`;\n const targetMarker = `${nameOf(ctx, target.model)}.${target.field}`;\n issues.push({\n code: \"FK012\",\n message:\n `'${marker}' would store ${describeIdDomain(domain)} as ${split.own} on ${split.dialect} ` +\n `and the key it references, '${targetMarker}', as ${split.theirs}. ` +\n \"A foreign key stores its key's values in the key's own physical form.\",\n severity: \"error\",\n model: nameOf(ctx, model),\n field,\n candidates: [marker, targetMarker],\n repair: `Give '${marker}' the same ${split.dialect} native type as '${targetMarker}' (${split.theirs})`,\n });\n }\n }\n }\n\n // The polymorphic row carrier's ONE private id column stores every variant's\n // key, so every variant's key must hold one domain — the same DISAGREEMENT\n // rule the shared-foreign-key case above states, over a column that is not a\n // field and therefore has no (model, field) of its own to key an issue by.\n //\n // It is checked HERE and not beside the rest of P002 because the answer may\n // be DERIVED: a variant whose primary key is its parent foreign key declares\n // nothing and still holds uuids, and the storage rule runs while the index it\n // would have to ask is still being built. Comparing declarations there\n // refused two variants that hold the same domain and admitted two that hold\n // different ones — the second of which is what types the carrier column from\n // one variant and writes another variant's key through it.\n for (const edge of resolvedEdges(index)) {\n if (edge.kind !== \"variantRowCarrier\") continue;\n const carrier = `${nameOf(ctx, edge.carrier.source)}.${edge.carrier.field}`;\n // A published carrier has at least one member — the edge type says so.\n const [head, ...rest] = edge.members;\n const agreed = resolve(head.targetModel, head.referencedField);\n let agreedFrom = `${nameOf(ctx, head.targetModel)}.${head.referencedField}`;\n for (const member of rest) {\n const domain = resolve(member.targetModel, member.referencedField);\n if (sameIdDomain(agreed, domain)) continue;\n const marker = `${nameOf(ctx, member.targetModel)}.${member.referencedField}`;\n issues.push({\n code: \"P002\",\n message:\n `The one id column of '${carrier}' would hold ${describeIdDomain2(agreed)} ` +\n `through '${agreedFrom}' and ${describeIdDomain2(domain)} through '${marker}'. ` +\n \"A column stores one identifier domain.\",\n severity: \"error\",\n model: nameOf(ctx, edge.carrier.source),\n relation: edge.carrier.field,\n candidates: [agreedFrom, marker],\n repair: `Give every variant target of '${carrier}' the same identifier format, prefix and length`,\n });\n agreedFrom = marker;\n }\n }\n\n // Every model the index registers, so a declared domain on a relationless\n // model is checked too. The resolved index holds one slot map per registered\n // model, including an empty one.\n for (const model of index.keys()) {\n const scalars = model[\"~\"].state.scalars;\n for (const field of Object.keys(scalars)) {\n const domain = resolve(model, field);\n if (domain === undefined) continue;\n refuseUnusableNativeType(\n model,\n field,\n scalars[field]?.[\"~\"].nativeType,\n domain,\n ctx,\n issues\n );\n }\n }\n\n // The topology gate already pays for this derivation. Publish its successful\n // answer on the same index so the first operation consumes it directly.\n if (issues.length === 0) MEMO.set(index, domains);\n return { domains, issues };\n}\n\n/**\n * Refuse a native type override the declared domain cannot live in.\n *\n * The override says what the COLUMN is; the domain says what the column holds.\n * `varchar(26)` holds a ULID as text, `BINARY(16)` holds its bytes, and\n * `INTEGER` holds neither — and nothing downstream can repair that choice: the\n * migration would emit the column the override named and the engine would bind\n * the value the domain named, which is a table that refuses every row.\n *\n * Asked of EVERY dialect the declaration selects a native type on — one\n * dialect for the tagged shorthand, each entry of a map — because no dialect is\n * bound yet and each of them is a column some migration will create. It is\n * checked HERE rather than in the advisory rule list because `skipValidation`\n * may drop advice and must not be able to drop this.\n */\nfunction refuseUnusableNativeType(\n model: Model<any>,\n field: string,\n declaration: NativeTypeDeclaration | undefined,\n domain: IdDomain,\n ctx: ValidationContext | undefined,\n issues: SchemaValidationIssue[]\n): void {\n for (const dialect of NATIVE_DIALECTS) {\n const nativeType = nativeTypeFor(declaration, dialect);\n if (nativeType === undefined) continue;\n if (idStorageOf(domain, declaration, dialect) !== undefined) continue;\n const marker = `${nameOf(ctx, model)}.${field}`;\n issues.push({\n code: \"F013\",\n message: `'${marker}' holds ${describeIdDomain(domain)}, which cannot live in the ${dialect} column '${nativeType.type}'.`,\n severity: \"error\",\n model: nameOf(ctx, model),\n field,\n repair: `Declare '${marker}' with one of: ${describeIdNativeTypes(domain.format, dialect)} — or drop the native type and take the automatic column.`,\n });\n }\n}\n\n/**\n * The first dialect on which two columns holding one domain store it\n * differently, with each column's spelling there; `undefined` when they agree.\n *\n * Compared by REPRESENTATION, the one physical fact the engine binds by: two\n * text spellings (`varchar(40)` beside `text`) hold the same public strings.\n * An override this domain cannot live in answers nothing here — `F013` refuses\n * it by name.\n */\nfunction storageDisagreement(\n domain: IdDomain,\n own: NativeTypeDeclaration | undefined,\n theirs: NativeTypeDeclaration | undefined\n):\n | { readonly dialect: string; readonly own: string; readonly theirs: string }\n | undefined {\n // Every dialect: one neither declaration selects gives both columns the same\n // automatic storage, so asking it too costs nothing and cannot disagree.\n for (const dialect of NATIVE_DIALECTS) {\n const ownStorage = idStorageOf(domain, own, dialect);\n const theirStorage = idStorageOf(domain, theirs, dialect);\n if (ownStorage === undefined || theirStorage === undefined) continue;\n if (ownStorage.representation === theirStorage.representation) continue;\n return {\n dialect,\n own: ownStorage.columnType,\n theirs: theirStorage.columnType,\n };\n }\n return undefined;\n}\n\n/** `describeIdDomain`, extended to the absence of one. */\nfunction describeIdDomain2(domain: IdDomain | undefined): string {\n return domain === undefined\n ? \"no identifier domain\"\n : describeIdDomain(domain);\n}\n\n/**\n * The derived domains of one resolved index, computed once per index identity.\n *\n * Every consumer that already threads the index reads this — the write path's\n * parameter encoding, the read projection, the result decode, the operation\n * schemas and the migration serializer — so there is one derivation per schema\n * and not one per query. The issues are dropped here: a schema whose domains\n * disagree never becomes an index (the gate refuses it), so by the time anyone\n * asks this question there is nothing left to report.\n */\nexport function idDomainsOf(index: ResolvedRelationIndex): IdDomainIndex {\n const existing = MEMO.get(index);\n if (existing) return existing;\n return deriveIdDomains(index).domains;\n}\n\n/**\n * The identifier domain of one model field: the ONE lookup every consumer uses.\n *\n * Declared first, derived second — and never both, because a declaration that\n * disagrees with what it references is refused before an index exists. Reads\n * the index only when the field declares nothing, so a schema with no relations\n * pays nothing.\n */\nexport function idDomainOf(\n model: Model<any>,\n field: string,\n index: ResolvedRelationIndex | undefined\n): IdDomain | undefined {\n const declared = declaredDomainOf(model, field);\n if (declared !== undefined || index === undefined) return declared;\n return idDomainsOf(index).get(model)?.get(field);\n}\n","// The stored-reference subowner.\n//\n// It proves that a declared `.fields(...).references(...)` pair is physically\n// legal — every member exists, aligns by position with its counterpart, matches\n// scalar types, and references a key the target can be addressed by — and\n// returns the one `ResolvedStoredReference` the trusted edge carries. The\n// mandatory relation-definition gate is its only caller; no consumer repeats\n// these checks and none receives the untrusted declaration.\n//\n// Arity is not checked here: `.references(...)` accepts only an equal-arity\n// tuple, so an unequal pair cannot be constructed.\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { findReferenceableKey, type Model } from \"../../model\";\nimport type { ForeignKeyDeclaration } from \"../../relation\";\nimport { sqliteDateTimePhysicalForm } from \"../../scalars/datetime/physical\";\nimport type { ResolvedStoredReference } from \"../relation-resolution\";\nimport type { SchemaValidationIssue } from \"../types\";\n\nexport interface StoredReferenceInput {\n readonly modelName: string;\n readonly model: Model<any>;\n readonly relationName: string;\n readonly targetName: string;\n readonly target: Model<any>;\n readonly foreignKey: ForeignKeyDeclaration;\n}\n\nexport interface StoredReferenceCheck {\n /** Present only when every structural fact above held. */\n readonly reference: ResolvedStoredReference | undefined;\n readonly issues: readonly SchemaValidationIssue[];\n /** Ordered local members whose scalar accepts NULL. */\n readonly nullableForeignFields: readonly string[];\n}\n\nexport function checkStoredReference(\n input: StoredReferenceInput\n): StoredReferenceCheck {\n const { modelName, model, relationName, targetName, target } = input;\n const { fields, references, onDelete, onUpdate } = input.foreignKey;\n const issues: SchemaValidationIssue[] = [];\n const localScalars = model[\"~\"].state.scalars;\n const targetScalars = target[\"~\"].state.scalars;\n const nullableForeignFields: string[] = [];\n let legal = true;\n\n for (const [position, foreignField] of fields.entries()) {\n const local = localScalars[foreignField];\n if (!local) {\n legal = false;\n issues.push(fk001(modelName, relationName, foreignField));\n continue;\n }\n if (isDecimalList(local)) {\n legal = false;\n issues.push(fk010(modelName, relationName, foreignField));\n continue;\n }\n if (local[\"~\"].state.type === \"point\") {\n // Only the local member belongs here. A referenced GeoPoint cannot be an\n // addressable key, which is already owned by I005 and FK005.\n legal = false;\n issues.push(fk011(modelName, relationName, foreignField));\n }\n if (local[\"~\"].state.nullable) nullableForeignFields.push(foreignField);\n const referencedField = references[position]!;\n const remote = targetScalars[referencedField];\n if (!remote) {\n legal = false;\n issues.push(fk002(modelName, relationName, targetName, referencedField));\n continue;\n }\n const localState = local[\"~\"].state;\n const remoteState = remote[\"~\"].state;\n const localType = localState.type;\n const remoteType = remoteState.type;\n const localIsArray = localState.array === true;\n const remoteIsArray = remoteState.array === true;\n const localDecimal = localState.decimal;\n const remoteDecimal = remoteState.decimal;\n const arrayShapeMismatch =\n localType === remoteType && localIsArray !== remoteIsArray;\n const decimalDomainMismatch =\n localType === \"decimal\" &&\n remoteType === \"decimal\" &&\n !sameDecimalDescriptor(localDecimal, remoteDecimal);\n const localDateTimeForm =\n localType === \"datetime\" && !localIsArray\n ? sqliteDateTimePhysicalForm(local[\"~\"].nativeType)\n : undefined;\n const remoteDateTimeForm =\n remoteType === \"datetime\" && !remoteIsArray\n ? sqliteDateTimePhysicalForm(remote[\"~\"].nativeType)\n : undefined;\n const dateTimeDomainMismatch =\n localDateTimeForm !== undefined &&\n remoteDateTimeForm !== undefined &&\n localDateTimeForm !== remoteDateTimeForm;\n if (\n localType !== remoteType ||\n arrayShapeMismatch ||\n decimalDomainMismatch ||\n dateTimeDomainMismatch\n ) {\n legal = false;\n issues.push(\n fk003({\n modelName,\n relationName,\n targetName,\n foreignField,\n referencedField,\n localState,\n remoteState,\n localDateTimeForm,\n remoteDateTimeForm,\n arrayShapeMismatch,\n decimalDomainMismatch,\n dateTimeDomainMismatch,\n })\n );\n }\n }\n\n const targetKey = findReferenceableKey(target, references);\n if (!targetKey) {\n legal = false;\n issues.push(fk005(modelName, relationName, targetName, references));\n }\n\n if (onDelete === \"setNull\" || onUpdate === \"setNull\") {\n for (const foreignField of fields) {\n const local = localScalars[foreignField];\n if (local && !local[\"~\"].state.nullable) {\n legal = false;\n issues.push(ra004(modelName, relationName, foreignField));\n }\n }\n }\n\n if (onDelete === \"cascade\" && nullableForeignFields.length === 0) {\n issues.push(ra003(modelName, relationName));\n }\n\n // Published in the MATCHED KEY's order, not the declaration's. Each pair\n // travels whole, so the pairing the author wrote is untouched and both DDL\n // sides permute together. `static-membership.ts` reads the DECLARATION, so\n // its compile-time foreign-key tuple can be ordered differently; every shape\n // either side publishes is name-keyed, so the two orders never meet.\n const members = fields.map((foreignField, position) => ({\n foreignField,\n referencedField: references[position]!,\n }));\n if (targetKey) {\n members.sort(\n (left, right) =>\n targetKey.indexOf(left.referencedField) -\n targetKey.indexOf(right.referencedField)\n );\n }\n const [head, ...rest] = members;\n return {\n reference:\n legal && head\n ? {\n members: [head, ...rest],\n ...(onDelete ? { onDelete } : {}),\n ...(onUpdate ? { onUpdate } : {}),\n }\n : undefined,\n issues,\n nullableForeignFields,\n };\n}\n\n/**\n * A fixed-decimal LIST, which plan 2.1 excludes from every key position.\n *\n * Only the LOCAL member is asked here, and that is the whole exclusion for a\n * stored reference: the REFERENCED tuple has to be a key the target can be\n * addressed by (FK005), and a decimal list can be no part of one — the scalar\n * builder refuses `.id()` and `.unique()` on it and I004 refuses it inside a\n * compound key or a unique index. So the referenced side is already closed, by\n * the owners of the positions it would have to occupy.\n */\nfunction isDecimalList(\n scalar: Model<any>[\"~\"][\"state\"][\"scalars\"][string]\n): boolean {\n const state = scalar[\"~\"].state;\n return state.type === \"decimal\" && state.array === true;\n}\n\n// The issues below are built only for an invalid declaration; keeping them out\n// of `checkStoredReference` means a valid schema never compiles them.\n\ntype Issue = SchemaValidationIssue;\ntype ScalarState = Model<any>[\"~\"][\"state\"][\"scalars\"][string][\"~\"][\"state\"];\n\nfunction fk001(model: string, relation: string, field: string): Issue {\n return {\n code: \"FK001\",\n message: `FK '${field}' in '${relation}' not in '${model}'`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Declare a scalar '${field}' on '${model}' or name an existing one in .fields(...)`,\n };\n}\n\nfunction fk010(model: string, relation: string, field: string): Issue {\n return {\n code: \"FK010\",\n message: `FK '${field}' in '${relation}' is a fixed-decimal list, which cannot be a foreign-key member`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Store the reference in a scalar decimal (or another scalar type) on '${model}'`,\n };\n}\n\nfunction fk011(model: string, relation: string, field: string): Issue {\n return {\n code: \"FK011\",\n message: `FK '${field}' in '${relation}' is a GeoPoint, which cannot be a foreign-key member`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Store relation identity in a portable scalar key on '${model}'`,\n };\n}\n\nfunction fk002(\n model: string,\n relation: string,\n targetName: string,\n field: string\n): Issue {\n return {\n code: \"FK002\",\n message: `Reference '${field}' not in '${targetName}'`,\n severity: \"error\",\n model,\n relation,\n field,\n repair: `Reference a scalar declared on '${targetName}'`,\n };\n}\n\nfunction describeMember(\n state: ScalarState,\n dateTimeForm: string | undefined\n): string {\n if (state.array === true) return `${state.type}[]`;\n if (state.type === \"decimal\" && state.decimal)\n return `decimal(${state.decimal.precision},${state.decimal.scale})`;\n return dateTimeForm ? `datetime(${dateTimeForm})` : state.type;\n}\n\nfunction fk003(mismatch: {\n modelName: string;\n relationName: string;\n targetName: string;\n foreignField: string;\n referencedField: string;\n localState: ScalarState;\n remoteState: ScalarState;\n localDateTimeForm: string | undefined;\n remoteDateTimeForm: string | undefined;\n arrayShapeMismatch: boolean;\n decimalDomainMismatch: boolean;\n dateTimeDomainMismatch: boolean;\n}): Issue {\n const { foreignField, referencedField, targetName } = mismatch;\n const local = describeMember(mismatch.localState, mismatch.localDateTimeForm);\n const remote = describeMember(\n mismatch.remoteState,\n mismatch.remoteDateTimeForm\n );\n const same = mismatch.decimalDomainMismatch\n ? \"decimal precision and scale\"\n : mismatch.arrayShapeMismatch\n ? \"scalar/list shape\"\n : mismatch.dateTimeDomainMismatch\n ? \"SQLite DateTime physical form\"\n : \"scalar type\";\n return {\n code: \"FK003\",\n message: `Type mismatch: '${foreignField}' (${local}) → '${referencedField}' (${remote}) in ${targetName}`,\n severity: \"error\",\n model: mismatch.modelName,\n relation: mismatch.relationName,\n repair: `Give '${foreignField}' the same ${same} as '${targetName}.${referencedField}'`,\n };\n}\n\nfunction fk005(\n model: string,\n relation: string,\n targetName: string,\n references: readonly string[]\n): Issue {\n return {\n code: \"FK005\",\n message: `[${references.join(\", \")}] in '${targetName}' should be unique/ID`,\n severity: \"error\",\n model,\n relation,\n repair: `Declare the referenced tuple on '${targetName}' with .id(), .unique(), or a compound key`,\n };\n}\n\nfunction ra004(model: string, relation: string, field: string): Issue {\n return {\n code: \"RA004\",\n message: `SET NULL on '${relation}' but '${field}' not nullable`,\n severity: \"error\",\n model,\n relation,\n repair: `Make '${field}' .nullable() or choose another referential action`,\n };\n}\n\nfunction ra003(model: string, relation: string): Issue {\n return {\n code: \"RA003\",\n message: `CASCADE on required '${relation}' may cause data loss`,\n severity: \"warning\",\n model,\n relation,\n };\n}\n","import type { Model } from \"../../model\";\nimport type { AnyRelation } from \"../../relation\";\nimport type { Scalar } from \"../../scalars/base\";\n\nexport function getRelationValues(model: Model<any>): AnyRelation[] {\n return Object.values(model[\"~\"].state.relations) as AnyRelation[];\n}\n\nexport function getScalars(model: Model<any>): [string, Scalar][] {\n return Object.entries(model[\"~\"].state.scalars) as [string, Scalar][];\n}\n","// The variant-storage subowner.\n//\n// It owns the PHYSICAL half of a variant carrier: the row-held `(type, id)`\n// column pair and its portable-identity restriction, the per-variant member\n// junction names and topologies, and the schema-wide reservation set every\n// generated name is checked against. Pairing, inverse cardinality, and\n// uniqueness are the relation resolver's; this module never discovers an\n// inverse and never decides a topology.\n//\n// The mandatory relation-definition gate is its only caller.\n\nimport { sameDecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport { isValidSchemaIdentifier } from \"../../identifier\";\nimport { getModelKeyCatalog, type Model } from \"../../model\";\nimport { automaticForeignKeyIndexName } from \"../../relation/helpers\";\nimport {\n type ResolvedJunctionTopology,\n resolveJunctionTopology,\n resolveVariantMemberNames,\n type VariantMemberNames,\n} from \"../../relation/junction-topology\";\nimport type { VariantJunctionOverride } from \"../../relation/types\";\nimport { string } from \"../../scalars\";\nimport type { Scalar } from \"../../scalars/base\";\nimport { thrownAsError } from \"../error\";\nimport type { ResolvedVariantRowStorage } from \"../relation-resolution\";\nimport type {\n Schema,\n SchemaValidationIssue,\n ValidationContext,\n} from \"../types\";\nimport { getScalars } from \"./model-members\";\n\nconst PORTABLE_ID_TYPES = new Set([\"string\", \"int\", \"bigint\", \"decimal\"]);\n\nfunction issue(\n code: string,\n message: string,\n model: string,\n relation: string,\n repair: string\n): SchemaValidationIssue {\n return { code, message, severity: \"error\", model, relation, repair };\n}\n\n// =============================================================================\n// SCHEMA-WIDE PHYSICAL NAME RESERVATIONS\n// =============================================================================\n\n/** One resolved row foreign key, as the serializer's index derivation sees it. */\nexport interface StoredReferenceFact {\n readonly owner: Model<any>;\n readonly fields: readonly string[];\n /** A unique tuple is already covered and gets no automatic index. */\n readonly unique: boolean;\n}\n\nexport interface ReservationInput {\n readonly schema: Schema;\n readonly ctx: ValidationContext;\n /** Table and canonical reverse-index name of every resolved ordinary junction. */\n readonly junctionNames: readonly string[];\n readonly storedReferences: readonly StoredReferenceFact[];\n}\n\n/**\n * Every physical name the schema already claims, in the spelling the migration\n * serializer emits: table names, declared and generated indexes, primary-key and\n * unique constraint names, automatic foreign-key indexes, and ordinary junction\n * tables with their reverse indexes. A generated variant storage name that lands\n * in this set is refused rather than silently shadowing an existing object.\n */\nexport function collectReservedPhysicalNames(\n input: ReservationInput\n): Set<string> {\n const reserved = new Set<string>();\n for (const [candidateName, candidate] of input.schema) {\n const tableName = candidate[\"~\"].state.tableName ?? candidateName;\n for (const index of candidate[\"~\"].state.indexes) {\n reserved.add(\n index.options.name ?? `${tableName}_${index.fields.join(\"_\")}_idx`\n );\n }\n const scalars = getScalars(candidate);\n if (\n scalars.some(([, scalar]) => scalar[\"~\"].state.isId) ||\n candidate[\"~\"].state.compoundId\n ) {\n reserved.add(`${tableName}_pkey`);\n }\n for (const [field, scalar] of scalars) {\n if (scalar[\"~\"].state.isUnique && !scalar[\"~\"].state.isId) {\n const column = scalar[\"~\"].state.columnName ?? field;\n reserved.add(`${tableName}_${column}_key`);\n }\n }\n for (const constraint of Object.keys(\n candidate[\"~\"].state.compoundUniques ?? {}\n )) {\n reserved.add(`${tableName}_${constraint}_key`);\n }\n for (const indexName of automaticForeignKeyIndexNames(\n candidate,\n tableName,\n input.storedReferences\n )) {\n reserved.add(indexName);\n }\n }\n for (const tableName of input.ctx.tableToModels.keys())\n reserved.add(tableName);\n for (const junctionName of input.junctionNames) reserved.add(junctionName);\n return reserved;\n}\n\n/**\n * The index names the serializer generates for foreign keys that no declared\n * key or index already covers — reserved so a variant member junction cannot\n * claim one of them.\n */\nfunction automaticForeignKeyIndexNames(\n model: Model<any>,\n tableName: string,\n storedReferences: readonly StoredReferenceFact[]\n): readonly string[] {\n const state = model[\"~\"].state;\n const columnName = (field: string) =>\n state.scalars[field]?.[\"~\"].state.columnName ?? field;\n const primaryKeyColumns = getScalars(model)\n .filter(([, scalar]) => scalar[\"~\"].state.isId)\n .map(([field]) => columnName(field));\n // The FIRST declared compound id, read the way the key catalog reads it: a\n // second `.id([...])` is representable but F002 refuses it at push, so one\n // lookup answers and an absent record is simply no compound columns.\n const compoundIds: Record<string, { entries: Record<string, unknown> }> =\n state.compoundId ?? {};\n const [compoundId] = Object.values(compoundIds);\n if (compoundId) {\n primaryKeyColumns.push(...Object.keys(compoundId.entries).map(columnName));\n }\n const uniqueColumns = getScalars(model)\n .filter(([, scalar]) => scalar[\"~\"].state.isUnique)\n .map(([field]) => [columnName(field)]);\n if (state.compoundUniques) {\n for (const constraintName of Object.keys(state.compoundUniques)) {\n const constraint = state.compoundUniques[constraintName];\n if (constraint?.entries) {\n uniqueColumns.push(Object.keys(constraint.entries).map(columnName));\n }\n }\n }\n const declaredIndexes = state.indexes.map((index) => {\n const declaredName = index.options.name;\n return {\n name:\n typeof declaredName === \"string\"\n ? declaredName\n : `${tableName}_${index.fields.join(\"_\")}_idx`,\n columns: index.fields.map(columnName),\n where: index.options.where,\n };\n });\n const own = storedReferences.filter((fact) => fact.owner === model);\n const coveringColumns = [\n primaryKeyColumns,\n ...uniqueColumns,\n ...own\n .filter((fact) => fact.unique)\n .map((fact) => fact.fields.map(columnName)),\n ...declaredIndexes\n .filter((index) => !index.where)\n .map((index) => index.columns),\n ];\n const emittedNames = new Set<string>(\n declaredIndexes.map((index) => index.name)\n );\n const automaticNames: string[] = [];\n for (const fact of own) {\n if (fact.unique) continue;\n const foreignKeyColumns = fact.fields.map(columnName);\n const alreadyIndexed = coveringColumns.some((columns) =>\n foreignKeyColumns.every(\n (column, position) => columns[position] === column\n )\n );\n if (alreadyIndexed) continue;\n const name = automaticForeignKeyIndexName(\n tableName,\n foreignKeyColumns,\n emittedNames\n );\n if (name === undefined) continue;\n emittedNames.add(name);\n automaticNames.push(name);\n }\n return automaticNames;\n}\n\n// =============================================================================\n// ROW-HELD VARIANT STORAGE\n// =============================================================================\n\nexport interface VariantRowMemberInput {\n readonly variant: string;\n readonly target: Model<any>;\n}\n\nexport interface VariantRowStorageInput {\n readonly modelName: string;\n readonly ownerTable: string;\n readonly relationName: string;\n /** `.optional()` on the carrier — the nullability of both private columns. */\n readonly optional: boolean;\n readonly members: readonly VariantRowMemberInput[];\n /** The owner's own column names; mutated as each carrier claims its pair. */\n readonly reservedColumns: Set<string>;\n /** Schema-wide index names; mutated as each carrier claims its index. */\n readonly reservedIndexes: Set<string>;\n /** How many carriers in the whole schema generate each poly index name. */\n readonly indexNameCounts: ReadonlyMap<string, number>;\n}\n\nexport interface VariantRowStorageResult {\n /** Present only when every member resolved and the names are legal. */\n readonly storage: ResolvedVariantRowStorage | undefined;\n /** Variant key → the target's single scalar primary-key field. */\n readonly referencedFields: ReadonlyMap<string, string>;\n readonly issues: readonly SchemaValidationIssue[];\n}\n\n/**\n * The row-held `(type, id)` pair: one shared private column pair and one\n * composite index for the whole carrier, so every variant must expose the same\n * portable single-scalar identity.\n */\nexport function checkVariantRowStorage(\n input: VariantRowStorageInput\n): VariantRowStorageResult {\n const { modelName, relationName } = input;\n const issues: SchemaValidationIssue[] = [];\n const typeColumnName = `${relationName}_type`;\n const idColumnName = `${relationName}_id`;\n const indexName = `${input.ownerTable}_${relationName}_poly_idx`;\n const namesValid =\n isValidSchemaIdentifier(typeColumnName) &&\n isValidSchemaIdentifier(idColumnName) &&\n isValidSchemaIdentifier(indexName) &&\n !input.reservedColumns.has(typeColumnName) &&\n !input.reservedColumns.has(idColumnName) &&\n !input.reservedIndexes.has(indexName) &&\n // The prepass counted this exact name for every row carrier, so the entry\n // is there to read and a second default would be a second owner for it.\n input.indexNameCounts.get(indexName)! === 1;\n if (!namesValid) {\n issues.push(\n issue(\n \"P008\",\n `Variant relation '${relationName}' in '${modelName}' has invalid or colliding generated storage names`,\n modelName,\n relationName,\n `Rename the relation field or .map() the owner table so '${typeColumnName}', '${idColumnName}' and '${indexName}' are free`\n )\n );\n }\n input.reservedColumns.add(typeColumnName);\n input.reservedColumns.add(idColumnName);\n input.reservedIndexes.add(indexName);\n\n const referencedFields = new Map<string, string>();\n /**\n * Every variant's key, with the model that owns it.\n *\n * The FIRST is the carrier's own: its scalar types the private id column and\n * its (model, field) is what that column names as the key whose domain its\n * values carry. Every variant agrees on both or the carrier is refused — on\n * the representation below, and on the identifier domain in the derivation,\n * which is the one pass that can see a domain a variant DERIVES rather than\n * declares.\n */\n const keys: {\n readonly model: Model<any>;\n readonly field: string;\n readonly scalar: Scalar;\n }[] = [];\n for (const member of input.members) {\n const primaryKey = singlePrimaryKey(member.target);\n if (!primaryKey) {\n issues.push(\n issue(\n \"P009\",\n `Variant '${member.variant}' in '${modelName}.${relationName}' requires one scalar primary key`,\n modelName,\n relationName,\n `Give the '${member.variant}' target a single scalar .id() field`\n )\n );\n continue;\n }\n referencedFields.set(member.variant, primaryKey.field);\n keys.push({\n model: member.target,\n field: primaryKey.field,\n scalar: primaryKey.scalar,\n });\n }\n\n const carrierKey = keys[0];\n const portable =\n carrierKey !== undefined &&\n keys.every((key) =>\n hasCompatibleVariantIdentity(carrierKey.scalar, key.scalar)\n );\n if (keys.length > 0 && !portable) {\n issues.push(\n issue(\n \"P002\",\n `Variant targets in '${modelName}.${relationName}' require one compatible portable primary-key representation`,\n modelName,\n relationName,\n \"Give every variant target the same portable scalar id representation: one shared string, int, or bigint type, or decimal IDs with identical precision and scale\"\n )\n );\n }\n\n const complete =\n namesValid && portable && referencedFields.size === input.members.length;\n const nullable = input.optional;\n return {\n storage:\n complete && carrierKey\n ? {\n typeColumn: {\n name: typeColumnName,\n scalar: string(),\n nullable,\n },\n idColumn: {\n name: idColumnName,\n // The scalar and the pair are ONE key read two ways, never two\n // answers: the scalar types the column, the pair names the key\n // whose domain its values carry.\n scalar: carrierKey.scalar,\n nullable,\n reference: { model: carrierKey.model, field: carrierKey.field },\n },\n indexName,\n }\n : undefined,\n referencedFields,\n issues,\n };\n}\n\nfunction hasCompatibleVariantIdentity(\n first: Scalar,\n candidate: Scalar\n): boolean {\n const firstState = first[\"~\"].state;\n const candidateState = candidate[\"~\"].state;\n if (\n !PORTABLE_ID_TYPES.has(candidateState.type) ||\n candidateState.array === true ||\n candidate[\"~\"].nativeType !== undefined ||\n candidateState.type !== firstState.type\n ) {\n return false;\n }\n // The identifier DOMAIN is part of the representation too, and it is checked\n // where the DERIVED answer exists — in the identifier-domain derivation, over\n // the resolved index this rule runs before. A variant key may hold a domain\n // it never declared (the one-to-one child whose primary key is its parent\n // foreign key), and comparing declarations here refused those pairs while\n // admitting two derived domains that differ.\n if (candidateState.type !== \"decimal\") return true;\n const firstDescriptor = firstState.decimal;\n const candidateDescriptor = candidateState.decimal;\n return (\n firstDescriptor !== undefined &&\n candidateDescriptor !== undefined &&\n sameDecimalDescriptor(candidateDescriptor, firstDescriptor)\n );\n}\n\n/** The generated composite index name of one row-held carrier. */\nexport function variantRowIndexName(\n ownerTable: string,\n relationName: string\n): string {\n return `${ownerTable}_${relationName}_poly_idx`;\n}\n\nfunction singlePrimaryKey(\n model: Model<any>\n): { readonly field: string; readonly scalar: Scalar } | undefined {\n if (\n model[\"~\"].state.compoundId &&\n Object.keys(model[\"~\"].state.compoundId).length > 0\n ) {\n return undefined;\n }\n const primaryKeys = getScalars(model).filter(\n ([, scalar]) => scalar[\"~\"].state.isId\n );\n if (primaryKeys.length !== 1) return undefined;\n const [field, scalar] = primaryKeys[0]!;\n return { field, scalar };\n}\n\n// =============================================================================\n// MEMBER JUNCTION STORAGE\n// =============================================================================\n\nexport interface VariantMemberInput {\n readonly variant: string;\n readonly target: Model<any>;\n readonly targetName: string;\n readonly junction: VariantJunctionOverride | undefined;\n}\n\nexport interface VariantMemberJunctionInput {\n readonly modelName: string;\n readonly model: Model<any>;\n readonly ownerTable: string;\n readonly relationName: string;\n readonly members: readonly VariantMemberInput[];\n readonly reservedColumns: ReadonlySet<string>;\n /** Mutated: a refused member still claims its names, so a later flip cannot collide. */\n readonly reservedIndexes: Set<string>;\n /** Schema-wide claim counts, so a member can tell its own claim from a rival's. */\n readonly memberNameCounts: ReadonlyMap<string, number>;\n}\n\nexport interface VariantMemberJunctionResult {\n readonly topologies: ReadonlyMap<string, ResolvedJunctionTopology>;\n readonly issues: readonly SchemaValidationIssue[];\n}\n\n/** Per-variant member junctions: one fixed-target junction per variant. */\nexport function checkVariantMemberJunctions(\n input: VariantMemberJunctionInput\n): VariantMemberJunctionResult {\n const { modelName, relationName } = input;\n const issues: SchemaValidationIssue[] = [];\n const topologies = new Map<string, ResolvedJunctionTopology>();\n const ownerRowKey = getModelKeyCatalog(input.model).rowKey?.fields;\n if (!ownerRowKey?.length) {\n issues.push(\n issue(\n \"P018\",\n `Variant relation '${relationName}' in '${modelName}' requires a complete owner row key for its member junctions`,\n modelName,\n relationName,\n `Declare a primary key on '${modelName}'`\n )\n );\n return { topologies, issues };\n }\n\n for (const member of input.members) {\n const targetRowKey = getModelKeyCatalog(member.target).rowKey?.fields;\n if (!targetRowKey?.length) {\n issues.push(\n issue(\n \"P009\",\n `Variant '${member.variant}' in '${modelName}.${relationName}' requires a complete row key`,\n modelName,\n relationName,\n `Declare a primary key on '${member.targetName}'`\n )\n );\n continue;\n }\n const names = resolveVariantMemberNames({\n ownerTableName: input.ownerTable,\n ownerModelName: modelName,\n relationField: relationName,\n publicType: member.variant,\n ownerRowKeyIsCompound: ownerRowKey.length > 1,\n targetRowKeyIsCompound: targetRowKey.length > 1,\n junction: member.junction,\n });\n try {\n const topology = resolveJunctionTopology({\n table: names.table,\n source: {\n model: input.model,\n modelName,\n rowKey: ownerRowKey,\n token: names.sourceToken,\n },\n target: {\n model: member.target,\n modelName: member.targetName,\n rowKey: targetRowKey,\n token: names.targetToken,\n },\n pairName: `${modelName}.${relationName}.${member.variant}`,\n });\n const sourceForeignKey = topology.foreignKeyName(\"source\");\n const targetForeignKey = topology.foreignKeyName(\"target\");\n const reverseIndex = topology.reverseIndexName();\n const uniqueTarget = topology.uniqueTargetName();\n const collision = [names.table, reverseIndex].find(\n (physicalName) =>\n !isValidSchemaIdentifier(physicalName) ||\n input.reservedColumns.has(physicalName) ||\n input.reservedIndexes.has(physicalName) ||\n // Counted for every member the prepass planned, this one included.\n input.memberNameCounts.get(physicalName)! > 1\n );\n // Reserved even when refused: a refused member still claims its physical\n // names, so an inverse flip elsewhere cannot newly collide a schema that\n // was already valid.\n input.reservedIndexes.add(names.table);\n input.reservedIndexes.add(sourceForeignKey);\n input.reservedIndexes.add(targetForeignKey);\n input.reservedIndexes.add(reverseIndex);\n input.reservedIndexes.add(uniqueTarget);\n if (collision !== undefined) {\n issues.push(\n issue(\n \"P019\",\n `Variant '${member.variant}' in '${modelName}.${relationName}' has an invalid or colliding junction name '${collision}'`,\n modelName,\n relationName,\n `Give this variant an explicit .through({ ${member.variant}: { table, source, target } }) entry`\n )\n );\n continue;\n }\n topologies.set(member.variant, topology);\n } catch (error) {\n // Every throw on this path is a physical-name refusal: both row keys are\n // proven non-empty above, and no other guard exists on the member path.\n input.reservedIndexes.add(names.table);\n issues.push(\n issue(\n \"P019\",\n thrownAsError(error).message,\n modelName,\n relationName,\n `Give this variant an explicit .through({ ${member.variant}: { table, source, target } }) entry`\n )\n );\n }\n }\n return { topologies, issues };\n}\n\n/**\n * The names one member junction WOULD claim — the counting prepass's input, so\n * a member can tell \"someone else claims this name\" from its own single claim.\n * `undefined` when the member has no complete row key to expand.\n */\nexport function planVariantMemberNames(input: {\n readonly model: Model<any>;\n readonly modelName: string;\n readonly ownerTable: string;\n readonly relationName: string;\n readonly member: VariantMemberInput;\n}):\n | { readonly names: VariantMemberNames; readonly claims: readonly string[] }\n | undefined {\n const ownerRowKey = getModelKeyCatalog(input.model).rowKey?.fields;\n const targetRowKey = getModelKeyCatalog(input.member.target).rowKey?.fields;\n if (!(ownerRowKey?.length && targetRowKey?.length)) return undefined;\n const names = resolveVariantMemberNames({\n ownerTableName: input.ownerTable,\n ownerModelName: input.modelName,\n relationField: input.relationName,\n publicType: input.member.variant,\n ownerRowKeyIsCompound: ownerRowKey.length > 1,\n targetRowKeyIsCompound: targetRowKey.length > 1,\n junction: input.member.junction,\n });\n try {\n const topology = resolveJunctionTopology({\n table: names.table,\n source: {\n model: input.model,\n modelName: input.modelName,\n rowKey: ownerRowKey,\n token: names.sourceToken,\n },\n target: {\n model: input.member.target,\n modelName: input.member.targetName,\n rowKey: targetRowKey,\n token: names.targetToken,\n },\n pairName: undefined,\n });\n return {\n names,\n claims: [\n names.table,\n topology.foreignKeyName(\"source\"),\n topology.foreignKeyName(\"target\"),\n topology.reverseIndexName(),\n ],\n };\n } catch {\n // A member whose names cannot even be expanded claims only its table; the\n // per-member pass reports the refusal.\n return { names, claims: [names.table] };\n }\n}\n","/**\n * The one schema-wide relation topology owner (plan §6).\n *\n * A declaration states two facts: the slot cardinality its factory was spelled\n * with, and the target domain its argument names. Everything else about an edge\n * — who its partner is, which endpoint owns the foreign key, whether storage is\n * a row reference or a junction, whether that storage is unique, whether a\n * singular slot may be empty — is derived HERE, once per schema, from the whole\n * graph. Nothing downstream rescans for an inverse.\n *\n * The gate publishes a complete trusted index or a list of\n * `SchemaValidationIssue`s. There is no partial index and no `unresolved` arm: a\n * consumer holding an index holds a graph whose every physical fact the FK,\n * variant-storage and junction subowners invoked here have already proven.\n *\n * PAIRING IS A GRAPH, NOT A LADDER. Candidates are collected structurally, then\n * partitioned by the exact relation-name claim, then counted. No candidate wins\n * by being ordinary, variant, first, or sole.\n */\n\nimport { findReferenceableKey, getModelKeyCatalog, type Model } from \"../model\";\nimport {\n type JunctionOverrideView,\n JunctionPhysicalNameError,\n resolveOrdinaryJunctionNames,\n} from \"../relation/helpers\";\nimport {\n type ResolvedJunctionTopology,\n resolveJunctionTopology,\n} from \"../relation/junction-topology\";\nimport type { PolymorphicStorageColumn } from \"../relation/polymorphic\";\nimport type {\n AnyRelation,\n JunctionSideActions,\n ReferentialAction,\n RelationCardinality,\n RelationSlot,\n RelationState,\n VariantManyEntry,\n VariantOneEntry,\n} from \"../relation/types\";\nimport { thrownAsError } from \"./error\";\nimport { deriveIdDomains } from \"./id-domains\";\nimport { checkStoredReference } from \"./rules/fk\";\nimport { getScalars } from \"./rules/model-members\";\nimport {\n checkVariantMemberJunctions,\n checkVariantRowStorage,\n collectReservedPhysicalNames,\n planVariantMemberNames,\n type StoredReferenceFact,\n variantRowIndexName,\n} from \"./rules/polymorphic\";\nimport type { Schema, SchemaValidationIssue, ValidationContext } from \"./types\";\n\n// =============================================================================\n// TRUSTED FORMS (§6.6)\n// =============================================================================\n\nexport type ResolvedVariantRowStorage = {\n readonly typeColumn: PolymorphicStorageColumn;\n readonly idColumn: PolymorphicStorageColumn;\n readonly indexName: string;\n};\n\n/** The exact normalized entry, narrowed to what physical storage may read. */\nexport type ResolvedVariantStorageIdentity = {\n readonly storedValue: string;\n};\n\nexport type ResolvedVariantRowMember = {\n readonly variant: string;\n readonly entry: ResolvedVariantStorageIdentity;\n readonly targetModel: Model<any>;\n readonly referencedField: string;\n readonly inverse?: RelationSlot;\n};\n\nexport type ResolvedVariantJunctionMember = {\n readonly variant: string;\n readonly entry: ResolvedVariantStorageIdentity;\n readonly inverse?: RelationSlot;\n /** A singular bound inverse makes this member's target side unique. */\n readonly uniqueTarget: boolean;\n readonly topology: ResolvedJunctionTopology;\n};\n\nexport type ResolvedStoredReference = {\n readonly members: readonly [\n {\n readonly foreignField: string;\n readonly referencedField: string;\n },\n ...{\n readonly foreignField: string;\n readonly referencedField: string;\n }[],\n ];\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\nexport type ResolvedRelationEdge =\n | {\n readonly kind: \"foreignKey\";\n readonly endpoints: readonly [RelationSlot, RelationSlot];\n readonly owner: RelationSlot;\n readonly reference: ResolvedStoredReference;\n readonly unique: boolean;\n }\n | {\n readonly kind: \"junction\";\n readonly endpoints: readonly [RelationSlot, RelationSlot];\n /** Each side's foreign-key actions travel on that side. */\n readonly topology: ResolvedJunctionTopology;\n }\n | {\n readonly kind: \"variantRowCarrier\";\n readonly carrier: RelationSlot;\n readonly members: readonly [\n ResolvedVariantRowMember,\n ...ResolvedVariantRowMember[],\n ];\n readonly uniqueTarget: boolean;\n readonly storage: ResolvedVariantRowStorage;\n }\n | {\n readonly kind: \"variantJunctionCarrier\";\n readonly carrier: RelationSlot;\n readonly members: readonly [\n ResolvedVariantJunctionMember,\n ...ResolvedVariantJunctionMember[],\n ];\n };\n\nexport type ResolvedVariantRowEdge = Extract<\n ResolvedRelationEdge,\n { readonly kind: \"variantRowCarrier\" }\n>;\n\nexport type ResolvedVariantJunctionEdge = Extract<\n ResolvedRelationEdge,\n { readonly kind: \"variantJunctionCarrier\" }\n>;\n\nexport type ResolvedVariantEdge =\n | ResolvedVariantRowEdge\n | ResolvedVariantJunctionEdge;\n\n/** The two model-target edge forms, the only ones an ordinary slot resolves to. */\nexport type ResolvedOrdinaryEdge = Exclude<\n ResolvedRelationEdge,\n ResolvedVariantEdge\n>;\n\nexport type ResolvedSlot =\n | {\n readonly slot: RelationSlot;\n readonly edge: Exclude<ResolvedRelationEdge, ResolvedVariantEdge>;\n readonly member?: never;\n }\n | {\n /** The public carrier slot spans the edge's complete member collection. */\n readonly slot: RelationSlot;\n readonly edge: ResolvedVariantEdge;\n readonly member?: never;\n }\n | {\n /** An ordinary inverse is a view of exactly one existing member record. */\n readonly slot: RelationSlot;\n readonly edge: ResolvedVariantRowEdge;\n readonly member: ResolvedVariantRowEdge[\"members\"][number];\n }\n | {\n readonly slot: RelationSlot;\n readonly edge: ResolvedVariantJunctionEdge;\n readonly member: ResolvedVariantJunctionEdge[\"members\"][number];\n };\n\nexport type ResolvedRelationIndex = ReadonlyMap<\n Model<any>,\n ReadonlyMap<string, ResolvedSlot>\n>;\n\n/**\n * The trusted index XOR the reasons there is none.\n *\n * `issues` is present on BOTH arms and means the same thing on each: everything\n * the gate has to say about this schema. On the successful arm it can only hold\n * WARNINGS — one error is what makes the arm unsuccessful — and dropping them\n * there would silently lose every advisory the subowners produce about a schema\n * that happens to be valid, which is most of them.\n */\nexport type RelationResolution =\n | {\n readonly ok: true;\n readonly index: ResolvedRelationIndex;\n readonly issues: readonly SchemaValidationIssue[];\n }\n | {\n readonly ok: false;\n readonly issues: readonly SchemaValidationIssue[];\n readonly cause?: Error;\n };\n\n/**\n * The ON DELETE action a stored reference's constraint carries: the declared\n * one, else Prisma's default — SET NULL when every local member is nullable,\n * RESTRICT otherwise. TOTAL nullability, not the nullable subset the write side\n * clears: one referential action governs the whole constraint. The migration\n * serializer spells the constraint from this answer and the engine reads it to\n * know which deletes the database refuses, so the two cannot disagree.\n */\nexport function foreignKeyOnDelete(\n edge: Extract<ResolvedRelationEdge, { readonly kind: \"foreignKey\" }>\n): ReferentialAction {\n if (edge.reference.onDelete !== undefined) return edge.reference.onDelete;\n const scalars = edge.owner.source[\"~\"].state.scalars;\n return edge.reference.members.every(\n (member) => scalars[member.foreignField]?.[\"~\"].state.nullable === true\n )\n ? \"setNull\"\n : \"restrict\";\n}\n\n/** A junction side's ON DELETE action: the declared one, else CASCADE (Prisma parity). */\nexport function junctionOnDelete(\n side: Pick<ResolvedJunctionTopology[\"source\"], \"onDelete\">\n): ReferentialAction {\n return side.onDelete ?? \"cascade\";\n}\n\n/**\n * Stable unique edge enumeration, derived from the index rather than stored\n * beside it. Walk named schema/model/field order and yield an edge only at its\n * canonical anchor — a foreign key at its owner, a junction at `endpoints[0]`,\n * either variant family at its carrier — so carrier storage keeps its\n * historical serializer position even when an inverse model sorts earlier.\n */\nexport function* resolvedEdges(\n index: ResolvedRelationIndex\n): Generator<ResolvedRelationEdge> {\n for (const [model, slots] of index) {\n for (const [field, resolved] of slots) {\n if (resolved.member) continue;\n const edge = resolved.edge;\n const anchor =\n edge.kind === \"foreignKey\"\n ? edge.owner\n : edge.kind === \"junction\"\n ? edge.endpoints[0]\n : edge.carrier;\n if (anchor.source === model && anchor.field === field) yield edge;\n }\n }\n}\n\n// =============================================================================\n// CONTEXTUAL GRAPH NODES\n// =============================================================================\n\ninterface RegisteredModel {\n readonly model: Model<any>;\n readonly name: string;\n}\n\ninterface SlotNode {\n readonly slot: RelationSlot;\n readonly modelName: string;\n readonly field: string;\n readonly order: number;\n readonly state: RelationState;\n readonly relation: AnyRelation;\n}\n\n/** An ordinary slot, or one variant of a carrier: the two pairable things. */\ninterface Endpoint {\n readonly node: SlotNode;\n /** The variant key when this endpoint is one member of a carrier. */\n readonly variant: string | undefined;\n readonly target: Model<any>;\n readonly targetName: string;\n /** Members inherit the carrier's optional relation-name claim. */\n readonly name: string | undefined;\n readonly cardinality: RelationCardinality;\n /** Canonical position: model order, then field order, then variant order. */\n readonly order: number;\n}\n\n/**\n * An endpoint that IS one member of a carrier, so its variant key is settled.\n *\n * Carrier resolution asks each member for its key many times — for the name\n * prepass, the storage columns, the bound inverse, the junction override. That\n * key is settled exactly once, HERE, by the partition that selects members;\n * every later reader takes it as a fact rather than re-defaulting it.\n */\ntype VariantMember = Endpoint & { readonly variant: string };\n\nconst isVariantMember = (endpoint: Endpoint): endpoint is VariantMember =>\n endpoint.variant !== undefined;\n\ntype Verdict =\n | { readonly kind: \"paired\"; readonly partner: Endpoint }\n | { readonly kind: \"missing\" }\n | { readonly kind: \"nameMismatch\" }\n | { readonly kind: \"ambiguous\" };\n\ntype VariantMapEntry = VariantOneEntry | VariantManyEntry;\n\n// =============================================================================\n// THE GATE\n// =============================================================================\n\nexport function resolveSchemaRelations(\n schema: Schema,\n context: ValidationContext,\n // A schema `viborm check` validated skips the passes that only report\n // (required cycles, junction claims); everything the topology needs runs.\n checked = false\n): RelationResolution {\n const issues: SchemaValidationIssue[] = [];\n const registration = registerModels(schema);\n\n const nodes = collectSlotNodes(registration.models);\n const settlement = settleTargets(nodes, registration.byIdentity, issues);\n if (settlement.cause) {\n return { ok: false, issues, cause: settlement.cause };\n }\n\n const endpoints = settlement.endpoints;\n const byHolder = new Map<Model<any>, Endpoint[]>();\n for (const endpoint of endpoints) {\n const held = byHolder.get(endpoint.node.slot.source);\n if (held) held.push(endpoint);\n else byHolder.set(endpoint.node.slot.source, [endpoint]);\n }\n\n const structural = new Map<Endpoint, Endpoint[]>();\n const verdicts = new Map<Endpoint, Verdict>();\n for (const endpoint of endpoints) {\n const candidates = (byHolder.get(endpoint.target) ?? []).filter(\n (candidate) =>\n candidate.target === endpoint.node.slot.source &&\n // The asking slot itself is never a candidate; a self edge needs two\n // distinct fields.\n candidate.node !== endpoint.node &&\n // Two direct variant carriers never pair: neither owns the other's\n // storage, and a carrier-wide name cannot choose a member.\n !(candidate.variant !== undefined && endpoint.variant !== undefined)\n );\n structural.set(endpoint, candidates);\n verdicts.set(endpoint, decide(endpoint, candidates));\n }\n\n reportPairingIssues(endpoints, structural, verdicts, issues);\n\n const publication: Publication = {\n edges: [],\n slots: [],\n storedReferences: [],\n junctionTables: new Map(),\n junctionNames: [],\n issues,\n };\n\n for (const endpoint of endpoints) {\n const verdict = verdicts.get(endpoint);\n if (verdict?.kind !== \"paired\") continue;\n const partner = verdict.partner;\n if (endpoint.variant !== undefined || partner.variant !== undefined) {\n continue;\n }\n // Both endpoints of an ordinary pair must select each other, and the pair\n // is resolved once, from its canonically first endpoint.\n if (verdicts.get(partner)?.kind !== \"paired\") continue;\n if (endpoint.order > partner.order) continue;\n const edge = resolveOrdinaryPair(endpoint, partner, publication);\n if (!edge) continue;\n publication.edges.push(edge);\n publication.slots.push(\n { slot: endpoint.node.slot, edge },\n { slot: partner.node.slot, edge }\n );\n }\n reportJunctionTableClaims(publication, context, checked);\n if (!checked) {\n reportRequiredCycles(publication, registration.byIdentity);\n }\n\n resolveVariantCarriers(\n { schema, context, nodes, endpoints, verdicts },\n publication\n );\n\n if (issues.some((entry) => entry.severity === \"error\")) {\n return { ok: false, issues };\n }\n const index = buildIndex(registration.models, publication.slots);\n // Identifier domains are DERIVED from the edges just published, so they are\n // derived here and not by a rule beside the gate: every consumer that threads\n // the index reads them, and a schema whose foreign keys cannot agree on what\n // a column holds must not become an index at all.\n const identifiers = deriveIdDomains(index, context);\n if (identifiers.issues.length > 0) {\n return { ok: false, issues: [...issues, ...identifiers.issues] };\n }\n return { ok: true, index, issues };\n}\n\ninterface Publication {\n readonly edges: ResolvedRelationEdge[];\n readonly slots: ResolvedSlot[];\n readonly storedReferences: StoredReferenceFact[];\n /** Junction table name → the endpoint paths that claim it. */\n readonly junctionTables: Map<string, string[]>;\n /** Table and reverse-index names every ordinary junction reserves. */\n readonly junctionNames: string[];\n readonly issues: SchemaValidationIssue[];\n}\n\n// =============================================================================\n// REGISTRATION\n// =============================================================================\n\ninterface Registration {\n /** Schema key → model, first claim only. */\n readonly models: ReadonlyMap<string, Model<any>>;\n /** Identity lookup from a settled target value to the model it is. */\n readonly byIdentity: ReadonlyMap<unknown, RegisteredModel>;\n}\n\n/**\n * Index the schema by key and by model identity.\n *\n * There is no duplicate-registration check HERE. \"One model object binds one\n * schema key\" is proved by the registration preflight before hydration writes\n * anything (§7.1), which every effect-capable boundary runs before it reaches\n * this gate — so a second check would be a second guard for one invariant, and a\n * later one, after the names it protects were already written.\n */\nfunction registerModels(schema: Schema): Registration {\n const models = new Map<string, Model<any>>();\n const byIdentity = new Map<unknown, RegisteredModel>();\n for (const [name, model] of schema) {\n models.set(name, model);\n byIdentity.set(model, { model, name });\n }\n return { models, byIdentity };\n}\n\n// =============================================================================\n// SLOT NODES AND TARGET SETTLEMENT\n// =============================================================================\n\nfunction collectSlotNodes(models: ReadonlyMap<string, Model<any>>): SlotNode[] {\n const nodes: SlotNode[] = [];\n let order = 0;\n for (const [modelName, model] of models) {\n const relations: Record<string, AnyRelation> = model[\"~\"].state.relations;\n for (const [field, relation] of Object.entries(relations)) {\n nodes.push({\n slot: { source: model, field },\n modelName,\n field,\n order: order++,\n state: relation[\"~\"].state,\n relation,\n });\n }\n }\n return nodes;\n}\n\ninterface Settlement {\n readonly endpoints: Endpoint[];\n readonly cause: Error | undefined;\n}\n\n/**\n * Consume each terminal's lazy once-cell exactly once per slot, in canonical\n * order, and prove the settled value is a registered model.\n *\n * A thrown getter stops resolution: the first failure in canonical order emits\n * its contextual issue and returns the terminal's own settled `Error`, so every\n * schema context observes the same object and later getters stay uninvoked.\n */\nfunction settleTargets(\n nodes: readonly SlotNode[],\n byIdentity: ReadonlyMap<unknown, RegisteredModel>,\n issues: SchemaValidationIssue[]\n): Settlement {\n const endpoints: Endpoint[] = [];\n let order = 0;\n for (const node of nodes) {\n const target = node.state.target;\n if (target.kind === \"model\") {\n let settled: unknown;\n try {\n settled = node.relation[\"~\"].settleTarget();\n } catch (thrown) {\n issues.push(thrownTargetIssue(\"R006\", node, undefined, thrown));\n return { endpoints, cause: thrownAsError(thrown) };\n }\n const registered = byIdentity.get(settled);\n if (!registered) {\n issues.push(unregisteredTargetIssue(node));\n continue;\n }\n endpoints.push(makeEndpoint(node, undefined, registered, order++));\n continue;\n }\n const cause = settleVariantTargets(node, byIdentity, issues, endpoints);\n if (cause) return { endpoints, cause };\n order = endpoints.length;\n }\n return { endpoints, cause: undefined };\n}\n\n/** A polymorphic slot's variants, apart so ordinary schemas never compile it. */\nfunction settleVariantTargets(\n node: SlotNode,\n byIdentity: ReadonlyMap<unknown, RegisteredModel>,\n issues: SchemaValidationIssue[],\n endpoints: Endpoint[]\n): Error | undefined {\n // The caller settles `kind: \"model\"` targets itself.\n const target = node.state.target as Exclude<\n SlotNode[\"state\"][\"target\"],\n { kind: \"model\" }\n >;\n let order = endpoints.length;\n for (const variant of Object.keys(target.entries)) {\n let settled: unknown;\n try {\n settled = node.relation[\"~\"].settleTarget(variant);\n } catch (thrown) {\n issues.push(thrownTargetIssue(\"P001\", node, variant, thrown));\n return thrownAsError(thrown);\n }\n const registered = byIdentity.get(settled);\n if (!registered) {\n issues.push({\n code: \"P001\",\n message: `Variant '${variant}' in '${node.modelName}.${node.field}' is not registered in the schema`,\n severity: \"error\",\n model: node.modelName,\n relation: node.field,\n repair: `Register the '${variant}' target model in the schema`,\n });\n continue;\n }\n endpoints.push(makeEndpoint(node, variant, registered, order++));\n }\n}\n\nfunction unregisteredTargetIssue(node: SlotNode): SchemaValidationIssue {\n return {\n code: \"R006\",\n message: `'${node.field}' in '${node.modelName}' targets a model that is not registered in the schema`,\n severity: \"error\",\n model: node.modelName,\n relation: node.field,\n repair: \"Register the target model in the schema passed to the client\",\n };\n}\n\nfunction makeEndpoint(\n node: SlotNode,\n variant: string | undefined,\n registered: RegisteredModel,\n order: number\n): Endpoint {\n return {\n node,\n variant,\n target: registered.model,\n targetName: registered.name,\n name: node.state.name,\n cardinality: node.state.cardinality,\n order,\n };\n}\n\nfunction thrownTargetIssue(\n code: string,\n node: SlotNode,\n variant: string | undefined,\n thrown: unknown\n): SchemaValidationIssue {\n const where = variant ? `variant '${variant}' of ` : \"\";\n return {\n code,\n message: `Target getter for ${where}'${node.modelName}.${node.field}' threw: ${thrownAsError(thrown).message}`,\n severity: \"error\",\n model: node.modelName,\n relation: node.field,\n repair: \"Make the target getter return a registered model without throwing\",\n };\n}\n\n// =============================================================================\n// THE CANDIDATE GRAPH (§6.2)\n// =============================================================================\n\nfunction decide(endpoint: Endpoint, candidates: readonly Endpoint[]): Verdict {\n const exact = matching(endpoint, candidates);\n const [only] = exact;\n if (only && exact.length === 1) return { kind: \"paired\", partner: only };\n if (exact.length > 1) return { kind: \"ambiguous\" };\n // §6.2 rule 4 reads the candidate count AFTER the label partition, so a\n // variant member left with no same-named candidate has zero candidates and\n // stays a valid direct-only member. The differently named candidate is always\n // an ordinary slot — carriers never pair with carriers — and it must itself\n // pair, so the mistake this could hide still reports exactly one diagnostic,\n // at that slot.\n if (candidates.length === 0 || endpoint.variant !== undefined) {\n return { kind: \"missing\" };\n }\n return { kind: \"nameMismatch\" };\n}\n\nfunction matching(\n endpoint: Endpoint,\n candidates: readonly Endpoint[]\n): Endpoint[] {\n return candidates.filter((candidate) => candidate.name === endpoint.name);\n}\n\nfunction reportPairingIssues(\n endpoints: readonly Endpoint[],\n structural: ReadonlyMap<Endpoint, Endpoint[]>,\n verdicts: ReadonlyMap<Endpoint, Verdict>,\n issues: SchemaValidationIssue[]\n): void {\n for (const endpoint of endpoints) {\n const verdict = verdicts.get(endpoint);\n // Both maps were filled from this same endpoint list, one entry each.\n const candidates = structural.get(endpoint)!;\n if (verdict?.kind === \"missing\") {\n // A variant member with no candidate is a valid direct-only member.\n if (endpoint.variant !== undefined) continue;\n issues.push(missingInverseIssue(endpoint));\n continue;\n }\n if (verdict?.kind === \"ambiguous\") {\n const competing = matching(endpoint, candidates);\n issues.push(competingInverseIssue(endpoint, competing));\n continue;\n }\n if (verdict?.kind !== \"nameMismatch\") continue;\n // A mismatch is a fact about the PAIR, so it is reported once, at the\n // canonically first of the endpoints that disagree.\n const disagreeing = candidates.filter(\n (candidate) => verdicts.get(candidate)?.kind === \"nameMismatch\"\n );\n if (disagreeing.some((partner) => partner.order < endpoint.order)) continue;\n issues.push(nameMismatchIssue(endpoint, candidates));\n }\n}\n\nfunction describe(endpoint: Endpoint): string {\n return endpoint.variant === undefined\n ? `'${endpoint.node.modelName}.${endpoint.node.field}'`\n : `Variant '${endpoint.variant}' of '${endpoint.node.modelName}.${endpoint.node.field}'`;\n}\n\nfunction path(endpoint: Endpoint): string {\n return endpoint.variant === undefined\n ? `${endpoint.node.modelName}.${endpoint.node.field}`\n : `${endpoint.node.modelName}.${endpoint.node.field}.${endpoint.variant}`;\n}\n\nfunction label(name: string | undefined): string {\n return name === undefined ? \"no name\" : `'${name}'`;\n}\n\n// =============================================================================\n// ORDINARY TOPOLOGY (§6.3, §6.4)\n// =============================================================================\n\nfunction resolveOrdinaryPair(\n first: Endpoint,\n second: Endpoint,\n publication: Publication\n): ResolvedOrdinaryEdge | undefined {\n const issues = publication.issues;\n const endpoints: readonly [RelationSlot, RelationSlot] = [\n first.node.slot,\n second.node.slot,\n ];\n if (first.cardinality === \"many\" && second.cardinality === \"many\") {\n return resolveJunctionEdge(first, second, endpoints, publication);\n }\n\n for (const endpoint of [first, second]) {\n if (endpoint.node.state.junction === undefined) continue;\n issues.push(\n misplaced(endpoint, \"junction configuration\", \"an ordinary junction pair\")\n );\n return undefined;\n }\n\n const owners = [first, second].filter(\n (endpoint) => endpoint.node.state.foreignKey !== undefined\n );\n if (owners.length === 2) {\n issues.push(doubleOwnerIssue(first, second));\n return undefined;\n }\n const owner = owners[0];\n if (!owner) {\n // Name the ONE singular endpoint when exactly one is singular — that is\n // the end whose slot cannot be empty and so the one that must store the\n // key. Otherwise the canonically first endpoint carries the refusal.\n const [onlySingular, alsoSingular] = [first, second].filter(\n (endpoint) => endpoint.cardinality === \"one\"\n );\n const required = onlySingular && !alsoSingular ? onlySingular : first;\n issues.push(missingForeignKeyIssue(required));\n return undefined;\n }\n\n const partner = owner === first ? second : first;\n // `owners` IS the endpoints whose foreign key is defined, so re-asking here\n // would be a second owner for the fact that filter already decided.\n const foreignKey = owner.node.state.foreignKey!;\n const check = checkStoredReference({\n modelName: owner.node.modelName,\n model: owner.node.slot.source,\n relationName: owner.node.field,\n targetName: partner.node.modelName,\n target: partner.node.slot.source,\n foreignKey,\n });\n issues.push(...check.issues);\n\n const unique = first.cardinality === \"one\" && second.cardinality === \"one\";\n if (!unique && declaresUniqueKey(owner.node.slot.source, foreignKey.fields)) {\n issues.push(uniqueCollectionKeyIssue(owner, partner, foreignKey));\n return undefined;\n }\n if (!check.reference) return undefined;\n // The published local columns follow the NORMALIZED member order (a permuted\n // referenced tuple is reordered to its matched target key by\n // `checkStoredReference`), so the automatic-index name this fact reserves is\n // the same one the serializer derives from the members.\n publication.storedReferences.push({\n owner: owner.node.slot.source,\n fields: check.reference.members.map((member) => member.foreignField),\n unique,\n });\n return {\n kind: \"foreignKey\",\n endpoints,\n owner: owner.node.slot,\n reference: check.reference,\n unique,\n };\n}\n\nfunction resolveJunctionEdge(\n first: Endpoint,\n second: Endpoint,\n endpoints: readonly [RelationSlot, RelationSlot],\n publication: Publication\n): ResolvedOrdinaryEdge | undefined {\n const issues = publication.issues;\n const configured = [first, second].filter(\n (endpoint) => endpoint.node.state.junction !== undefined\n );\n if (configured.length === 2) {\n issues.push({\n code: \"R011\",\n message: `'${first.node.modelName}.${first.node.field}' and '${second.node.modelName}.${second.node.field}' both configure this junction; exactly one endpoint owns every override`,\n severity: \"error\",\n model: first.node.modelName,\n relation: first.node.field,\n candidates: [path(first), path(second)],\n repair: \"Keep the junction configuration on one endpoint only\",\n });\n return undefined;\n }\n // `configured` holds the endpoints whose junction value is set, so the sole\n // configuring endpoint's overrides are there to read.\n const configuring = configured[0];\n const overrides =\n configuring === undefined\n ? undefined\n : configuring === first\n ? configuring.node.state.junction\n : mirrorOverrides(configuring.node.state.junction!);\n\n const sourceRowKey =\n getModelKeyCatalog(first.node.slot.source).rowKey?.fields ?? [];\n const targetRowKey =\n getModelKeyCatalog(second.node.slot.source).rowKey?.fields ?? [];\n const names = resolveOrdinaryJunctionNames({\n sourceModelName: first.node.modelName,\n targetModelName: second.node.modelName,\n sourceField: first.node.field,\n targetField: second.node.field,\n sourceRowKeyIsCompound: sourceRowKey.length > 1,\n targetRowKeyIsCompound: targetRowKey.length > 1,\n pairName: first.name,\n overrides,\n });\n claimJunctionTable(publication, names.table, first, second);\n try {\n const topology = resolveJunctionTopology({\n table: names.table,\n source: {\n model: first.node.slot.source,\n modelName: first.node.modelName,\n rowKey: sourceRowKey,\n token: names.sourceToken,\n ...sideActions(overrides, \"source\"),\n },\n target: {\n model: second.node.slot.source,\n modelName: second.node.modelName,\n rowKey: targetRowKey,\n token: names.targetToken,\n ...sideActions(overrides, \"target\"),\n },\n pairName: first.name,\n });\n topology.foreignKeyName(\"source\");\n topology.foreignKeyName(\"target\");\n publication.junctionNames.push(names.table, topology.reverseIndexName());\n return { kind: \"junction\", endpoints, topology };\n } catch (error) {\n issues.push({\n code:\n error instanceof JunctionPhysicalNameError && error.kind === \"collision\"\n ? \"JT003\"\n : \"JT002\",\n message: thrownAsError(error).message,\n severity: \"error\",\n model: first.node.modelName,\n relation: first.node.field,\n repair:\n \"Give this junction an explicit .through(...) table and distinct .source(...)/.target(...) tokens\",\n });\n return undefined;\n }\n}\n\nfunction claimJunctionTable(\n publication: Publication,\n table: string,\n first: Endpoint,\n second: Endpoint\n): void {\n const claims = publication.junctionTables.get(table);\n const claim = `${path(first)}, ${path(second)}`;\n if (claims) claims.push(claim);\n else publication.junctionTables.set(table, [claim]);\n}\n\n/** JT001: one physical junction table belongs to exactly one resolved pair. */\nfunction reportJunctionTableClaims(\n publication: Publication,\n context: ValidationContext,\n checked: boolean\n): void {\n for (const [table, claims] of publication.junctionTables) {\n const models = context.tableToModels.get(table);\n if (models) {\n publication.issues.push({\n code: \"JT003\",\n message: `Junction '${table}' for ${claims.join(\"; \")} collides with the table of registered model ${models.join(\", \")}`,\n severity: \"error\",\n candidates: models,\n repair:\n \"Choose an unoccupied .through(...) table or map the model to a distinct table\",\n });\n }\n if (checked || claims.length < 2) continue;\n publication.issues.push({\n code: \"JT001\",\n message: `Junction '${table}' is claimed by more than one relation pair: ${claims.join(\"; \")}`,\n severity: \"error\",\n candidates: claims,\n repair:\n \"Give each pair its own .through(...) table or a distinct .name(...)\",\n });\n }\n}\n\n/**\n * CM002: a cycle of required foreign keys can never be inserted.\n *\n * \"Required\" is derived, not declared: a foreign key whose every local member is\n * non-nullable makes its target an insert dependency of its owner.\n */\nfunction reportRequiredCycles(\n publication: Publication,\n byIdentity: ReadonlyMap<unknown, RegisteredModel>\n): void {\n const graph = new Map<string, string[]>();\n for (const registered of byIdentity.values()) graph.set(registered.name, []);\n for (const edge of publication.edges) {\n if (edge.kind !== \"foreignKey\") continue;\n const owner = edge.owner;\n const scalars = owner.source[\"~\"].state.scalars;\n const required = edge.reference.members.every(\n (member) => scalars[member.foreignField]?.[\"~\"].state.nullable !== true\n );\n if (!required) continue;\n const [first, second] = edge.endpoints;\n const partner = first === owner ? second : first;\n const from = byIdentity.get(owner.source)?.name;\n const to = byIdentity.get(partner.source)?.name;\n if (from !== undefined && to !== undefined) graph.get(from)?.push(to);\n }\n\n const visited = new Set<string>();\n const stack = new Set<string>();\n const reported = new Set<string>();\n const walk = (node: string, trail: string[]): void => {\n if (stack.has(node)) {\n const cycle = [...trail.slice(trail.indexOf(node)), node];\n const key = [...cycle].sort().join(\"->\");\n if (reported.has(key)) return;\n reported.add(key);\n publication.issues.push(requiredCycleIssue(cycle));\n return;\n }\n if (visited.has(node)) return;\n visited.add(node);\n stack.add(node);\n trail.push(node);\n // Seeded for every registered model, and a neighbour IS a registered name.\n for (const neighbor of graph.get(node)!) walk(neighbor, trail);\n stack.delete(node);\n trail.pop();\n };\n for (const node of graph.keys()) {\n if (!visited.has(node)) walk(node, []);\n }\n}\n\n/**\n * The other endpoint's view of one owner's overrides: the two sides swap —\n * the side tokens and, with them, each action pair's sides.\n */\nfunction mirrorOverrides(\n overrides: JunctionOverrideView\n): JunctionOverrideView {\n return {\n ...(overrides.table === undefined ? {} : { table: overrides.table }),\n ...(overrides.target === undefined ? {} : { source: overrides.target }),\n ...(overrides.source === undefined ? {} : { target: overrides.source }),\n ...(overrides.onDelete === undefined\n ? {}\n : { onDelete: swapSides(overrides.onDelete) }),\n ...(overrides.onUpdate === undefined\n ? {}\n : { onUpdate: swapSides(overrides.onUpdate) }),\n };\n}\n\nfunction swapSides(actions: JunctionSideActions): JunctionSideActions {\n return { source: actions.target, target: actions.source };\n}\n\n/** One oriented side's slice of the owner's actions, for the topology. */\nfunction sideActions(\n overrides: JunctionOverrideView | undefined,\n side: \"source\" | \"target\"\n) {\n const onDelete = overrides?.onDelete?.[side];\n const onUpdate = overrides?.onUpdate?.[side];\n return {\n ...(onDelete === undefined ? {} : { onDelete }),\n ...(onUpdate === undefined ? {} : { onUpdate }),\n };\n}\n\nfunction misplaced(\n endpoint: Endpoint,\n what: string,\n where: string\n): SchemaValidationIssue {\n return {\n code: \"R012\",\n message: `${describe(endpoint)} declares ${what}, which only ${where} may carry`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n repair: `Remove ${what} from '${endpoint.node.modelName}.${endpoint.node.field}'`,\n };\n}\n\nfunction declaresUniqueKey(\n model: Model<any>,\n fields: readonly string[]\n): boolean {\n return findReferenceableKey(model, fields) !== undefined;\n}\n\n// =============================================================================\n// VARIANT TOPOLOGY (§6.5)\n// =============================================================================\n\ninterface GraphView {\n readonly schema: Schema;\n readonly context: ValidationContext;\n readonly nodes: readonly SlotNode[];\n readonly endpoints: readonly Endpoint[];\n readonly verdicts: ReadonlyMap<Endpoint, Verdict>;\n}\n\nfunction resolveVariantCarriers(\n graph: GraphView,\n publication: Publication\n): void {\n // The variant map is read ONCE per carrier, here, where the partition that\n // selects carriers is the same expression that narrows the target. Every\n // later reader takes the entries as a fact instead of re-classifying a\n // declaration it already knows is a carrier's.\n const carriers: SlotNode[] = [];\n const entriesByCarrier = new Map<\n SlotNode,\n Readonly<Record<string, VariantMapEntry>>\n >();\n for (const node of graph.nodes) {\n const target = node.state.target;\n if (target.kind !== \"variants\") continue;\n carriers.push(node);\n entriesByCarrier.set(node, target.entries);\n }\n if (carriers.length === 0) return;\n resolveCarriers(graph, publication, carriers, entriesByCarrier);\n}\n\n/** The carriers found above, resolved; schemas without one never compile it. */\nfunction resolveCarriers(\n graph: GraphView,\n publication: Publication,\n carriers: SlotNode[],\n entriesByCarrier: Map<SlotNode, Readonly<Record<string, VariantMapEntry>>>\n): void {\n // Every carrier gets an entry, empty or not: a carrier whose targets were all\n // refused above contributed no member, and the two passes below then read one\n // settled list in carrier order instead of each re-deciding what an absent\n // carrier means. A member's node IS a carrier — the same\n // `target.kind === \"variants\"` partition selected both — so the seeded list\n // is always there to push into.\n const membersByCarrier = new Map<SlotNode, VariantMember[]>();\n for (const carrier of carriers) membersByCarrier.set(carrier, []);\n for (const endpoint of graph.endpoints) {\n if (!isVariantMember(endpoint)) continue;\n membersByCarrier.get(endpoint.node)!.push(endpoint);\n }\n\n const memberNameCounts = new Map<string, number>();\n const indexNameCounts = new Map<string, number>();\n for (const [carrier, members] of membersByCarrier) {\n if (carrier.state.cardinality === \"one\") {\n const indexName = variantRowIndexName(tableOf(carrier), carrier.field);\n indexNameCounts.set(indexName, (indexNameCounts.get(indexName) ?? 0) + 1);\n continue;\n }\n for (const member of members) {\n const plan = planVariantMemberNames({\n model: carrier.slot.source,\n modelName: carrier.modelName,\n ownerTable: tableOf(carrier),\n relationName: carrier.field,\n member: memberInput(entriesByCarrier.get(carrier)!, member),\n });\n for (const claim of plan?.claims ?? []) {\n memberNameCounts.set(claim, (memberNameCounts.get(claim) ?? 0) + 1);\n }\n }\n }\n\n const reservedIndexes = collectReservedPhysicalNames({\n schema: graph.schema,\n ctx: graph.context,\n junctionNames: publication.junctionNames,\n storedReferences: publication.storedReferences,\n });\n\n for (const [carrier, members] of membersByCarrier) {\n const reservedColumns = new Set(\n getScalars(carrier.slot.source).map(\n ([field, scalar]) => scalar[\"~\"].state.columnName ?? field\n )\n );\n const bound = bindMembers(members, graph, publication);\n const edge: ResolvedVariantEdge | undefined =\n carrier.state.cardinality === \"one\"\n ? resolveRowCarrier({\n carrier,\n entries: entriesByCarrier.get(carrier)!,\n members,\n bound,\n reservedColumns,\n reservedIndexes,\n indexNameCounts,\n publication,\n })\n : resolveMemberJunctionCarrier({\n carrier,\n entries: entriesByCarrier.get(carrier)!,\n members,\n bound,\n reservedColumns,\n reservedIndexes,\n memberNameCounts,\n publication,\n });\n if (!edge) continue;\n publication.edges.push(edge);\n publication.slots.push({ slot: carrier.slot, edge });\n // An inverse view points at the EXACT member object the carrier edge already\n // owns — `member.inverse` is the slot that member bound, so there is no\n // second lookup that could miss. The two storage families are walked\n // separately only because `ResolvedSlot` pairs each edge form with its own\n // member type; the bodies are one rule.\n if (edge.kind === \"variantRowCarrier\") {\n for (const member of edge.members) {\n if (member.inverse) {\n publication.slots.push({ slot: member.inverse, edge, member });\n }\n }\n continue;\n }\n for (const member of edge.members) {\n if (member.inverse) {\n publication.slots.push({ slot: member.inverse, edge, member });\n }\n }\n }\n}\n\n/**\n * Variant key → the ordinary slot resolved onto that member.\n *\n * A bound inverse is a VIEW over carrier-owned storage: it configures neither a\n * foreign key nor a junction, because the carrier already owns both.\n */\nfunction bindMembers(\n members: readonly VariantMember[],\n graph: GraphView,\n publication: Publication\n): Map<string, Endpoint> {\n const bound = new Map<string, Endpoint>();\n for (const member of members) {\n const verdict = graph.verdicts.get(member);\n if (verdict?.kind !== \"paired\") continue;\n const inverse = verdict.partner;\n if (graph.verdicts.get(inverse)?.kind !== \"paired\") continue;\n if (inverse.node.state.foreignKey !== undefined) {\n publication.issues.push(\n misplaced(inverse, \"a foreign key\", \"an ordinary edge's owner\")\n );\n continue;\n }\n if (inverse.node.state.junction !== undefined) {\n publication.issues.push(\n misplaced(\n inverse,\n \"junction configuration\",\n \"an ordinary junction pair\"\n )\n );\n continue;\n }\n bound.set(member.variant, inverse);\n }\n return bound;\n}\n\ninterface CarrierInput {\n readonly carrier: SlotNode;\n /** The carrier's normalized variant map, narrowed once at the partition. */\n readonly entries: Readonly<Record<string, VariantMapEntry>>;\n readonly members: readonly VariantMember[];\n readonly bound: ReadonlyMap<string, Endpoint>;\n readonly reservedColumns: Set<string>;\n readonly reservedIndexes: Set<string>;\n readonly publication: Publication;\n}\n\nfunction resolveRowCarrier(\n input: CarrierInput & {\n readonly indexNameCounts: ReadonlyMap<string, number>;\n }\n): ResolvedVariantRowEdge | undefined {\n const { carrier, members, bound, publication } = input;\n const cardinalities = new Set(\n [...bound.values()].map((inverse) => inverse.cardinality)\n );\n if (cardinalities.size > 1) {\n publication.issues.push({\n code: \"P012\",\n message: `Variant relation '${carrier.field}' in '${carrier.modelName}' cannot mix to-one and to-many inverses; one composite index serves the whole carrier`,\n severity: \"error\",\n model: carrier.modelName,\n relation: carrier.field,\n repair: \"Give every bound inverse of this carrier the same cardinality\",\n });\n return undefined;\n }\n const storage = checkVariantRowStorage({\n modelName: carrier.modelName,\n ownerTable: tableOf(carrier),\n relationName: carrier.field,\n optional: carrier.state.optional === true,\n members: members.map((member) => ({\n variant: member.variant,\n target: member.target,\n })),\n reservedColumns: input.reservedColumns,\n reservedIndexes: input.reservedIndexes,\n indexNameCounts: input.indexNameCounts,\n });\n publication.issues.push(...storage.issues);\n if (!storage.storage) return undefined;\n\n const entries = input.entries;\n const resolved: ResolvedVariantRowMember[] = [];\n for (const member of members) {\n const variant = member.variant;\n // Storage is published ONLY when every member resolved a referenced field,\n // and each member's key came from this same entry map — so both lookups are\n // reads of what the completeness check above already decided.\n const referencedField = storage.referencedFields.get(variant)!;\n const entry = entries[variant]!;\n const inverse = bound.get(variant);\n resolved.push({\n variant,\n entry,\n targetModel: member.target,\n referencedField,\n ...(inverse ? { inverse: inverse.node.slot } : {}),\n });\n }\n // Published storage requires one portable identity, so a carrier that reaches\n // here resolved at least one member.\n const [head, ...rest] = resolved;\n return {\n kind: \"variantRowCarrier\",\n carrier: carrier.slot,\n members: [head!, ...rest],\n uniqueTarget: cardinalities.has(\"one\"),\n storage: storage.storage,\n };\n}\n\nfunction resolveMemberJunctionCarrier(\n input: CarrierInput & {\n readonly memberNameCounts: ReadonlyMap<string, number>;\n }\n): ResolvedVariantJunctionEdge | undefined {\n const { carrier, members, bound, publication } = input;\n const junctions = checkVariantMemberJunctions({\n modelName: carrier.modelName,\n model: carrier.slot.source,\n ownerTable: tableOf(carrier),\n relationName: carrier.field,\n members: members.map((member) => memberInput(input.entries, member)),\n reservedColumns: input.reservedColumns,\n reservedIndexes: input.reservedIndexes,\n memberNameCounts: input.memberNameCounts,\n });\n publication.issues.push(...junctions.issues);\n\n const entries = input.entries;\n const resolved: ResolvedVariantJunctionMember[] = [];\n for (const member of members) {\n const variant = member.variant;\n const topology = junctions.topologies.get(variant);\n const entry = entries[variant];\n if (!(topology && entry)) return undefined;\n const inverse = bound.get(variant);\n resolved.push({\n variant,\n entry,\n uniqueTarget: inverse?.cardinality === \"one\",\n topology,\n ...(inverse ? { inverse: inverse.node.slot } : {}),\n });\n }\n const [head, ...rest] = resolved;\n if (!head) return undefined;\n return {\n kind: \"variantJunctionCarrier\",\n carrier: carrier.slot,\n members: [head, ...rest],\n };\n}\n\nfunction memberInput(\n entries: Readonly<Record<string, VariantMapEntry>>,\n member: VariantMember\n) {\n return {\n variant: member.variant,\n target: member.target,\n targetName: member.targetName,\n junction: entries[member.variant]?.junction,\n };\n}\n\nfunction tableOf(node: SlotNode): string {\n return node.slot.source[\"~\"].state.tableName ?? node.modelName;\n}\n\n// =============================================================================\n// PUBLICATION\n// =============================================================================\n\n/**\n * Publish the slots as a per-model map in DECLARATION order.\n *\n * Resolution order is edge order — ordinary pairs first, at their canonically\n * first endpoint, then every variant carrier — so inserting `slots` as they were\n * produced would put a model's variant carrier after an ordinary slot declared\n * later. `resolvedEdges` promises schema/model/field order and the migration\n * serializer emits from it, so the shape order the model already holds is what\n * decides the map's order; the resolved slots are only looked up by it.\n */\nfunction buildIndex(\n models: ReadonlyMap<string, Model<any>>,\n slots: readonly ResolvedSlot[]\n): ResolvedRelationIndex {\n const resolvedBySlot = new Map<Model<any>, Map<string, ResolvedSlot>>();\n for (const resolved of slots) {\n const held = resolvedBySlot.get(resolved.slot.source);\n if (held) held.set(resolved.slot.field, resolved);\n else\n resolvedBySlot.set(\n resolved.slot.source,\n new Map([[resolved.slot.field, resolved]])\n );\n }\n const index = new Map<Model<any>, Map<string, ResolvedSlot>>();\n for (const model of models.values()) {\n const declared = resolvedBySlot.get(model);\n const ordered = new Map<string, ResolvedSlot>();\n const relations: Record<string, AnyRelation> = model[\"~\"].state.relations;\n for (const field of Object.keys(relations)) {\n const resolved = declared?.get(field);\n if (resolved) ordered.set(field, resolved);\n }\n index.set(model, ordered);\n }\n return index;\n}\n\n// Issue builders, apart from the resolution so a valid schema never compiles\n// them.\n\nfunction missingInverseIssue(endpoint: Endpoint): SchemaValidationIssue {\n return {\n code: \"R002\",\n message: `'${endpoint.node.modelName}.${endpoint.node.field}' has no inverse relation in '${endpoint.targetName}'`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n repair: `Declare a slot on '${endpoint.targetName}' whose target is '${endpoint.node.modelName}'`,\n };\n}\n\nfunction competingInverseIssue(\n endpoint: Endpoint,\n competing: readonly Endpoint[]\n): SchemaValidationIssue {\n return {\n code: \"R009\",\n message: `${describe(endpoint)} has ${competing.length} competing inverse candidates in '${endpoint.targetName}'`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n candidates: competing.map(path),\n repair:\n \"Give each intended pair the same distinct .name(...) on both endpoints\",\n };\n}\n\nfunction nameMismatchIssue(\n endpoint: Endpoint,\n candidates: readonly Endpoint[]\n): SchemaValidationIssue {\n return {\n code: \"R010\",\n message: `${describe(endpoint)} claims relation name ${label(endpoint.name)}, but no candidate in '${endpoint.targetName}' claims the same name`,\n severity: \"error\",\n model: endpoint.node.modelName,\n relation: endpoint.node.field,\n candidates: candidates.map(path),\n repair: \"Spell the same .name(...) on both endpoints, or omit it on both\",\n };\n}\n\nfunction doubleOwnerIssue(\n first: Endpoint,\n second: Endpoint\n): SchemaValidationIssue {\n return {\n code: \"CM003\",\n message: `'${first.node.modelName}.${first.node.field}' and '${second.node.modelName}.${second.node.field}' both complete a foreign key; exactly one endpoint owns it`,\n severity: \"error\",\n model: first.node.modelName,\n relation: first.node.field,\n candidates: [path(first), path(second)],\n repair: \"Drop .fields(...).references(...) from one endpoint\",\n };\n}\n\nfunction missingForeignKeyIssue(required: Endpoint): SchemaValidationIssue {\n return {\n code: \"FK004\",\n message: `'${required.node.modelName}.${required.node.field}' stores no foreign key; one endpoint of this edge must complete .fields(...).references(...)`,\n severity: \"error\",\n model: required.node.modelName,\n relation: required.node.field,\n repair: `Complete .fields(...).references(...) on '${required.node.modelName}.${required.node.field}'`,\n };\n}\n\nfunction uniqueCollectionKeyIssue(\n owner: Endpoint,\n partner: Endpoint,\n foreignKey: NonNullable<Endpoint[\"node\"][\"state\"][\"foreignKey\"]>\n): SchemaValidationIssue {\n return {\n code: \"FK009\",\n message: `'${owner.node.modelName}.${owner.node.field}' stores a unique foreign key, which contradicts the collection '${partner.node.modelName}.${partner.node.field}' declares`,\n severity: \"error\",\n model: owner.node.modelName,\n relation: owner.node.field,\n repair: `Drop the unique key on [${foreignKey.fields.join(\", \")}], or declare '${partner.node.modelName}.${partner.node.field}' with s.toOne`,\n };\n}\n\nfunction requiredCycleIssue(cycle: readonly string[]): SchemaValidationIssue {\n return {\n code: \"CM002\",\n message: `Circular required relations: ${cycle.join(\" → \")}`,\n severity: \"error\",\n repair: \"Make one foreign key in the cycle nullable\",\n };\n}\n","// Model & Scalar Validation Rules\n\nimport { validateSchema } from \"../../../validation/primitives/helpers\";\nimport { isValidSchemaIdentifier } from \"../../identifier\";\nimport { jsonNullKindOf } from \"../../json-null\";\nimport type { Model, ModelState } from \"../../model\";\nimport { getAmbiguousPublicSelectorNames } from \"../../model/keys\";\nimport { isGeneratorDefault } from \"../../scalars/common\";\nimport type { Schema, SchemaValidationIssue } from \"../types\";\nimport { getScalars } from \"./model-members\";\n\nfunction validateFieldNames(\n modelName: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n for (const fieldName of Object.keys(model[\"~\"].state.shape)) {\n if (isValidSchemaIdentifier(fieldName)) continue;\n errors.push({\n code: \"F001\",\n message: `Field '${fieldName}' in '${modelName}' is invalid identifier`,\n severity: \"error\",\n model: modelName,\n field: fieldName,\n });\n }\n return errors;\n}\n\n// =============================================================================\n// MODEL RULES (M001-M006)\n// =============================================================================\n\n/** M002: Model must have at least one scalar field */\nexport function modelHasFields(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n if (Object.keys(model[\"~\"].state.scalars).length === 0) {\n return [\n {\n code: \"M002\",\n message: `'${name}' must have at least one field`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n/** M005: Model name must be valid identifier */\nexport function modelNameValid(\n _s: Schema,\n name: string,\n _m: Model<any>\n): SchemaValidationIssue[] {\n if (!isValidSchemaIdentifier(name)) {\n return [\n {\n code: \"M005\",\n message: `'${name}' is not a valid identifier`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n/** M007: Mapped table name (.map()) must be a valid identifier */\nexport function modelMappedNameValid(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const tableName = model[\"~\"].state.tableName;\n if (tableName !== undefined && !isValidSchemaIdentifier(tableName)) {\n return [\n {\n code: \"M007\",\n message: `Mapped table name '${String(tableName)}' on '${name}' is not a valid identifier`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n/** M006: A model must not occupy the client Promise-assimilation hook. */\nexport function modelNameNotReserved(\n _s: Schema,\n name: string,\n _m: Model<any>\n): SchemaValidationIssue[] {\n if (name === \"then\") {\n return [\n {\n code: \"M006\",\n message: `Model 'then' conflicts with the client's Promise-assimilation hook; rename the model key and use .map(\"then\") to retain the table name`,\n severity: \"error\",\n model: name,\n },\n ];\n }\n return [];\n}\n\n// =============================================================================\n// FIELD RULES (F001-F008) - SINGLE PASS\n// =============================================================================\n\n/** Helper: Get compound ID field names from state */\nexport function getCompoundIdFields(model: Model<any>): string[] {\n const compoundId = model[\"~\"].state.compoundId;\n if (!compoundId) return [];\n const constraints: NonNullable<ModelState[\"compoundId\"]> = compoundId;\n return Object.keys(Object.values(constraints)[0]!.entries);\n}\n\n/** Helper: Get compound unique constraints from state */\nexport function getCompoundUniques(\n model: Model<any>\n): Array<{ name: string; fields: string[] }> {\n const compoundUniques: ModelState[\"compoundUniques\"] =\n model[\"~\"].state.compoundUniques;\n if (!compoundUniques) return [];\n return Object.entries(compoundUniques).map(([name, schema]) => ({\n name,\n fields: Object.keys(schema.entries),\n }));\n}\n\n/**\n * Single-pass field validation\n * Combines: F001, F002, F003, F004, F006, F007, F008\n * Iterates scalars once instead of 7 separate passes\n */\nexport function validateFieldsSinglePass(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors = validateFieldNames(name, model);\n\n // Accumulators for cross-scalar checks\n let idCount = 0;\n const columnToFields = new Map<string, string[]>();\n\n for (const [fname, scalar] of getScalars(model)) {\n const st = scalar[\"~\"].state;\n\n // F009: Mapped column name (.map()) valid\n if (\n st.columnName !== undefined &&\n !isValidSchemaIdentifier(st.columnName)\n ) {\n errors.push({\n code: \"F009\",\n message: `Mapped column name '${String(st.columnName)}' for '${fname}' in '${name}' is not a valid identifier`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n\n // F002: Count ID scalars\n if (st.isId) idCount++;\n\n // F003: Track column names\n const col = st.columnName ?? fname;\n if (!columnToFields.has(col)) columnToFields.set(col, []);\n columnToFields.get(col)!.push(fname);\n\n // F004: Default type match. A decimal literal crossed its complete field\n // codec when `.default()` retained it, so this downstream boundary trusts\n // that canonical output instead of applying a custom schema twice.\n if (\n st.hasDefault &&\n st.default !== undefined &&\n typeof st.default !== \"function\" &&\n st.type !== \"decimal\"\n ) {\n const jsonKind =\n st.type === \"json\" ? jsonNullKindOf(st.default) : undefined;\n const result =\n jsonKind === undefined\n ? validateSchema(scalar[\"~\"].state.base, st.default)\n : jsonKind === \"JsonNull\" || (jsonKind === \"DbNull\" && st.nullable)\n ? { value: st.default, issues: undefined }\n : {\n issues: [\n {\n message:\n \"JSON default names a null this column cannot store\",\n },\n ],\n };\n if (result.issues) {\n errors.push({\n code: \"F004\",\n message: `Default value for '${fname}' in '${name}' doesn't match type`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n }\n\n // F006: ID not nullable\n if (st.isId && st.nullable) {\n errors.push({\n code: \"F006\",\n message: `ID '${fname}' in '${name}' cannot be nullable`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n\n // F007: ID not array\n if (st.isId && st.array) {\n errors.push({\n code: \"F007\",\n message: `ID '${fname}' in '${name}' cannot be array`,\n severity: \"error\",\n model: name,\n field: fname,\n });\n }\n\n // F008: Surface actual generated defaults on non-key fields.\n if (\n !st.isId &&\n (st.autoGenerate?.kind === \"increment\" || isGeneratorDefault(st.default))\n ) {\n errors.push({\n code: \"F008\",\n message: `Generated default on non-key '${fname}' in '${name}'; verify generation is intended`,\n severity: \"warning\",\n model: name,\n field: fname,\n });\n }\n }\n\n // Check for compound ID\n const compoundIdCount = Object.keys(model[\"~\"].state.compoundId ?? {}).length;\n const hasCompoundId = compoundIdCount > 0;\n\n // M001: No ID field (allow if compound ID exists)\n if (idCount === 0 && !hasCompoundId) {\n errors.push({\n code: \"M001\",\n message: `'${name}' must have an ID field (or use .id() for compound key)`,\n severity: \"error\",\n model: name,\n });\n }\n\n // F002: Multiple single-field IDs, single + compound, or multiple .id() calls\n if (idCount > 1 || (idCount > 0 && hasCompoundId) || compoundIdCount > 1) {\n errors.push({\n code: \"F002\",\n message: `'${name}' has conflicting ID definitions (use either single field .id() or model .id())`,\n severity: \"error\",\n model: name,\n });\n }\n\n // F003: Duplicate columns\n for (const [col, fields] of columnToFields) {\n if (fields.length > 1) {\n errors.push({\n code: \"F003\",\n message: `Column '${col}' used by multiple fields in '${name}': ${fields.join(\n \", \"\n )}`,\n severity: \"error\",\n model: name,\n });\n }\n }\n\n return errors;\n}\n\n// =============================================================================\n// INDEX RULES (I001-I005)\n// =============================================================================\n\n/** I001: Index fields must exist */\nexport function indexFieldsExist(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n const fields = new Set(Object.keys(model[\"~\"].state.scalars));\n for (const idx of model[\"~\"].state.indexes) {\n for (const f of idx.fields) {\n if (!fields.has(f)) {\n errors.push({\n code: \"I001\",\n message: `Index field '${f}' not in '${name}'`,\n severity: \"error\",\n model: name,\n field: f,\n });\n }\n }\n }\n return errors;\n}\n\n/** I002: Index names must be unique */\nexport function indexNameUnique(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const names = new Map<string, number>();\n for (const idx of model[\"~\"].state.indexes) {\n if (idx.options.name) {\n names.set(idx.options.name, (names.get(idx.options.name) ?? 0) + 1);\n }\n }\n const errors: SchemaValidationIssue[] = [];\n for (const [iname, count] of names) {\n if (count > 1) {\n errors.push({\n code: \"I002\",\n message: `Index name '${iname}' duplicated in '${name}'`,\n severity: \"error\",\n model: name,\n });\n }\n }\n return errors;\n}\n\n/** I003: Compound unique/id constraints must contain at least one field. */\nexport function compoundConstraintsNonEmpty(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n\n const compoundIdFields = getCompoundIdFields(model);\n if (model[\"~\"].state.compoundId && compoundIdFields.length === 0) {\n errors.push({\n code: \"I003\",\n message: `Compound ID in '${name}' must contain at least one field`,\n severity: \"error\",\n model: name,\n });\n }\n const compoundUniques = getCompoundUniques(model);\n for (const constraint of compoundUniques) {\n if (constraint.fields.length === 0) {\n errors.push({\n code: \"I003\",\n message: `Compound unique '${constraint.name}' in '${name}' must contain at least one field`,\n severity: \"error\",\n model: name,\n });\n }\n }\n\n return errors;\n}\n\n/**\n * F010's reserved names, each with the output it is reserved for. Both are\n * keys a selection publishes on its own (owner rulings, 2026-09-26: \"_count is\n * a reserved word\", \"_distance is reserved too\"): `_count` in `select` and\n * `include` is the relation-count projection, and `_distance` is the key a\n * selected point or vector distance publishes under.\n */\nconst RESERVED_MEMBER_NAMES = {\n _count: \"relation counts\",\n _distance: \"distance results\",\n} as const;\n\n/**\n * F010: a model member never takes a reserved name.\n *\n * A member named `_count` or `_distance` — a scalar, a relation or a variant\n * slot — would give that output key two producers, and every reader of a\n * selection (admission, the engine's projection, the schema-only renderer,\n * the static types) then needs its own answer to which one wins. Refusing the\n * name here leaves each key one meaning everywhere downstream. The two names\n * share one sentence because they share the reason and the remedy: the column\n * name stays available, and a renamed scalar keeps it with `.map(...)`.\n *\n * TypeScript callers meet the refusal earlier: the shape parameter of\n * `s.model` and `.extends` forbids both keys (`DeclaredModelShape`). That is a\n * convenience for them only; a JavaScript caller, a cast or a computed key\n * reaches this rule, so F010 is the contract for every caller.\n */\nexport function memberNamesAreNotReserved(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const shape = model[\"~\"].state.shape;\n return Object.entries(RESERVED_MEMBER_NAMES)\n .filter(([reserved]) => Object.hasOwn(shape, reserved))\n .map(\n ([reserved, output]): SchemaValidationIssue => ({\n code: \"F010\",\n message: `Model '${name}' declares a member named '${reserved}'; '${reserved}' is reserved for ${output}. Rename it, and use .map(\"${reserved}\") on a renamed scalar to keep its column name.`,\n severity: \"error\",\n model: name,\n field: reserved,\n })\n );\n}\n\n/** I006: one model-local public unique-where name has one meaning. */\nexport function publicSelectorNamesAreUnambiguous(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n return getAmbiguousPublicSelectorNames(model).map((selector) => ({\n code: \"I006\",\n message: `Public selector name '${selector}' is ambiguous in '${name}'; a compound selector must not reuse a model field, logical filter, or another compound selector name`,\n severity: \"error\",\n model: name,\n }));\n}\n\n/**\n * I004: a fixed-decimal LIST is not a member of a key or an index (plan 2.1).\n *\n * The MODEL-level half of the exclusion. `.id()` and `.unique()` are refused on\n * the declaration itself, where the chain writes them, but a compound key, a\n * compound unique and an index name their members by string from the model, so\n * the declaration never sees them and this is the only place they exist.\n *\n * Why a decimal list in particular: on two of three providers the column holds\n * ONE JSON container, so an index or a key over it addresses a document by its\n * spelling rather than by its members — and `[\"1.2\"]` and `[\"1.20\"]` are the\n * same list. Other array scalars are not refused: PostgreSQL indexes native\n * arrays meaningfully, and this program speaks only for the fixed decimal.\n */\nexport function decimalListsAreNotKeyMembers(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const scalars = model[\"~\"].state.scalars;\n const isDecimalList = (field: string): boolean => {\n const state = scalars[field]?.[\"~\"].state;\n return state?.type === \"decimal\" && state.array === true;\n };\n\n const positions: Array<{ field: string; position: string }> = [];\n for (const index of model[\"~\"].state.indexes) {\n for (const field of index.fields) {\n positions.push({ field, position: \"an index\" });\n }\n }\n for (const field of getCompoundIdFields(model)) {\n positions.push({ field, position: \"a compound ID\" });\n }\n for (const constraint of getCompoundUniques(model)) {\n for (const field of constraint.fields) {\n positions.push({ field, position: `unique '${constraint.name}'` });\n }\n }\n\n const errors: SchemaValidationIssue[] = [];\n for (const { field, position } of positions) {\n if (!isDecimalList(field)) continue;\n errors.push({\n code: \"I004\",\n message: `'${field}' in '${name}' is a fixed-decimal list, which cannot be a member of ${position}`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n return errors;\n}\n\n/**\n * I005: GeoPoint has one portable physical index role and no key role.\n *\n * The scalar class has no `.id()`/`.unique()` methods and the typed model\n * surface excludes compound keys and ordinary indexes. This definition gate\n * owns hostile JavaScript and decoded schema values that bypass those types.\n */\nexport function geoPointRolesArePortable(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const state = model[\"~\"].state;\n const isPoint = (field: string): boolean =>\n state.scalars[field]?.[\"~\"].state.type === \"point\";\n const issues: SchemaValidationIssue[] = [];\n\n for (const [field, scalar] of getScalars(model)) {\n const scalarState = scalar[\"~\"].state;\n if (\n scalarState.type === \"point\" &&\n (scalarState.isId || scalarState.isUnique)\n ) {\n issues.push({\n code: \"I005\",\n message: `GeoPoint '${field}' in '${name}' cannot be an ID or unique field`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n }\n\n for (const field of getCompoundIdFields(model)) {\n if (!isPoint(field)) continue;\n issues.push({\n code: \"I005\",\n message: `GeoPoint '${field}' in '${name}' cannot be a compound ID member`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n for (const constraint of getCompoundUniques(model)) {\n for (const field of constraint.fields) {\n if (!isPoint(field)) continue;\n issues.push({\n code: \"I005\",\n message: `GeoPoint '${field}' in '${name}' cannot be a member of unique '${constraint.name}'`,\n severity: \"error\",\n model: name,\n field,\n });\n }\n }\n\n for (const index of state.indexes) {\n const pointFields = index.fields.filter(isPoint);\n const point =\n pointFields.length === 1\n ? state.scalars[pointFields[0]!]?.[\"~\"].state\n : undefined;\n const valid =\n index.fields.length === 1 &&\n pointFields.length === 1 &&\n point?.nullable === false &&\n index.options.type === \"spatial\" &&\n index.options.unique === undefined &&\n index.options.where === undefined;\n if (valid) continue;\n if (pointFields.length === 0 && index.options.type !== \"spatial\") continue;\n const field = pointFields[0] ?? index.fields[0];\n issues.push({\n code: \"I005\",\n message: `A spatial index in '${name}' must contain exactly one non-null GeoPoint and cannot be unique or partial`,\n severity: \"error\",\n model: name,\n ...(field ? { field } : {}),\n });\n }\n\n return issues;\n}\n\nexport const modelRules = [\n // Model-level checks (don't iterate fields)\n modelHasFields,\n modelNameValid,\n modelNameNotReserved,\n modelMappedNameValid,\n // Single-pass field validation (M001, F001-F008)\n validateFieldsSinglePass,\n // Index checks (iterate indexes, not fields)\n indexFieldsExist,\n indexNameUnique,\n // Compound key checks\n compoundConstraintsNonEmpty,\n publicSelectorNamesAreUnambiguous,\n memberNamesAreNotReserved,\n decimalListsAreNotKeyMembers,\n geoPointRolesArePortable,\n];\n","// Advisory cross-model relation rules.\n//\n// Every structural relation invariant — pairing, ownership, uniqueness, modifier\n// placement, physical junction naming — belongs to the mandatory\n// relation-definition gate (`../relation-resolution`). What survives here is\n// advice about how a schema is SPELLED, which the gate has no opinion about:\n// scalars that look like foreign keys but are not, a required insert cycle, and\n// the hand-rolled `*_type` + `*_id` pattern a variant carrier replaces.\n\nimport type { Model } from \"../../model\";\nimport type { Schema, SchemaValidationIssue } from \"../types\";\nimport { getCompoundIdFields, getCompoundUniques } from \"./model\";\nimport { getRelationValues, getScalars } from \"./model-members\";\n\n/** CM001: FK fields should have corresponding relation (warning) */\nexport function noOrphanFkFields(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n const fkFields = new Set<string>();\n for (const rel of getRelationValues(model)) {\n for (const field of rel[\"~\"].state.foreignKey?.fields ?? []) {\n fkFields.add(field);\n }\n }\n // Compound key members (e.g. orgId in .id([\"orgId\", \"memberId\"])) are\n // legitimate non-relation fields\n const compoundFields = new Set(getCompoundIdFields(model));\n for (const cu of getCompoundUniques(model)) {\n for (const f of cu.fields) compoundFields.add(f);\n }\n for (const [fname, scalar] of getScalars(model)) {\n // Heuristic: scalar key ending in \"Id\" might be FK\n if (\n fname.endsWith(\"Id\") &&\n !fkFields.has(fname) &&\n !compoundFields.has(fname) &&\n !scalar[\"~\"].state.isId\n ) {\n errors.push({\n code: \"CM001\",\n message: `'${fname}' in '${name}' looks like FK but no relation uses it`,\n severity: \"warning\",\n model: name,\n field: fname,\n });\n }\n }\n return errors;\n}\n\n/**\n * CM004: the hand-rolled polymorphic pattern.\n *\n * A `*_type` + `*_id` scalar pair with no relation using the id column is the\n * shape `s.toOne({ ... })` owns natively, with a real discriminator, exact\n * result types and validated targets.\n */\nconst POLYMORPHIC_TYPE_REGEX = /_type$|Type$/;\nexport function polymorphicRelationWarning(\n _s: Schema,\n name: string,\n model: Model<any>\n): SchemaValidationIssue[] {\n const errors: SchemaValidationIssue[] = [];\n const fieldNames = Object.keys(model[\"~\"].state.scalars);\n\n for (const fname of fieldNames) {\n if (!(fname.endsWith(\"_type\") || fname.endsWith(\"Type\"))) continue;\n\n // Extract base name: \"commentable_type\" -> \"commentable\"\n const base = fname.replace(POLYMORPHIC_TYPE_REGEX, \"\");\n const idField = fieldNames.find(\n (f) => f === `${base}_id` || f === `${base}Id`\n );\n\n if (!idField) continue;\n const hasRelation = getRelationValues(model).some((relation) =>\n relation[\"~\"].state.foreignKey?.fields.includes(idField)\n );\n if (hasRelation) continue;\n errors.push({\n code: \"CM004\",\n message: `'${fname}' + '${idField}' in '${name}' looks like polymorphic pattern (not type-safe)`,\n severity: \"warning\",\n model: name,\n field: fname,\n });\n }\n return errors;\n}\n\nexport const relationRules = [noOrphanFkFields, polymorphicRelationWarning];\n","// Advisory validation rules.\n//\n// Structural relation topology is not here: the mandatory gate\n// (`../relation-resolution`) owns it and runs at every effect-capable boundary,\n// including the ones that skip this list.\n\nexport * from \"./model\";\nexport * from \"./relation\";\n\nimport type { ValidationRule } from \"../types\";\nimport { modelRules } from \"./model\";\nimport { relationRules } from \"./relation\";\n\nexport const allRules: ValidationRule[] = [...modelRules, ...relationRules];\n","// Schema Validator\n//\n// TWO layers, one boundary. The mandatory relation-definition gate\n// (`./relation-resolution`) decides every structural topology fact and runs at\n// every effect-capable boundary; the rule list beside it carries advice about\n// how a schema is spelled. `skipValidation` may drop the advice. It cannot drop\n// the gate: no query or migration is allowed to guess an edge.\n\nimport type { Model } from \"../model\";\nimport { preflightModelRegistrationIdentity } from \"../registration-preflight\";\nimport { SchemaValidationError } from \"./error\";\nimport {\n type RelationResolution,\n type ResolvedRelationIndex,\n resolveSchemaRelations,\n} from \"./relation-resolution\";\nimport { allRules } from \"./rules\";\nimport {\n memberNamesAreNotReserved,\n publicSelectorNamesAreUnambiguous,\n} from \"./rules/model\";\nimport type {\n Schema,\n SchemaValidationIssue,\n ValidationContext,\n ValidationResult,\n ValidationRule,\n} from \"./types\";\n\n/** Build context once, use everywhere */\nfunction buildContext(schema: Schema): ValidationContext {\n const modelToName = new Map<Model<any>, string>();\n const tableToModels = new Map<string, string[]>();\n\n for (const [name, model] of schema) {\n modelToName.set(model, name);\n const tableName = model[\"~\"].state.tableName ?? name;\n if (!tableToModels.has(tableName)) {\n tableToModels.set(tableName, []);\n }\n tableToModels.get(tableName)!.push(name);\n }\n\n return { modelToName, tableToModels };\n}\n\n/**\n * The public validator: every advisory rule unless told otherwise. Client\n * construction does not use it; {@link resolveSchemaOrThrow} runs only the\n * selector rules, so a client bundle does not carry the advisory ones.\n */\nexport class SchemaValidator {\n readonly #schema: Schema = new Map();\n /** One resolution per validator lifecycle: the gate runs once per schema. */\n #resolution: RelationResolution | undefined;\n\n /** Register a model with a name */\n register(name: string, model: Model<any>): this {\n const registered = this.#schema.get(name);\n if (registered) {\n if (registered === model) {\n this.#resolution = undefined;\n return this;\n }\n throw validationError([\n {\n code: \"M003\",\n message: `Model name '${name}' is duplicated`,\n severity: \"error\",\n model: name,\n },\n ]);\n }\n this.#schema.set(name, model);\n this.#resolution = undefined;\n return this;\n }\n\n /** Register multiple models */\n registerAll(models: Record<string, Model<any>>): this {\n for (const [name, model] of Object.entries(models)) {\n this.register(name, model);\n }\n return this;\n }\n\n /**\n * Resolve the relation graph. The successful arm is the one trusted topology\n * view; the failure arm carries the issues and, for a thrown lazy getter, the\n * terminal's own settled `Error`.\n */\n resolve(): RelationResolution {\n this.#resolution ??= resolveRegistered(\n this.#schema,\n buildContext(this.#schema)\n );\n return this.#resolution;\n }\n\n /** Validate all registered models */\n validate(rules: ValidationRule[] = allRules): ValidationResult {\n const errors: SchemaValidationIssue[] = [];\n const warnings: SchemaValidationIssue[] = [];\n for (const issue of schemaIssues(\n this.#schema,\n buildContext(this.#schema),\n this.resolve(),\n rules\n )) {\n (issue.severity === \"error\" ? errors : warnings).push(issue);\n }\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n\n /**\n * Validate and throw if invalid; a valid schema publishes the one trusted\n * topology. `validate` already reports every resolution issue by severity,\n * so validity and a successful resolution are one fact stated here once.\n */\n validateOrThrow(rules: ValidationRule[] = allRules): ResolvedRelationIndex {\n const result = this.validate(rules);\n const resolution = this.resolve();\n if (result.valid && resolution.ok) return resolution.index;\n throw validationError(\n result.errors,\n resolution.ok ? undefined : resolution.cause\n );\n }\n}\n\n/** The identity preflight, then the relation gate. */\nfunction resolveRegistered(\n schema: Schema,\n ctx: ValidationContext\n): RelationResolution {\n const identityIssue = preflightModelRegistrationIdentity(schema);\n return identityIssue\n ? { ok: false, issues: [identityIssue] }\n : resolveSchemaRelations(schema, ctx);\n}\n\n/**\n * Every issue a schema carries, in report order: shared tables, then the gate's\n * own issues — it reports on every schema, valid or not, since a successful\n * resolution still carries the advisories its subowners produced — then every\n * rule on every model. A throwing rule is S001.\n */\nfunction schemaIssues(\n schema: Schema,\n ctx: ValidationContext,\n resolution: RelationResolution,\n rules: readonly ValidationRule[]\n): SchemaValidationIssue[] {\n const issues: SchemaValidationIssue[] = [];\n for (const [tableName, models] of ctx.tableToModels) {\n if (models.length > 1) issues.push(sharedTableIssue(tableName, models));\n }\n for (const issue of resolution.issues) issues.push(issue);\n for (const [modelName, model] of schema) {\n for (const rule of rules) {\n let results: SchemaValidationIssue[];\n try {\n results = rule(schema, modelName, model, ctx);\n } catch (cause) {\n throw ruleFailure(rule, modelName, cause);\n }\n for (const result of results) issues.push(result);\n }\n }\n return issues;\n}\n\n/** Validate a schema object directly */\nexport function validateSchema(\n models: Record<string, Model<any>>\n): ValidationResult {\n return new SchemaValidator().registerAll(models).validate();\n}\n\n/**\n * Validate or throw — the structural gate plus the advisory rules, resolved\n * exactly once. The resolved index is an internal execution capability, not a\n * public validation result.\n */\nexport function validateSchemaOrThrow(\n models: Record<string, Model<any>>\n): void {\n validateResolvedSchemaOrThrow(models, allRules);\n}\n\n/** Internal validation boundary that also publishes the trusted topology. */\nexport function validateResolvedSchemaOrThrow(\n models: Record<string, Model<any>>,\n rules: ValidationRule[]\n): ResolvedRelationIndex {\n return new SchemaValidator().registerAll(models).validateOrThrow(rules);\n}\n\n/**\n * The rules every effect-capable boundary runs beside the relation gate: each\n * gives one admitted selector one meaning — a compound selector never reuses a\n * member name (I006), and no member takes an output key a selection\n * reserves, `_count` or `_distance` (F010).\n */\nconst SELECTOR_RULES: ValidationRule[] = [\n publicSelectorNamesAreUnambiguous,\n memberNamesAreNotReserved,\n];\n\n/**\n * The mandatory structural gate, for every boundary that can produce effects:\n * client construction, standalone registry construction, and migration\n * serialization/generation/push — including `push({ skipValidation: true })`,\n * which may skip advice but never this.\n *\n * It validates the definition contracts every query client relies on: the\n * relation gate plus the schema-wide model-identity checks a client needs to\n * address a model at all (one schema key per model object, no shared table)\n * and the selector rules, resolved exactly once. Advisory rules about how a\n * schema is spelled — a missing id, a reserved model name, an index shape —\n * remain at the boundary that writes DDL. Public selector ambiguity is\n * structural: every client operation relies on one stable meaning for each\n * admitted selector. Only errors are collected: no caller of this gate reads\n * an advisory.\n *\n * Returns the one trusted index. The caller owns it for its own lifecycle and\n * passes it on by identity rather than copying it.\n */\nexport function resolveSchemaOrThrow(\n models: Record<string, Model<any>>\n): ResolvedRelationIndex {\n // `Object.entries` keys are unique, so no name can be registered twice.\n const schema: Schema = new Map(Object.entries(models));\n const ctx = buildContext(schema);\n const resolution = resolveRegistered(schema, ctx);\n const errors = schemaIssues(schema, ctx, resolution, SELECTOR_RULES).filter(\n (issue) => issue.severity === \"error\"\n );\n if (errors.length === 0 && resolution.ok) return resolution.index;\n throw validationError(errors, resolution.ok ? undefined : resolution.cause);\n}\n\n/**\n * The client gate for a schema `viborm check` already validated: relation\n * resolution only, because the engine needs its topology. The identity,\n * table-name, selector-name and cycle checks are the check command's.\n */\nexport function resolveCheckedSchemaOrThrow(\n models: Record<string, Model<any>>\n): ResolvedRelationIndex {\n const schema: Schema = new Map(Object.entries(models));\n const resolution = resolveSchemaRelations(schema, buildContext(schema), true);\n if (resolution.ok) return resolution.index;\n throw validationError(\n resolution.issues.filter((issue) => issue.severity === \"error\"),\n resolution.cause\n );\n}\n\n/** One construction path for every thrown schema-validation result. */\nfunction validationError(\n issues: readonly SchemaValidationIssue[],\n cause?: Error\n): SchemaValidationError {\n return new SchemaValidationError(issues, cause ? { cause } : undefined);\n}\n\n/** M004, built only when two models share a table. */\nfunction sharedTableIssue(\n tableName: string,\n models: readonly string[]\n): SchemaValidationIssue {\n return {\n code: \"M004\",\n message: `Table name '${tableName}' used by multiple models: ${models.join(\", \")}`,\n severity: \"error\",\n };\n}\n\n/** A rule that threw, reported as the schema error it is. */\nfunction ruleFailure(\n rule: ValidationRule,\n modelName: string,\n cause: unknown\n): SchemaValidationError {\n const message = cause instanceof Error ? cause.message : String(cause);\n return new SchemaValidationError(\n [\n {\n code: \"S001\",\n message: `Schema rule '${rule.name || \"anonymous\"}' failed for '${modelName}': ${message}`,\n severity: \"error\",\n model: modelName,\n },\n ],\n cause instanceof Error ? { cause } : undefined\n );\n}\n"],"mappings":"sWAuEA,MAAM,EAAe,IAAI,QAEzB,SAAgB,mBAAmB,EAAoC,CACrE,IAAM,EAAS,EAAa,IAAI,EAAM,CACtC,GAAI,EACF,OAAO,EAET,IAAM,EAAU,qBAAqB,EAAM,CAE3C,OADA,EAAa,IAAI,EAAO,EAAQ,CACzB,EAUT,SAAgB,mBACd,EACA,EAC6B,CAC7B,IAAK,IAAM,KAAO,mBAAmB,EAAM,CAAC,gBAE1C,IADiB,EAAI,MAAQ,EAAI,OAAO,MACvB,EACf,OAAO,EAMb,MAAM,EAAuB,CAAC,MAAO,KAAM,MAAM,CAUjD,SAAgB,gCACd,EACmB,CACnB,IAAM,EAAQ,EAAM,KAAK,MACnB,EAAW,IAAI,IAAY,CAC/B,GAAG,OAAO,KAAK,EAAM,MAAM,CAC3B,GAAG,EACJ,CAAC,CACI,EAAY,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