@rebasepro/server 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
- package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
- package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
- package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
- package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
- package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
- package/dist/api/errors.d.ts +4 -0
- package/dist/api/rest/api-generator.d.ts +8 -0
- package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
- package/dist/auth-Bfwjg4Bg.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +10 -0
- package/dist/backend/services.d.ts +9 -0
- package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
- package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
- package/dist/boot/bundle.d.ts +11 -1
- package/dist/boot/env.d.ts +5 -0
- package/dist/boot/security-headers.d.ts +15 -5
- package/dist/boot/static-routing.d.ts +58 -0
- package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
- package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
- package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
- package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
- package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
- package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
- package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
- package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
- package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
- package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
- package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
- package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
- package/dist/dist-C1vNURUy.js +19354 -0
- package/dist/dist-C1vNURUy.js.map +1 -0
- package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
- package/dist/errors-NVbAQU25.js.map +1 -0
- package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
- package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
- package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
- package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
- package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
- package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
- package/dist/functions/index.d.ts +2 -0
- package/dist/functions/index.js +162 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/rate-limit.d.ts +71 -0
- package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
- package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
- package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
- package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.es.js +1241 -213
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
- package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
- package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
- package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
- package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
- package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
- package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
- package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
- package/dist/{load-schema-Cv5XLVjW.js → load-schema-CSEXeduP.js} +36 -5
- package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-CSEXeduP.js.map} +1 -1
- package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
- package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
- package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
- package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
- package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
- package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
- package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
- package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
- package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
- package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
- package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
- package/dist/push/push-options.d.ts +26 -0
- package/dist/push/push-routes.d.ts +30 -0
- package/dist/push/push-service.d.ts +13 -0
- package/dist/push/push-store.d.ts +45 -0
- package/dist/push/set-up.d.ts +25 -0
- package/dist/push/subscription-input.d.ts +26 -0
- package/dist/push/vapid-config.d.ts +35 -0
- package/dist/push/web-push-crypto.d.ts +44 -0
- package/dist/push/web-push-sender.d.ts +10 -0
- package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
- package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
- package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
- package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
- package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
- package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
- package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-BxN0Q85n.js} +5 -5
- package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-BxN0Q85n.js.map} +1 -1
- package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
- package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
- package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
- package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
- package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
- package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
- package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
- package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
- package/dist/serve-spa.d.ts +12 -0
- package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
- package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
- package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
- package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
- package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
- package/dist/src-CNZB3fuE.js.map +1 -0
- package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-DCJgZEz9.js} +3 -3
- package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-DCJgZEz9.js.map} +1 -1
- package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
- package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-BOz84vIr.js.map +0 -1
- package/dist/dist-fBcYxf4h.js +0 -19354
- package/dist/dist-fBcYxf4h.js.map +0 -1
- package/dist/errors-DpTMfX77.js.map +0 -1
- package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
- package/dist/src-DLIb1O9l.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-schema-Cv5XLVjW.js","names":[],"sources":["../../common/src/collections/soft-delete.ts","../../common/src/schema/errors.ts","../../common/src/schema/derive-names.ts","../../common/src/schema/resolve-rls.ts","../../common/src/schema/custom-sql-type.ts","../../common/src/schema/validate-tables.ts","../../common/src/schema/compile-tables.ts","../../common/src/schema/compile-schema.ts","../src/schema/load-schema.ts"],"sourcesContent":["/** The field `softDelete: true` means, when the object form names none. */\nexport const DEFAULT_SOFT_DELETE_FIELD = \"deletedAt\";\n","/**\n * What is wrong with one table definition.\n *\n * @group Schema\n */\nexport interface SchemaDefinitionProblem {\n /** The table (or view) the problem is in, by the name it was defined under. */\n table: string;\n /** The column or relation key, when the problem is about one. */\n key?: string;\n /** What is wrong and what to write instead. */\n message: string;\n}\n\n/**\n * A schema that cannot be compiled.\n *\n * Thrown by every door that reads `backend/schema` — `rebase db generate`,\n * `db push`, the doctor and server boot — so a definition that would leave a\n * table unprotected or unservable stops all of them the same way. Carries every\n * problem found, not only the first.\n *\n * @group Schema\n */\nexport class SchemaDefinitionError extends Error {\n\n readonly code = \"SCHEMA_DEFINITION_INVALID\";\n\n constructor(\n /** Every problem found, in declaration order. */\n readonly problems: readonly SchemaDefinitionProblem[]\n ) {\n super(SchemaDefinitionError.describe(problems));\n this.name = \"SchemaDefinitionError\";\n }\n\n private static describe(problems: readonly SchemaDefinitionProblem[]): string {\n const lines = problems.map(problem => {\n const where = problem.key ? `${problem.table}.${problem.key}` : problem.table;\n return ` - ${where}: ${problem.message}`;\n });\n const count = problems.length === 1 ? \"1 problem\" : `${problems.length} problems`;\n return `The schema cannot be used (${count}):\\n${lines.join(\"\\n\")}`;\n }\n}\n\n/**\n * Whether an error is a {@link SchemaDefinitionError}, from this copy of the\n * package or another.\n *\n * @group Schema\n */\nexport function isSchemaDefinitionError(error: unknown): error is SchemaDefinitionError {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"SCHEMA_DEFINITION_INVALID\";\n}\n","import type { ColumnDef, ColumnType, JoinStep } from \"@rebasepro/types\";\nimport { generateForeignKeyName, toSnakeCase, toWireKey } from \"@rebasepro/utils\";\n\n/**\n * Every name the schema compiler derives, in one place.\n *\n * Each rule here is the rule today's collection pipeline applies — a deployed\n * database must not see one identifier move when its collections become\n * `defineTable`s. Where the legacy rule lives in a helper that takes a\n * `CollectionConfig` (`resolveRelation`, `getTableName`), it is mirrored here\n * over plain inputs, and `test/schema/compile-names.test.ts` feeds both the\n * same tables and compares.\n */\n\n/** The Postgres schema a table lives in when it names none. */\nexport const DEFAULT_TABLE_SCHEMA = \"public\";\n\n/** The schema a junction table is always created in, whatever its endpoints declare. */\nexport const JUNCTION_TABLE_SCHEMA = \"public\";\n\n/**\n * The SQL table of a `defineTable(name, …)`: `table` when given, else the name\n * it was defined under.\n *\n * @group Schema\n */\nexport function deriveTableName(name: string, table: string | undefined): string {\n return table ?? name;\n}\n\n/**\n * The API slug of a `defineTable(name, …)`: `slug` when given, else the name.\n *\n * @group Schema\n */\nexport function deriveSlug(name: string, slug: string | undefined): string {\n return slug ?? name;\n}\n\n/**\n * The Postgres schema of a table: `schema` when given, else `public`.\n *\n * @group Schema\n */\nexport function deriveSchemaName(schema: string | undefined): string {\n return schema ?? DEFAULT_TABLE_SCHEMA;\n}\n\n/**\n * The SQL column of a `columns` entry: `.column(name)` when given, else the\n * snake_case of its key.\n *\n * `toSnakeCase` tokenises on case boundaries and drops every separator, so\n * `__order` becomes `order` and `photoURL` becomes `photo_url` — exactly the\n * column today's planner gives the same property.\n *\n * @group Schema\n */\nexport function deriveColumnName(key: string, def: Pick<ColumnDef, \"column\">): string {\n return def.column ?? toSnakeCase(key);\n}\n\n/**\n * The foreign-key column of a `belongsTo`: `localKey` when given, else\n * `<singular relation name>_id`.\n *\n * @group Schema\n */\nexport function deriveBelongsToLocalKey(relationName: string, localKey: string | undefined): string {\n return localKey ?? generateForeignKeyName(relationName);\n}\n\n/**\n * The row key a derived foreign-key column is served under: the camelCase of\n * its column (`author_id` → `authorId`).\n *\n * @group Schema\n */\nexport function deriveForeignKeyField(localKey: string): string {\n return toWireKey(localKey);\n}\n\n/**\n * The column on the target of a `hasOne` / `hasMany` that points back:\n * `foreignKey` when given, else `<singular source slug>_id`.\n *\n * @group Schema\n */\nexport function deriveTargetForeignKey(sourceSlug: string, foreignKey: string | undefined): string {\n return foreignKey ?? generateForeignKeyName(toSnakeCase(sourceSlug));\n}\n\n/**\n * The junction table of a `manyToMany`: `through` when given, else the two\n * SQL table names sorted and joined by `_`, so both sides of one link derive\n * the same table without agreeing in advance.\n *\n * @group Schema\n */\nexport function deriveJunctionTable(sourceTable: string, targetTable: string, through: string | undefined): string {\n return through ?? [sourceTable, targetTable].sort().join(\"_\");\n}\n\n/**\n * The junction column pointing at the declaring table: `sourceKey` when given,\n * else `<singular source slug>_id`.\n *\n * @group Schema\n */\nexport function deriveJunctionSourceKey(sourceSlug: string, sourceKey: string | undefined): string {\n return sourceKey ?? generateForeignKeyName(toSnakeCase(sourceSlug));\n}\n\n/**\n * The junction column pointing at the target: `targetKey` when given, else\n * `<singular relation name>_id`.\n *\n * @group Schema\n */\nexport function deriveJunctionTargetKey(relationName: string, targetKey: string | undefined): string {\n return targetKey ?? generateForeignKeyName(relationName);\n}\n\n/**\n * The type a column pointing at a primary key must have: the key's own type,\n * except that a serial key's sequence is not copied — a column referencing a\n * `serial` is the plain `integer` of the same width.\n *\n * An enum key is referenced by its own enum type, so the referencing column\n * names the type the key's table created rather than deriving one of its own.\n *\n * @param keyTable The SQL table the key belongs to, which names an enum type\n * declared without an explicit `name`.\n * @param keyColumn The key's SQL column, for the same reason.\n *\n * @group Schema\n */\nexport function deriveReferencingType(keyType: ColumnType, keyTable: string, keyColumn: string): ColumnType {\n switch (keyType.kind) {\n case \"smallserial\": return { kind: \"smallint\" };\n case \"serial\": return { kind: \"integer\" };\n case \"bigserial\": return { kind: \"bigint\" };\n case \"enum\": return { kind: \"enum\", values: [...keyType.values], name: keyType.name ?? `${keyTable}_${keyColumn}` };\n default: return keyType;\n }\n}\n\n/**\n * The name of the Postgres enum type an enum column uses: its explicit `name`,\n * else `<table>_<column>`.\n *\n * @group Schema\n */\nexport function deriveEnumTypeName(type: Extract<ColumnType, { kind: \"enum\" }>, table: string, column: string): string {\n return type.name ?? `${table}_${column}`;\n}\n\n/**\n * Whether a `via` chain can be written through: a to-one chain of one step, or\n * a to-many chain of two steps through one table between the ends — and every\n * step joins on one condition.\n *\n * The same answer `resolveRelation` gives a legacy `via` relation.\n *\n * @group Schema\n */\nexport function deriveViaWritable(cardinality: \"one\" | \"many\", steps: readonly Pick<JoinStep, \"table\" | \"on\">[]): boolean {\n if (steps.some(step => Array.isArray(step.on) && step.on.length !== 1)) return false;\n if (cardinality === \"one\") return steps.length === 1;\n return steps.length === 2 && steps[0].table !== steps[1].table;\n}\n","import type { DefaultRls, RlsDescriptor, RlsPosture, SecurityRule } from \"@rebasepro/types\";\n\n/**\n * What {@link resolveRls} returns: the resolved posture, or why there is none.\n *\n * @group Schema\n */\nexport type RlsResolution =\n | { ok: true; rls: RlsDescriptor }\n | { ok: false; message: string };\n\n/**\n * A table's `rls` (and `defaultPolicies`) resolved against the project's\n * `defaultRls`.\n *\n * - `\"admin-only\"` → `{ posture: \"admin-only\", rules: [], defaultPolicies: true }`.\n * - a list → `{ posture: \"rules\", rules, defaultPolicies }`, the rules exactly\n * as written: a policy's name is a hash of its rule, so a rule is never\n * reordered, copied key by key or normalized.\n * - `\"inherit\"` → the project's `defaultRls`, resolved the same way and marked\n * `inherited`.\n *\n * Refused, never defaulted: a missing or empty posture, `\"inherit\"` without a\n * `defaultRls`, and `\"admin-only\"` (written or inherited) beside\n * `defaultPolicies: false`, which would leave the table readable by nobody at\n * all — not even the admins it is locked to.\n *\n * @param posture What the table wrote. Typed `unknown` because a JavaScript\n * caller, or a cast, can hand over anything; every shape is checked here.\n *\n * @group Schema\n */\nexport function resolveRls(\n posture: RlsPosture | unknown,\n defaultPolicies: boolean | undefined,\n defaultRls: DefaultRls | undefined\n): RlsResolution {\n if (posture === \"inherit\") {\n if (defaultRls === undefined) {\n return {\n ok: false,\n message:\n \"`rls: \\\"inherit\\\"` takes the project's `defaultRls`, and none was given. Export \" +\n \"`defaultRls` from backend/schema/index.ts (`\\\"admin-only\\\"` or a list of rules), or write \" +\n \"this table's own `rls`.\"\n };\n }\n const inherited = resolveRls(defaultRls, defaultPolicies, undefined);\n if (!inherited.ok) {\n return { ok: false, message: `\\`rls: \"inherit\"\\` resolves to the project's \\`defaultRls\\`, which is unusable: ${inherited.message}` };\n }\n return { ok: true, rls: { ...inherited.rls, inherited: true } };\n }\n if (posture === \"admin-only\") {\n if (defaultPolicies === false) {\n return {\n ok: false,\n message:\n \"`rls: \\\"admin-only\\\"` with `defaultPolicies: false` grants nobody anything: \\\"admin-only\\\" \" +\n \"is exactly the injected admin baseline, and `defaultPolicies: false` removes it. Drop \" +\n \"`defaultPolicies: false`, or replace \\\"admin-only\\\" with the rules that should apply.\"\n };\n }\n return { ok: true, rls: { posture: \"admin-only\", rules: [], defaultPolicies: true, ...(defaultPolicies === true ? { declaredDefaultPolicies: true } : {}) } };\n }\n if (Array.isArray(posture)) {\n if (posture.length === 0) {\n return {\n ok: false,\n message:\n \"`rls: []` grants nothing and says nothing. Write `rls: \\\"admin-only\\\"` to lock the table \" +\n \"to admins, or list the rules that grant access.\"\n };\n }\n const rules: SecurityRule[] = [];\n for (const rule of posture) {\n if (typeof rule !== \"object\" || rule === null) {\n return { ok: false, message: \"every entry of `rls` must be a security rule object.\" };\n }\n if (\"redacted\" in rule) {\n return {\n ok: false,\n message:\n \"an entry of `rls` carries `redacted`, the marker `GET /api/schema/tables` serves in place of a \" +\n \"rule whose SQL it withheld. It describes a policy and cannot become one: write the rule itself.\"\n };\n }\n rules.push(rule);\n }\n return { ok: true, rls: { posture: \"rules\", rules, defaultPolicies: defaultPolicies !== false, ...(defaultPolicies === true ? { declaredDefaultPolicies: true } : {}) } };\n }\n return {\n ok: false,\n message:\n \"the table has no usable `rls`. Every table needs an explicit row-level security posture: \" +\n \"`\\\"admin-only\\\"`, `\\\"inherit\\\"` (the `defaultRls` exported from backend/schema/index.ts), or a \" +\n \"non-empty list of rules.\"\n };\n}\n\n// ── Rule shape ───────────────────────────────────────────────────────────────\n\n/** The clause keys of a rule whose combinations the `SecurityRule` union restricts. */\ntype RuleClauseKey = \"ownerField\" | \"access\" | \"using\" | \"withCheck\" | \"condition\" | \"check\";\n\n/**\n * Every pair of clauses the `SecurityRule` union excludes, read off its\n * variants' `never` fields:\n *\n * - `OwnerSecurityRule`: `ownerField` excludes `access`, `using`, `withCheck`,\n * `condition` and `check`;\n * - `PublicSecurityRule` / `AuthenticatedSecurityRule` /\n * `RegisteredSecurityRule` / `ConditionalAccessSecurityRule` /\n * `CheckedAccessSecurityRule`: `access` excludes `ownerField`, `using` and\n * `withCheck` (it combines with `condition` / `check`);\n * - `StructuredSecurityRule`: `condition` / `check` exclude `ownerField`,\n * `using` and `withCheck`;\n * - `RawSQLSecurityRule` / `RawSQLCheckOnlySecurityRule`: `using` /\n * `withCheck` exclude `ownerField`, `access`, `condition` and `check`.\n *\n * `roles`, `mode`, `pgRoles`, `name` and `operation(s)` combine with all of\n * them (`roles` is ANDed on).\n */\nconst EXCLUDED_PAIRS: readonly (readonly [RuleClauseKey, RuleClauseKey])[] = [\n [\"access\", \"ownerField\"],\n [\"access\", \"using\"],\n [\"access\", \"withCheck\"],\n [\"ownerField\", \"using\"],\n [\"ownerField\", \"withCheck\"],\n [\"ownerField\", \"condition\"],\n [\"ownerField\", \"check\"],\n [\"condition\", \"using\"],\n [\"condition\", \"withCheck\"],\n [\"check\", \"using\"],\n [\"check\", \"withCheck\"]\n];\n\nconst ACCESS_VALUES: readonly unknown[] = [\"public\", \"authenticated\", \"registered\"];\nconst MODE_VALUES: readonly unknown[] = [\"permissive\", \"restrictive\"];\nconst OPERATION_VALUES: readonly unknown[] = [\"select\", \"insert\", \"update\", \"delete\", \"all\"];\n\n/** Whether a rule carries a clause: present and not `null`/`undefined` (what the policy compiler tests). */\nfunction carries(rule: object, key: RuleClauseKey): boolean {\n const value: unknown = Reflect.get(rule, key);\n return value !== undefined && value !== null && value !== \"\";\n}\n\n/** The pairs of clauses a rule carries that the `SecurityRule` union excludes. */\nexport function excludedClausePairs(rule: object): (readonly [RuleClauseKey, RuleClauseKey])[] {\n return EXCLUDED_PAIRS.filter(([a, b]) => carries(rule, a) && carries(rule, b));\n}\n\n/** The remedy for one excluded pair: what to write instead. */\nfunction remedyFor(a: RuleClauseKey, b: RuleClauseKey): string {\n const pair = new Set([a, b]);\n if (pair.has(\"access\") && pair.has(\"ownerField\")) {\n return \"For rows the caller owns, write `{ ownerField }` alone. To grant the `access` callers the rows that \" +\n \"match a test, write `access` with a `condition` (`condition: policy.compare(policy.field(\\\"<column>\\\"), \\\"eq\\\", policy.authUid())` \" +\n \"is the owner test as a condition).\";\n }\n if (pair.has(\"access\")) {\n return \"Raw SQL carries no `access` gate: write `access` with a structured `condition` / `check`, or put the \" +\n \"caller test into the SQL (`rebase.uid()`), without `access`.\";\n }\n if (pair.has(\"ownerField\")) {\n return \"Write the owner test into the other clause (`policy.compare(policy.field(\\\"<column>\\\"), \\\"eq\\\", \" +\n \"policy.authUid())` in a `condition`, or `<column> = rebase.uid()` in raw SQL), or split it into two rules.\";\n }\n return \"Write the whole test in one form: a structured `condition` / `check`, or raw `using` / `withCheck`.\";\n}\n\n/**\n * What is wrong with one rule's shape, independent of the table's columns:\n * clauses the `SecurityRule` union excludes from each other (see\n * {@link excludedClausePairs}), and an `access`, `mode`, `operation`,\n * `operations` or `roles` value the type does not allow.\n *\n * Refused rather than resolved: the policy compiler used to pick one clause\n * of such a rule by the order of its checks, so `{ access: \"authenticated\",\n * ownerField }` compiled to \"every signed-in caller\" and dropped the owner\n * test, and a misspelt `mode: \"restricitve\"` compiled to a permissive policy.\n *\n * @param label How the message names the rule (`rule #2`, `rule \"owner_read\"`).\n *\n * @group Schema\n */\nexport function ruleShapeProblems(rule: object, label: string): string[] {\n const problems: string[] = [];\n for (const [a, b] of excludedClausePairs(rule)) {\n problems.push(`${label} combines \\`${a}\\` with \\`${b}\\`, which the SecurityRule type does not allow: a policy ` +\n `cannot honour both, and a policy that honours one widens the other. ${remedyFor(a, b)}`);\n }\n const access: unknown = Reflect.get(rule, \"access\");\n if (access !== undefined && !ACCESS_VALUES.includes(access)) {\n problems.push(`${label} has \\`access: ${JSON.stringify(access)}\\`. \\`access\\` is \"public\", \"authenticated\" ` +\n \"(any signed-in caller, guests included) or \\\"registered\\\" (a signed-in caller with an account).\");\n }\n const mode: unknown = Reflect.get(rule, \"mode\");\n if (mode !== undefined && !MODE_VALUES.includes(mode)) {\n problems.push(`${label} has \\`mode: ${JSON.stringify(mode)}\\`, which would compile as \"permissive\". ` +\n \"Write \\\"permissive\\\" (the default: any passing rule grants) or \\\"restrictive\\\" (every one must pass).\");\n }\n const operation: unknown = Reflect.get(rule, \"operation\");\n if (operation !== undefined && !OPERATION_VALUES.includes(operation)) {\n problems.push(`${label} has \\`operation: ${JSON.stringify(operation)}\\`. Write one of \"select\", \"insert\", ` +\n \"\\\"update\\\", \\\"delete\\\" or \\\"all\\\".\");\n }\n const operations: unknown = Reflect.get(rule, \"operations\");\n if (operations !== undefined && (!Array.isArray(operations) || operations.some(op => !OPERATION_VALUES.includes(op)))) {\n problems.push(`${label} has \\`operations: ${JSON.stringify(operations)}\\`. Write a list of \"select\", ` +\n \"\\\"insert\\\", \\\"update\\\", \\\"delete\\\" and \\\"all\\\".\");\n }\n const roles: unknown = Reflect.get(rule, \"roles\");\n if (roles !== undefined && (!Array.isArray(roles) || roles.some(role => typeof role !== \"string\"))) {\n problems.push(`${label} has \\`roles: ${JSON.stringify(roles)}\\`. \\`roles\\` is a list of application role ` +\n \"names, such as `[\\\"editor\\\"]`.\");\n }\n return problems;\n}\n\n/**\n * What a legacy rule's clause compiled to before tables replaced collections,\n * when the policy compiler resolved the first match of `condition`, `using`,\n * `access: \"public\"`, `ownerField` and ignored the rest (`access:\n * \"authenticated\"` was no value it knew).\n */\nfunction legacyClauseMeaning(rule: object, clause: \"using\" | \"withCheck\"): string {\n if (clause === \"withCheck\") {\n if (carries(rule, \"check\")) return \"its structured `check`\";\n if (carries(rule, \"withCheck\")) return \"its raw `withCheck` SQL\";\n }\n if (carries(rule, \"condition\")) return \"its structured `condition`\";\n if (carries(rule, \"using\")) return \"its raw `using` SQL\";\n if (Reflect.get(rule, \"access\") === \"public\") return \"every caller (`access: \\\"public\\\"`)\";\n if (carries(rule, \"ownerField\")) return `owner-only rows (\\`${String(Reflect.get(rule, \"ownerField\"))} = rebase.uid()\\`)`;\n return \"nothing (a policy that grants no row)\";\n}\n\n/**\n * Why a legacy collection rule cannot be carried to a table as written, or\n * `undefined` when it can. What `rebase migrate collections-to-tables`\n * refuses so that a migration never resolves a rule to a different clause\n * than it compiled to: every combination {@link ruleShapeProblems} refuses,\n * with what the rule meant on the previous version (whichever clause its\n * compiler checked first) and what to write to keep that.\n *\n * @group Schema\n */\nexport function legacyRuleRefusal(rule: object, label: string): string | undefined {\n const shape = ruleShapeProblems(rule, label);\n if (shape.length === 0) return undefined;\n const using = legacyClauseMeaning(rule, \"using\");\n const withCheck = legacyClauseMeaning(rule, \"withCheck\");\n const meant = using === withCheck\n ? `On the previous version this rule granted ${using}.`\n : `On the previous version this rule's USING granted ${using} and its WITH CHECK ${withCheck}.`;\n return `${shape.join(\" \")} ${meant} Write that clause alone — \\`{ ownerField }\\` for owner-only rows, or ` +\n \"`access` with a `condition` to grant those callers the rows that match it — and migrate again.\";\n}\n\n/** The operations a legacy rule applies to — `operations` wins over `operation`, `\"all\"` by default. */\nfunction legacyOperations(rule: object): string[] {\n const operations: unknown = Reflect.get(rule, \"operations\");\n if (Array.isArray(operations) && operations.length > 0) return operations.filter((op): op is string => typeof op === \"string\");\n const operation: unknown = Reflect.get(rule, \"operation\");\n return [typeof operation === \"string\" ? operation : \"all\"];\n}\n\n/**\n * The roles a caller who is not signed in holds: an anonymous request carries\n * `anon`, and a rule naming `public` matches every caller.\n */\nconst ROLES_WITHOUT_SIGN_IN = [\"anon\", \"public\"];\n\n/**\n * How a legacy rule that is carried as written compiles to a different\n * policy than it did on the previous version, or `undefined` when it does not.\n *\n * The previous compiler read `condition`, else `using`, else `access:\n * \"public\"`, else `ownerField` for USING (`check`, else `withCheck`, else the\n * same for WITH CHECK), ANDed `roles` on (a restrictive rule: `NOT roles OR\n * clause`, or `NOT roles` alone), and knew no other `access` value. The\n * current one ANDs `access: \"authenticated\"` / `\"registered\"` onto every\n * clause, or makes it the clause when there is none. `\"public\"` meant `true`\n * on both. So, for a rule {@link legacyRuleRefusal} accepts with a gating\n * `access` (which excludes `ownerField` and raw SQL), each policy clause the\n * rule's operations need is either:\n *\n * - **a clause it had** (`condition`, or `check` for WITH CHECK): `X` became\n * `access AND X` — a narrowing, felt by whoever passes `X` without passing\n * `access`. With `roles`, only a role holder who fails `access` feels it: a\n * guest under `\"registered\"`, or a caller not signed in holding `anon` /\n * `public`; under `\"authenticated\"` with any other role, nobody;\n * - **no clause**: the previous policy had none — it granted nothing, or, for\n * a restrictive rule, denied every caller it applied to — and now has\n * `access`: a widening (permissive or restrictive, with or without\n * `roles`), except a permissive role grant (`roles` alone admitted the\n * holders), which only narrows as above.\n *\n * The verdict is per clause and the first change found is described,\n * widenings first. A policy's name never moves with this: it is a hash of the\n * rule as written. `test/schema/legacy-rule-meaning-sweep.test.ts` checks this\n * against the previous compiler over every combination of clauses.\n *\n * @group Schema\n */\nexport function legacyRuleMeaningChange(rule: object): string | undefined {\n const access: unknown = Reflect.get(rule, \"access\");\n // The previous compiler knew `\"public\"` (USING `true`, as now): every\n // shape it is accepted in compiles as it did.\n if (access === undefined || access === \"public\") return undefined;\n const rolesValue: unknown = Reflect.get(rule, \"roles\");\n const roles = Array.isArray(rolesValue) ? rolesValue.filter((role): role is string => typeof role === \"string\") : [];\n const hasRoles = roles.length > 0;\n const restrictive = Reflect.get(rule, \"mode\") === \"restrictive\";\n const hasCondition = carries(rule, \"condition\");\n const hasCheck = carries(rule, \"check\");\n const operations = legacyOperations(rule);\n const needsUsing = operations.some(op => op !== \"insert\");\n const needsWithCheck = operations.some(op => op !== \"select\" && op !== \"delete\");\n\n const accessText = `\\`access: ${JSON.stringify(access)}\\``;\n const signedIn = access === \"registered\"\n ? \"every signed-in caller with an account (guests excluded)\"\n : \"every signed-in caller, guests included\";\n const roleList = roles.map(role => JSON.stringify(role)).join(\", \");\n /** A holder of the roles who fails `access`: a guest under \"registered\", or a caller not signed in. */\n const holderMayFail = access === \"registered\" || roles.some(role => ROLES_WITHOUT_SIGN_IN.includes(role));\n const failingHolders = access === \"registered\"\n ? (roles.some(role => ROLES_WITHOUT_SIGN_IN.includes(role)) ? \"guests and callers who are not signed in\" : \"guests (anonymous sign-ins)\")\n : \"callers who are not signed in\";\n\n /** A holder of the roles who passes `access`: anyone holding a role a signed-in caller can hold. */\n const holderMayPass = roles.some(role => role !== \"anon\");\n\n // Per clause the operations need: whether the rule had one there, and so\n // whether `access` widened it (no clause before) or narrowed it.\n const clauses = [\n ...(needsUsing ? [hasCondition] : []),\n ...(needsWithCheck ? [hasCheck || hasCondition] : [])\n ].map(had => ({\n had,\n widens: !had && (hasRoles ? restrictive && holderMayPass : true),\n narrows: hasRoles ? holderMayFail && (had || !restrictive) : had\n }));\n\n // Widenings first: a clause the previous policy did not have.\n if (clauses.some(({ widens }) => widens)) {\n if (restrictive && hasRoles) {\n return `This restrictive rule gates the holders of ${roleList}. The previous version did not know ` +\n `${accessText}, so it denied them every row. Carried as written it now lets ${signedIn} among them ` +\n \"through. To keep denying them, drop `access` (a restrictive `{ roles }` rule alone denies its role holders).\";\n }\n if (restrictive) {\n return `${accessText} was not a value the previous version knew, so this restrictive rule passed nobody: it ` +\n `denied every caller. Carried as written it now lets ${signedIn} through. To keep denying everyone, write ` +\n \"the restriction as `condition: policy.false()`; to restrict to callers with an account, write `access: \\\"registered\\\"`.\";\n }\n if (hasCheck && !hasCondition) {\n return `This rule has a \\`check\\` and no \\`condition\\`: on the previous version it had no USING clause and ` +\n `granted no existing row for ${operations.join(\"/\")}. It now grants ${signedIn} every existing row. To ` +\n \"keep granting no existing row, make the rule `operation: \\\"insert\\\"`; to grant some, add a `condition`.\";\n }\n return `${accessText} was not a value the previous version knew, so this rule granted nothing. Carried as ` +\n `written it now admits ${signedIn}. To keep granting only callers with an account, write ` +\n \"`access: \\\"registered\\\"`; to keep granting nothing, remove the rule.\";\n }\n\n // Narrowings: `access` now ANDed onto what was there (or onto `roles`).\n if (!clauses.some(({ narrows }) => narrows)) return undefined;\n if (hasRoles && clauses.every(({ had }) => !had)) {\n return `${accessText} was not a value the previous version knew, so this rule admitted every holder of ` +\n `${roleList}. It now also requires ${signedIn}, so ${failingHolders} holding them are refused. To keep the ` +\n \"old meaning, drop `access`.\";\n }\n if (hasRoles) {\n return `${accessText} was ignored by the previous version, so this rule's clauses admitted every holder of ` +\n `${roleList} they matched. It now also requires ${signedIn}, so ${failingHolders} holding them are refused. ` +\n \"To keep the old meaning, drop `access`.\";\n }\n if (hasCondition) {\n return `${accessText} was ignored by the previous version, so this rule's \\`condition\\` admitted any caller, ` +\n `signed in or not. It now admits only ${signedIn} to the rows it matches. To keep the old meaning, write ` +\n \"`access: \\\"public\\\"` with the same condition.\";\n }\n return `${accessText} was ignored by the previous version, so any caller could insert a row matching this rule's ` +\n `\\`check\\`. It now admits only ${signedIn}. To keep the old meaning, write \\`access: \"public\"\\`.`;\n}\n","/**\n * What a `col.custom()` type may be: the shape of a Postgres type name, which\n * DDL writes verbatim. Shared by the compiler (`checkColumnDef`) and the\n * planner, which refuses it again for a definition no compiler checked.\n */\n\n// ── A custom type, as DDL may name it ────────────────────────────────────────\n\n/** One token of a type name: a word, a quoted identifier, `.`, a modifier list, `[]`. */\nconst CUSTOM_TYPE_TOKEN = /\\s*(?:([A-Za-z_][A-Za-z0-9_$]*)|(\"(?:[^\"]|\"\")+\")|(\\.)|(\\(\\s*[A-Za-z0-9_+\\-.]+\\s*(?:,\\s*[A-Za-z0-9_+\\-.]+\\s*)*\\))|(\\[\\d*\\]))/y;\n\n/**\n * Why a `col.custom(sqlType)` type cannot be written into DDL, or `undefined`\n * when it can.\n *\n * The type is written verbatim — into `CREATE TABLE`, `ADD COLUMN` and the\n * Drizzle file — so only the shape of a Postgres type name is accepted, and\n * nothing in it can end the statement or open a string:\n *\n * - words, separated by spaces (`timestamp without time zone`,\n * `double precision`), or double-quoted identifiers (`\"My Type\"`);\n * - one schema qualifier (`public.citext`, `\"geo\".\"point3\"`);\n * - a modifier list after a word, of words, numbers and signs separated by\n * commas (`geometry(Point, 4326)`, `numeric(10, 2)`, `timestamp(3)`);\n * - array brackets at the end (`inet[]`, `int4range[][]`, `text[3]`).\n *\n * Anything else is refused: a single quote, a semicolon, a comment, an\n * operator, an unbalanced bracket, more than 200 characters. A column clause\n * written after the name (`inet DEFAULT x`, `inet NOT NULL`) has the shape of\n * more words, so the words that begin one are refused by name.\n *\n * @group Schema\n *\n * @internal Shared with @rebasepro/server-postgres's planner; not part of the public API.\n */\nexport function customSqlTypeProblem(sqlType: string): string | undefined {\n const text = sqlType.trim();\n if (text.length === 0) return \"is empty\";\n if (text.length > 200) return \"is longer than 200 characters\";\n let state: \"start\" | \"name\" | \"dot\" | \"modified\" | \"array\" = \"start\";\n const words: string[] = [];\n CUSTOM_TYPE_TOKEN.lastIndex = 0;\n let position = 0;\n while (position < text.length) {\n CUSTOM_TYPE_TOKEN.lastIndex = position;\n const match = CUSTOM_TYPE_TOKEN.exec(text);\n if (!match || match[0].length === 0) return `cannot be read as a type name at \"${text.slice(position)}\"`;\n position = CUSTOM_TYPE_TOKEN.lastIndex;\n const [, word, quoted, dot, modifiers, brackets] = match;\n if (word !== undefined || quoted !== undefined) {\n if (state === \"array\") return \"has a word after its array brackets\";\n if (word !== undefined) words.push(word.toLowerCase());\n state = \"name\";\n } else if (dot !== undefined) {\n if (state !== \"name\") return \"has a `.` that does not separate a schema from a type\";\n state = \"dot\";\n } else if (modifiers !== undefined) {\n if (state !== \"name\") return \"has a modifier list that follows no type name\";\n state = \"modified\";\n } else if (brackets !== undefined) {\n if (state === \"start\" || state === \"dot\") return \"has array brackets that follow no type name\";\n state = \"array\";\n }\n }\n if (state === \"start\" || state === \"dot\") return \"ends without a type name\";\n const clause = words.find(word => CLAUSE_WORDS.has(word));\n if (clause !== undefined) return `holds \\`${clause}\\`, which starts a column clause, not a type`;\n return undefined;\n}\n\n/** Words that begin a column clause after a type — never part of a type name. */\nconst CLAUSE_WORDS: ReadonlySet<string> = new Set([\n \"default\", \"not\", \"null\", \"constraint\", \"references\", \"check\", \"unique\", \"primary\", \"generated\", \"collate\", \"using\"\n]);\n","import type {\n ColumnDef,\n ColumnType,\n ColumnValidation,\n JsonShapeDef,\n PolicyExpression,\n PolicyOperand,\n SecurityRule\n} from \"@rebasepro/types\";\nimport { columnTypeLabel } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\nimport { customSqlTypeProblem } from \"./custom-sql-type\";\nimport type { SchemaDefinitionProblem } from \"./errors\";\nimport { deriveEnumTypeName } from \"./derive-names\";\n\n/**\n * The column-level and rule-level checks of the schema compiler.\n *\n * Each returns the problems it found rather than throwing, so the compiler can\n * report every problem of every table at once. Messages name the column and\n * say what to write instead.\n */\n\nconst INTEGER_KINDS = new Set([\"smallint\", \"integer\", \"bigint\"]);\nconst TEMPORAL_KINDS = new Set([\"timestamptz\", \"date\", \"time\"]);\nconst USER_STAMP_KINDS = new Set([\"text\", \"varchar\", \"char\", \"uuid\"]);\nconst ONE_OF_KINDS = new Set([\n \"text\", \"varchar\", \"char\",\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"real\", \"doublePrecision\", \"numeric\"\n]);\n\n/**\n * Problems in one column's own definition: modifiers that contradict each\n * other or do not apply to its type, an unusable enum, a private key.\n *\n * The builders' types already refuse most of these; this is the runtime half,\n * for JavaScript callers and for a builder reached through a cast.\n *\n * @param table The name the table was defined under, for the problem.\n * @param key The column's key.\n * @param sqlColumn The column's SQL name.\n *\n * @group Schema\n */\nexport function checkColumnDef(\n table: string,\n key: string,\n def: ColumnDef,\n sqlColumn: string\n): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string) => problems.push({ table, key, message });\n const kind = def.type.kind;\n\n if (sqlColumn.length === 0) {\n refuse(`the key \"${key}\" has no snake_case form to name a SQL column with. Give it one as the builder's first argument: \\`col.text(\"…\")\\`.`);\n }\n if (def.generatedAs !== undefined) {\n if (def.default !== undefined) {\n refuse(\n \"`.generatedAlwaysAs()` and a default contradict each other: Postgres computes a generated column \" +\n \"on every write and refuses any default for it. Keep one of the two.\"\n );\n }\n if (def.stamp !== undefined) {\n refuse(\n \"`.generatedAlwaysAs()` and a stamp (`.onCreateNow()`, `.onUpdateUser()`, …) contradict each other: \" +\n \"nobody, not even the server, writes a generated column. Keep one of the two.\"\n );\n }\n }\n if (def.default?.kind === \"identity\" && !INTEGER_KINDS.has(kind)) {\n refuse(`\\`.generatedByDefaultAsIdentity()\\` needs a \\`smallint\\`, \\`integer\\` or \\`bigint\\` column, and this one is \\`${columnTypeLabel(def.type)}\\`.`);\n }\n if (def.default?.kind === \"random-uuid\" && kind !== \"uuid\") {\n refuse(\n `\\`.defaultRandom()\\` writes \\`gen_random_uuid()\\`, which needs a \\`uuid\\` column, and this one is ` +\n `\\`${columnTypeLabel(def.type)}\\`. Use \\`col.uuid()\\`, or \\`.default(sql\\`gen_random_uuid()::text\\`)\\`.`\n );\n }\n if (def.stamp?.value === \"now\" && !TEMPORAL_KINDS.has(kind)) {\n refuse(\n `\\`.${def.stamp.on === \"create\" ? \"onCreateNow\" : \"onUpdateNow\"}()\\` stamps the current time, which ` +\n `needs a \\`timestamptz\\`, \\`date\\` or \\`time\\` column, and this one is \\`${columnTypeLabel(def.type)}\\`.`\n );\n }\n if (def.stamp?.value === \"user\" && !USER_STAMP_KINDS.has(kind)) {\n refuse(\n `\\`.${def.stamp.on === \"create\" ? \"onCreateUser\" : \"onUpdateUser\"}()\\` stores the caller's id, which ` +\n `needs a text or \\`uuid\\` column, and this one is \\`${columnTypeLabel(def.type)}\\`.`\n );\n }\n if (def.private && def.primaryKey) {\n refuse(\n \"a primary-key column cannot be `.private()`: the key is how every row is addressed on the wire — \" +\n \"in URLs, in relations, in realtime events. Drop `.private()`, or key the table on another column.\"\n );\n }\n if (def.primaryKey && (kind === \"timestamptz\" || kind === \"time\")) {\n refuse(\n `a \\`${kind}\\` column cannot be part of the key: an instant addressed by its text is not a stable ` +\n \"address. Key on a `date` (a calendar day the caller supplies), a string or a number, and keep the \" +\n \"timestamp beside it.\"\n );\n }\n const keyProblem = def.primaryKey ? keyTypeProblem(def.type, def.semantic) : undefined;\n if (keyProblem !== undefined) refuse(keyProblem);\n if (def.private && def.access !== undefined) {\n refuse(\n \"`.private()` and `.access()` contradict each other: a private column is never served to or written \" +\n \"by a client, so access rules say nothing. Drop one of the two.\"\n );\n }\n if (def.transform !== undefined && def.json?.transform !== undefined) {\n refuse(\n \"declares a `.transform()` on the column and another on its JSON shape. They are the same hook on the \" +\n \"same value, and only one would run: keep one of the two.\"\n );\n }\n if (kind === \"array\") {\n const elementProblem = arrayElementProblem(def.type.of, def.element?.semantic);\n if (elementProblem !== undefined) refuse(elementProblem);\n }\n for (const problem of unsupportedRules(def)) refuse(problem);\n if (def.oneOf !== undefined && !ONE_OF_KINDS.has(kind)) {\n refuse(`\\`.oneOf()\\` takes a text or numeric column, and this one is \\`${columnTypeLabel(def.type)}\\`. Use \\`col.enum([...])\\` for a Postgres enum.`);\n }\n if (def.oneOf !== undefined && def.oneOf.length === 0) {\n refuse(\"`.oneOf([])` accepts no value at all. List the accepted values, or drop `.oneOf()`.\");\n }\n problems.push(...checkColumnType(table, key, def.type));\n if (def.type.kind === \"enum\" && def.default?.kind === \"literal\" && !def.type.values.includes(String(def.default.value))) {\n refuse(\n `the default ${JSON.stringify(def.default.value)} is not one of the enum's values ` +\n `(${def.type.values.join(\", \")}). Postgres refuses the DEFAULT. Default to one of them.`\n );\n }\n if (def.element) {\n if (def.element.oneOf !== undefined && def.element.oneOf.length === 0) {\n refuse(\"the array's items take `.oneOf([])`, which accepts no value at all. List the accepted values.\");\n }\n const columnOnly = elementColumnModifiers(def.element);\n if (columnOnly.length > 0) {\n refuse(\n `the array's items declare ${columnOnly.join(\", \")}, which apply to a column, not to the items of one. ` +\n \"An item takes `.validate()`, `.oneOf()`, storage, `.userId()`, `.describe()` and `.transform()`; put a \" +\n \"default, `.notNull()`, `.unique()`, access, a stamp or `.private()` on the array column itself.\"\n );\n }\n }\n return problems;\n}\n\n/**\n * The modifiers an array's item declares that only a column can carry: a\n * default, nullability, a key, uniqueness, generation, access, privacy, a\n * stamp, a JSON shape, a vector index. The item rules the API checks\n * (`validate`, `oneOf`), storage, `.userId()`, the description and a\n * transform apply to each item and are kept.\n */\nfunction elementColumnModifiers(element: ColumnDef): string[] {\n const out: string[] = [];\n if (element.notNull) out.push(\"`.notNull()`\");\n if (element.unique) out.push(\"`.unique()`\");\n if (element.primaryKey) out.push(\"`.primaryKey()`\");\n if (element.default !== undefined) out.push(\"a default\");\n if (element.generatedAs !== undefined) out.push(\"`.generatedAlwaysAs()`\");\n if (element.readOnly) out.push(\"`.readOnly()`\");\n if (element.private) out.push(\"`.private()`\");\n if (element.access !== undefined) out.push(\"`.access()`\");\n if (element.stamp !== undefined) out.push(\"a stamp\");\n if (element.json !== undefined) out.push(\"a JSON shape\");\n if (element.vectorIndex !== undefined) out.push(\"a vector index\");\n return out;\n}\n\n/**\n * The column types a key may have: the scalars a row is addressed by — in\n * every URL, filter, cursor and foreign key. (`timestamptz` and `time` are\n * scalars too, refused as keys with their own message.)\n */\nconst KEY_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\n \"text\", \"varchar\", \"char\", \"uuid\", \"enum\",\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"real\", \"doublePrecision\", \"numeric\",\n \"boolean\", \"timestamptz\", \"date\", \"time\"\n]);\n\n/** Whether a `col.custom()` type is an array type (`inet[]`, `text[3]`). */\nconst isCustomArrayType = (sqlType: string): boolean => /\\]\\s*$/.test(sqlType);\n\n/**\n * Why a column of this type cannot be (part of) a primary key, or `undefined`\n * when it can.\n *\n * A row is addressed by its key as text, so a key is a scalar. A JSON\n * document, a geopoint, a vector, binary data and a list are not; a\n * `col.custom()` scalar (`citext`, `inet`) is served as the text the driver\n * returns and may key a table, a custom list type may not.\n *\n * @param semantic The column's `semantic` (`\"geopoint\"` marks a point stored as `jsonb`).\n *\n * @group Schema\n */\nexport function keyTypeProblem(type: ColumnType, semantic?: ColumnDef[\"semantic\"]): string | undefined {\n const passThrough = type.kind === \"other\" && !isCustomArrayType(type.sqlType);\n if (semantic !== \"geopoint\" && (KEY_KINDS.has(type.kind) || passThrough)) return undefined;\n const label = semantic === \"geopoint\" ? \"geopoint\" : `\\`${columnTypeLabel(type)}\\``;\n return (\n `a ${label} column cannot be part of the key. A row is addressed by its key — in every URL, filter, ` +\n \"cursor and foreign key — so a key is a scalar: text, varchar, char, uuid, an enum, a number, a boolean \" +\n \"or a date. Key the table on such a column (several make a composite key) and keep this one as an \" +\n \"ordinary column.\"\n );\n}\n\n/**\n * Element types a Postgres array column does not take here: a JSON document\n * or a vector is a list already, a `bytea` item would need a binary codec per\n * element, and a `col.custom()` list is spelled as its own type. The planner\n * refuses the same set.\n */\nconst NON_ELEMENT_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"json\", \"jsonb\", \"vector\", \"bytea\", \"other\"]);\n\n/**\n * Why an array column cannot hold items of this type, or `undefined` when it\n * can. (An array of arrays is refused by the type check.)\n *\n * @param elementSemantic The item's `semantic` (`\"geopoint\"` for `col.geopoint().array()`).\n *\n * @group Schema\n */\nexport function arrayElementProblem(of: ColumnType, elementSemantic?: ColumnDef[\"semantic\"]): string | undefined {\n if (elementSemantic !== \"geopoint\" && !NON_ELEMENT_KINDS.has(of.kind)) return undefined;\n if (of.kind === \"other\") {\n return (\n `\\`.array()\\` of \\`col.custom({ dataType: ${JSON.stringify(of.sqlType)} })\\` is not an array column Rebase plans. ` +\n `Name the list type itself: \\`col.custom({ dataType: ${JSON.stringify(`${of.sqlType}[]`)} })\\`.`\n );\n }\n const items = elementSemantic === \"geopoint\" ? \"geopoints\" : `\\`${columnTypeLabel(of)}\\` values`;\n return (\n `an array (\\`.array()\\`) of ${items} is not a Postgres array column Rebase reads and writes. An array ` +\n \"column holds scalars — text, uuid, numbers, booleans, dates, enums; a list of documents, points or \" +\n \"vectors is `col.jsonb(json.array(…))`.\"\n );\n}\n\n// ── Validation rules a column kind checks ───────────────────────────────────\n\nconst STRING_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"min\", \"max\", \"length\", \"matches\", \"matchesFlags\", \"matchesMessage\", \"email\", \"url\", \"trim\", \"lowercase\", \"uppercase\"]);\nconst NUMBER_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"min\", \"max\", \"lessThan\", \"moreThan\", \"positive\", \"negative\", \"integer\"]);\nconst DATE_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"min\", \"max\"]);\nconst LIST_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"minItems\", \"maxItems\", \"uniqueItems\"]);\nconst BASE_RULES: ReadonlySet<string> = new Set([\"requiredMessage\"]);\n\n/** The `.validate()` rules a value of this Postgres type is checked by (besides `uniqueBy`, which `checkUniqueBy` owns). */\nfunction rulesOfType(type: ColumnType): ReadonlySet<string> {\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"uuid\":\n case \"enum\":\n return STRING_RULES;\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"smallserial\":\n case \"serial\":\n case \"bigserial\":\n case \"real\":\n case \"doublePrecision\":\n case \"numeric\":\n return NUMBER_RULES;\n case \"timestamptz\":\n case \"date\":\n case \"time\":\n return DATE_RULES;\n case \"array\":\n return LIST_RULES;\n default:\n return BASE_RULES;\n }\n}\n\n/** The rules a JSON shape node is checked by. */\nfunction rulesOfShape(node: JsonShapeDef): ReadonlySet<string> {\n switch (node.kind) {\n case \"string\": return STRING_RULES;\n case \"number\": return NUMBER_RULES;\n case \"date\": return DATE_RULES;\n case \"array\": return LIST_RULES;\n default: return BASE_RULES;\n }\n}\n\n/**\n * The `.validate()` rules declared where nothing checks them: on the column\n * (by its kind — a JSON array column takes the list rules), on an array's\n * items, and on every node of a JSON shape. `.validate()` is typed per kind,\n * so such a rule is a definition built by hand or through a cast; served, it\n * would read as a constraint the API never enforces.\n */\nfunction unsupportedRules(def: ColumnDef): string[] {\n const out: string[] = [];\n const check = (rules: ColumnValidation | undefined, allowed: ReadonlySet<string>, where: string, verb = \"declares\"): void => {\n for (const [rule, value] of Object.entries(rules ?? {})) {\n if (value === undefined || rule === \"uniqueBy\" || allowed.has(rule)) continue;\n out.push(\n `${where} ${verb} the validation rule \\`${rule}\\`, which a ${describeRuleSet(allowed)} does not check. ` +\n `Drop it, or move it to a column whose kind checks it.`\n );\n }\n };\n const columnRules = def.semantic === \"geopoint\"\n ? BASE_RULES\n : def.json?.kind === \"array\" ? LIST_RULES : rulesOfType(def.type);\n check(def.validate, columnRules, \"the column\");\n if (def.type.kind === \"array\" && def.element) check(def.element.validate, rulesOfType(def.type.of), \"the array's items\", \"declare\");\n const visit = (node: JsonShapeDef, path: string): void => {\n if (\"validate\" in node) check(node.validate, rulesOfShape(node), path === \"\" ? \"the document\" : `\"${path}\"`);\n switch (node.kind) {\n case \"object\":\n for (const [field, child] of Object.entries(node.fields)) visit(child, path === \"\" ? field : `${path}.${field}`);\n return;\n case \"array\":\n visit(node.of, path === \"\" ? \"[]\" : `${path}[]`);\n return;\n case \"oneOf\":\n for (const [variant, child] of Object.entries(node.variants)) visit(child, path === \"\" ? variant : `${path}.${variant}`);\n return;\n default:\n return;\n }\n };\n if (def.json) visit(def.json, \"\");\n return out;\n}\n\nconst describeRuleSet = (rules: ReadonlySet<string>): string => {\n if (rules === STRING_RULES) return \"text value\";\n if (rules === NUMBER_RULES) return \"number\";\n if (rules === DATE_RULES) return \"date/time value\";\n if (rules === LIST_RULES) return \"list\";\n return \"value of this kind (it takes only `requiredMessage`)\";\n};\n\n/** Problems in a column type itself: an enum with no or repeated values, a non-positive size. */\nfunction checkColumnType(table: string, key: string, type: ColumnType): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string) => problems.push({ table, key, message });\n switch (type.kind) {\n case \"enum\": {\n if (type.values.length === 0) {\n refuse(\n \"the enum lists no values. They become the labels of a Postgres enum type, and a type with no \" +\n \"labels cannot be created. List the values, or use a plain `col.text()`.\"\n );\n }\n const seen = new Set<string>();\n for (const value of type.values) {\n if (typeof value !== \"string\" || value.length === 0) {\n refuse(\"the enum has a blank value. Each value is a label of the Postgres enum type, and a label cannot be empty.\");\n continue;\n }\n if (seen.has(value)) {\n refuse(\n `the enum lists \"${value}\" twice. The values become the labels of one Postgres enum type, ` +\n \"which cannot hold the same label twice, so `CREATE TYPE` would fail. List it once.\"\n );\n }\n seen.add(value);\n }\n break;\n }\n case \"varchar\":\n case \"char\":\n if (!Number.isInteger(type.length) || type.length <= 0) {\n refuse(`\\`col.${type.kind}(n)\\` takes a positive whole number of characters, got ${String(type.length)}.`);\n }\n break;\n case \"vector\":\n if (!Number.isInteger(type.dimensions) || type.dimensions <= 0) {\n refuse(`\\`col.vector(dimensions)\\` takes a positive whole number, got ${String(type.dimensions)}.`);\n }\n break;\n case \"numeric\":\n if (type.scale !== undefined && type.precision === undefined) {\n refuse(\"`col.numeric(precision, scale)`: a scale needs a precision — `NUMERIC(p, s)` has no form without `p`.\");\n }\n break;\n case \"other\": {\n const problem = customSqlTypeProblem(type.sqlType);\n if (problem !== undefined) {\n refuse(\n `\\`col.custom({ dataType: ${JSON.stringify(type.sqlType)} })\\`: that type name ${problem}. It is written into ` +\n \"DDL verbatim, so it must be a Postgres type as `format_type` prints it — `inet`, `timestamp(3) without \" +\n \"time zone`, `geometry(Point, 4326)`, `inet[]` — and nothing after it.\"\n );\n }\n break;\n }\n case \"array\":\n if (type.of.kind === \"array\") {\n refuse(\"an array of arrays is not supported. Use `col.jsonb()` for nested lists.\");\n } else {\n problems.push(...checkColumnType(table, key, type.of));\n }\n break;\n default:\n break;\n }\n return problems;\n}\n\n/**\n * Whether two column types are the same Postgres type — what a foreign key\n * needs of the column it binds and the key it points at.\n *\n * An enum compares by the type it names and its values, each side's name\n * resolved against its own table: two unnamed enums on two tables are two\n * types, even with the same labels.\n *\n * @group Schema\n */\nexport function sameColumnType(\n a: ColumnType,\n aTable: string,\n aColumn: string,\n b: ColumnType,\n bTable: string,\n bColumn: string\n): boolean {\n if (a.kind !== b.kind) return false;\n switch (a.kind) {\n case \"varchar\":\n case \"char\":\n return b.kind === a.kind && a.length === b.length;\n case \"numeric\":\n return b.kind === \"numeric\" && a.precision === b.precision && a.scale === b.scale;\n case \"vector\":\n return b.kind === \"vector\" && a.dimensions === b.dimensions;\n case \"enum\":\n return b.kind === \"enum\"\n && deriveEnumTypeName(a, aTable, aColumn) === deriveEnumTypeName(b, bTable, bColumn)\n && a.values.length === b.values.length\n && a.values.every((value, index) => value === b.values[index]);\n case \"array\":\n return b.kind === \"array\" && sameColumnType(a.of, aTable, aColumn, b.of, bTable, bColumn);\n case \"other\":\n return b.kind === \"other\" && a.sqlType === b.sqlType;\n default:\n return true;\n }\n}\n\n/**\n * The names a rule may use for a column of its table: the column keys, the\n * SQL column names, and the `belongsTo` relation names (which address their\n * foreign-key column).\n *\n * @group Schema\n */\nexport interface RuleFieldScope {\n /** Every name that addresses a column of the table. */\n names: ReadonlySet<string>;\n}\n\n/**\n * Whether a field name in a rule addresses a column — by key, by relation, or\n * by the snake_case form the policy compiler falls back to (`ownerField:\n * \"author_id\"` reaches the derived `author_id` column, as it always has).\n */\nfunction addresses(scope: RuleFieldScope, name: string): boolean {\n return scope.names.has(name) || scope.names.has(toSnakeCase(name));\n}\n\n/**\n * Problems in a rule's field references: an `ownerField`, or a `field` /\n * `outerField` operand of a structured `condition` / `check`, naming no\n * column of the table.\n *\n * The policy compiler snake-cases a name it does not recognise and compiles a\n * comparison against that column, so a typo reached `CREATE POLICY` and failed\n * there — on a table whose RLS was already enabled, which then served nobody.\n * Fields inside an `existsIn` belong to the other table and are not checked\n * here; its `outerField`s are, because they read this one. Raw SQL is not\n * parsed.\n *\n * @param index The rule's position in `rls`, for the message.\n *\n * @group Schema\n */\nexport function checkRuleFields(\n table: string,\n rule: SecurityRule,\n index: number,\n scope: RuleFieldScope\n): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const label = rule.name ? `rule \"${rule.name}\"` : `rule #${index}`;\n const refuse = (message: string) => problems.push({ table, key: `rls[${index}]`, message });\n\n if (typeof rule.ownerField === \"string\" && !addresses(scope, rule.ownerField)) {\n refuse(\n `${label} has \\`ownerField: \"${rule.ownerField}\"\\`, and the table has no such column or \\`belongsTo\\` ` +\n \"relation. The policy would compare a column that does not exist and fail when it is created. Name \" +\n \"the column (or relation) that holds the owner's user id.\"\n );\n }\n const checkName = (name: string, clause: \"condition\" | \"check\"): void => {\n if (addresses(scope, name)) return;\n refuse(\n `${label} compares the field \"${name}\" in its \\`${clause}\\`, and the table has no such column ` +\n \"or `belongsTo` relation. The policy would fail when it is created. Name a column key of this table.\"\n );\n };\n const checkOperand = (operand: PolicyOperand, clause: \"condition\" | \"check\", inExists: boolean): void => {\n if (operand.kind === \"field\" && !inExists) checkName(operand.name, clause);\n if (operand.kind === \"outerField\" && inExists) checkName(operand.name, clause);\n };\n const walk = (node: unknown, clause: \"condition\" | \"check\", inExists: boolean): void => {\n if (typeof node !== \"object\" || node === null) return;\n if (!isPolicyExpression(node)) {\n // The plain-object shorthand, `{ status: \"published\" }`: every key\n // is a column of this table (inside an `existsIn`, of the other one).\n if (!inExists) for (const key of Object.keys(node)) checkName(key, clause);\n return;\n }\n switch (node.kind) {\n case \"and\":\n case \"or\":\n for (const operand of node.operands) walk(operand, clause, inExists);\n return;\n case \"not\":\n walk(node.operand, clause, inExists);\n return;\n case \"existsIn\": {\n const searched: unknown = node.table;\n if (typeof searched !== \"string\" || searched.trim() === \"\") {\n const legacy = \"collection\" in node && typeof node.collection === \"string\" ? ` (it names \\`collection: \"${node.collection}\"\\`, the 0.30 key)` : \"\";\n refuse(\n `${label} has an \\`existsIn\\` in its \\`${clause}\\` with no table to search${legacy}. The policy would ` +\n \"compile to a subquery over no table. Write `policy.existsIn({ table: \\\"<slug of the table to search>\\\", where })`.\"\n );\n }\n walk(node.where, clause, true);\n return;\n }\n case \"compare\":\n checkOperand(node.left, clause, inExists);\n checkOperand(node.right, clause, inExists);\n return;\n default:\n return;\n }\n };\n if (\"condition\" in rule) walk(rule.condition, \"condition\", false);\n if (\"check\" in rule) walk(rule.check, \"check\", false);\n return problems;\n}\n\n/** Whether a rule's condition node is a structured expression (it carries `kind`) rather than the shorthand object. */\nfunction isPolicyExpression(node: object): node is PolicyExpression {\n return \"kind\" in node && typeof node.kind === \"string\";\n}\n","import type {\n ColumnType,\n AnyTableDef,\n AnyViewDef,\n AuthTableDescriptor,\n ColumnDef,\n ColumnDescriptor,\n ColumnElementDescriptor,\n DefaultRls,\n JsonShapeDef,\n OrderByTuple,\n RelationDef,\n RelationDescriptor,\n RlsDescriptor,\n SearchConfig,\n TableDescriptor,\n TableHookFlags,\n TableIndex,\n TableIndexKey,\n TableIndexPredicate,\n TenantDescriptor,\n TenantSource\n} from \"@rebasepro/types\";\nimport {\n DEFAULT_DATA_SOURCE_KEY,\n columnTypeLabel,\n describeJsonShape,\n isAuthTableDef,\n isColumnBuilder,\n isRelationDef,\n isTableDef,\n isViewDef,\n resourceKeyOf\n} from \"@rebasepro/types\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\n\nimport { authSecretsMissingExclusion } from \"../collections/auth-secrets\";\nimport { DEFAULT_SOFT_DELETE_FIELD } from \"../collections/soft-delete\";\nimport { SchemaDefinitionError, type SchemaDefinitionProblem } from \"./errors\";\nimport {\n JUNCTION_TABLE_SCHEMA,\n deriveBelongsToLocalKey,\n deriveColumnName,\n deriveEnumTypeName,\n deriveForeignKeyField,\n deriveJunctionSourceKey,\n deriveJunctionTable,\n deriveJunctionTargetKey,\n deriveReferencingType,\n deriveSchemaName,\n deriveSlug,\n deriveTableName,\n deriveTargetForeignKey,\n deriveViaWritable\n} from \"./derive-names\";\nimport { resolveRls, ruleShapeProblems } from \"./resolve-rls\";\nimport { checkColumnDef, checkRuleFields, sameColumnType } from \"./validate-tables\";\n\n/**\n * Options of {@link compileTables}.\n *\n * @group Schema\n */\nexport interface CompileTablesOptions {\n /**\n * The project's `defaultRls` (exported from `backend/schema/index.ts`):\n * what every `rls: \"inherit\"` table takes. Without it, `\"inherit\"` is\n * refused.\n */\n defaultRls?: DefaultRls;\n}\n\n/** A table or view definition, as `compileTables` takes them. */\nexport type AnySchemaDef = AnyTableDef | AnyViewDef;\n\n/** One declared column, with the SQL name it resolves to. */\ninterface PreparedColumn {\n key: string;\n def: ColumnDef;\n column: string;\n}\n\n/** What every other table needs to know about one definition before any is compiled. */\ninterface PreparedDef {\n def: AnySchemaDef;\n kind: \"table\" | \"view\";\n name: string;\n slug: string;\n table: string;\n schema: string;\n columns: PreparedColumn[];\n relations: [string, RelationDef][];\n}\n\n/** The resolved target of a relation. */\ntype TargetResolution = { ok: true; target: PreparedDef } | { ok: false; message: string };\n\n/**\n * Whether a column declares a field-level hook anywhere: on itself, inside its\n * JSON shape, or on its array element.\n */\nfunction declaresFieldHook(def: ColumnDef): boolean {\n const hook = (transform: ColumnDef[\"transform\"]): boolean =>\n transform !== undefined && (typeof transform.beforeSave === \"function\" || typeof transform.afterRead === \"function\");\n const inShape = (shape: JsonShapeDef): boolean => {\n if (hook(shape.transform)) return true;\n switch (shape.kind) {\n case \"object\": return Object.values(shape.fields).some(inShape);\n case \"array\": return inShape(shape.of);\n case \"oneOf\": return Object.values(shape.variants).some(inShape);\n default: return false;\n }\n };\n return hook(def.transform) || (def.json !== undefined && inShape(def.json))\n || (def.element !== undefined && declaresFieldHook(def.element));\n}\n\n/** A junction table some relation claims, for the cross-table checks. */\ninterface JunctionClaim {\n keys: string;\n owner: string;\n table: string;\n}\n\nconst TABLE_HOOKS = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\nconst VIEW_HOOKS = [\"beforeQuery\", \"afterRead\"] as const;\nconst TENANT_KINDS = new Set([\n \"text\", \"varchar\", \"char\", \"uuid\", \"enum\",\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"numeric\"\n]);\nconst TEMPORAL_KINDS = new Set([\"timestamptz\", \"date\", \"time\"]);\n/**\n * Integer widths. A foreign key holds between any two of them — Postgres\n * compares `integer` with `bigint` in one operator family — so a bound column\n * keeps its declared width when it points at a key of another one (the shape\n * a database grown over years holds: an `integer` column into a `bigint` key).\n */\nconst INTEGER_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\"]);\n\n/**\n * Compile table and view definitions into the descriptors the backend runs on\n * and `GET /api/schema/tables` serves.\n *\n * Every default is applied and every name derived exactly as today's\n * collection pipeline derives it (see `derive-names.ts`), every relation is\n * resolved to its target's slug, and `rls` is resolved against `defaultRls`.\n *\n * Fails closed: every problem in every definition is collected, and one\n * {@link SchemaDefinitionError} carrying all of them is thrown — a table with\n * no primary key, no usable `rls`, a relation that points outside the list,\n * modifiers that contradict each other, and the rest listed in the error's\n * documentation.\n *\n * Pure and deterministic: no environment, no I/O; tables come out in input\n * order and columns in physical order (declared columns, then the foreign-key\n * columns `belongsTo` relations derive, in relation order).\n *\n * @group Schema\n */\nexport function compileTables(defs: readonly AnySchemaDef[], options: CompileTablesOptions = {}): TableDescriptor[] {\n const problems: SchemaDefinitionProblem[] = [];\n const prepared: PreparedDef[] = [];\n defs.forEach((def, index) => {\n const result = prepareDef(def, index);\n if (\"problem\" in result) problems.push(result.problem);\n else prepared.push(result);\n });\n\n problems.push(...checkTablesTogether(prepared));\n\n const byDef = new Map<unknown, PreparedDef>(prepared.map(entry => [entry.def, entry]));\n const resolve = (thunk: () => unknown): TargetResolution => resolveTarget(thunk, byDef);\n const junctions = new Map<string, JunctionClaim>();\n const descriptors: TableDescriptor[] = [];\n for (const entry of prepared) {\n const { descriptor, problems: found } = compileOne(entry, resolve, options, junctions);\n problems.push(...found);\n descriptors.push(descriptor);\n }\n\n problems.push(...checkStoredIdentifiers(descriptors, prepared));\n\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n return descriptors;\n}\n\n/**\n * Compile one definition, given how to resolve a relation's target.\n *\n * The building block of {@link compileTables}, exported for callers that hold\n * a resolver of their own. Returns the descriptor together with the problems\n * found in that one definition rather than throwing, so the caller decides how\n * to report them; checks that need every table at once (duplicate names,\n * identifiers that collide once Postgres truncates them, one junction claimed\n * with two shapes) are only made by {@link compileTables}.\n *\n * @param resolveTarget Called with a relation's target thunk; returns the\n * definition it points at, or why it does not resolve.\n *\n * @group Schema\n */\nexport function compileTable(\n def: AnySchemaDef,\n resolveTarget: (thunk: () => unknown) => { ok: true; target: AnySchemaDef } | { ok: false; message: string },\n options: CompileTablesOptions = {}\n): { descriptor: TableDescriptor | undefined; problems: SchemaDefinitionProblem[] } {\n const entry = prepareDef(def, 0);\n if (\"problem\" in entry) return { descriptor: undefined, problems: [entry.problem] };\n const cache = new Map<unknown, PreparedDef>([[def, entry]]);\n const resolve = (thunk: () => unknown): TargetResolution => {\n const result = resolveTarget(thunk);\n if (!result.ok) return result;\n let target = cache.get(result.target);\n if (!target) {\n const preparedTarget = prepareDef(result.target, 0);\n if (\"problem\" in preparedTarget) return { ok: false, message: preparedTarget.problem.message };\n target = preparedTarget;\n cache.set(result.target, target);\n }\n return { ok: true, target };\n };\n return compileOne(entry, resolve, options, new Map());\n}\n\n/**\n * The descriptor of one declared column: its key, its SQL name and every flag\n * that is set. Flags that are false or absent are left out, so a descriptor\n * stays small and stable as options are added.\n *\n * @param key The column's key in `columns`.\n * @param column The SQL column name (`.column()`, or the snake_case of the key).\n *\n * @group Schema\n */\nexport function describeColumn(key: string, def: ColumnDef, column: string): ColumnDescriptor {\n const out: ColumnDescriptor = {\n key,\n column,\n type: def.type,\n nullable: !(def.notNull || def.primaryKey)\n };\n if (def.primaryKey) out.primaryKey = true;\n // A key column is unique by being the key; today's planner never writes a\n // second UNIQUE on it, so neither does the descriptor.\n if (def.unique && !def.primaryKey) out.unique = true;\n if (def.default !== undefined) out.default = def.default;\n if (def.generatedAs !== undefined) out.generated = { expression: def.generatedAs };\n if (def.readOnly || def.generatedAs !== undefined) out.readOnly = true;\n if (def.private) out.private = true;\n if (def.access !== undefined) out.access = def.access;\n if (def.stamp !== undefined) out.stamp = def.stamp;\n if (def.validate !== undefined && Object.keys(def.validate).length > 0) out.validate = def.validate;\n if (def.oneOf !== undefined) out.oneOf = def.oneOf;\n if (def.description !== undefined) out.description = def.description;\n if (def.storage !== undefined) out.storage = def.storage;\n if (def.semantic !== undefined) out.semantic = def.semantic;\n if (def.vectorIndex !== undefined) out.vectorIndex = def.vectorIndex;\n if (def.json !== undefined) out.json = describeJsonShape(def.json);\n if (def.element !== undefined) {\n const element: ColumnElementDescriptor = {};\n if (def.element.validate !== undefined && Object.keys(def.element.validate).length > 0) element.validate = def.element.validate;\n if (def.element.oneOf !== undefined) element.oneOf = def.element.oneOf;\n if (def.element.storage !== undefined) element.storage = def.element.storage;\n if (def.element.semantic === \"user\") element.semantic = \"user\";\n if (Object.keys(element).length > 0) out.element = element;\n }\n if (def.transform !== undefined) {\n const transforms: { beforeSave?: true; afterRead?: true } = {};\n if (typeof def.transform.beforeSave === \"function\") transforms.beforeSave = true;\n if (typeof def.transform.afterRead === \"function\") transforms.afterRead = true;\n if (Object.keys(transforms).length > 0) out.transforms = transforms;\n }\n return out;\n}\n\n// ── Preparation ──────────────────────────────────────────────────────────────\n\nfunction prepareDef(def: unknown, index: number): PreparedDef | { problem: SchemaDefinitionProblem } {\n const view = isViewDef(def);\n if (!view && !isTableDef(def)) {\n return {\n problem: {\n table: `#${index}`,\n message: \"is not a `defineTable(...)`, `defineAuthTable(...)` or `defineView(...)` result. Export only table and view definitions from backend/schema/index.ts.\"\n }\n };\n }\n const name = def.name;\n const config = def.config;\n const rawColumns: unknown = config.columns;\n if (typeof rawColumns !== \"object\" || rawColumns === null) {\n return { problem: { table: name, message: \"declares no `columns`.\" } };\n }\n const columns: PreparedColumn[] = [];\n for (const [key, builder] of Object.entries(rawColumns)) {\n if (!isColumnBuilder(builder)) {\n return { problem: { table: name, key, message: \"is not a `col.*` builder.\" } };\n }\n columns.push({ key, def: builder.def, column: deriveColumnName(key, builder.def) });\n }\n const relations: [string, RelationDef][] = [];\n const rawRelations: unknown = config.relations;\n if (rawRelations !== undefined && rawRelations !== null) {\n if (typeof rawRelations !== \"object\") {\n return { problem: { table: name, message: \"`relations` must be an object of `rel.*` results.\" } };\n }\n for (const [key, relation] of Object.entries(rawRelations)) {\n if (!isRelationDef(relation)) {\n return { problem: { table: name, key, message: \"is not a `rel.*` result.\" } };\n }\n relations.push([key, relation]);\n }\n }\n const table = deriveTableName(name, def.config.table);\n return {\n def,\n kind: view ? \"view\" : \"table\",\n name,\n slug: deriveSlug(name, config.slug),\n table,\n schema: deriveSchemaName(config.schema),\n columns,\n relations\n };\n}\n\nfunction resolveTarget(thunk: () => unknown, byDef: ReadonlyMap<unknown, PreparedDef>): TargetResolution {\n let value: unknown;\n try {\n value = thunk();\n } catch (error) {\n if (error instanceof ReferenceError) {\n return {\n ok: false,\n message:\n \"its target is not initialized yet — almost always an import cycle between the two schema \" +\n \"files. Break the cycle (move the shared piece into a third module) so the target's module \" +\n \"finishes evaluating before the schema is compiled.\"\n };\n }\n return { ok: false, message: `its target thunk threw: ${error instanceof Error ? error.message : String(error)}` };\n }\n // A cycle transpiled to CommonJS hands the thunk the module namespace,\n // whose `default` slot holds the definition by the time the thunk runs.\n if (!isTableDef(value) && !isViewDef(value) && typeof value === \"object\" && value !== null && \"default\" in value) {\n const inner: unknown = value.default;\n if (isTableDef(inner) || isViewDef(inner)) value = inner;\n }\n if (!isTableDef(value) && !isViewDef(value)) {\n return {\n ok: false,\n message:\n `its target resolved to ${value === undefined ? \"`undefined`\" : \"something that is not a table\"}. ` +\n \"The thunk must return the `defineTable` / `defineView` result itself: `() => users`.\"\n };\n }\n const target = byDef.get(value);\n if (!target) {\n return {\n ok: false,\n message:\n `its target \"${value.name}\" is not one of the tables being compiled. Export it from ` +\n \"backend/schema/index.ts beside this one.\"\n };\n }\n return { ok: true, target };\n}\n\n// ── One table ────────────────────────────────────────────────────────────────\n\nfunction compileOne(\n entry: PreparedDef,\n resolve: (thunk: () => unknown) => TargetResolution,\n options: CompileTablesOptions,\n junctions: Map<string, JunctionClaim>\n): { descriptor: TableDescriptor; problems: SchemaDefinitionProblem[] } {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string, key?: string): void => {\n problems.push(key === undefined ? { table: entry.name, message } : { table: entry.name, key, message });\n };\n const { def, name } = entry;\n const config = def.config;\n const auth = entry.kind === \"table\" && isAuthTableDef(def);\n\n // ── Columns ──────────────────────────────────────────────────────────────\n const secrets = auth ? new Set(authSecretsMissingExclusion({\n auth: true,\n properties: Object.fromEntries(entry.columns.map(c => [c.key, { excludeFromApi: c.def.private, columnName: c.column }]))\n })) : new Set<string>();\n const columns: ColumnDescriptor[] = [];\n for (const column of entry.columns) {\n problems.push(...checkColumnDef(name, column.key, column.def, column.column));\n problems.push(...checkUniqueBy(name, column.key, column.def));\n const described = describeColumn(column.key, column.def, column.column);\n // The user store's secrets never leave the server, whatever the\n // declaration says: a redeclared users table is where the flag goes\n // missing unnoticed.\n if (secrets.has(column.key)) described.private = true;\n columns.push(described);\n }\n const primaryKey = entry.columns.filter(c => c.def.primaryKey).map(c => c.key);\n if (primaryKey.length === 0) {\n refuse(\n entry.kind === \"view\"\n ? \"the view has no primary key: mark the column(s) that identify a row `.primaryKey()`.\"\n : \"the table has no primary key. Mark a column `.primaryKey()` — e.g. `id: col.uuid().primaryKey().defaultRandom()`; several make a composite key in declaration order.\"\n );\n }\n const keyOwners = new Map<string, string>();\n for (const column of entry.columns) keyOwners.set(column.key, `column \"${column.key}\"`);\n for (const [relationName] of entry.relations) {\n if (keyOwners.has(relationName)) {\n refuse(\n `the table has both a column and a relation named \"${relationName}\". A relation's key is what ` +\n \"`include` names; give the foreign-key column its own key.\",\n relationName\n );\n } else {\n keyOwners.set(relationName, `relation \"${relationName}\"`);\n }\n }\n\n // ── Relations ────────────────────────────────────────────────────────────\n const relations: RelationDescriptor[] = [];\n const derivedColumns: ColumnDescriptor[] = [];\n const boundBy = new Map<string, string>();\n for (const [relationName, relation] of entry.relations) {\n const resolved = resolve(relation.target);\n if (!resolved.ok) {\n refuse(`the relation ${resolved.message}`, relationName);\n continue;\n }\n const target = resolved.target;\n const targetKeys = target.columns.filter(c => c.def.primaryKey);\n const sourceKeys = entry.columns.filter(c => c.def.primaryKey);\n const compositeRefusal = (side: PreparedDef, count: number, link: string, fix: string): void => refuse(\n `${link} is one column, and \\`${side.name}\\` is keyed on ${count} columns together — one column ` +\n `cannot reference a composite key. ${fix}`,\n relationName\n );\n const viaFix = \"or express the link as `rel.via(...)`, whose steps compare every key column.\";\n const before = relations.length;\n switch (relation.kind) {\n case \"belongsTo\": {\n const localKey = deriveBelongsToLocalKey(relationName, relation.localKey);\n const bound = entry.columns.find(c => c.column === localKey);\n if (targetKeys.length > 1) {\n compositeRefusal(target, targetKeys.length, `\\`localKey: \"${localKey}\"\\``, `Point the relation at a table with a single-column key, ${viaFix}`);\n }\n const targetKey = targetKeys.length === 1 ? targetKeys[0] : undefined;\n const referencing = targetKey ? deriveReferencingType(targetKey.def.type, target.table, targetKey.column) : undefined;\n let localField: string;\n if (bound) {\n localField = bound.key;\n const previous = boundBy.get(bound.key);\n if (previous !== undefined) {\n refuse(`the relations \"${previous}\" and \"${relationName}\" both use the column \"${localKey}\" as their foreign key. One column holds one link; give one of them its own \\`localKey\\`.`, relationName);\n }\n boundBy.set(bound.key, relationName);\n if (targetKey && referencing\n && !sameColumnType(bound.def.type, entry.table, bound.column, referencing, target.table, targetKey.column)\n && !(INTEGER_KINDS.has(bound.def.type.kind) && INTEGER_KINDS.has(referencing.kind))) {\n refuse(\n `the relation binds the column \"${bound.key}\" (\\`${columnTypeLabel(bound.def.type)}\\`) as its foreign key, ` +\n `and \\`${target.name}\\`'s key \"${targetKey.key}\" is \\`${columnTypeLabel(referencing)}\\`. A foreign key ` +\n \"only holds between columns of one type. Declare the column with the key's type, or drop it and let \" +\n \"the relation derive it.\",\n relationName\n );\n }\n if (relation.notNull === true && !(bound.def.notNull || bound.def.primaryKey)) {\n refuse(\n `\\`notNull: true\\` applies to a derived foreign key, and this relation binds the declared column \"${bound.key}\", ` +\n \"which is nullable. A bound column says so itself: write `.notNull()` on it and drop `notNull` here.\",\n relationName\n );\n }\n if (relation.unique === true && !(bound.def.unique || bound.def.primaryKey)) {\n refuse(\n `\\`unique: true\\` applies to a derived foreign key, and this relation binds the declared column \"${bound.key}\", ` +\n \"which is not unique. Write `.unique()` on the column and drop `unique` here.\",\n relationName\n );\n }\n const index = columns.findIndex(c => c.key === bound.key);\n if (index >= 0) columns[index] = { ...columns[index], foreignKeyOf: relationName };\n } else {\n localField = deriveForeignKeyField(localKey);\n const owner = keyOwners.get(localField);\n if (owner !== undefined) {\n refuse(\n `the relation derives the foreign-key column \"${localKey}\", served as \"${localField}\", and the ${owner} ` +\n `already has that key. Declare the column yourself (\\`${localField}: col.…(\"${localKey}\")\\`, the SQL name as the builder's first argument, ` +\n \"binds it), or give the relation another `localKey`.\",\n relationName\n );\n } else if (entry.columns.some(c => c.column === localKey) || derivedColumns.some(c => c.column === localKey)) {\n refuse(`the relation derives the column \"${localKey}\", which another relation already derives. Give one of them its own \\`localKey\\`.`, relationName);\n } else {\n keyOwners.set(localField, `foreign key of relation \"${relationName}\"`);\n const column: ColumnDescriptor = {\n key: localField,\n column: localKey,\n type: referencing ?? { kind: \"text\" },\n nullable: relation.notNull !== true,\n foreignKeyOf: relationName,\n derived: true\n };\n if (relation.unique === true) column.unique = true;\n derivedColumns.push(column);\n }\n }\n const descriptor: RelationDescriptor = {\n name: relationName,\n kind: \"belongsTo\",\n target: target.slug,\n cardinality: \"one\",\n localKey,\n localField,\n index: relation.index !== false,\n constraint: relation.constraint !== false && entry.kind === \"table\" && target.kind === \"table\"\n };\n if (relation.onDelete !== undefined) descriptor.onDelete = relation.onDelete;\n if (relation.onUpdate !== undefined) descriptor.onUpdate = relation.onUpdate;\n relations.push(descriptor);\n break;\n }\n case \"hasOne\":\n case \"hasMany\": {\n const foreignKey = deriveTargetForeignKey(entry.slug, relation.foreignKey);\n if (relation.sourceKey === undefined && sourceKeys.length > 1) {\n compositeRefusal(entry, sourceKeys.length, `\\`foreignKey: \"${foreignKey}\"\\``,\n `Give the relation a \\`sourceKey\\` naming a single unique column of \\`${entry.name}\\` to point at, ${viaFix}`);\n }\n const base = { name: relationName, target: target.slug, foreignKey };\n const withSource = relation.sourceKey !== undefined ? { ...base, sourceKey: relation.sourceKey } : base;\n if (relation.kind === \"hasOne\") {\n relations.push({ ...withSource, kind: \"hasOne\", cardinality: \"one\" });\n } else {\n const orderBy = normalizeOrderBy(relation.orderBy);\n relations.push(orderBy\n ? { ...withSource, kind: \"hasMany\", cardinality: \"many\", orderBy }\n : { ...withSource, kind: \"hasMany\", cardinality: \"many\" });\n }\n break;\n }\n case \"manyToMany\": {\n if (sourceKeys.length > 1 || targetKeys.length > 1) {\n const side = sourceKeys.length > 1 ? entry : target;\n compositeRefusal(side, Math.max(sourceKeys.length, targetKeys.length), \"A junction column\",\n `A junction column points at a single-column key; ${viaFix}`);\n }\n const through = deriveJunctionTable(entry.table, target.table, relation.through);\n const sourceKey = deriveJunctionSourceKey(entry.slug, relation.sourceKey);\n const targetKey = deriveJunctionTargetKey(relationName, relation.targetKey);\n if (sourceKey === targetKey) {\n // Both defaults are derived independently — the source's\n // singular slug and the relation's name — so a link from a\n // table to itself named after the table (`tracks.track`)\n // derives one column twice, which no CREATE TABLE takes.\n refuse(\n `both junction columns of \"${through}\" are named \"${sourceKey}\": one column cannot hold both ` +\n `ends of the link. Name the target's apart, e.g. \\`targetKey: \"related_${sourceKey}\"\\`.`,\n relationName\n );\n }\n const pivot: ColumnDescriptor[] = [];\n for (const [key, builder] of Object.entries(relation.pivot ?? {})) {\n if (!isColumnBuilder(builder)) {\n refuse(`the pivot column \"${key}\" is not a \\`col.*\\` builder.`, relationName);\n continue;\n }\n if (builder.def.primaryKey) {\n refuse(\n `the pivot column \"${key}\" is marked \\`.primaryKey()\\`. The junction's key is its two link ` +\n \"columns, which Rebase declares; a pivot column is payload the link carries. Drop `.primaryKey()`.\",\n relationName\n );\n }\n if (declaresFieldHook(builder.def)) {\n // Field hooks run off a table's own columns; nothing\n // runs a pivot column's, so an `afterRead` there would\n // be a mask that never masks. Refused, not ignored.\n refuse(\n `the pivot column \"${key}\" declares \\`.transform()\\`, and a pivot column's field hooks never ` +\n \"run: `_pivot` is served and written as stored. Mask it in the target table's `hooks.afterRead` \" +\n \"(it sees `_pivot`), or move the value onto a table of its own.\",\n relationName\n );\n }\n const column = deriveColumnName(key, builder.def);\n // A payload column on a key column is not planned today; it\n // is not described either.\n if (column === sourceKey || column === targetKey) continue;\n for (const problem of checkColumnDef(name, `${relationName}.pivot.${key}`, builder.def, column)) problems.push(problem);\n pivot.push(describeColumn(key, builder.def, column));\n }\n claimJunction(junctions, through, entry, relationName, sourceKey, targetKey, target, refuse);\n const descriptor: RelationDescriptor = {\n name: relationName,\n kind: \"manyToMany\",\n target: target.slug,\n cardinality: \"many\",\n through: { table: through, sourceKey, targetKey, pivot }\n };\n if (relation.onDelete !== undefined) descriptor.onDelete = relation.onDelete;\n relations.push(descriptor);\n break;\n }\n case \"via\": {\n const steps = Array.isArray(relation.steps) ? relation.steps : [];\n if (steps.length === 0) {\n refuse(\"`rel.via(target, { steps })` needs at least one join step.\", relationName);\n }\n const cardinality = relation.cardinality ?? \"many\";\n relations.push({\n name: relationName,\n kind: \"via\",\n target: target.slug,\n cardinality,\n steps: steps.map(step => ({ ...step })),\n writable: steps.length > 0 && deriveViaWritable(cardinality, steps)\n });\n break;\n }\n default: {\n const exhaustive: never = relation;\n refuse(`unknown relation kind ${JSON.stringify(exhaustive)}.`);\n }\n }\n if (relations.length > before) {\n const described = relations[relations.length - 1];\n if (relation.private === true && relation.access !== undefined) {\n refuse(\n \"the relation is `private: true` and declares `access`. A private relation is never served to or \" +\n \"written by a client, so access rules say nothing; drop one of the two.\",\n relationName\n );\n }\n if (relation.private === true) described.private = true;\n else if (relation.access !== undefined) described.access = relation.access;\n }\n }\n const allColumns = [...columns, ...derivedColumns];\n\n // ── Names a table-level option may use ───────────────────────────────────\n const byKey = new Map(allColumns.map(c => [c.key, c]));\n const belongsToField = new Map<string, string>();\n for (const relation of relations) {\n if (relation.kind === \"belongsTo\") belongsToField.set(relation.name, relation.localField);\n }\n /** A column key, or a `belongsTo` relation name standing for its foreign-key column. */\n const columnOf = (key: string): ColumnDescriptor | undefined => byKey.get(key) ?? byKey.get(belongsToField.get(key) ?? \"\");\n\n const descriptor: TableDescriptor = {\n name,\n slug: entry.slug,\n table: entry.table,\n schema: entry.schema,\n kind: entry.kind,\n columns: allColumns,\n primaryKey,\n relations,\n rls: { posture: \"admin-only\", rules: [], defaultPolicies: true }\n };\n const database = config.database !== undefined ? resourceKeyOf(config.database) : undefined;\n if (database !== undefined && database !== DEFAULT_DATA_SOURCE_KEY) descriptor.database = database;\n if (config.description !== undefined) descriptor.description = config.description;\n if (config.metadata !== undefined) descriptor.metadata = { ...config.metadata };\n\n // ── Indexes ──────────────────────────────────────────────────────────────\n const indexes: unknown = config.indexes;\n if (indexes !== undefined) {\n if (!Array.isArray(indexes)) {\n refuse(\"`indexes` must be a list of `{ columns, … }`.\");\n } else {\n if (entry.kind === \"view\" && !isMaterialized(def)) {\n refuse(\"only a materialized view stores rows to index; a plain view reads the indexes of its tables. Drop `indexes`, or make the view `materialized: true`.\");\n }\n const list: TableIndex[] = [];\n indexes.forEach((index: TableIndex, position: number) => {\n for (const key of indexKeysOf(index)) {\n if (!columnOf(key)) {\n refuse(`\\`indexes[${position}]\\` names \"${key}\", which is no column key or \\`belongsTo\\` relation of the table. Name a key from \\`columns\\`.`);\n }\n }\n list.push(index);\n });\n descriptor.indexes = list;\n }\n }\n\n // ── Views and tables part ways ───────────────────────────────────────────\n if (isViewDef(def)) {\n const viewConfig = def.config;\n if (typeof viewConfig.query !== \"string\" || viewConfig.query.trim().length === 0) {\n refuse(\"the view needs a `query`: the SELECT that defines it.\");\n }\n if (viewConfig.roles !== undefined && !viewConfig.materialized) {\n refuse(\n \"the view lists `roles` but is not materialized. A plain view is governed by the row-level security \" +\n \"of the tables it reads; `roles` gates a materialized view only. Drop `roles`, or add `materialized: true`.\"\n );\n }\n for (const key of [\"tenant\", \"softDelete\", \"history\", \"search\", \"rls\"] as const) {\n if (key in viewConfig && Reflect.get(viewConfig, key) !== undefined && Reflect.get(viewConfig, key) !== false) {\n refuse(`\\`${key}\\` cannot be declared on a view: a view is never written and has no policies of its own; declare it on the tables the view reads.`);\n }\n }\n const materialized = viewConfig.materialized === true;\n descriptor.view = materialized\n ? { materialized: true, roles: [...(viewConfig.roles ?? [\"admin\"])], query: viewConfig.query }\n : { materialized: false, query: viewConfig.query };\n // A view carries no policies: a plain one runs as the caller, a\n // materialized one is gated by `view.roles`. Neither grants through\n // `rls`, which says so with its own posture, no rules and no baseline.\n descriptor.rls = { posture: \"view\", rules: [], defaultPolicies: false };\n const hooks = hookFlags(viewConfig.hooks, VIEW_HOOKS);\n if (hooks) descriptor.hooks = hooks;\n return { descriptor, problems };\n }\n\n const tableConfig = def.config;\n\n // ── rls ──────────────────────────────────────────────────────────────────\n const rls = resolveRls(tableConfig.rls, tableConfig.defaultPolicies, options.defaultRls);\n if (!rls.ok) {\n refuse(rls.message);\n } else {\n descriptor.rls = rls.rls;\n problems.push(...checkRules(name, rls.rls, allColumns, relations, auth));\n }\n\n // ── tenant ───────────────────────────────────────────────────────────────\n if (tableConfig.tenant !== undefined) {\n const tenant = compileTenant(tableConfig.tenant, columnOf, refuse);\n if (tenant) {\n descriptor.tenant = tenant;\n // The planner makes the tenant column NOT NULL whatever it was declared.\n const index = allColumns.findIndex(c => c.key === tenant.field);\n if (index >= 0) allColumns[index] = { ...allColumns[index], nullable: false };\n }\n }\n\n // ── softDelete ───────────────────────────────────────────────────────────\n const softDelete: unknown = tableConfig.softDelete;\n if (softDelete !== undefined && softDelete !== false) {\n let field: string | undefined;\n if (softDelete === true) field = DEFAULT_SOFT_DELETE_FIELD;\n else if (typeof softDelete === \"object\" && softDelete !== null) {\n const named: unknown = \"field\" in softDelete ? softDelete.field : undefined;\n field = typeof named === \"string\" && named.length > 0 ? named : DEFAULT_SOFT_DELETE_FIELD;\n } else {\n refuse(\"`softDelete` must be `true` or `{ field }`.\");\n }\n if (field !== undefined) {\n const column = byKey.get(field);\n if (!column) {\n refuse(\n `\\`softDelete\\` records the deletion in \"${field}\", and the table has no such column. Declare it — ` +\n `\\`${field}: col.timestamp({ withTimezone: true })\\` — or name an existing timestamp column with \\`softDelete: { field: \"…\" }\\`. ` +\n \"The flag says what a column means; it does not add one.\"\n );\n } else if (!TEMPORAL_KINDS.has(column.type.kind)) {\n refuse(`\\`softDelete\\` stamps \"${field}\" with the time of the deletion, and that column is \\`${columnTypeLabel(column.type)}\\`. Make it \\`col.timestamp({ withTimezone: true })\\`.`);\n } else {\n descriptor.softDelete = { field };\n }\n }\n }\n\n if (tableConfig.history === true) descriptor.history = true;\n\n // ── search ───────────────────────────────────────────────────────────────\n if (tableConfig.search !== undefined) {\n problems.push(...checkSearch(name, tableConfig.search, byKey));\n descriptor.search = { ...tableConfig.search, fields: [...tableConfig.search.fields] };\n }\n\n // ── auth ─────────────────────────────────────────────────────────────────\n if (auth && def.auth) {\n const authDescriptor: AuthTableDescriptor = {};\n if (def.auth.roles !== undefined) authDescriptor.roles = def.auth.roles;\n if (def.auth.scopes !== undefined) authDescriptor.scopes = def.auth.scopes;\n if (def.auth.personalKeys !== undefined) authDescriptor.personalKeys = def.auth.personalKeys;\n const authHooks: { onCreateUser?: true; onResetPassword?: true } = {};\n if (typeof def.auth.onCreateUser === \"function\") authHooks.onCreateUser = true;\n if (typeof def.auth.onResetPassword === \"function\") authHooks.onResetPassword = true;\n if (Object.keys(authHooks).length > 0) authDescriptor.hooks = authHooks;\n descriptor.auth = authDescriptor;\n }\n\n const hooks = hookFlags(tableConfig.hooks, TABLE_HOOKS);\n if (hooks) descriptor.hooks = hooks;\n if (tableConfig.strictWrites === false) descriptor.strictWrites = false;\n\n return { descriptor, problems };\n}\n\n/**\n * `uniqueBy` names fields of the items of a JSON array of objects\n * (`json.array(json.object({...})).validate({ uniqueBy: [...] })`, or the\n * rules of a column holding one). Anywhere else — another column's rules, an\n * array of scalars, a field the item does not have — it would be a rule\n * nothing can check, so it is refused.\n */\nfunction checkUniqueBy(table: string, key: string, def: ColumnDef): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string): void => {\n problems.push({ table, key, message });\n };\n // A JSON array column's list rules may sit on the column (the lift puts\n // them there) or on its shape: both describe the one array.\n const columnUniqueBy = def.validate?.uniqueBy;\n if (columnUniqueBy !== undefined && def.json?.kind !== \"array\") {\n refuse(\n \"`uniqueBy` compares the items of a JSON array of objects, and this column is not one. Declare the column \" +\n \"`col.jsonb(json.array(json.object({ … })).validate({ uniqueBy: [\\\"field\\\"] }))`; for an array of plain \" +\n \"values, `uniqueItems: true`.\"\n );\n }\n if (def.element?.validate?.uniqueBy !== undefined) {\n refuse(\"the array's items declare `uniqueBy`, which compares a JSON array's object items. For a Postgres array, use `uniqueItems: true` on the column.\");\n }\n const visit = (node: JsonShapeDef, path: string): void => {\n const at = path === \"\" ? \"the document\" : `\"${path}\"`;\n const uniqueBy = \"validate\" in node ? node.validate?.uniqueBy : undefined;\n if (uniqueBy !== undefined) {\n if (node.kind !== \"array\") {\n refuse(`${at} declares \\`uniqueBy\\`, which applies to a JSON array of objects, and it is a JSON ${node.kind}.`);\n } else if (node.of.kind !== \"object\") {\n refuse(`${at} declares \\`uniqueBy\\`, and its items are JSON ${node.of.kind} values, not objects. For plain values, use \\`uniqueItems: true\\`.`);\n } else if (uniqueBy.length === 0) {\n refuse(`${at} declares \\`uniqueBy: []\\`, which compares nothing. Name the item fields that must be unique, or drop it.`);\n } else {\n const fields = node.of.fields;\n const missing = uniqueBy.filter(field => !Object.prototype.hasOwnProperty.call(fields, field));\n if (missing.length > 0) {\n refuse(\n `${at} declares \\`uniqueBy\\` naming ${missing.map(field => `\"${field}\"`).join(\", \")}, which the items do not have ` +\n `(they have ${Object.keys(fields).map(field => `\"${field}\"`).join(\", \") || \"no fields\"}).`\n );\n }\n }\n }\n switch (node.kind) {\n case \"object\":\n for (const [field, child] of Object.entries(node.fields)) visit(child, path === \"\" ? field : `${path}.${field}`);\n return;\n case \"array\":\n visit(node.of, `${path}[]`);\n return;\n case \"oneOf\":\n for (const [variant, child] of Object.entries(node.variants)) visit(child, `${path}[${variant}]`);\n return;\n default:\n return;\n }\n };\n if (def.json !== undefined) {\n visit(def.json.kind === \"array\" && columnUniqueBy !== undefined\n ? { ...def.json, validate: { ...def.json.validate, uniqueBy: columnUniqueBy } }\n : def.json, \"\");\n }\n return problems;\n}\n\nfunction isMaterialized(def: AnySchemaDef): boolean {\n return isViewDef(def) && def.config.materialized === true;\n}\n\nfunction normalizeOrderBy(orderBy: OrderByTuple | readonly OrderByTuple[] | undefined): OrderByTuple[] | undefined {\n if (orderBy === undefined || orderBy.length === 0) return undefined;\n const tuples: OrderByTuple[] = [];\n if (isOrderByTuple(orderBy)) {\n tuples.push([...orderBy]);\n } else {\n for (const tuple of orderBy) tuples.push([...tuple]);\n }\n return tuples;\n}\n\nfunction isOrderByTuple(value: OrderByTuple | readonly OrderByTuple[]): value is OrderByTuple {\n return typeof value[0] === \"string\";\n}\n\nfunction hookFlags(hooks: object | undefined, names: readonly (keyof TableHookFlags)[]): TableHookFlags | undefined {\n if (!hooks) return undefined;\n const flags: TableHookFlags = {};\n for (const name of names) {\n if (typeof Reflect.get(hooks, name) === \"function\") flags[name] = true;\n }\n return Object.keys(flags).length > 0 ? flags : undefined;\n}\n\nfunction indexKeysOf(index: TableIndex): string[] {\n const keys: string[] = [];\n const keyOf = (entry: string | TableIndexKey): string => typeof entry === \"string\" ? entry : entry.column;\n for (const entry of index.columns ?? []) keys.push(keyOf(entry));\n for (const entry of index.include ?? []) keys.push(entry);\n const walk = (predicate: TableIndexPredicate | undefined): void => {\n if (!predicate) return;\n if (\"and\" in predicate) {\n for (const inner of predicate.and) walk(inner);\n return;\n }\n keys.push(predicate.column);\n };\n walk(index.where);\n return keys;\n}\n\nfunction compileTenant(\n tenant: { field: string; from: TenantSource; bypassRoles?: readonly string[] },\n columnOf: (key: string) => ColumnDescriptor | undefined,\n refuse: (message: string) => void\n): TenantDescriptor | undefined {\n const column = columnOf(tenant.field);\n if (!column) {\n refuse(\n `\\`tenant\\` scopes rows by \"${tenant.field}\", and the table has no such column or \\`belongsTo\\` relation. ` +\n `Declare it — \\`${tenant.field}: col.uuid().notNull()\\` — or name the column that already holds the tenant id. ` +\n \"The flag says what a column means; it does not add one.\"\n );\n return undefined;\n }\n let ok = true;\n if (!TENANT_KINDS.has(column.type.kind)) {\n refuse(`\"${tenant.field}\" is \\`${columnTypeLabel(column.type)}\\`, which cannot hold a tenant id. Use a text, \\`uuid\\` or integer column, or a \\`belongsTo\\` the tenants table.`);\n ok = false;\n }\n if (column.private || column.access?.read !== undefined) {\n refuse(\n `\"${tenant.field}\" is the tenant every row belongs to, and it is also hidden from callers ` +\n `(\\`${column.private ? \".private()\" : \"access.read\"}\\`), so a client could never see which tenant a row it ` +\n \"just wrote is in. Drop the restriction, or drop `tenant`.\"\n );\n ok = false;\n }\n if (\"membership\" in tenant.from) {\n const searched: unknown = tenant.from.membership.table;\n if (typeof searched !== \"string\" || searched.trim() === \"\") {\n refuse(\n \"`tenant.from.membership` names no table to read the memberships from, so the tenant test would search no table. \" +\n \"Write `membership: { table: \\\"<slug of the memberships table>\\\", userField, tenantField }`.\"\n );\n ok = false;\n }\n }\n if (!ok) return undefined;\n const out: TenantDescriptor = { field: column.key, from: tenant.from };\n if (tenant.bypassRoles !== undefined) out.bypassRoles = [...tenant.bypassRoles];\n return out;\n}\n\nfunction checkSearch(table: string, search: SearchConfig, byKey: ReadonlyMap<string, ColumnDescriptor>): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string) => problems.push({ table, key: \"search\", message });\n if (!Array.isArray(search.fields) || search.fields.length === 0) {\n refuse(\"`search.fields` lists no field. Name the text columns to index, e.g. `search: { fields: [\\\"title\\\"] }`.\");\n return problems;\n }\n for (const entry of search.fields) {\n const path = typeof entry === \"string\" ? entry : entry.path;\n const [head, ...rest] = path.split(\".\");\n const column = byKey.get(head);\n if (!column) {\n refuse(`\\`search.fields\\` names \"${path}\", and \"${head}\" is no column key of the table. Name a column from \\`columns\\`.`);\n continue;\n }\n if (rest.length > 0 && column.type.kind !== \"json\" && column.type.kind !== \"jsonb\") {\n refuse(`\\`search.fields\\` names the path \"${path}\", and \"${head}\" is \\`${columnTypeLabel(column.type)}\\`, not a JSON column. A dotted path reads into a \\`col.jsonb()\\` document.`);\n }\n if (column.private || column.access?.read !== undefined) {\n refuse(\n `\"${path}\" is named in \\`search.fields\\` and also restricted by \\`${column.private ? \".private()\" : \"access.read\"}\\`. ` +\n \"The search index is one generated column shared by every caller, so the field would stay matchable \" +\n \"to callers who can never see its value — recoverable a term at a time. Remove it from \" +\n \"`search.fields`, or drop the read restriction.\"\n );\n }\n }\n return problems;\n}\n\n/** The columns every auth table has whether it declares them or not, by key and SQL name. */\nconst AUTH_TABLE_NAMES = [\n \"id\", \"email\", \"displayName\", \"display_name\", \"photoURL\", \"photo_url\", \"roles\", \"passwordHash\", \"password_hash\",\n \"emailVerified\", \"email_verified\", \"emailVerificationToken\", \"email_verification_token\",\n \"emailVerificationSentAt\", \"email_verification_sent_at\", \"metadata\", \"createdAt\", \"created_at\", \"updatedAt\", \"updated_at\",\n \"isAnonymous\", \"is_anonymous\", \"tokensValidAfter\", \"tokens_valid_after\"\n];\n\nfunction checkRules(\n table: string,\n rls: RlsDescriptor,\n columns: readonly ColumnDescriptor[],\n relations: readonly RelationDescriptor[],\n auth: boolean\n): SchemaDefinitionProblem[] {\n const names = new Set<string>();\n for (const column of columns) {\n names.add(column.key);\n names.add(column.column);\n }\n for (const relation of relations) {\n if (relation.kind === \"belongsTo\") names.add(relation.name);\n }\n if (auth) for (const name of AUTH_TABLE_NAMES) names.add(name);\n return rls.rules.flatMap((rule, index) => [\n ...ruleShapeProblems(rule, rule.name ? `rule \"${rule.name}\"` : `rule #${index}`)\n .map(message => ({ table, key: `rls[${index}]`, message })),\n ...checkRuleFields(table, rule, index, { names })\n ]);\n}\n\n// ── Across tables ────────────────────────────────────────────────────────────\n\nfunction checkTablesTogether(prepared: readonly PreparedDef[]): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const names = new Map<string, PreparedDef>();\n const slugs = new Map<string, PreparedDef>();\n const tables = new Map<string, PreparedDef>();\n let authTable: PreparedDef | undefined;\n for (const entry of prepared) {\n const sameName = names.get(entry.name);\n if (sameName) {\n problems.push({ table: entry.name, message: `two definitions are named \"${entry.name}\". Each table and view needs its own name.` });\n } else {\n names.set(entry.name, entry);\n }\n const sameSlug = slugs.get(entry.slug);\n if (sameSlug && sameSlug !== sameName) {\n problems.push({\n table: entry.name,\n message:\n `its slug \"${entry.slug}\" is also the slug of \"${sameSlug.name}\". The slug is the table's API path, ` +\n \"its SDK accessor and what scopes name. Give one of them its own `slug`.\"\n });\n } else if (!sameSlug) {\n slugs.set(entry.slug, entry);\n }\n const qualified = `${entry.schema}.${entry.table}`;\n const sameTable = tables.get(qualified);\n if (sameTable && sameTable !== sameName && sameTable !== sameSlug) {\n problems.push({\n table: entry.name,\n message:\n `it resolves to the SQL table \\`${qualified}\\`, which \"${sameTable.name}\" resolves to too. A table has ` +\n \"one owner. Give one of them another `table` or `schema`.\"\n });\n } else if (!sameTable) {\n tables.set(qualified, entry);\n }\n if (entry.kind === \"table\" && isAuthTableDef(entry.def)) {\n if (authTable) {\n problems.push({\n table: entry.name,\n message:\n `is a second \\`defineAuthTable\\` — \"${authTable.name}\" is already the table users are stored in. ` +\n \"A project has one user store; make this one a `defineTable`.\"\n });\n } else {\n authTable = entry;\n }\n }\n }\n return problems;\n}\n\nfunction claimJunction(\n junctions: Map<string, JunctionClaim>,\n through: string,\n source: PreparedDef,\n relationName: string,\n sourceKey: string,\n targetKey: string,\n target: PreparedDef,\n refuse: (message: string, key?: string) => void\n): void {\n const keys = JSON.stringify([[sourceKey, source.table], [targetKey, target.table]].sort());\n const owner = `the relation \"${relationName}\" of \"${source.name}\" (\"${sourceKey}\" → ${source.table}, \"${targetKey}\" → ${target.table})`;\n const first = junctions.get(through);\n if (!first) {\n junctions.set(through, { keys, owner, table: source.table });\n return;\n }\n if (first.keys === keys) return;\n refuse(\n `two many-to-many relations resolve to the junction table \"${through}\" with different key columns: ` +\n `${first.owner} and ${owner}. Only one table is created, so one of them would read and write columns ` +\n `that do not exist. Give this one its own junction — \\`through: \"${source.table}_${relationName}\"\\` — or, if ` +\n \"both are meant to be one link, declare it once.\",\n relationName\n );\n}\n\n/**\n * Identifiers that are distinct as written and one name once Postgres keeps\n * their first 63 bytes: tables, views, junction tables and enum types share a\n * namespace per schema (every table owns a row type of its name), and the\n * columns of one table share another. Also: one enum type name given two\n * different lists of values.\n */\nfunction checkStoredIdentifiers(descriptors: readonly TableDescriptor[], prepared: readonly PreparedDef[]): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n interface Claim { full: string; what: string; table: string; values?: readonly string[] }\n const relationsClaims = new Map<string, Claim>();\n const claim = (schema: string, full: string, what: string, table: string, values?: readonly string[], key?: string): void => {\n const stored = `${schema}.${toPostgresIdentifier(full)}`;\n const first = relationsClaims.get(stored);\n if (!first) {\n relationsClaims.set(stored, { full, what, table, values });\n return;\n }\n if (first.full === full) {\n const bothEnums = first.values !== undefined && values !== undefined;\n if (bothEnums && first.values && values && (first.values.length !== values.length || first.values.some((v, i) => v !== values[i]))) {\n problems.push({\n table,\n key,\n message:\n `the enum type \"${schema}\".\"${full}\" is given the values (${values.join(\", \")}) here and ` +\n `(${first.values.join(\", \")}) by ${first.what}. Columns sharing a named enum type must list the ` +\n \"same values, in the same order. Make them agree, or give one column its own type `name`.\"\n });\n }\n // A junction both sides declare, an enum type two columns share,\n // and a duplicate table (refused on its own) are one name on purpose.\n if (bothEnums || first.values === undefined && values === undefined) return;\n }\n problems.push({\n table,\n key,\n message:\n `${what} and ${first.what} both become \"${schema}\".\"${toPostgresIdentifier(full)}\" in Postgres, which keeps ` +\n \"only the first 63 bytes of an identifier — and tables, views, junction tables and enum types share \" +\n \"one namespace. The push would fail with \\\"already exists\\\". Give one of them a shorter name (a \" +\n \"`table`, a `.column()`, or an enum `name`).\"\n });\n };\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n claim(descriptor.schema, descriptor.table, `${descriptor.kind} \"${descriptor.table}\"`, entry.name);\n });\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n claim(JUNCTION_TABLE_SCHEMA, relation.through.table, `junction table \"${relation.through.table}\"`, entry.name, undefined, relation.name);\n }\n });\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n if (descriptor.kind !== \"table\") return;\n const enumOf = (column: ColumnDescriptor, table: string, schema: string, key: string): void => {\n const type = column.type.kind === \"array\" ? column.type.of : column.type;\n if (type.kind !== \"enum\") return;\n // A column referencing an enum key uses the key table's type.\n if (column.derived) return;\n const name = deriveEnumTypeName(type, table, column.column);\n claim(schema, name, `the enum type of \"${entry.name}.${key}\"`, entry.name, type.values, key);\n };\n for (const column of descriptor.columns) enumOf(column, descriptor.table, descriptor.schema, column.key);\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n for (const column of relation.through.pivot) enumOf(column, relation.through.table, JUNCTION_TABLE_SCHEMA, `${relation.name}.pivot.${column.key}`);\n }\n });\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n const seen = new Map<string, ColumnDescriptor>();\n for (const column of descriptor.columns) {\n const stored = toPostgresIdentifier(column.column);\n const first = seen.get(stored);\n if (!first) {\n seen.set(stored, column);\n continue;\n }\n problems.push({\n table: entry.name,\n key: column.key,\n message: first.column === column.column\n ? `\"${column.key}\" and \"${first.key}\" both resolve to the SQL column \"${column.column}\" (a column is its ` +\n \"`.column()`, or its key in snake_case), so the table would declare it twice. Rename one, or give \" +\n \"it its own `.column(\\\"…\\\")`.\"\n : `\"${column.key}\" and \"${first.key}\" resolve to the columns \"${column.column}\" and \"${first.column}\", ` +\n `which are one name — \"${stored}\" — once Postgres keeps the first 63 bytes. Give one a shorter \\`.column()\\`.`\n });\n }\n });\n return problems;\n}\n","/**\n * From table definitions to what the server runs on: `CompiledTable[]`.\n *\n * `compileTables` produces the wire-safe descriptors; this adds, per table,\n * the server-only parts the descriptor cannot carry — the table's hooks, its\n * columns' field-level hooks (addressed by column key and nested path) and the\n * auth table's lifecycle hooks — collected from the very definitions that were\n * compiled, so the two halves cannot describe different tables.\n *\n * @module\n */\nimport type {\n AnyTableDef,\n AnyViewDef,\n ColumnDef,\n CompiledAuthHooks,\n CompiledTable,\n CompiledTransform,\n DefaultRls,\n JsonShapeDef,\n TableDescriptor,\n TableHooks,\n TransformNode,\n JsonPathStep\n} from \"@rebasepro/types\";\nimport { isAuthTableDef, isColumnBuilder } from \"@rebasepro/types\";\n\nimport { compileTables } from \"./compile-tables\";\nimport { SchemaDefinitionError, type SchemaDefinitionProblem } from \"./errors\";\nimport { keyTypeProblem } from \"./validate-tables\";\nimport { tableDefsFromDescriptors, type TableDefsFromDescriptorsOptions } from \"./descriptor-to-def\";\n\n/**\n * Options of {@link compileSchema}.\n *\n * @group Schema\n */\nexport interface CompileSchemaOptions {\n /**\n * The project's `defaultRls` (exported from `backend/schema/index.ts`):\n * what every `rls: \"inherit\"` table takes. Without it, `\"inherit\"` is\n * refused.\n */\n defaultRls?: DefaultRls;\n}\n\n/**\n * Compile table and view definitions into the tables the server runs on.\n *\n * The descriptors are exactly `compileTables(defs, options)` — same order,\n * same errors: every problem in every definition is collected into one\n * `SchemaDefinitionError`. Each comes back with the definition it was compiled\n * from and the server-only parts of that definition: `hooks`, the field-level\n * hooks of its columns as {@link TransformNode} trees by column key, and, for\n * a `defineAuthTable`, `onCreateUser` / `onResetPassword`.\n *\n * Pure: nothing is registered, nothing is called.\n *\n * @group Schema\n */\nexport function compileSchema(\n defs: readonly (AnyTableDef | AnyViewDef)[],\n options: CompileSchemaOptions = {}\n): CompiledTable[] {\n const descriptors = compileTables(defs, options.defaultRls !== undefined ? { defaultRls: options.defaultRls } : {});\n // `compileTables` throws unless every definition compiled, and returns them\n // in input order: descriptor i is definition i.\n return descriptors.map((descriptor, index) => compiledTable(defs[index], descriptor));\n}\n\n/**\n * Tables the server runs on for descriptors nobody authored — what\n * introspection reads from a database no project declared.\n *\n * Each descriptor is kept exactly as given (its row-level security is the\n * catalogue's, its key what the database holds, possibly none); the\n * definition beside it is the one {@link tableDefsFromDescriptors} states for\n * it, so a reader of `def` sees the same table. Such a table declares no hooks.\n *\n * A table keyed on a column no row can be addressed by — a JSON document,\n * binary data, a vector, a list — is refused (a {@link SchemaDefinitionError}\n * naming it), as a declared one is; introspection drops it with that reason.\n *\n * @param options Passed to {@link tableDefsFromDescriptors}: introspection\n * replaces each `rls` with `\"admin-only\"`, because Rebase generates no policy\n * for a table it did not declare.\n *\n * @group Schema\n */\nexport function compileDescribedTables(\n descriptors: readonly TableDescriptor[],\n options: TableDefsFromDescriptorsOptions = {}\n): CompiledTable[] {\n const problems: SchemaDefinitionProblem[] = [];\n for (const descriptor of descriptors) {\n for (const column of descriptor.columns) {\n if (!descriptor.primaryKey.includes(column.key)) continue;\n const problem = keyTypeProblem(column.type, column.semantic);\n if (problem !== undefined) problems.push({ table: descriptor.name, key: column.key, message: problem });\n }\n }\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n const defs = tableDefsFromDescriptors(descriptors, options);\n return descriptors.map((descriptor, index) => ({ descriptor, def: defs[index] }));\n}\n\n/**\n * Every field-level hook of a compiled table, flattened: one entry per hook,\n * with its column key and the path inside the column's value. Columns in the\n * table's physical order; inside a column, the column's own hook first, then\n * its nested ones depth first.\n *\n * @group Schema\n */\nexport function listTransforms(table: CompiledTable): CompiledTransform[] {\n const out: CompiledTransform[] = [];\n if (!table.transforms) return out;\n const visit = (column: string, node: TransformNode, path: JsonPathStep[]): void => {\n if (node.transform) out.push({ column, path, transform: node.transform });\n for (const [field, child] of Object.entries(node.fields ?? {})) visit(column, child, [...path, { field }]);\n if (node.items) visit(column, node.items, [...path, { items: true }]);\n for (const [variant, child] of Object.entries(node.variants ?? {})) visit(column, child, [...path, { variant }]);\n };\n const transforms = table.transforms;\n for (const column of table.descriptor.columns) {\n const node = transforms[column.key];\n if (node) visit(column.key, node, []);\n }\n return out;\n}\n\n// ── One table ────────────────────────────────────────────────────────────────\n\n/**\n * One compiled table from a definition and the descriptor it compiled to: the\n * server-only parts collected from `def` beside `descriptor`. What\n * {@link compileSchema} does per table, for a caller that compiled the\n * descriptor itself (`compileTable` with a resolver of its own).\n *\n * @group Schema\n */\nexport function compiledTable(def: AnyTableDef | AnyViewDef, descriptor: TableDescriptor): CompiledTable {\n const compiled: CompiledTable = { descriptor, def };\n const hooks = hooksOf(def);\n if (hooks) compiled.hooks = hooks;\n const transforms = transformsOf(def);\n if (transforms) compiled.transforms = transforms;\n if (isAuthTableDef(def)) {\n const auth: CompiledAuthHooks = {};\n if (typeof def.auth.onCreateUser === \"function\") auth.onCreateUser = def.auth.onCreateUser;\n if (typeof def.auth.onResetPassword === \"function\") auth.onResetPassword = def.auth.onResetPassword;\n if (auth.onCreateUser || auth.onResetPassword) compiled.auth = auth;\n }\n return compiled;\n}\n\n/** The table's hooks, or `undefined` when it declares none. A view has read hooks only. */\nfunction hooksOf(def: AnyTableDef | AnyViewDef): TableHooks | undefined {\n const declared: TableHooks | undefined = def.config.hooks;\n if (!declared) return undefined;\n const hooks: TableHooks = { ...declared };\n return Object.values(hooks).some(hook => typeof hook === \"function\") ? hooks : undefined;\n}\n\n/** The transform tree of every column that declares a field-level hook, by column key. */\nfunction transformsOf(def: AnyTableDef | AnyViewDef): Record<string, TransformNode> | undefined {\n const out: Record<string, TransformNode> = {};\n for (const [key, builder] of Object.entries(def.config.columns)) {\n if (!isColumnBuilder(builder)) continue;\n const node = columnNode(builder.def);\n if (node) out[key] = node;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** The node for one column: its own hook, its JSON shape's and its array element's. */\nfunction columnNode(def: ColumnDef): TransformNode | undefined {\n const node: TransformNode = {};\n if (hasHook(def.transform)) node.transform = def.transform;\n if (def.json) {\n const shape = shapeNode(def.json);\n if (shape) Object.assign(node, shape);\n }\n if (def.element) {\n const items = columnNode(def.element);\n if (items) node.items = items;\n }\n return isEmpty(node) ? undefined : node;\n}\n\n/** The node for one position of a JSON shape. */\nfunction shapeNode(shape: JsonShapeDef): TransformNode | undefined {\n const node: TransformNode = {};\n if (hasHook(shape.transform)) node.transform = shape.transform;\n switch (shape.kind) {\n case \"object\": {\n const fields: Record<string, TransformNode> = {};\n for (const [key, field] of Object.entries(shape.fields)) {\n const child = shapeNode(field);\n if (child) fields[key] = child;\n }\n if (Object.keys(fields).length > 0) node.fields = fields;\n break;\n }\n case \"array\": {\n const items = shapeNode(shape.of);\n if (items) node.items = items;\n break;\n }\n case \"oneOf\": {\n const variants: Record<string, TransformNode> = {};\n for (const [name, variant] of Object.entries(shape.variants)) {\n const child = shapeNode(variant);\n if (child) variants[name] = child;\n }\n if (Object.keys(variants).length > 0) node.variants = variants;\n break;\n }\n default:\n break;\n }\n return isEmpty(node) ? undefined : node;\n}\n\nfunction hasHook(transform: ColumnDef[\"transform\"]): transform is NonNullable<ColumnDef[\"transform\"]> {\n return transform !== undefined && (typeof transform.beforeSave === \"function\" || typeof transform.afterRead === \"function\");\n}\n\nfunction isEmpty(node: TransformNode): boolean {\n return !node.transform && !node.fields && !node.items && !node.variants;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport {\n LEGACY_LAYOUT_REMEDY,\n isTableDef,\n isViewDef,\n type AnyTableDef,\n type AnyViewDef,\n type CompiledTable,\n type DefaultRls,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { SchemaDefinitionError, compileSchema, compileTables, type SchemaDefinitionProblem } from \"@rebasepro/common\";\n\n/**\n * The one definition of \"the tables\".\n *\n * Every door that reads a project's `backend/schema` — server boot, the stock\n * runtime, `rebase db generate`, `db push`, the doctor, SDK generation — calls\n * {@link loadBackendSchema}, so they cannot disagree about which tables exist\n * or which of them are protected. A definition that would leave a table\n * unprotected stops all of them the same way.\n */\n\n/** The module names that make a directory a schema: its `index`. */\nconst INDEX_FILES = [\"index.ts\", \"index.mts\", \"index.js\", \"index.mjs\"] as const;\nconst MODULE_EXTENSIONS = [\".ts\", \".mts\", \".js\", \".mjs\"] as const;\n\n/**\n * A `backend/schema` directory, imported and checked.\n *\n * @group Schema\n */\nexport interface LoadedSchema {\n /** The schema directory, absolute. */\n dir: string;\n /**\n * The index module the definitions were read from, absolute. Empty when the\n * directory has no index — the project declares no tables, and the runtime\n * introspects the database instead.\n */\n indexFile: string;\n /**\n * Every table and view the index exports, each once, in the order the\n * index module's namespace lists them (an ES module namespace lists its\n * exports by name; a CommonJS build in declaration order).\n */\n defs: (AnyTableDef | AnyViewDef)[];\n /** The `defaultRls` the index exports: what `rls: \"inherit\"` resolves to. */\n defaultRls?: DefaultRls;\n}\n\n/**\n * Options of {@link loadBackendSchema}.\n *\n * @group Schema\n */\nexport interface LoadBackendSchemaOptions {\n /**\n * The project root, where a legacy `config/collections` directory would\n * be. Defaults to two levels above `dir` (`<root>/backend/schema`).\n * `false` skips that check — for a built bundle, whose layout the\n * manifest's format version already vouches for.\n */\n projectRoot?: string | false;\n /**\n * How a module of the directory is imported: the index and every sibling\n * module go through it. Defaults to a plain `import()`.\n *\n * The default is right wherever a loader already handles TypeScript — the\n * server under tsx, the stock runtime reading a compiled bundle, a test\n * runner. A CLI process is not running under a TypeScript loader, and a\n * schema module's relative imports are extensionless (`./users`), which\n * Node's own type stripping cannot resolve; such a caller passes an\n * importer that can (the CLI passes jiti). Whatever it returns must be the\n * module's namespace: the definitions are read off its exports.\n */\n importModule?: SchemaModuleImporter;\n}\n\n/**\n * A module importer for {@link LoadBackendSchemaOptions.importModule}: takes an\n * absolute file path, returns the module's exports.\n *\n * @group Schema\n */\nexport type SchemaModuleImporter = (file: string) => Promise<Record<string, unknown>>;\n\n/**\n * The schema directory could not be read: a module failed to import, the\n * project is still on the `config/collections` layout, or the index does not\n * export what its siblings define.\n *\n * Distinct from {@link SchemaDefinitionError}, which says a definition is\n * wrong; this says the files could not be turned into definitions at all.\n *\n * @group Schema\n */\nexport class SchemaLoadError extends Error {\n\n readonly code = \"SCHEMA_LOAD_FAILED\";\n\n constructor(\n message: string,\n /** The file the failure is about, absolute, when there is one. */\n readonly file?: string,\n options?: { cause?: unknown }\n ) {\n super(message, options);\n this.name = \"SchemaLoadError\";\n }\n}\n\n/**\n * Whether an error is a {@link SchemaLoadError}, from this copy of the package\n * or another.\n *\n * @group Schema\n */\nexport function isSchemaLoadError(error: unknown): error is SchemaLoadError {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"SCHEMA_LOAD_FAILED\";\n}\n\nasync function nativeImport(file: string): Promise<Record<string, unknown>> {\n // A plain import(), so the tsx loader (or the runtime's own resolution of a\n // compiled bundle) resolves `.ts` and workspace specifiers.\n return await import(pathToFileURL(file).href);\n}\n\nasync function importOrThrow(importModule: SchemaModuleImporter, file: string, role: string): Promise<Record<string, unknown>> {\n try {\n return await importModule(file);\n } catch (error) {\n throw new SchemaLoadError(\n `Could not import ${file} (${role}).\\n\\n` +\n `${error instanceof Error ? error.message : String(error)}\\n\\n` +\n \"Every module in backend/schema must import cleanly: a table that cannot be read is a route \" +\n \"without policies, or policies without a route. Fix the file, or delete it.\",\n file,\n { cause: error }\n );\n }\n}\n\n/** A legacy collection: a plain object with `properties`, the shape `defineCollection` returned. */\nfunction isLegacyCollection(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null || isTableDef(value) || isViewDef(value)) return false;\n if (!(\"properties\" in value) || typeof value.properties !== \"object\" || value.properties === null) return false;\n return (\"slug\" in value && typeof value.slug === \"string\") || (\"name\" in value && typeof value.name === \"string\");\n}\n\nfunction legacyLayoutError(what: string, file?: string): SchemaLoadError {\n return new SchemaLoadError(\n `${what}. This runtime reads tables from backend/schema (\\`defineTable\\`, \\`defineAuthTable\\`, ` +\n `\\`defineView\\`); \\`defineCollection\\` and config/collections are no longer read. To migrate: ` +\n `${LEGACY_LAYOUT_REMEDY}.`,\n file\n );\n}\n\n/** Every module file under `dir` other than its index, depth first, sorted, for a stable error order. */\nfunction siblingModules(dir: string): string[] {\n const out: string[] = [];\n const walk = (current: string, top: boolean): void => {\n const entries = fs.readdirSync(current, { withFileTypes: true })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n for (const entry of entries) {\n // Dotfiles are never modules (macOS AppleDouble sidecars `._x.ts`\n // are binary blobs whose names end in .ts).\n if (entry.name.startsWith(\".\")) continue;\n const full = path.join(current, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\" || entry.name === \"__tests__\") continue;\n walk(full, false);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!MODULE_EXTENSIONS.some(ext => entry.name.endsWith(ext))) continue;\n if (/\\.d\\.[mc]?ts$/.test(entry.name) || /\\.(test|spec)\\./.test(entry.name)) continue;\n if (top && (INDEX_FILES as readonly string[]).includes(entry.name)) continue;\n out.push(full);\n }\n };\n walk(dir, true);\n return out;\n}\n\nfunction isDefaultRls(value: unknown): value is DefaultRls {\n return value === \"admin-only\" || (Array.isArray(value) && value.length > 0);\n}\n\n/**\n * Import a project's `backend/schema` directory.\n *\n * - Reads `<dir>/index.(ts|mts|js|mjs)` and collects every export that is a\n * `defineTable` / `defineAuthTable` / `defineView` result, and `defaultRls`.\n * - The index is authoritative: every other module under `dir` is imported\n * too, and one defining a table or view the index does not export is\n * refused. A table with policies generated but no route — or a route with\n * no policies — is the bug that prevents.\n * - A module that fails to import is a {@link SchemaLoadError} naming the file;\n * nothing is ever skipped.\n * - A project still on the legacy layout (a `config/collections` directory, or\n * `defineCollection` results exported) is refused with the codemod to run.\n * - Validates by compiling: every problem with every definition (no `rls`,\n * `rls: []`, `\"inherit\"` without `defaultRls`, no primary key, a relation to\n * a table that is not exported…) is thrown together as one\n * {@link SchemaDefinitionError}.\n *\n * Returns the definitions, not lowered: see {@link compileLoadedSchema}. A\n * directory that does not exist, or has no index, declares no tables\n * (`defs: []`) — unless a sibling module defines one.\n *\n * @group Schema\n */\nexport async function loadBackendSchema(dir: string, options: LoadBackendSchemaOptions = {}): Promise<LoadedSchema> {\n const resolved = path.resolve(dir);\n const importModule = options.importModule ?? nativeImport;\n\n if (resolved.split(path.sep).join(\"/\").endsWith(\"/config/collections\")) {\n throw legacyLayoutError(`${resolved} is a config/collections directory`, resolved);\n }\n if (options.projectRoot !== false) {\n const projectRoot = path.resolve(options.projectRoot ?? path.join(resolved, \"..\", \"..\"));\n const legacyDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(legacyDir) && fs.statSync(legacyDir).isDirectory()) {\n throw legacyLayoutError(`The project still has ${legacyDir}`, legacyDir);\n }\n }\n\n if (!fs.existsSync(resolved)) {\n return { dir: resolved, indexFile: \"\", defs: [] };\n }\n if (!fs.statSync(resolved).isDirectory()) {\n throw new SchemaLoadError(\n `${resolved} is a file. The schema is a directory whose index exports the tables: point at backend/schema.`,\n resolved\n );\n }\n\n const indexName = INDEX_FILES.find(name => fs.existsSync(path.join(resolved, name)));\n const indexFile = indexName ? path.join(resolved, indexName) : \"\";\n\n const defs: (AnyTableDef | AnyViewDef)[] = [];\n let defaultRls: DefaultRls | undefined;\n if (indexFile) {\n const mod = await importOrThrow(importModule, indexFile, \"the schema index\");\n for (const [name, value] of Object.entries(mod)) {\n if (isTableDef(value) || isViewDef(value)) {\n if (!defs.includes(value)) defs.push(value);\n continue;\n }\n if (name === \"defaultRls\") {\n if (value !== undefined && !isDefaultRls(value)) {\n throw new SchemaDefinitionError([{\n table: \"defaultRls\",\n message:\n `exported from ${indexFile} is ${JSON.stringify(value)}. It must be \\`\"admin-only\"\\` or a ` +\n \"non-empty list of rules — what every `rls: \\\"inherit\\\"` table takes. (`\\\"inherit\\\"` and `[]` \" +\n \"are not postures a default can have.)\"\n }]);\n }\n if (value !== undefined) defaultRls = value;\n continue;\n }\n if (isLegacyCollection(value) || ((name === \"collections\" || name === \"backendCollections\") && Array.isArray(value))) {\n throw legacyLayoutError(`${indexFile} exports \\`${name}\\`, a collection`, indexFile);\n }\n }\n }\n\n // The index is authoritative: a definition anywhere else that it does not\n // export is refused, every one of them reported at once.\n const exported = new Set<unknown>(defs);\n const exportedNames = new Set(defs.map(def => `${def.brand}:${def.name}`));\n const problems: SchemaDefinitionProblem[] = [];\n for (const file of siblingModules(resolved)) {\n const mod = await importOrThrow(importModule, file, \"a schema module\");\n const relative = path.relative(resolved, file);\n for (const [name, value] of Object.entries(mod)) {\n if (isLegacyCollection(value)) {\n throw legacyLayoutError(`${file} exports \\`${name}\\`, a collection (\\`defineCollection\\`)`, file);\n }\n if (!isTableDef(value) && !isViewDef(value)) continue;\n // The same object reached twice through two module instances is\n // still the exported definition; match those by kind and name.\n if (exported.has(value) || exportedNames.has(`${value.brand}:${value.name}`)) continue;\n const kind = isViewDef(value) ? \"view\" : \"table\";\n problems.push({\n table: value.name,\n message:\n `is a ${kind} defined in ${relative} (export \\`${name}\\`) that ${indexFile ? path.basename(indexFile) : \"no index\"} ` +\n `does not export. Only what backend/schema/index exports is served and protected: add ` +\n `\\`export { ${name} } from \"./${relative.replace(/\\.[mc]?[jt]s$/, \"\")}\";\\` to the index, or delete the definition.`\n });\n }\n }\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n\n // Fail closed, for every caller: compiling is the validation.\n compileTables(defs, defaultRls !== undefined ? { defaultRls } : {});\n\n return { dir: resolved, indexFile, defs, ...(defaultRls !== undefined ? { defaultRls } : {}) };\n}\n\n/**\n * A loaded schema compiled, the same way for every caller.\n *\n * @group Schema\n */\nexport interface CompiledSchema {\n /**\n * The compiled tables, in definition order: each descriptor with its\n * hooks, field-level hooks and definition. What the data driver runs on.\n */\n tables: CompiledTable[];\n /** The descriptors, in definition order: `tables[i].descriptor`. */\n descriptors: TableDescriptor[];\n}\n\n/**\n * Compile table and view definitions to {@link CompiledSchema.tables} and their\n * descriptors. Boot, the runtime and the CLI all compile through this.\n *\n * @group Schema\n */\nexport function compileSchemaDefs(\n defs: readonly (AnyTableDef | AnyViewDef)[],\n defaultRls?: DefaultRls\n): CompiledSchema {\n const options = defaultRls !== undefined ? { defaultRls } : {};\n const tables = compileSchema(defs, options);\n return { tables, descriptors: tables.map(table => table.descriptor) };\n}\n\n/**\n * {@link compileSchemaDefs} over what {@link loadBackendSchema} returned.\n *\n * @group Schema\n */\nexport function compileLoadedSchema(loaded: LoadedSchema): CompiledSchema {\n return compileSchemaDefs(loaded.defs, loaded.defaultRls);\n}\n"],"mappings":";;;;;;;;;;;;;AACA,IAAa,4BAA4B;;;;;;;;;;;;;ACuBzC,IAAa,wBAAb,MAAa,8BAA8B,MAAM;CAMhC;CAJb,OAAgB;CAEhB,YAEI,UACF;EACE,MAAM,sBAAsB,SAAS,QAAQ,CAAC;EAFrC,KAAA,WAAA;EAGT,KAAK,OAAO;CAChB;CAEA,OAAe,SAAS,UAAsD;EAC1E,MAAM,QAAQ,SAAS,KAAI,YAAW;GAElC,OAAO,OADO,QAAQ,MAAM,GAAG,QAAQ,MAAM,GAAG,QAAQ,QAAQ,QAAQ,MACpD,IAAI,QAAQ;EACpC,CAAC;EAED,OAAO,8BADO,SAAS,WAAW,IAAI,cAAc,GAAG,S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CAC1C,OAAO;EAAE;EAAQ,aAAa,OAAO,KAAI,UAAS,MAAM,UAAU;CAAE;AACxE;;;;;;AAOA,SAAgB,oBAAoB,QAAsC;CACtE,OAAO,kBAAkB,OAAO,MAAM,OAAO,UAAU;AAC3D"}
|
|
1
|
+
{"version":3,"file":"load-schema-CSEXeduP.js","names":[],"sources":["../../common/src/collections/soft-delete.ts","../../common/src/schema/errors.ts","../../common/src/schema/derive-names.ts","../../common/src/schema/resolve-rls.ts","../../common/src/schema/custom-sql-type.ts","../../common/src/schema/validate-tables.ts","../../common/src/schema/compile-tables.ts","../../common/src/schema/compile-schema.ts","../src/schema/load-schema.ts"],"sourcesContent":["/** The field `softDelete: true` means, when the object form names none. */\nexport const DEFAULT_SOFT_DELETE_FIELD = \"deletedAt\";\n","/**\n * What is wrong with one table definition.\n *\n * @group Schema\n */\nexport interface SchemaDefinitionProblem {\n /** The table (or view) the problem is in, by the name it was defined under. */\n table: string;\n /** The column or relation key, when the problem is about one. */\n key?: string;\n /** What is wrong and what to write instead. */\n message: string;\n}\n\n/**\n * A schema that cannot be compiled.\n *\n * Thrown by every door that reads `backend/schema` — `rebase db generate`,\n * `db push`, the doctor and server boot — so a definition that would leave a\n * table unprotected or unservable stops all of them the same way. Carries every\n * problem found, not only the first.\n *\n * @group Schema\n */\nexport class SchemaDefinitionError extends Error {\n\n readonly code = \"SCHEMA_DEFINITION_INVALID\";\n\n constructor(\n /** Every problem found, in declaration order. */\n readonly problems: readonly SchemaDefinitionProblem[]\n ) {\n super(SchemaDefinitionError.describe(problems));\n this.name = \"SchemaDefinitionError\";\n }\n\n private static describe(problems: readonly SchemaDefinitionProblem[]): string {\n const lines = problems.map(problem => {\n const where = problem.key ? `${problem.table}.${problem.key}` : problem.table;\n return ` - ${where}: ${problem.message}`;\n });\n const count = problems.length === 1 ? \"1 problem\" : `${problems.length} problems`;\n return `The schema cannot be used (${count}):\\n${lines.join(\"\\n\")}`;\n }\n}\n\n/**\n * Whether an error is a {@link SchemaDefinitionError}, from this copy of the\n * package or another.\n *\n * @group Schema\n */\nexport function isSchemaDefinitionError(error: unknown): error is SchemaDefinitionError {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"SCHEMA_DEFINITION_INVALID\";\n}\n","import type { ColumnDef, ColumnType, JoinStep } from \"@rebasepro/types\";\nimport { generateForeignKeyName, toSnakeCase, toWireKey } from \"@rebasepro/utils\";\n\n/**\n * Every name the schema compiler derives, in one place.\n *\n * Each rule here is the rule today's collection pipeline applies — a deployed\n * database must not see one identifier move when its collections become\n * `defineTable`s. Where the legacy rule lives in a helper that takes a\n * `CollectionConfig` (`resolveRelation`, `getTableName`), it is mirrored here\n * over plain inputs, and `test/schema/compile-names.test.ts` feeds both the\n * same tables and compares.\n */\n\n/** The Postgres schema a table lives in when it names none. */\nexport const DEFAULT_TABLE_SCHEMA = \"public\";\n\n/** The schema a junction table is always created in, whatever its endpoints declare. */\nexport const JUNCTION_TABLE_SCHEMA = \"public\";\n\n/**\n * The SQL table of a `defineTable(name, …)`: `table` when given, else the name\n * it was defined under.\n *\n * @group Schema\n */\nexport function deriveTableName(name: string, table: string | undefined): string {\n return table ?? name;\n}\n\n/**\n * The API slug of a `defineTable(name, …)`: `slug` when given, else the name.\n *\n * @group Schema\n */\nexport function deriveSlug(name: string, slug: string | undefined): string {\n return slug ?? name;\n}\n\n/**\n * The Postgres schema of a table: `schema` when given, else `public`.\n *\n * @group Schema\n */\nexport function deriveSchemaName(schema: string | undefined): string {\n return schema ?? DEFAULT_TABLE_SCHEMA;\n}\n\n/**\n * The SQL column of a `columns` entry: `.column(name)` when given, else the\n * snake_case of its key.\n *\n * `toSnakeCase` tokenises on case boundaries and drops every separator, so\n * `__order` becomes `order` and `photoURL` becomes `photo_url` — exactly the\n * column today's planner gives the same property.\n *\n * @group Schema\n */\nexport function deriveColumnName(key: string, def: Pick<ColumnDef, \"column\">): string {\n return def.column ?? toSnakeCase(key);\n}\n\n/**\n * The foreign-key column of a `belongsTo`: `localKey` when given, else\n * `<singular relation name>_id`.\n *\n * @group Schema\n */\nexport function deriveBelongsToLocalKey(relationName: string, localKey: string | undefined): string {\n return localKey ?? generateForeignKeyName(relationName);\n}\n\n/**\n * The row key a derived foreign-key column is served under: the camelCase of\n * its column (`author_id` → `authorId`).\n *\n * @group Schema\n */\nexport function deriveForeignKeyField(localKey: string): string {\n return toWireKey(localKey);\n}\n\n/**\n * The column on the target of a `hasOne` / `hasMany` that points back:\n * `foreignKey` when given, else `<singular source slug>_id`.\n *\n * @group Schema\n */\nexport function deriveTargetForeignKey(sourceSlug: string, foreignKey: string | undefined): string {\n return foreignKey ?? generateForeignKeyName(toSnakeCase(sourceSlug));\n}\n\n/**\n * The junction table of a `manyToMany`: `through` when given, else the two\n * SQL table names sorted and joined by `_`, so both sides of one link derive\n * the same table without agreeing in advance.\n *\n * @group Schema\n */\nexport function deriveJunctionTable(sourceTable: string, targetTable: string, through: string | undefined): string {\n return through ?? [sourceTable, targetTable].sort().join(\"_\");\n}\n\n/**\n * The junction column pointing at the declaring table: `sourceKey` when given,\n * else `<singular source slug>_id`.\n *\n * @group Schema\n */\nexport function deriveJunctionSourceKey(sourceSlug: string, sourceKey: string | undefined): string {\n return sourceKey ?? generateForeignKeyName(toSnakeCase(sourceSlug));\n}\n\n/**\n * The junction column pointing at the target: `targetKey` when given, else\n * `<singular relation name>_id`.\n *\n * @group Schema\n */\nexport function deriveJunctionTargetKey(relationName: string, targetKey: string | undefined): string {\n return targetKey ?? generateForeignKeyName(relationName);\n}\n\n/**\n * The type a column pointing at a primary key must have: the key's own type,\n * except that a serial key's sequence is not copied — a column referencing a\n * `serial` is the plain `integer` of the same width.\n *\n * An enum key is referenced by its own enum type, so the referencing column\n * names the type the key's table created rather than deriving one of its own.\n *\n * @param keyTable The SQL table the key belongs to, which names an enum type\n * declared without an explicit `name`.\n * @param keyColumn The key's SQL column, for the same reason.\n *\n * @group Schema\n */\nexport function deriveReferencingType(keyType: ColumnType, keyTable: string, keyColumn: string): ColumnType {\n switch (keyType.kind) {\n case \"smallserial\": return { kind: \"smallint\" };\n case \"serial\": return { kind: \"integer\" };\n case \"bigserial\": return { kind: \"bigint\" };\n case \"enum\": return { kind: \"enum\", values: [...keyType.values], name: keyType.name ?? `${keyTable}_${keyColumn}` };\n default: return keyType;\n }\n}\n\n/**\n * The name of the Postgres enum type an enum column uses: its explicit `name`,\n * else `<table>_<column>`.\n *\n * @group Schema\n */\nexport function deriveEnumTypeName(type: Extract<ColumnType, { kind: \"enum\" }>, table: string, column: string): string {\n return type.name ?? `${table}_${column}`;\n}\n\n/**\n * Whether a `via` chain can be written through: a to-one chain of one step, or\n * a to-many chain of two steps through one table between the ends — and every\n * step joins on one condition.\n *\n * The same answer `resolveRelation` gives a legacy `via` relation.\n *\n * @group Schema\n */\nexport function deriveViaWritable(cardinality: \"one\" | \"many\", steps: readonly Pick<JoinStep, \"table\" | \"on\">[]): boolean {\n if (steps.some(step => Array.isArray(step.on) && step.on.length !== 1)) return false;\n if (cardinality === \"one\") return steps.length === 1;\n return steps.length === 2 && steps[0].table !== steps[1].table;\n}\n","import type { DefaultRls, RlsDescriptor, RlsPosture, SecurityRule } from \"@rebasepro/types\";\n\n/**\n * What {@link resolveRls} returns: the resolved posture, or why there is none.\n *\n * @group Schema\n */\nexport type RlsResolution =\n | { ok: true; rls: RlsDescriptor }\n | { ok: false; message: string };\n\n/**\n * A table's `rls` (and `defaultPolicies`) resolved against the project's\n * `defaultRls`.\n *\n * - `\"admin-only\"` → `{ posture: \"admin-only\", rules: [], defaultPolicies: true }`.\n * - a list → `{ posture: \"rules\", rules, defaultPolicies }`, the rules exactly\n * as written: a policy's name is a hash of its rule, so a rule is never\n * reordered, copied key by key or normalized.\n * - `\"inherit\"` → the project's `defaultRls`, resolved the same way and marked\n * `inherited`.\n *\n * Refused, never defaulted: a missing or empty posture, `\"inherit\"` without a\n * `defaultRls`, and `\"admin-only\"` (written or inherited) beside\n * `defaultPolicies: false`, which would leave the table readable by nobody at\n * all — not even the admins it is locked to.\n *\n * @param posture What the table wrote. Typed `unknown` because a JavaScript\n * caller, or a cast, can hand over anything; every shape is checked here.\n *\n * @group Schema\n */\nexport function resolveRls(\n posture: RlsPosture | unknown,\n defaultPolicies: boolean | undefined,\n defaultRls: DefaultRls | undefined\n): RlsResolution {\n if (posture === \"inherit\") {\n if (defaultRls === undefined) {\n return {\n ok: false,\n message:\n \"`rls: \\\"inherit\\\"` takes the project's `defaultRls`, and none was given. Export \" +\n \"`defaultRls` from backend/schema/index.ts (`\\\"admin-only\\\"` or a list of rules), or write \" +\n \"this table's own `rls`.\"\n };\n }\n const inherited = resolveRls(defaultRls, defaultPolicies, undefined);\n if (!inherited.ok) {\n return { ok: false, message: `\\`rls: \"inherit\"\\` resolves to the project's \\`defaultRls\\`, which is unusable: ${inherited.message}` };\n }\n return { ok: true, rls: { ...inherited.rls, inherited: true } };\n }\n if (posture === \"admin-only\") {\n if (defaultPolicies === false) {\n return {\n ok: false,\n message:\n \"`rls: \\\"admin-only\\\"` with `defaultPolicies: false` grants nobody anything: \\\"admin-only\\\" \" +\n \"is exactly the injected admin baseline, and `defaultPolicies: false` removes it. Drop \" +\n \"`defaultPolicies: false`, or replace \\\"admin-only\\\" with the rules that should apply.\"\n };\n }\n return { ok: true, rls: { posture: \"admin-only\", rules: [], defaultPolicies: true, ...(defaultPolicies === true ? { declaredDefaultPolicies: true } : {}) } };\n }\n if (Array.isArray(posture)) {\n if (posture.length === 0) {\n return {\n ok: false,\n message:\n \"`rls: []` grants nothing and says nothing. Write `rls: \\\"admin-only\\\"` to lock the table \" +\n \"to admins, or list the rules that grant access.\"\n };\n }\n const rules: SecurityRule[] = [];\n for (const rule of posture) {\n if (typeof rule !== \"object\" || rule === null) {\n return { ok: false, message: \"every entry of `rls` must be a security rule object.\" };\n }\n if (\"redacted\" in rule) {\n return {\n ok: false,\n message:\n \"an entry of `rls` carries `redacted`, the marker `GET /api/schema/tables` serves in place of a \" +\n \"rule whose SQL it withheld. It describes a policy and cannot become one: write the rule itself.\"\n };\n }\n rules.push(rule);\n }\n return { ok: true, rls: { posture: \"rules\", rules, defaultPolicies: defaultPolicies !== false, ...(defaultPolicies === true ? { declaredDefaultPolicies: true } : {}) } };\n }\n return {\n ok: false,\n message:\n \"the table has no usable `rls`. Every table needs an explicit row-level security posture: \" +\n \"`\\\"admin-only\\\"`, `\\\"inherit\\\"` (the `defaultRls` exported from backend/schema/index.ts), or a \" +\n \"non-empty list of rules.\"\n };\n}\n\n// ── Rule shape ───────────────────────────────────────────────────────────────\n\n/** The clause keys of a rule whose combinations the `SecurityRule` union restricts. */\ntype RuleClauseKey = \"ownerField\" | \"access\" | \"using\" | \"withCheck\" | \"condition\" | \"check\";\n\n/**\n * Every pair of clauses the `SecurityRule` union excludes, read off its\n * variants' `never` fields:\n *\n * - `OwnerSecurityRule`: `ownerField` excludes `access`, `using`, `withCheck`,\n * `condition` and `check`;\n * - `PublicSecurityRule` / `AuthenticatedSecurityRule` /\n * `RegisteredSecurityRule` / `ConditionalAccessSecurityRule` /\n * `CheckedAccessSecurityRule`: `access` excludes `ownerField`, `using` and\n * `withCheck` (it combines with `condition` / `check`);\n * - `StructuredSecurityRule`: `condition` / `check` exclude `ownerField`,\n * `using` and `withCheck`;\n * - `RawSQLSecurityRule` / `RawSQLCheckOnlySecurityRule`: `using` /\n * `withCheck` exclude `ownerField`, `access`, `condition` and `check`.\n *\n * `roles`, `mode`, `pgRoles`, `name` and `operation(s)` combine with all of\n * them (`roles` is ANDed on).\n */\nconst EXCLUDED_PAIRS: readonly (readonly [RuleClauseKey, RuleClauseKey])[] = [\n [\"access\", \"ownerField\"],\n [\"access\", \"using\"],\n [\"access\", \"withCheck\"],\n [\"ownerField\", \"using\"],\n [\"ownerField\", \"withCheck\"],\n [\"ownerField\", \"condition\"],\n [\"ownerField\", \"check\"],\n [\"condition\", \"using\"],\n [\"condition\", \"withCheck\"],\n [\"check\", \"using\"],\n [\"check\", \"withCheck\"]\n];\n\nconst ACCESS_VALUES: readonly unknown[] = [\"public\", \"authenticated\", \"registered\"];\nconst MODE_VALUES: readonly unknown[] = [\"permissive\", \"restrictive\"];\nconst OPERATION_VALUES: readonly unknown[] = [\"select\", \"insert\", \"update\", \"delete\", \"all\"];\n\n/** Whether a rule carries a clause: present and not `null`/`undefined` (what the policy compiler tests). */\nfunction carries(rule: object, key: RuleClauseKey): boolean {\n const value: unknown = Reflect.get(rule, key);\n return value !== undefined && value !== null && value !== \"\";\n}\n\n/** The pairs of clauses a rule carries that the `SecurityRule` union excludes. */\nexport function excludedClausePairs(rule: object): (readonly [RuleClauseKey, RuleClauseKey])[] {\n return EXCLUDED_PAIRS.filter(([a, b]) => carries(rule, a) && carries(rule, b));\n}\n\n/** The remedy for one excluded pair: what to write instead. */\nfunction remedyFor(a: RuleClauseKey, b: RuleClauseKey): string {\n const pair = new Set([a, b]);\n if (pair.has(\"access\") && pair.has(\"ownerField\")) {\n return \"For rows the caller owns, write `{ ownerField }` alone. To grant the `access` callers the rows that \" +\n \"match a test, write `access` with a `condition` (`condition: policy.compare(policy.field(\\\"<column>\\\"), \\\"eq\\\", policy.authUid())` \" +\n \"is the owner test as a condition).\";\n }\n if (pair.has(\"access\")) {\n return \"Raw SQL carries no `access` gate: write `access` with a structured `condition` / `check`, or put the \" +\n \"caller test into the SQL (`rebase.uid()`), without `access`.\";\n }\n if (pair.has(\"ownerField\")) {\n return \"Write the owner test into the other clause (`policy.compare(policy.field(\\\"<column>\\\"), \\\"eq\\\", \" +\n \"policy.authUid())` in a `condition`, or `<column> = rebase.uid()` in raw SQL), or split it into two rules.\";\n }\n return \"Write the whole test in one form: a structured `condition` / `check`, or raw `using` / `withCheck`.\";\n}\n\n/**\n * What is wrong with one rule's shape, independent of the table's columns:\n * clauses the `SecurityRule` union excludes from each other (see\n * {@link excludedClausePairs}), and an `access`, `mode`, `operation`,\n * `operations` or `roles` value the type does not allow.\n *\n * Refused rather than resolved: the policy compiler used to pick one clause\n * of such a rule by the order of its checks, so `{ access: \"authenticated\",\n * ownerField }` compiled to \"every signed-in caller\" and dropped the owner\n * test, and a misspelt `mode: \"restricitve\"` compiled to a permissive policy.\n *\n * @param label How the message names the rule (`rule #2`, `rule \"owner_read\"`).\n *\n * @group Schema\n */\nexport function ruleShapeProblems(rule: object, label: string): string[] {\n const problems: string[] = [];\n for (const [a, b] of excludedClausePairs(rule)) {\n problems.push(`${label} combines \\`${a}\\` with \\`${b}\\`, which the SecurityRule type does not allow: a policy ` +\n `cannot honour both, and a policy that honours one widens the other. ${remedyFor(a, b)}`);\n }\n const access: unknown = Reflect.get(rule, \"access\");\n if (access !== undefined && !ACCESS_VALUES.includes(access)) {\n problems.push(`${label} has \\`access: ${JSON.stringify(access)}\\`. \\`access\\` is \"public\", \"authenticated\" ` +\n \"(any signed-in caller, guests included) or \\\"registered\\\" (a signed-in caller with an account).\");\n }\n const mode: unknown = Reflect.get(rule, \"mode\");\n if (mode !== undefined && !MODE_VALUES.includes(mode)) {\n problems.push(`${label} has \\`mode: ${JSON.stringify(mode)}\\`, which would compile as \"permissive\". ` +\n \"Write \\\"permissive\\\" (the default: any passing rule grants) or \\\"restrictive\\\" (every one must pass).\");\n }\n const operation: unknown = Reflect.get(rule, \"operation\");\n if (operation !== undefined && !OPERATION_VALUES.includes(operation)) {\n problems.push(`${label} has \\`operation: ${JSON.stringify(operation)}\\`. Write one of \"select\", \"insert\", ` +\n \"\\\"update\\\", \\\"delete\\\" or \\\"all\\\".\");\n }\n const operations: unknown = Reflect.get(rule, \"operations\");\n if (operations !== undefined && (!Array.isArray(operations) || operations.some(op => !OPERATION_VALUES.includes(op)))) {\n problems.push(`${label} has \\`operations: ${JSON.stringify(operations)}\\`. Write a list of \"select\", ` +\n \"\\\"insert\\\", \\\"update\\\", \\\"delete\\\" and \\\"all\\\".\");\n }\n const roles: unknown = Reflect.get(rule, \"roles\");\n if (roles !== undefined && (!Array.isArray(roles) || roles.some(role => typeof role !== \"string\"))) {\n problems.push(`${label} has \\`roles: ${JSON.stringify(roles)}\\`. \\`roles\\` is a list of application role ` +\n \"names, such as `[\\\"editor\\\"]`.\");\n }\n return problems;\n}\n\n/**\n * What a legacy rule's clause compiled to before tables replaced collections,\n * when the policy compiler resolved the first match of `condition`, `using`,\n * `access: \"public\"`, `ownerField` and ignored the rest (`access:\n * \"authenticated\"` was no value it knew).\n */\nfunction legacyClauseMeaning(rule: object, clause: \"using\" | \"withCheck\"): string {\n if (clause === \"withCheck\") {\n if (carries(rule, \"check\")) return \"its structured `check`\";\n if (carries(rule, \"withCheck\")) return \"its raw `withCheck` SQL\";\n }\n if (carries(rule, \"condition\")) return \"its structured `condition`\";\n if (carries(rule, \"using\")) return \"its raw `using` SQL\";\n if (Reflect.get(rule, \"access\") === \"public\") return \"every caller (`access: \\\"public\\\"`)\";\n if (carries(rule, \"ownerField\")) return `owner-only rows (\\`${String(Reflect.get(rule, \"ownerField\"))} = rebase.uid()\\`)`;\n return \"nothing (a policy that grants no row)\";\n}\n\n/**\n * Why a legacy collection rule cannot be carried to a table as written, or\n * `undefined` when it can. What `rebase migrate collections-to-tables`\n * refuses so that a migration never resolves a rule to a different clause\n * than it compiled to: every combination {@link ruleShapeProblems} refuses,\n * with what the rule meant on the previous version (whichever clause its\n * compiler checked first) and what to write to keep that.\n *\n * @group Schema\n */\nexport function legacyRuleRefusal(rule: object, label: string): string | undefined {\n const shape = ruleShapeProblems(rule, label);\n if (shape.length === 0) return undefined;\n const using = legacyClauseMeaning(rule, \"using\");\n const withCheck = legacyClauseMeaning(rule, \"withCheck\");\n const meant = using === withCheck\n ? `On the previous version this rule granted ${using}.`\n : `On the previous version this rule's USING granted ${using} and its WITH CHECK ${withCheck}.`;\n return `${shape.join(\" \")} ${meant} Write that clause alone — \\`{ ownerField }\\` for owner-only rows, or ` +\n \"`access` with a `condition` to grant those callers the rows that match it — and migrate again.\";\n}\n\n/** The operations a legacy rule applies to — `operations` wins over `operation`, `\"all\"` by default. */\nfunction legacyOperations(rule: object): string[] {\n const operations: unknown = Reflect.get(rule, \"operations\");\n if (Array.isArray(operations) && operations.length > 0) return operations.filter((op): op is string => typeof op === \"string\");\n const operation: unknown = Reflect.get(rule, \"operation\");\n return [typeof operation === \"string\" ? operation : \"all\"];\n}\n\n/**\n * The roles a caller who is not signed in holds: an anonymous request carries\n * `anon`, and a rule naming `public` matches every caller.\n */\nconst ROLES_WITHOUT_SIGN_IN = [\"anon\", \"public\"];\n\n/**\n * How a legacy rule that is carried as written compiles to a different\n * policy than it did on the previous version, or `undefined` when it does not.\n *\n * The previous compiler read `condition`, else `using`, else `access:\n * \"public\"`, else `ownerField` for USING (`check`, else `withCheck`, else the\n * same for WITH CHECK), ANDed `roles` on (a restrictive rule: `NOT roles OR\n * clause`, or `NOT roles` alone), and knew no other `access` value. The\n * current one ANDs `access: \"authenticated\"` / `\"registered\"` onto every\n * clause, or makes it the clause when there is none. `\"public\"` meant `true`\n * on both. So, for a rule {@link legacyRuleRefusal} accepts with a gating\n * `access` (which excludes `ownerField` and raw SQL), each policy clause the\n * rule's operations need is either:\n *\n * - **a clause it had** (`condition`, or `check` for WITH CHECK): `X` became\n * `access AND X` — a narrowing, felt by whoever passes `X` without passing\n * `access`. With `roles`, only a role holder who fails `access` feels it: a\n * guest under `\"registered\"`, or a caller not signed in holding `anon` /\n * `public`; under `\"authenticated\"` with any other role, nobody;\n * - **no clause**: the previous policy had none — it granted nothing, or, for\n * a restrictive rule, denied every caller it applied to — and now has\n * `access`: a widening (permissive or restrictive, with or without\n * `roles`), except a permissive role grant (`roles` alone admitted the\n * holders), which only narrows as above.\n *\n * The verdict is per clause and the first change found is described,\n * widenings first. A policy's name never moves with this: it is a hash of the\n * rule as written. `test/schema/legacy-rule-meaning-sweep.test.ts` checks this\n * against the previous compiler over every combination of clauses.\n *\n * @group Schema\n */\nexport function legacyRuleMeaningChange(rule: object): string | undefined {\n const access: unknown = Reflect.get(rule, \"access\");\n // The previous compiler knew `\"public\"` (USING `true`, as now): every\n // shape it is accepted in compiles as it did.\n if (access === undefined || access === \"public\") return undefined;\n const rolesValue: unknown = Reflect.get(rule, \"roles\");\n const roles = Array.isArray(rolesValue) ? rolesValue.filter((role): role is string => typeof role === \"string\") : [];\n const hasRoles = roles.length > 0;\n const restrictive = Reflect.get(rule, \"mode\") === \"restrictive\";\n const hasCondition = carries(rule, \"condition\");\n const hasCheck = carries(rule, \"check\");\n const operations = legacyOperations(rule);\n const needsUsing = operations.some(op => op !== \"insert\");\n const needsWithCheck = operations.some(op => op !== \"select\" && op !== \"delete\");\n\n const accessText = `\\`access: ${JSON.stringify(access)}\\``;\n const signedIn = access === \"registered\"\n ? \"every signed-in caller with an account (guests excluded)\"\n : \"every signed-in caller, guests included\";\n const roleList = roles.map(role => JSON.stringify(role)).join(\", \");\n /** A holder of the roles who fails `access`: a guest under \"registered\", or a caller not signed in. */\n const holderMayFail = access === \"registered\" || roles.some(role => ROLES_WITHOUT_SIGN_IN.includes(role));\n const failingHolders = access === \"registered\"\n ? (roles.some(role => ROLES_WITHOUT_SIGN_IN.includes(role)) ? \"guests and callers who are not signed in\" : \"guests (anonymous sign-ins)\")\n : \"callers who are not signed in\";\n\n /** A holder of the roles who passes `access`: anyone holding a role a signed-in caller can hold. */\n const holderMayPass = roles.some(role => role !== \"anon\");\n\n // Per clause the operations need: whether the rule had one there, and so\n // whether `access` widened it (no clause before) or narrowed it.\n const clauses = [\n ...(needsUsing ? [hasCondition] : []),\n ...(needsWithCheck ? [hasCheck || hasCondition] : [])\n ].map(had => ({\n had,\n widens: !had && (hasRoles ? restrictive && holderMayPass : true),\n narrows: hasRoles ? holderMayFail && (had || !restrictive) : had\n }));\n\n // Widenings first: a clause the previous policy did not have.\n if (clauses.some(({ widens }) => widens)) {\n if (restrictive && hasRoles) {\n return `This restrictive rule gates the holders of ${roleList}. The previous version did not know ` +\n `${accessText}, so it denied them every row. Carried as written it now lets ${signedIn} among them ` +\n \"through. To keep denying them, drop `access` (a restrictive `{ roles }` rule alone denies its role holders).\";\n }\n if (restrictive) {\n return `${accessText} was not a value the previous version knew, so this restrictive rule passed nobody: it ` +\n `denied every caller. Carried as written it now lets ${signedIn} through. To keep denying everyone, write ` +\n \"the restriction as `condition: policy.false()`; to restrict to callers with an account, write `access: \\\"registered\\\"`.\";\n }\n if (hasCheck && !hasCondition) {\n return `This rule has a \\`check\\` and no \\`condition\\`: on the previous version it had no USING clause and ` +\n `granted no existing row for ${operations.join(\"/\")}. It now grants ${signedIn} every existing row. To ` +\n \"keep granting no existing row, make the rule `operation: \\\"insert\\\"`; to grant some, add a `condition`.\";\n }\n return `${accessText} was not a value the previous version knew, so this rule granted nothing. Carried as ` +\n `written it now admits ${signedIn}. To keep granting only callers with an account, write ` +\n \"`access: \\\"registered\\\"`; to keep granting nothing, remove the rule.\";\n }\n\n // Narrowings: `access` now ANDed onto what was there (or onto `roles`).\n if (!clauses.some(({ narrows }) => narrows)) return undefined;\n if (hasRoles && clauses.every(({ had }) => !had)) {\n return `${accessText} was not a value the previous version knew, so this rule admitted every holder of ` +\n `${roleList}. It now also requires ${signedIn}, so ${failingHolders} holding them are refused. To keep the ` +\n \"old meaning, drop `access`.\";\n }\n if (hasRoles) {\n return `${accessText} was ignored by the previous version, so this rule's clauses admitted every holder of ` +\n `${roleList} they matched. It now also requires ${signedIn}, so ${failingHolders} holding them are refused. ` +\n \"To keep the old meaning, drop `access`.\";\n }\n if (hasCondition) {\n return `${accessText} was ignored by the previous version, so this rule's \\`condition\\` admitted any caller, ` +\n `signed in or not. It now admits only ${signedIn} to the rows it matches. To keep the old meaning, write ` +\n \"`access: \\\"public\\\"` with the same condition.\";\n }\n return `${accessText} was ignored by the previous version, so any caller could insert a row matching this rule's ` +\n `\\`check\\`. It now admits only ${signedIn}. To keep the old meaning, write \\`access: \"public\"\\`.`;\n}\n","/**\n * What a `col.custom()` type may be: the shape of a Postgres type name, which\n * DDL writes verbatim. Shared by the compiler (`checkColumnDef`) and the\n * planner, which refuses it again for a definition no compiler checked.\n */\n\n// ── A custom type, as DDL may name it ────────────────────────────────────────\n\n/** One token of a type name: a word, a quoted identifier, `.`, a modifier list, `[]`. */\nconst CUSTOM_TYPE_TOKEN = /\\s*(?:([A-Za-z_][A-Za-z0-9_$]*)|(\"(?:[^\"]|\"\")+\")|(\\.)|(\\(\\s*[A-Za-z0-9_+\\-.]+\\s*(?:,\\s*[A-Za-z0-9_+\\-.]+\\s*)*\\))|(\\[\\d*\\]))/y;\n\n/**\n * Why a `col.custom(sqlType)` type cannot be written into DDL, or `undefined`\n * when it can.\n *\n * The type is written verbatim — into `CREATE TABLE`, `ADD COLUMN` and the\n * Drizzle file — so only the shape of a Postgres type name is accepted, and\n * nothing in it can end the statement or open a string:\n *\n * - words, separated by spaces (`timestamp without time zone`,\n * `double precision`), or double-quoted identifiers (`\"My Type\"`);\n * - one schema qualifier (`public.citext`, `\"geo\".\"point3\"`);\n * - a modifier list after a word, of words, numbers and signs separated by\n * commas (`geometry(Point, 4326)`, `numeric(10, 2)`, `timestamp(3)`);\n * - array brackets at the end (`inet[]`, `int4range[][]`, `text[3]`).\n *\n * Anything else is refused: a single quote, a semicolon, a comment, an\n * operator, an unbalanced bracket, more than 200 characters. A column clause\n * written after the name (`inet DEFAULT x`, `inet NOT NULL`) has the shape of\n * more words, so the words that begin one are refused by name.\n *\n * @group Schema\n *\n * @internal Shared with @rebasepro/server-postgres's planner; not part of the public API.\n */\nexport function customSqlTypeProblem(sqlType: string): string | undefined {\n const text = sqlType.trim();\n if (text.length === 0) return \"is empty\";\n if (text.length > 200) return \"is longer than 200 characters\";\n let state: \"start\" | \"name\" | \"dot\" | \"modified\" | \"array\" = \"start\";\n const words: string[] = [];\n CUSTOM_TYPE_TOKEN.lastIndex = 0;\n let position = 0;\n while (position < text.length) {\n CUSTOM_TYPE_TOKEN.lastIndex = position;\n const match = CUSTOM_TYPE_TOKEN.exec(text);\n if (!match || match[0].length === 0) return `cannot be read as a type name at \"${text.slice(position)}\"`;\n position = CUSTOM_TYPE_TOKEN.lastIndex;\n const [, word, quoted, dot, modifiers, brackets] = match;\n if (word !== undefined || quoted !== undefined) {\n if (state === \"array\") return \"has a word after its array brackets\";\n if (word !== undefined) words.push(word.toLowerCase());\n state = \"name\";\n } else if (dot !== undefined) {\n if (state !== \"name\") return \"has a `.` that does not separate a schema from a type\";\n state = \"dot\";\n } else if (modifiers !== undefined) {\n if (state !== \"name\") return \"has a modifier list that follows no type name\";\n state = \"modified\";\n } else if (brackets !== undefined) {\n if (state === \"start\" || state === \"dot\") return \"has array brackets that follow no type name\";\n state = \"array\";\n }\n }\n if (state === \"start\" || state === \"dot\") return \"ends without a type name\";\n const clause = words.find(word => CLAUSE_WORDS.has(word));\n if (clause !== undefined) return `holds \\`${clause}\\`, which starts a column clause, not a type`;\n return undefined;\n}\n\n/** Words that begin a column clause after a type — never part of a type name. */\nconst CLAUSE_WORDS: ReadonlySet<string> = new Set([\n \"default\", \"not\", \"null\", \"constraint\", \"references\", \"check\", \"unique\", \"primary\", \"generated\", \"collate\", \"using\"\n]);\n","import type {\n ColumnDef,\n ColumnType,\n ColumnValidation,\n JsonShapeDef,\n PolicyExpression,\n PolicyOperand,\n SecurityRule\n} from \"@rebasepro/types\";\nimport { columnTypeLabel } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\nimport { customSqlTypeProblem } from \"./custom-sql-type\";\nimport type { SchemaDefinitionProblem } from \"./errors\";\nimport { deriveEnumTypeName } from \"./derive-names\";\n\n/**\n * The column-level and rule-level checks of the schema compiler.\n *\n * Each returns the problems it found rather than throwing, so the compiler can\n * report every problem of every table at once. Messages name the column and\n * say what to write instead.\n */\n\nconst INTEGER_KINDS = new Set([\"smallint\", \"integer\", \"bigint\"]);\nconst TEMPORAL_KINDS = new Set([\"timestamptz\", \"date\", \"time\"]);\nconst USER_STAMP_KINDS = new Set([\"text\", \"varchar\", \"char\", \"uuid\"]);\nconst ONE_OF_KINDS = new Set([\n \"text\", \"varchar\", \"char\",\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"real\", \"doublePrecision\", \"numeric\"\n]);\n\n/**\n * Problems in one column's own definition: modifiers that contradict each\n * other or do not apply to its type, an unusable enum, a private key.\n *\n * The builders' types already refuse most of these; this is the runtime half,\n * for JavaScript callers and for a builder reached through a cast.\n *\n * @param table The name the table was defined under, for the problem.\n * @param key The column's key.\n * @param sqlColumn The column's SQL name.\n *\n * @group Schema\n */\nexport function checkColumnDef(\n table: string,\n key: string,\n def: ColumnDef,\n sqlColumn: string\n): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string) => problems.push({ table, key, message });\n const kind = def.type.kind;\n\n if (sqlColumn.length === 0) {\n refuse(`the key \"${key}\" has no snake_case form to name a SQL column with. Give it one as the builder's first argument: \\`col.text(\"…\")\\`.`);\n }\n if (def.generatedAs !== undefined) {\n if (def.default !== undefined) {\n refuse(\n \"`.generatedAlwaysAs()` and a default contradict each other: Postgres computes a generated column \" +\n \"on every write and refuses any default for it. Keep one of the two.\"\n );\n }\n if (def.stamp !== undefined) {\n refuse(\n \"`.generatedAlwaysAs()` and a stamp (`.onCreateNow()`, `.onUpdateUser()`, …) contradict each other: \" +\n \"nobody, not even the server, writes a generated column. Keep one of the two.\"\n );\n }\n }\n if (def.default?.kind === \"identity\" && !INTEGER_KINDS.has(kind)) {\n refuse(`\\`.generatedByDefaultAsIdentity()\\` needs a \\`smallint\\`, \\`integer\\` or \\`bigint\\` column, and this one is \\`${columnTypeLabel(def.type)}\\`.`);\n }\n if (def.default?.kind === \"random-uuid\" && kind !== \"uuid\") {\n refuse(\n `\\`.defaultRandom()\\` writes \\`gen_random_uuid()\\`, which needs a \\`uuid\\` column, and this one is ` +\n `\\`${columnTypeLabel(def.type)}\\`. Use \\`col.uuid()\\`, or \\`.default(sql\\`gen_random_uuid()::text\\`)\\`.`\n );\n }\n if (def.stamp?.value === \"now\" && !TEMPORAL_KINDS.has(kind)) {\n refuse(\n `\\`.${def.stamp.on === \"create\" ? \"onCreateNow\" : \"onUpdateNow\"}()\\` stamps the current time, which ` +\n `needs a \\`timestamptz\\`, \\`date\\` or \\`time\\` column, and this one is \\`${columnTypeLabel(def.type)}\\`.`\n );\n }\n if (def.stamp?.value === \"user\" && !USER_STAMP_KINDS.has(kind)) {\n refuse(\n `\\`.${def.stamp.on === \"create\" ? \"onCreateUser\" : \"onUpdateUser\"}()\\` stores the caller's id, which ` +\n `needs a text or \\`uuid\\` column, and this one is \\`${columnTypeLabel(def.type)}\\`.`\n );\n }\n if (def.private && def.primaryKey) {\n refuse(\n \"a primary-key column cannot be `.private()`: the key is how every row is addressed on the wire — \" +\n \"in URLs, in relations, in realtime events. Drop `.private()`, or key the table on another column.\"\n );\n }\n if (def.primaryKey && (kind === \"timestamptz\" || kind === \"time\")) {\n refuse(\n `a \\`${kind}\\` column cannot be part of the key: an instant addressed by its text is not a stable ` +\n \"address. Key on a `date` (a calendar day the caller supplies), a string or a number, and keep the \" +\n \"timestamp beside it.\"\n );\n }\n const keyProblem = def.primaryKey ? keyTypeProblem(def.type, def.semantic) : undefined;\n if (keyProblem !== undefined) refuse(keyProblem);\n if (def.private && def.access !== undefined) {\n refuse(\n \"`.private()` and `.access()` contradict each other: a private column is never served to or written \" +\n \"by a client, so access rules say nothing. Drop one of the two.\"\n );\n }\n if (def.transform !== undefined && def.json?.transform !== undefined) {\n refuse(\n \"declares a `.transform()` on the column and another on its JSON shape. They are the same hook on the \" +\n \"same value, and only one would run: keep one of the two.\"\n );\n }\n if (kind === \"array\") {\n const elementProblem = arrayElementProblem(def.type.of, def.element?.semantic);\n if (elementProblem !== undefined) refuse(elementProblem);\n }\n for (const problem of unsupportedRules(def)) refuse(problem);\n if (def.oneOf !== undefined && !ONE_OF_KINDS.has(kind)) {\n refuse(`\\`.oneOf()\\` takes a text or numeric column, and this one is \\`${columnTypeLabel(def.type)}\\`. Use \\`col.enum([...])\\` for a Postgres enum.`);\n }\n if (def.oneOf !== undefined && def.oneOf.length === 0) {\n refuse(\"`.oneOf([])` accepts no value at all. List the accepted values, or drop `.oneOf()`.\");\n }\n problems.push(...checkColumnType(table, key, def.type));\n if (def.type.kind === \"enum\" && def.default?.kind === \"literal\" && !def.type.values.includes(String(def.default.value))) {\n refuse(\n `the default ${JSON.stringify(def.default.value)} is not one of the enum's values ` +\n `(${def.type.values.join(\", \")}). Postgres refuses the DEFAULT. Default to one of them.`\n );\n }\n if (def.element) {\n if (def.element.oneOf !== undefined && def.element.oneOf.length === 0) {\n refuse(\"the array's items take `.oneOf([])`, which accepts no value at all. List the accepted values.\");\n }\n const columnOnly = elementColumnModifiers(def.element);\n if (columnOnly.length > 0) {\n refuse(\n `the array's items declare ${columnOnly.join(\", \")}, which apply to a column, not to the items of one. ` +\n \"An item takes `.validate()`, `.oneOf()`, storage, `.userId()`, `.describe()` and `.transform()`; put a \" +\n \"default, `.notNull()`, `.unique()`, access, a stamp or `.private()` on the array column itself.\"\n );\n }\n }\n return problems;\n}\n\n/**\n * The modifiers an array's item declares that only a column can carry: a\n * default, nullability, a key, uniqueness, generation, access, privacy, a\n * stamp, a JSON shape, a vector index. The item rules the API checks\n * (`validate`, `oneOf`), storage, `.userId()`, the description and a\n * transform apply to each item and are kept.\n */\nfunction elementColumnModifiers(element: ColumnDef): string[] {\n const out: string[] = [];\n if (element.notNull) out.push(\"`.notNull()`\");\n if (element.unique) out.push(\"`.unique()`\");\n if (element.primaryKey) out.push(\"`.primaryKey()`\");\n if (element.default !== undefined) out.push(\"a default\");\n if (element.generatedAs !== undefined) out.push(\"`.generatedAlwaysAs()`\");\n if (element.readOnly) out.push(\"`.readOnly()`\");\n if (element.private) out.push(\"`.private()`\");\n if (element.access !== undefined) out.push(\"`.access()`\");\n if (element.stamp !== undefined) out.push(\"a stamp\");\n if (element.json !== undefined) out.push(\"a JSON shape\");\n if (element.vectorIndex !== undefined) out.push(\"a vector index\");\n return out;\n}\n\n/**\n * The column types a key may have: the scalars a row is addressed by — in\n * every URL, filter, cursor and foreign key. (`timestamptz` and `time` are\n * scalars too, refused as keys with their own message.)\n */\nconst KEY_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\n \"text\", \"varchar\", \"char\", \"uuid\", \"enum\",\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"real\", \"doublePrecision\", \"numeric\",\n \"boolean\", \"timestamptz\", \"date\", \"time\"\n]);\n\n/** Whether a `col.custom()` type is an array type (`inet[]`, `text[3]`). */\nconst isCustomArrayType = (sqlType: string): boolean => /\\]\\s*$/.test(sqlType);\n\n/**\n * Why a column of this type cannot be (part of) a primary key, or `undefined`\n * when it can.\n *\n * A row is addressed by its key as text, so a key is a scalar. A JSON\n * document, a geopoint, a vector, binary data and a list are not; a\n * `col.custom()` scalar (`citext`, `inet`) is served as the text the driver\n * returns and may key a table, a custom list type may not.\n *\n * @param semantic The column's `semantic` (`\"geopoint\"` marks a point stored as `jsonb`).\n *\n * @group Schema\n */\nexport function keyTypeProblem(type: ColumnType, semantic?: ColumnDef[\"semantic\"]): string | undefined {\n const passThrough = type.kind === \"other\" && !isCustomArrayType(type.sqlType);\n if (semantic !== \"geopoint\" && (KEY_KINDS.has(type.kind) || passThrough)) return undefined;\n const label = semantic === \"geopoint\" ? \"geopoint\" : `\\`${columnTypeLabel(type)}\\``;\n return (\n `a ${label} column cannot be part of the key. A row is addressed by its key — in every URL, filter, ` +\n \"cursor and foreign key — so a key is a scalar: text, varchar, char, uuid, an enum, a number, a boolean \" +\n \"or a date. Key the table on such a column (several make a composite key) and keep this one as an \" +\n \"ordinary column.\"\n );\n}\n\n/**\n * Element types a Postgres array column does not take here: a JSON document\n * or a vector is a list already, a `bytea` item would need a binary codec per\n * element, and a `col.custom()` list is spelled as its own type. The planner\n * refuses the same set.\n */\nconst NON_ELEMENT_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"json\", \"jsonb\", \"vector\", \"bytea\", \"other\"]);\n\n/**\n * Why an array column cannot hold items of this type, or `undefined` when it\n * can. (An array of arrays is refused by the type check.)\n *\n * @param elementSemantic The item's `semantic` (`\"geopoint\"` for `col.geopoint().array()`).\n *\n * @group Schema\n */\nexport function arrayElementProblem(of: ColumnType, elementSemantic?: ColumnDef[\"semantic\"]): string | undefined {\n if (elementSemantic !== \"geopoint\" && !NON_ELEMENT_KINDS.has(of.kind)) return undefined;\n if (of.kind === \"other\") {\n return (\n `\\`.array()\\` of \\`col.custom({ dataType: ${JSON.stringify(of.sqlType)} })\\` is not an array column Rebase plans. ` +\n `Name the list type itself: \\`col.custom({ dataType: ${JSON.stringify(`${of.sqlType}[]`)} })\\`.`\n );\n }\n const items = elementSemantic === \"geopoint\" ? \"geopoints\" : `\\`${columnTypeLabel(of)}\\` values`;\n return (\n `an array (\\`.array()\\`) of ${items} is not a Postgres array column Rebase reads and writes. An array ` +\n \"column holds scalars — text, uuid, numbers, booleans, dates, enums; a list of documents, points or \" +\n \"vectors is `col.jsonb(json.array(…))`.\"\n );\n}\n\n// ── Validation rules a column kind checks ───────────────────────────────────\n\nconst STRING_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"min\", \"max\", \"length\", \"matches\", \"matchesFlags\", \"matchesMessage\", \"email\", \"url\", \"trim\", \"lowercase\", \"uppercase\"]);\nconst NUMBER_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"min\", \"max\", \"lessThan\", \"moreThan\", \"positive\", \"negative\", \"integer\"]);\nconst DATE_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"min\", \"max\"]);\nconst LIST_RULES: ReadonlySet<string> = new Set([\"requiredMessage\", \"minItems\", \"maxItems\", \"uniqueItems\"]);\nconst BASE_RULES: ReadonlySet<string> = new Set([\"requiredMessage\"]);\n\n/** The `.validate()` rules a value of this Postgres type is checked by (besides `uniqueBy`, which `checkUniqueBy` owns). */\nfunction rulesOfType(type: ColumnType): ReadonlySet<string> {\n switch (type.kind) {\n case \"text\":\n case \"varchar\":\n case \"char\":\n case \"uuid\":\n case \"enum\":\n return STRING_RULES;\n case \"smallint\":\n case \"integer\":\n case \"bigint\":\n case \"smallserial\":\n case \"serial\":\n case \"bigserial\":\n case \"real\":\n case \"doublePrecision\":\n case \"numeric\":\n return NUMBER_RULES;\n case \"timestamptz\":\n case \"date\":\n case \"time\":\n return DATE_RULES;\n case \"array\":\n return LIST_RULES;\n default:\n return BASE_RULES;\n }\n}\n\n/** The rules a JSON shape node is checked by. */\nfunction rulesOfShape(node: JsonShapeDef): ReadonlySet<string> {\n switch (node.kind) {\n case \"string\": return STRING_RULES;\n case \"number\": return NUMBER_RULES;\n case \"date\": return DATE_RULES;\n case \"array\": return LIST_RULES;\n default: return BASE_RULES;\n }\n}\n\n/**\n * The `.validate()` rules declared where nothing checks them: on the column\n * (by its kind — a JSON array column takes the list rules), on an array's\n * items, and on every node of a JSON shape. `.validate()` is typed per kind,\n * so such a rule is a definition built by hand or through a cast; served, it\n * would read as a constraint the API never enforces.\n */\nfunction unsupportedRules(def: ColumnDef): string[] {\n const out: string[] = [];\n const check = (rules: ColumnValidation | undefined, allowed: ReadonlySet<string>, where: string, verb = \"declares\"): void => {\n for (const [rule, value] of Object.entries(rules ?? {})) {\n if (value === undefined || rule === \"uniqueBy\" || allowed.has(rule)) continue;\n out.push(\n `${where} ${verb} the validation rule \\`${rule}\\`, which a ${describeRuleSet(allowed)} does not check. ` +\n `Drop it, or move it to a column whose kind checks it.`\n );\n }\n };\n const columnRules = def.semantic === \"geopoint\"\n ? BASE_RULES\n : def.json?.kind === \"array\" ? LIST_RULES : rulesOfType(def.type);\n check(def.validate, columnRules, \"the column\");\n if (def.type.kind === \"array\" && def.element) check(def.element.validate, rulesOfType(def.type.of), \"the array's items\", \"declare\");\n const visit = (node: JsonShapeDef, path: string): void => {\n if (\"validate\" in node) check(node.validate, rulesOfShape(node), path === \"\" ? \"the document\" : `\"${path}\"`);\n switch (node.kind) {\n case \"object\":\n for (const [field, child] of Object.entries(node.fields)) visit(child, path === \"\" ? field : `${path}.${field}`);\n return;\n case \"array\":\n visit(node.of, path === \"\" ? \"[]\" : `${path}[]`);\n return;\n case \"oneOf\":\n for (const [variant, child] of Object.entries(node.variants)) visit(child, path === \"\" ? variant : `${path}.${variant}`);\n return;\n default:\n return;\n }\n };\n if (def.json) visit(def.json, \"\");\n return out;\n}\n\nconst describeRuleSet = (rules: ReadonlySet<string>): string => {\n if (rules === STRING_RULES) return \"text value\";\n if (rules === NUMBER_RULES) return \"number\";\n if (rules === DATE_RULES) return \"date/time value\";\n if (rules === LIST_RULES) return \"list\";\n return \"value of this kind (it takes only `requiredMessage`)\";\n};\n\n/** Problems in a column type itself: an enum with no or repeated values, a non-positive size. */\nfunction checkColumnType(table: string, key: string, type: ColumnType): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string) => problems.push({ table, key, message });\n switch (type.kind) {\n case \"enum\": {\n if (type.values.length === 0) {\n refuse(\n \"the enum lists no values. They become the labels of a Postgres enum type, and a type with no \" +\n \"labels cannot be created. List the values, or use a plain `col.text()`.\"\n );\n }\n const seen = new Set<string>();\n for (const value of type.values) {\n if (typeof value !== \"string\" || value.length === 0) {\n refuse(\"the enum has a blank value. Each value is a label of the Postgres enum type, and a label cannot be empty.\");\n continue;\n }\n if (seen.has(value)) {\n refuse(\n `the enum lists \"${value}\" twice. The values become the labels of one Postgres enum type, ` +\n \"which cannot hold the same label twice, so `CREATE TYPE` would fail. List it once.\"\n );\n }\n seen.add(value);\n }\n break;\n }\n case \"varchar\":\n case \"char\":\n if (!Number.isInteger(type.length) || type.length <= 0) {\n refuse(`\\`col.${type.kind}(n)\\` takes a positive whole number of characters, got ${String(type.length)}.`);\n }\n break;\n case \"vector\":\n if (!Number.isInteger(type.dimensions) || type.dimensions <= 0) {\n refuse(`\\`col.vector(dimensions)\\` takes a positive whole number, got ${String(type.dimensions)}.`);\n }\n break;\n case \"numeric\":\n if (type.scale !== undefined && type.precision === undefined) {\n refuse(\"`col.numeric(precision, scale)`: a scale needs a precision — `NUMERIC(p, s)` has no form without `p`.\");\n }\n break;\n case \"other\": {\n const problem = customSqlTypeProblem(type.sqlType);\n if (problem !== undefined) {\n refuse(\n `\\`col.custom({ dataType: ${JSON.stringify(type.sqlType)} })\\`: that type name ${problem}. It is written into ` +\n \"DDL verbatim, so it must be a Postgres type as `format_type` prints it — `inet`, `timestamp(3) without \" +\n \"time zone`, `geometry(Point, 4326)`, `inet[]` — and nothing after it.\"\n );\n }\n break;\n }\n case \"array\":\n if (type.of.kind === \"array\") {\n refuse(\"an array of arrays is not supported. Use `col.jsonb()` for nested lists.\");\n } else {\n problems.push(...checkColumnType(table, key, type.of));\n }\n break;\n default:\n break;\n }\n return problems;\n}\n\n/**\n * Whether two column types are the same Postgres type — what a foreign key\n * needs of the column it binds and the key it points at.\n *\n * An enum compares by the type it names and its values, each side's name\n * resolved against its own table: two unnamed enums on two tables are two\n * types, even with the same labels.\n *\n * @group Schema\n */\nexport function sameColumnType(\n a: ColumnType,\n aTable: string,\n aColumn: string,\n b: ColumnType,\n bTable: string,\n bColumn: string\n): boolean {\n if (a.kind !== b.kind) return false;\n switch (a.kind) {\n case \"varchar\":\n case \"char\":\n return b.kind === a.kind && a.length === b.length;\n case \"numeric\":\n return b.kind === \"numeric\" && a.precision === b.precision && a.scale === b.scale;\n case \"vector\":\n return b.kind === \"vector\" && a.dimensions === b.dimensions;\n case \"enum\":\n return b.kind === \"enum\"\n && deriveEnumTypeName(a, aTable, aColumn) === deriveEnumTypeName(b, bTable, bColumn)\n && a.values.length === b.values.length\n && a.values.every((value, index) => value === b.values[index]);\n case \"array\":\n return b.kind === \"array\" && sameColumnType(a.of, aTable, aColumn, b.of, bTable, bColumn);\n case \"other\":\n return b.kind === \"other\" && a.sqlType === b.sqlType;\n default:\n return true;\n }\n}\n\n/**\n * The names a rule may use for a column of its table: the column keys, the\n * SQL column names, and the `belongsTo` relation names (which address their\n * foreign-key column).\n *\n * @group Schema\n */\nexport interface RuleFieldScope {\n /** Every name that addresses a column of the table. */\n names: ReadonlySet<string>;\n}\n\n/**\n * Whether a field name in a rule addresses a column — by key, by relation, or\n * by the snake_case form the policy compiler falls back to (`ownerField:\n * \"author_id\"` reaches the derived `author_id` column, as it always has).\n */\nfunction addresses(scope: RuleFieldScope, name: string): boolean {\n return scope.names.has(name) || scope.names.has(toSnakeCase(name));\n}\n\n/**\n * Problems in a rule's field references: an `ownerField`, or a `field` /\n * `outerField` operand of a structured `condition` / `check`, naming no\n * column of the table.\n *\n * The policy compiler snake-cases a name it does not recognise and compiles a\n * comparison against that column, so a typo reached `CREATE POLICY` and failed\n * there — on a table whose RLS was already enabled, which then served nobody.\n * Fields inside an `existsIn` belong to the other table and are not checked\n * here; its `outerField`s are, because they read this one. Raw SQL is not\n * parsed.\n *\n * @param index The rule's position in `rls`, for the message.\n *\n * @group Schema\n */\nexport function checkRuleFields(\n table: string,\n rule: SecurityRule,\n index: number,\n scope: RuleFieldScope\n): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const label = rule.name ? `rule \"${rule.name}\"` : `rule #${index}`;\n const refuse = (message: string) => problems.push({ table, key: `rls[${index}]`, message });\n\n if (typeof rule.ownerField === \"string\" && !addresses(scope, rule.ownerField)) {\n refuse(\n `${label} has \\`ownerField: \"${rule.ownerField}\"\\`, and the table has no such column or \\`belongsTo\\` ` +\n \"relation. The policy would compare a column that does not exist and fail when it is created. Name \" +\n \"the column (or relation) that holds the owner's user id.\"\n );\n }\n const checkName = (name: string, clause: \"condition\" | \"check\"): void => {\n if (addresses(scope, name)) return;\n refuse(\n `${label} compares the field \"${name}\" in its \\`${clause}\\`, and the table has no such column ` +\n \"or `belongsTo` relation. The policy would fail when it is created. Name a column key of this table.\"\n );\n };\n const checkOperand = (operand: PolicyOperand, clause: \"condition\" | \"check\", inExists: boolean): void => {\n if (operand.kind === \"field\" && !inExists) checkName(operand.name, clause);\n if (operand.kind === \"outerField\" && inExists) checkName(operand.name, clause);\n };\n const walk = (node: unknown, clause: \"condition\" | \"check\", inExists: boolean): void => {\n if (typeof node !== \"object\" || node === null) return;\n if (!isPolicyExpression(node)) {\n // The plain-object shorthand, `{ status: \"published\" }`: every key\n // is a column of this table (inside an `existsIn`, of the other one).\n if (!inExists) for (const key of Object.keys(node)) checkName(key, clause);\n return;\n }\n switch (node.kind) {\n case \"and\":\n case \"or\":\n for (const operand of node.operands) walk(operand, clause, inExists);\n return;\n case \"not\":\n walk(node.operand, clause, inExists);\n return;\n case \"existsIn\": {\n const searched: unknown = node.table;\n if (typeof searched !== \"string\" || searched.trim() === \"\") {\n const legacy = \"collection\" in node && typeof node.collection === \"string\" ? ` (it names \\`collection: \"${node.collection}\"\\`, the 0.30 key)` : \"\";\n refuse(\n `${label} has an \\`existsIn\\` in its \\`${clause}\\` with no table to search${legacy}. The policy would ` +\n \"compile to a subquery over no table. Write `policy.existsIn({ table: \\\"<slug of the table to search>\\\", where })`.\"\n );\n }\n walk(node.where, clause, true);\n return;\n }\n case \"compare\":\n checkOperand(node.left, clause, inExists);\n checkOperand(node.right, clause, inExists);\n return;\n default:\n return;\n }\n };\n if (\"condition\" in rule) walk(rule.condition, \"condition\", false);\n if (\"check\" in rule) walk(rule.check, \"check\", false);\n return problems;\n}\n\n/** Whether a rule's condition node is a structured expression (it carries `kind`) rather than the shorthand object. */\nfunction isPolicyExpression(node: object): node is PolicyExpression {\n return \"kind\" in node && typeof node.kind === \"string\";\n}\n","import type {\n ColumnType,\n AnyTableDef,\n AnyViewDef,\n AuthTableDescriptor,\n ColumnDef,\n ColumnDescriptor,\n ColumnElementDescriptor,\n DefaultRls,\n JsonShapeDef,\n OrderByTuple,\n RelationDef,\n RelationDescriptor,\n RlsDescriptor,\n SearchConfig,\n TableDescriptor,\n TableHookFlags,\n TableIndex,\n TableIndexKey,\n TableIndexPredicate,\n TenantDescriptor,\n TenantSource\n} from \"@rebasepro/types\";\nimport {\n DEFAULT_DATA_SOURCE_KEY,\n columnTypeLabel,\n describeJsonShape,\n isAuthTableDef,\n isColumnBuilder,\n isRelationDef,\n isTableDef,\n isViewDef,\n resourceKeyOf\n} from \"@rebasepro/types\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\n\nimport { authSecretsMissingExclusion } from \"../collections/auth-secrets\";\nimport { DEFAULT_SOFT_DELETE_FIELD } from \"../collections/soft-delete\";\nimport { SchemaDefinitionError, type SchemaDefinitionProblem } from \"./errors\";\nimport {\n JUNCTION_TABLE_SCHEMA,\n deriveBelongsToLocalKey,\n deriveColumnName,\n deriveEnumTypeName,\n deriveForeignKeyField,\n deriveJunctionSourceKey,\n deriveJunctionTable,\n deriveJunctionTargetKey,\n deriveReferencingType,\n deriveSchemaName,\n deriveSlug,\n deriveTableName,\n deriveTargetForeignKey,\n deriveViaWritable\n} from \"./derive-names\";\nimport { resolveRls, ruleShapeProblems } from \"./resolve-rls\";\nimport { checkColumnDef, checkRuleFields, sameColumnType } from \"./validate-tables\";\n\n/**\n * Options of {@link compileTables}.\n *\n * @group Schema\n */\nexport interface CompileTablesOptions {\n /**\n * The project's `defaultRls` (exported from `backend/schema/index.ts`):\n * what every `rls: \"inherit\"` table takes. Without it, `\"inherit\"` is\n * refused.\n */\n defaultRls?: DefaultRls;\n}\n\n/** A table or view definition, as `compileTables` takes them. */\nexport type AnySchemaDef = AnyTableDef | AnyViewDef;\n\n/** One declared column, with the SQL name it resolves to. */\ninterface PreparedColumn {\n key: string;\n def: ColumnDef;\n column: string;\n}\n\n/** What every other table needs to know about one definition before any is compiled. */\ninterface PreparedDef {\n def: AnySchemaDef;\n kind: \"table\" | \"view\";\n name: string;\n slug: string;\n table: string;\n schema: string;\n columns: PreparedColumn[];\n relations: [string, RelationDef][];\n}\n\n/** The resolved target of a relation. */\ntype TargetResolution = { ok: true; target: PreparedDef } | { ok: false; message: string };\n\n/**\n * Whether a column declares a field-level hook anywhere: on itself, inside its\n * JSON shape, or on its array element.\n */\nfunction declaresFieldHook(def: ColumnDef): boolean {\n const hook = (transform: ColumnDef[\"transform\"]): boolean =>\n transform !== undefined && (typeof transform.beforeSave === \"function\" || typeof transform.afterRead === \"function\");\n const inShape = (shape: JsonShapeDef): boolean => {\n if (hook(shape.transform)) return true;\n switch (shape.kind) {\n case \"object\": return Object.values(shape.fields).some(inShape);\n case \"array\": return inShape(shape.of);\n case \"oneOf\": return Object.values(shape.variants).some(inShape);\n default: return false;\n }\n };\n return hook(def.transform) || (def.json !== undefined && inShape(def.json))\n || (def.element !== undefined && declaresFieldHook(def.element));\n}\n\n/** A junction table some relation claims, for the cross-table checks. */\ninterface JunctionClaim {\n keys: string;\n owner: string;\n table: string;\n}\n\nconst TABLE_HOOKS = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\nconst VIEW_HOOKS = [\"beforeQuery\", \"afterRead\"] as const;\nconst TENANT_KINDS = new Set([\n \"text\", \"varchar\", \"char\", \"uuid\", \"enum\",\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"numeric\"\n]);\nconst TEMPORAL_KINDS = new Set([\"timestamptz\", \"date\", \"time\"]);\n/**\n * Integer widths. A foreign key holds between any two of them — Postgres\n * compares `integer` with `bigint` in one operator family — so a bound column\n * keeps its declared width when it points at a key of another one (the shape\n * a database grown over years holds: an `integer` column into a `bigint` key).\n */\nconst INTEGER_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\"]);\n\n/**\n * Compile table and view definitions into the descriptors the backend runs on\n * and `GET /api/schema/tables` serves.\n *\n * Every default is applied and every name derived exactly as today's\n * collection pipeline derives it (see `derive-names.ts`), every relation is\n * resolved to its target's slug, and `rls` is resolved against `defaultRls`.\n *\n * Fails closed: every problem in every definition is collected, and one\n * {@link SchemaDefinitionError} carrying all of them is thrown — a table with\n * no primary key, no usable `rls`, a relation that points outside the list,\n * modifiers that contradict each other, and the rest listed in the error's\n * documentation.\n *\n * Pure and deterministic: no environment, no I/O; tables come out in input\n * order and columns in physical order (declared columns, then the foreign-key\n * columns `belongsTo` relations derive, in relation order).\n *\n * @group Schema\n */\nexport function compileTables(defs: readonly AnySchemaDef[], options: CompileTablesOptions = {}): TableDescriptor[] {\n const problems: SchemaDefinitionProblem[] = [];\n const prepared: PreparedDef[] = [];\n defs.forEach((def, index) => {\n const result = prepareDef(def, index);\n if (\"problem\" in result) problems.push(result.problem);\n else prepared.push(result);\n });\n\n problems.push(...checkTablesTogether(prepared));\n\n const byDef = new Map<unknown, PreparedDef>(prepared.map(entry => [entry.def, entry]));\n const resolve = (thunk: () => unknown): TargetResolution => resolveTarget(thunk, byDef);\n const junctions = new Map<string, JunctionClaim>();\n const descriptors: TableDescriptor[] = [];\n for (const entry of prepared) {\n const { descriptor, problems: found } = compileOne(entry, resolve, options, junctions);\n problems.push(...found);\n descriptors.push(descriptor);\n }\n\n problems.push(...checkStoredIdentifiers(descriptors, prepared));\n\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n return descriptors;\n}\n\n/**\n * Compile one definition, given how to resolve a relation's target.\n *\n * The building block of {@link compileTables}, exported for callers that hold\n * a resolver of their own. Returns the descriptor together with the problems\n * found in that one definition rather than throwing, so the caller decides how\n * to report them; checks that need every table at once (duplicate names,\n * identifiers that collide once Postgres truncates them, one junction claimed\n * with two shapes) are only made by {@link compileTables}.\n *\n * @param resolveTarget Called with a relation's target thunk; returns the\n * definition it points at, or why it does not resolve.\n *\n * @group Schema\n */\nexport function compileTable(\n def: AnySchemaDef,\n resolveTarget: (thunk: () => unknown) => { ok: true; target: AnySchemaDef } | { ok: false; message: string },\n options: CompileTablesOptions = {}\n): { descriptor: TableDescriptor | undefined; problems: SchemaDefinitionProblem[] } {\n const entry = prepareDef(def, 0);\n if (\"problem\" in entry) return { descriptor: undefined, problems: [entry.problem] };\n const cache = new Map<unknown, PreparedDef>([[def, entry]]);\n const resolve = (thunk: () => unknown): TargetResolution => {\n const result = resolveTarget(thunk);\n if (!result.ok) return result;\n let target = cache.get(result.target);\n if (!target) {\n const preparedTarget = prepareDef(result.target, 0);\n if (\"problem\" in preparedTarget) return { ok: false, message: preparedTarget.problem.message };\n target = preparedTarget;\n cache.set(result.target, target);\n }\n return { ok: true, target };\n };\n return compileOne(entry, resolve, options, new Map());\n}\n\n/**\n * The descriptor of one declared column: its key, its SQL name and every flag\n * that is set. Flags that are false or absent are left out, so a descriptor\n * stays small and stable as options are added.\n *\n * @param key The column's key in `columns`.\n * @param column The SQL column name (`.column()`, or the snake_case of the key).\n *\n * @group Schema\n */\nexport function describeColumn(key: string, def: ColumnDef, column: string): ColumnDescriptor {\n const out: ColumnDescriptor = {\n key,\n column,\n type: def.type,\n nullable: !(def.notNull || def.primaryKey)\n };\n if (def.primaryKey) out.primaryKey = true;\n // A key column is unique by being the key; today's planner never writes a\n // second UNIQUE on it, so neither does the descriptor.\n if (def.unique && !def.primaryKey) out.unique = true;\n if (def.default !== undefined) out.default = def.default;\n if (def.generatedAs !== undefined) out.generated = { expression: def.generatedAs };\n if (def.readOnly || def.generatedAs !== undefined) out.readOnly = true;\n if (def.private) out.private = true;\n if (def.access !== undefined) out.access = def.access;\n if (def.stamp !== undefined) out.stamp = def.stamp;\n if (def.validate !== undefined && Object.keys(def.validate).length > 0) out.validate = def.validate;\n if (def.oneOf !== undefined) out.oneOf = def.oneOf;\n if (def.description !== undefined) out.description = def.description;\n if (def.storage !== undefined) out.storage = def.storage;\n if (def.semantic !== undefined) out.semantic = def.semantic;\n if (def.vectorIndex !== undefined) out.vectorIndex = def.vectorIndex;\n if (def.json !== undefined) out.json = describeJsonShape(def.json);\n if (def.element !== undefined) {\n const element: ColumnElementDescriptor = {};\n if (def.element.validate !== undefined && Object.keys(def.element.validate).length > 0) element.validate = def.element.validate;\n if (def.element.oneOf !== undefined) element.oneOf = def.element.oneOf;\n if (def.element.storage !== undefined) element.storage = def.element.storage;\n if (def.element.semantic === \"user\") element.semantic = \"user\";\n if (Object.keys(element).length > 0) out.element = element;\n }\n if (def.transform !== undefined) {\n const transforms: { beforeSave?: true; afterRead?: true } = {};\n if (typeof def.transform.beforeSave === \"function\") transforms.beforeSave = true;\n if (typeof def.transform.afterRead === \"function\") transforms.afterRead = true;\n if (Object.keys(transforms).length > 0) out.transforms = transforms;\n }\n return out;\n}\n\n// ── Preparation ──────────────────────────────────────────────────────────────\n\nfunction prepareDef(def: unknown, index: number): PreparedDef | { problem: SchemaDefinitionProblem } {\n const view = isViewDef(def);\n if (!view && !isTableDef(def)) {\n return {\n problem: {\n table: `#${index}`,\n message: \"is not a `defineTable(...)`, `defineAuthTable(...)` or `defineView(...)` result. Export only table and view definitions from backend/schema/index.ts.\"\n }\n };\n }\n const name = def.name;\n const config = def.config;\n const rawColumns: unknown = config.columns;\n if (typeof rawColumns !== \"object\" || rawColumns === null) {\n return { problem: { table: name, message: \"declares no `columns`.\" } };\n }\n const columns: PreparedColumn[] = [];\n for (const [key, builder] of Object.entries(rawColumns)) {\n if (!isColumnBuilder(builder)) {\n return { problem: { table: name, key, message: \"is not a `col.*` builder.\" } };\n }\n columns.push({ key, def: builder.def, column: deriveColumnName(key, builder.def) });\n }\n const relations: [string, RelationDef][] = [];\n const rawRelations: unknown = config.relations;\n if (rawRelations !== undefined && rawRelations !== null) {\n if (typeof rawRelations !== \"object\") {\n return { problem: { table: name, message: \"`relations` must be an object of `rel.*` results.\" } };\n }\n for (const [key, relation] of Object.entries(rawRelations)) {\n if (!isRelationDef(relation)) {\n return { problem: { table: name, key, message: \"is not a `rel.*` result.\" } };\n }\n relations.push([key, relation]);\n }\n }\n const table = deriveTableName(name, def.config.table);\n return {\n def,\n kind: view ? \"view\" : \"table\",\n name,\n slug: deriveSlug(name, config.slug),\n table,\n schema: deriveSchemaName(config.schema),\n columns,\n relations\n };\n}\n\nfunction resolveTarget(thunk: () => unknown, byDef: ReadonlyMap<unknown, PreparedDef>): TargetResolution {\n let value: unknown;\n try {\n value = thunk();\n } catch (error) {\n if (error instanceof ReferenceError) {\n return {\n ok: false,\n message:\n \"its target is not initialized yet — almost always an import cycle between the two schema \" +\n \"files. Break the cycle (move the shared piece into a third module) so the target's module \" +\n \"finishes evaluating before the schema is compiled.\"\n };\n }\n return { ok: false, message: `its target thunk threw: ${error instanceof Error ? error.message : String(error)}` };\n }\n // A cycle transpiled to CommonJS hands the thunk the module namespace,\n // whose `default` slot holds the definition by the time the thunk runs.\n if (!isTableDef(value) && !isViewDef(value) && typeof value === \"object\" && value !== null && \"default\" in value) {\n const inner: unknown = value.default;\n if (isTableDef(inner) || isViewDef(inner)) value = inner;\n }\n if (!isTableDef(value) && !isViewDef(value)) {\n return {\n ok: false,\n message:\n `its target resolved to ${value === undefined ? \"`undefined`\" : \"something that is not a table\"}. ` +\n \"The thunk must return the `defineTable` / `defineView` result itself: `() => users`.\"\n };\n }\n const target = byDef.get(value);\n if (!target) {\n return {\n ok: false,\n message:\n `its target \"${value.name}\" is not one of the tables being compiled. Export it from ` +\n \"backend/schema/index.ts beside this one.\"\n };\n }\n return { ok: true, target };\n}\n\n// ── One table ────────────────────────────────────────────────────────────────\n\nfunction compileOne(\n entry: PreparedDef,\n resolve: (thunk: () => unknown) => TargetResolution,\n options: CompileTablesOptions,\n junctions: Map<string, JunctionClaim>\n): { descriptor: TableDescriptor; problems: SchemaDefinitionProblem[] } {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string, key?: string): void => {\n problems.push(key === undefined ? { table: entry.name, message } : { table: entry.name, key, message });\n };\n const { def, name } = entry;\n const config = def.config;\n const auth = entry.kind === \"table\" && isAuthTableDef(def);\n\n // ── Columns ──────────────────────────────────────────────────────────────\n const secrets = auth ? new Set(authSecretsMissingExclusion({\n auth: true,\n properties: Object.fromEntries(entry.columns.map(c => [c.key, { excludeFromApi: c.def.private, columnName: c.column }]))\n })) : new Set<string>();\n const columns: ColumnDescriptor[] = [];\n for (const column of entry.columns) {\n problems.push(...checkColumnDef(name, column.key, column.def, column.column));\n problems.push(...checkUniqueBy(name, column.key, column.def));\n const described = describeColumn(column.key, column.def, column.column);\n // The user store's secrets never leave the server, whatever the\n // declaration says: a redeclared users table is where the flag goes\n // missing unnoticed.\n if (secrets.has(column.key)) described.private = true;\n columns.push(described);\n }\n const primaryKey = entry.columns.filter(c => c.def.primaryKey).map(c => c.key);\n if (primaryKey.length === 0) {\n refuse(\n entry.kind === \"view\"\n ? \"the view has no primary key: mark the column(s) that identify a row `.primaryKey()`.\"\n : \"the table has no primary key. Mark a column `.primaryKey()` — e.g. `id: col.uuid().primaryKey().defaultRandom()`; several make a composite key in declaration order.\"\n );\n }\n const keyOwners = new Map<string, string>();\n for (const column of entry.columns) keyOwners.set(column.key, `column \"${column.key}\"`);\n for (const [relationName] of entry.relations) {\n if (keyOwners.has(relationName)) {\n refuse(\n `the table has both a column and a relation named \"${relationName}\". A relation's key is what ` +\n \"`include` names; give the foreign-key column its own key.\",\n relationName\n );\n } else {\n keyOwners.set(relationName, `relation \"${relationName}\"`);\n }\n }\n\n // ── Relations ────────────────────────────────────────────────────────────\n const relations: RelationDescriptor[] = [];\n const derivedColumns: ColumnDescriptor[] = [];\n const boundBy = new Map<string, string>();\n for (const [relationName, relation] of entry.relations) {\n const resolved = resolve(relation.target);\n if (!resolved.ok) {\n refuse(`the relation ${resolved.message}`, relationName);\n continue;\n }\n const target = resolved.target;\n const targetKeys = target.columns.filter(c => c.def.primaryKey);\n const sourceKeys = entry.columns.filter(c => c.def.primaryKey);\n const compositeRefusal = (side: PreparedDef, count: number, link: string, fix: string): void => refuse(\n `${link} is one column, and \\`${side.name}\\` is keyed on ${count} columns together — one column ` +\n `cannot reference a composite key. ${fix}`,\n relationName\n );\n const viaFix = \"or express the link as `rel.via(...)`, whose steps compare every key column.\";\n const before = relations.length;\n switch (relation.kind) {\n case \"belongsTo\": {\n const localKey = deriveBelongsToLocalKey(relationName, relation.localKey);\n const bound = entry.columns.find(c => c.column === localKey);\n if (targetKeys.length > 1) {\n compositeRefusal(target, targetKeys.length, `\\`localKey: \"${localKey}\"\\``, `Point the relation at a table with a single-column key, ${viaFix}`);\n }\n const targetKey = targetKeys.length === 1 ? targetKeys[0] : undefined;\n const referencing = targetKey ? deriveReferencingType(targetKey.def.type, target.table, targetKey.column) : undefined;\n let localField: string;\n if (bound) {\n localField = bound.key;\n const previous = boundBy.get(bound.key);\n if (previous !== undefined) {\n refuse(`the relations \"${previous}\" and \"${relationName}\" both use the column \"${localKey}\" as their foreign key. One column holds one link; give one of them its own \\`localKey\\`.`, relationName);\n }\n boundBy.set(bound.key, relationName);\n if (targetKey && referencing\n && !sameColumnType(bound.def.type, entry.table, bound.column, referencing, target.table, targetKey.column)\n && !(INTEGER_KINDS.has(bound.def.type.kind) && INTEGER_KINDS.has(referencing.kind))) {\n refuse(\n `the relation binds the column \"${bound.key}\" (\\`${columnTypeLabel(bound.def.type)}\\`) as its foreign key, ` +\n `and \\`${target.name}\\`'s key \"${targetKey.key}\" is \\`${columnTypeLabel(referencing)}\\`. A foreign key ` +\n \"only holds between columns of one type. Declare the column with the key's type, or drop it and let \" +\n \"the relation derive it.\",\n relationName\n );\n }\n if (relation.notNull === true && !(bound.def.notNull || bound.def.primaryKey)) {\n refuse(\n `\\`notNull: true\\` applies to a derived foreign key, and this relation binds the declared column \"${bound.key}\", ` +\n \"which is nullable. A bound column says so itself: write `.notNull()` on it and drop `notNull` here.\",\n relationName\n );\n }\n if (relation.unique === true && !(bound.def.unique || bound.def.primaryKey)) {\n refuse(\n `\\`unique: true\\` applies to a derived foreign key, and this relation binds the declared column \"${bound.key}\", ` +\n \"which is not unique. Write `.unique()` on the column and drop `unique` here.\",\n relationName\n );\n }\n const index = columns.findIndex(c => c.key === bound.key);\n if (index >= 0) columns[index] = { ...columns[index], foreignKeyOf: relationName };\n } else {\n localField = deriveForeignKeyField(localKey);\n const owner = keyOwners.get(localField);\n if (owner !== undefined) {\n refuse(\n `the relation derives the foreign-key column \"${localKey}\", served as \"${localField}\", and the ${owner} ` +\n `already has that key. Declare the column yourself (\\`${localField}: col.…(\"${localKey}\")\\`, the SQL name as the builder's first argument, ` +\n \"binds it), or give the relation another `localKey`.\",\n relationName\n );\n } else if (entry.columns.some(c => c.column === localKey) || derivedColumns.some(c => c.column === localKey)) {\n refuse(`the relation derives the column \"${localKey}\", which another relation already derives. Give one of them its own \\`localKey\\`.`, relationName);\n } else {\n keyOwners.set(localField, `foreign key of relation \"${relationName}\"`);\n const column: ColumnDescriptor = {\n key: localField,\n column: localKey,\n type: referencing ?? { kind: \"text\" },\n nullable: relation.notNull !== true,\n foreignKeyOf: relationName,\n derived: true\n };\n if (relation.unique === true) column.unique = true;\n derivedColumns.push(column);\n }\n }\n const descriptor: RelationDescriptor = {\n name: relationName,\n kind: \"belongsTo\",\n target: target.slug,\n cardinality: \"one\",\n localKey,\n localField,\n index: relation.index !== false,\n constraint: relation.constraint !== false && entry.kind === \"table\" && target.kind === \"table\"\n };\n if (relation.onDelete !== undefined) descriptor.onDelete = relation.onDelete;\n if (relation.onUpdate !== undefined) descriptor.onUpdate = relation.onUpdate;\n relations.push(descriptor);\n break;\n }\n case \"hasOne\":\n case \"hasMany\": {\n const foreignKey = deriveTargetForeignKey(entry.slug, relation.foreignKey);\n if (relation.sourceKey === undefined && sourceKeys.length > 1) {\n compositeRefusal(entry, sourceKeys.length, `\\`foreignKey: \"${foreignKey}\"\\``,\n `Give the relation a \\`sourceKey\\` naming a single unique column of \\`${entry.name}\\` to point at, ${viaFix}`);\n }\n const base = { name: relationName, target: target.slug, foreignKey };\n const withSource = relation.sourceKey !== undefined ? { ...base, sourceKey: relation.sourceKey } : base;\n if (relation.kind === \"hasOne\") {\n relations.push({ ...withSource, kind: \"hasOne\", cardinality: \"one\" });\n } else {\n const orderBy = normalizeOrderBy(relation.orderBy);\n relations.push(orderBy\n ? { ...withSource, kind: \"hasMany\", cardinality: \"many\", orderBy }\n : { ...withSource, kind: \"hasMany\", cardinality: \"many\" });\n }\n break;\n }\n case \"manyToMany\": {\n if (sourceKeys.length > 1 || targetKeys.length > 1) {\n const side = sourceKeys.length > 1 ? entry : target;\n compositeRefusal(side, Math.max(sourceKeys.length, targetKeys.length), \"A junction column\",\n `A junction column points at a single-column key; ${viaFix}`);\n }\n const through = deriveJunctionTable(entry.table, target.table, relation.through);\n const sourceKey = deriveJunctionSourceKey(entry.slug, relation.sourceKey);\n const targetKey = deriveJunctionTargetKey(relationName, relation.targetKey);\n if (sourceKey === targetKey) {\n // Both defaults are derived independently — the source's\n // singular slug and the relation's name — so a link from a\n // table to itself named after the table (`tracks.track`)\n // derives one column twice, which no CREATE TABLE takes.\n refuse(\n `both junction columns of \"${through}\" are named \"${sourceKey}\": one column cannot hold both ` +\n `ends of the link. Name the target's apart, e.g. \\`targetKey: \"related_${sourceKey}\"\\`.`,\n relationName\n );\n }\n const pivot: ColumnDescriptor[] = [];\n for (const [key, builder] of Object.entries(relation.pivot ?? {})) {\n if (!isColumnBuilder(builder)) {\n refuse(`the pivot column \"${key}\" is not a \\`col.*\\` builder.`, relationName);\n continue;\n }\n if (builder.def.primaryKey) {\n refuse(\n `the pivot column \"${key}\" is marked \\`.primaryKey()\\`. The junction's key is its two link ` +\n \"columns, which Rebase declares; a pivot column is payload the link carries. Drop `.primaryKey()`.\",\n relationName\n );\n }\n if (declaresFieldHook(builder.def)) {\n // Field hooks run off a table's own columns; nothing\n // runs a pivot column's, so an `afterRead` there would\n // be a mask that never masks. Refused, not ignored.\n refuse(\n `the pivot column \"${key}\" declares \\`.transform()\\`, and a pivot column's field hooks never ` +\n \"run: `_pivot` is served and written as stored. Mask it in the target table's `hooks.afterRead` \" +\n \"(it sees `_pivot`), or move the value onto a table of its own.\",\n relationName\n );\n }\n const column = deriveColumnName(key, builder.def);\n // A payload column on a key column is not planned today; it\n // is not described either.\n if (column === sourceKey || column === targetKey) continue;\n for (const problem of checkColumnDef(name, `${relationName}.pivot.${key}`, builder.def, column)) problems.push(problem);\n pivot.push(describeColumn(key, builder.def, column));\n }\n claimJunction(junctions, through, entry, relationName, sourceKey, targetKey, target, refuse);\n const descriptor: RelationDescriptor = {\n name: relationName,\n kind: \"manyToMany\",\n target: target.slug,\n cardinality: \"many\",\n through: { table: through, sourceKey, targetKey, pivot }\n };\n if (relation.onDelete !== undefined) descriptor.onDelete = relation.onDelete;\n relations.push(descriptor);\n break;\n }\n case \"via\": {\n const steps = Array.isArray(relation.steps) ? relation.steps : [];\n if (steps.length === 0) {\n refuse(\"`rel.via(target, { steps })` needs at least one join step.\", relationName);\n }\n const cardinality = relation.cardinality ?? \"many\";\n relations.push({\n name: relationName,\n kind: \"via\",\n target: target.slug,\n cardinality,\n steps: steps.map(step => ({ ...step })),\n writable: steps.length > 0 && deriveViaWritable(cardinality, steps)\n });\n break;\n }\n default: {\n const exhaustive: never = relation;\n refuse(`unknown relation kind ${JSON.stringify(exhaustive)}.`);\n }\n }\n if (relations.length > before) {\n const described = relations[relations.length - 1];\n if (relation.private === true && relation.access !== undefined) {\n refuse(\n \"the relation is `private: true` and declares `access`. A private relation is never served to or \" +\n \"written by a client, so access rules say nothing; drop one of the two.\",\n relationName\n );\n }\n if (relation.private === true) described.private = true;\n else if (relation.access !== undefined) described.access = relation.access;\n }\n }\n const allColumns = [...columns, ...derivedColumns];\n\n // ── Names a table-level option may use ───────────────────────────────────\n const byKey = new Map(allColumns.map(c => [c.key, c]));\n const belongsToField = new Map<string, string>();\n for (const relation of relations) {\n if (relation.kind === \"belongsTo\") belongsToField.set(relation.name, relation.localField);\n }\n /** A column key, or a `belongsTo` relation name standing for its foreign-key column. */\n const columnOf = (key: string): ColumnDescriptor | undefined => byKey.get(key) ?? byKey.get(belongsToField.get(key) ?? \"\");\n\n const descriptor: TableDescriptor = {\n name,\n slug: entry.slug,\n table: entry.table,\n schema: entry.schema,\n kind: entry.kind,\n columns: allColumns,\n primaryKey,\n relations,\n rls: { posture: \"admin-only\", rules: [], defaultPolicies: true }\n };\n const database = config.database !== undefined ? resourceKeyOf(config.database) : undefined;\n if (database !== undefined && database !== DEFAULT_DATA_SOURCE_KEY) descriptor.database = database;\n if (config.description !== undefined) descriptor.description = config.description;\n if (config.metadata !== undefined) descriptor.metadata = { ...config.metadata };\n\n // ── Indexes ──────────────────────────────────────────────────────────────\n const indexes: unknown = config.indexes;\n if (indexes !== undefined) {\n if (!Array.isArray(indexes)) {\n refuse(\"`indexes` must be a list of `{ columns, … }`.\");\n } else {\n if (entry.kind === \"view\" && !isMaterialized(def)) {\n refuse(\"only a materialized view stores rows to index; a plain view reads the indexes of its tables. Drop `indexes`, or make the view `materialized: true`.\");\n }\n const list: TableIndex[] = [];\n indexes.forEach((index: TableIndex, position: number) => {\n for (const key of indexKeysOf(index)) {\n if (!columnOf(key)) {\n refuse(`\\`indexes[${position}]\\` names \"${key}\", which is no column key or \\`belongsTo\\` relation of the table. Name a key from \\`columns\\`.`);\n }\n }\n list.push(index);\n });\n descriptor.indexes = list;\n }\n }\n\n // ── Views and tables part ways ───────────────────────────────────────────\n if (isViewDef(def)) {\n const viewConfig = def.config;\n if (typeof viewConfig.query !== \"string\" || viewConfig.query.trim().length === 0) {\n refuse(\"the view needs a `query`: the SELECT that defines it.\");\n }\n if (viewConfig.roles !== undefined && !viewConfig.materialized) {\n refuse(\n \"the view lists `roles` but is not materialized. A plain view is governed by the row-level security \" +\n \"of the tables it reads; `roles` gates a materialized view only. Drop `roles`, or add `materialized: true`.\"\n );\n }\n for (const key of [\"tenant\", \"softDelete\", \"history\", \"search\", \"rls\"] as const) {\n if (key in viewConfig && Reflect.get(viewConfig, key) !== undefined && Reflect.get(viewConfig, key) !== false) {\n refuse(`\\`${key}\\` cannot be declared on a view: a view is never written and has no policies of its own; declare it on the tables the view reads.`);\n }\n }\n const materialized = viewConfig.materialized === true;\n descriptor.view = materialized\n ? { materialized: true, roles: [...(viewConfig.roles ?? [\"admin\"])], query: viewConfig.query }\n : { materialized: false, query: viewConfig.query };\n // A view carries no policies: a plain one runs as the caller, a\n // materialized one is gated by `view.roles`. Neither grants through\n // `rls`, which says so with its own posture, no rules and no baseline.\n descriptor.rls = { posture: \"view\", rules: [], defaultPolicies: false };\n const hooks = hookFlags(viewConfig.hooks, VIEW_HOOKS);\n if (hooks) descriptor.hooks = hooks;\n return { descriptor, problems };\n }\n\n const tableConfig = def.config;\n\n // ── rls ──────────────────────────────────────────────────────────────────\n const rls = resolveRls(tableConfig.rls, tableConfig.defaultPolicies, options.defaultRls);\n if (!rls.ok) {\n refuse(rls.message);\n } else {\n descriptor.rls = rls.rls;\n problems.push(...checkRules(name, rls.rls, allColumns, relations, auth));\n }\n\n // ── tenant ───────────────────────────────────────────────────────────────\n if (tableConfig.tenant !== undefined) {\n const tenant = compileTenant(tableConfig.tenant, columnOf, refuse);\n if (tenant) {\n descriptor.tenant = tenant;\n // The planner makes the tenant column NOT NULL whatever it was declared.\n const index = allColumns.findIndex(c => c.key === tenant.field);\n if (index >= 0) allColumns[index] = { ...allColumns[index], nullable: false };\n }\n }\n\n // ── softDelete ───────────────────────────────────────────────────────────\n const softDelete: unknown = tableConfig.softDelete;\n if (softDelete !== undefined && softDelete !== false) {\n let field: string | undefined;\n if (softDelete === true) field = DEFAULT_SOFT_DELETE_FIELD;\n else if (typeof softDelete === \"object\" && softDelete !== null) {\n const named: unknown = \"field\" in softDelete ? softDelete.field : undefined;\n field = typeof named === \"string\" && named.length > 0 ? named : DEFAULT_SOFT_DELETE_FIELD;\n } else {\n refuse(\"`softDelete` must be `true` or `{ field }`.\");\n }\n if (field !== undefined) {\n const column = byKey.get(field);\n if (!column) {\n refuse(\n `\\`softDelete\\` records the deletion in \"${field}\", and the table has no such column. Declare it — ` +\n `\\`${field}: col.timestamp({ withTimezone: true })\\` — or name an existing timestamp column with \\`softDelete: { field: \"…\" }\\`. ` +\n \"The flag says what a column means; it does not add one.\"\n );\n } else if (!TEMPORAL_KINDS.has(column.type.kind)) {\n refuse(`\\`softDelete\\` stamps \"${field}\" with the time of the deletion, and that column is \\`${columnTypeLabel(column.type)}\\`. Make it \\`col.timestamp({ withTimezone: true })\\`.`);\n } else {\n descriptor.softDelete = { field };\n }\n }\n }\n\n if (tableConfig.history === true) descriptor.history = true;\n\n // ── search ───────────────────────────────────────────────────────────────\n if (tableConfig.search !== undefined) {\n problems.push(...checkSearch(name, tableConfig.search, byKey));\n descriptor.search = { ...tableConfig.search, fields: [...tableConfig.search.fields] };\n }\n\n // ── auth ─────────────────────────────────────────────────────────────────\n if (auth && def.auth) {\n const authDescriptor: AuthTableDescriptor = {};\n if (def.auth.roles !== undefined) authDescriptor.roles = def.auth.roles;\n if (def.auth.scopes !== undefined) authDescriptor.scopes = def.auth.scopes;\n if (def.auth.personalKeys !== undefined) authDescriptor.personalKeys = def.auth.personalKeys;\n const authHooks: { onCreateUser?: true; onResetPassword?: true } = {};\n if (typeof def.auth.onCreateUser === \"function\") authHooks.onCreateUser = true;\n if (typeof def.auth.onResetPassword === \"function\") authHooks.onResetPassword = true;\n if (Object.keys(authHooks).length > 0) authDescriptor.hooks = authHooks;\n descriptor.auth = authDescriptor;\n }\n\n const hooks = hookFlags(tableConfig.hooks, TABLE_HOOKS);\n if (hooks) descriptor.hooks = hooks;\n if (tableConfig.strictWrites === false) descriptor.strictWrites = false;\n\n return { descriptor, problems };\n}\n\n/**\n * `uniqueBy` names fields of the items of a JSON array of objects\n * (`json.array(json.object({...})).validate({ uniqueBy: [...] })`, or the\n * rules of a column holding one). Anywhere else — another column's rules, an\n * array of scalars, a field the item does not have — it would be a rule\n * nothing can check, so it is refused.\n */\nfunction checkUniqueBy(table: string, key: string, def: ColumnDef): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string): void => {\n problems.push({ table, key, message });\n };\n // A JSON array column's list rules may sit on the column (the lift puts\n // them there) or on its shape: both describe the one array.\n const columnUniqueBy = def.validate?.uniqueBy;\n if (columnUniqueBy !== undefined && def.json?.kind !== \"array\") {\n refuse(\n \"`uniqueBy` compares the items of a JSON array of objects, and this column is not one. Declare the column \" +\n \"`col.jsonb(json.array(json.object({ … })).validate({ uniqueBy: [\\\"field\\\"] }))`; for an array of plain \" +\n \"values, `uniqueItems: true`.\"\n );\n }\n if (def.element?.validate?.uniqueBy !== undefined) {\n refuse(\"the array's items declare `uniqueBy`, which compares a JSON array's object items. For a Postgres array, use `uniqueItems: true` on the column.\");\n }\n const visit = (node: JsonShapeDef, path: string): void => {\n const at = path === \"\" ? \"the document\" : `\"${path}\"`;\n const uniqueBy = \"validate\" in node ? node.validate?.uniqueBy : undefined;\n if (uniqueBy !== undefined) {\n if (node.kind !== \"array\") {\n refuse(`${at} declares \\`uniqueBy\\`, which applies to a JSON array of objects, and it is a JSON ${node.kind}.`);\n } else if (node.of.kind !== \"object\") {\n refuse(`${at} declares \\`uniqueBy\\`, and its items are JSON ${node.of.kind} values, not objects. For plain values, use \\`uniqueItems: true\\`.`);\n } else if (uniqueBy.length === 0) {\n refuse(`${at} declares \\`uniqueBy: []\\`, which compares nothing. Name the item fields that must be unique, or drop it.`);\n } else {\n const fields = node.of.fields;\n const missing = uniqueBy.filter(field => !Object.prototype.hasOwnProperty.call(fields, field));\n if (missing.length > 0) {\n refuse(\n `${at} declares \\`uniqueBy\\` naming ${missing.map(field => `\"${field}\"`).join(\", \")}, which the items do not have ` +\n `(they have ${Object.keys(fields).map(field => `\"${field}\"`).join(\", \") || \"no fields\"}).`\n );\n }\n }\n }\n switch (node.kind) {\n case \"object\":\n for (const [field, child] of Object.entries(node.fields)) visit(child, path === \"\" ? field : `${path}.${field}`);\n return;\n case \"array\":\n visit(node.of, `${path}[]`);\n return;\n case \"oneOf\":\n for (const [variant, child] of Object.entries(node.variants)) visit(child, `${path}[${variant}]`);\n return;\n default:\n return;\n }\n };\n if (def.json !== undefined) {\n visit(def.json.kind === \"array\" && columnUniqueBy !== undefined\n ? { ...def.json, validate: { ...def.json.validate, uniqueBy: columnUniqueBy } }\n : def.json, \"\");\n }\n return problems;\n}\n\nfunction isMaterialized(def: AnySchemaDef): boolean {\n return isViewDef(def) && def.config.materialized === true;\n}\n\nfunction normalizeOrderBy(orderBy: OrderByTuple | readonly OrderByTuple[] | undefined): OrderByTuple[] | undefined {\n if (orderBy === undefined || orderBy.length === 0) return undefined;\n const tuples: OrderByTuple[] = [];\n if (isOrderByTuple(orderBy)) {\n tuples.push([...orderBy]);\n } else {\n for (const tuple of orderBy) tuples.push([...tuple]);\n }\n return tuples;\n}\n\nfunction isOrderByTuple(value: OrderByTuple | readonly OrderByTuple[]): value is OrderByTuple {\n return typeof value[0] === \"string\";\n}\n\nfunction hookFlags(hooks: object | undefined, names: readonly (keyof TableHookFlags)[]): TableHookFlags | undefined {\n if (!hooks) return undefined;\n const flags: TableHookFlags = {};\n for (const name of names) {\n if (typeof Reflect.get(hooks, name) === \"function\") flags[name] = true;\n }\n return Object.keys(flags).length > 0 ? flags : undefined;\n}\n\nfunction indexKeysOf(index: TableIndex): string[] {\n const keys: string[] = [];\n const keyOf = (entry: string | TableIndexKey): string => typeof entry === \"string\" ? entry : entry.column;\n for (const entry of index.columns ?? []) keys.push(keyOf(entry));\n for (const entry of index.include ?? []) keys.push(entry);\n const walk = (predicate: TableIndexPredicate | undefined): void => {\n if (!predicate) return;\n if (\"and\" in predicate) {\n for (const inner of predicate.and) walk(inner);\n return;\n }\n keys.push(predicate.column);\n };\n walk(index.where);\n return keys;\n}\n\nfunction compileTenant(\n tenant: { field: string; from: TenantSource; bypassRoles?: readonly string[] },\n columnOf: (key: string) => ColumnDescriptor | undefined,\n refuse: (message: string) => void\n): TenantDescriptor | undefined {\n const column = columnOf(tenant.field);\n if (!column) {\n refuse(\n `\\`tenant\\` scopes rows by \"${tenant.field}\", and the table has no such column or \\`belongsTo\\` relation. ` +\n `Declare it — \\`${tenant.field}: col.uuid().notNull()\\` — or name the column that already holds the tenant id. ` +\n \"The flag says what a column means; it does not add one.\"\n );\n return undefined;\n }\n let ok = true;\n if (!TENANT_KINDS.has(column.type.kind)) {\n refuse(`\"${tenant.field}\" is \\`${columnTypeLabel(column.type)}\\`, which cannot hold a tenant id. Use a text, \\`uuid\\` or integer column, or a \\`belongsTo\\` the tenants table.`);\n ok = false;\n }\n if (column.private || column.access?.read !== undefined) {\n refuse(\n `\"${tenant.field}\" is the tenant every row belongs to, and it is also hidden from callers ` +\n `(\\`${column.private ? \".private()\" : \"access.read\"}\\`), so a client could never see which tenant a row it ` +\n \"just wrote is in. Drop the restriction, or drop `tenant`.\"\n );\n ok = false;\n }\n if (\"membership\" in tenant.from) {\n const searched: unknown = tenant.from.membership.table;\n if (typeof searched !== \"string\" || searched.trim() === \"\") {\n refuse(\n \"`tenant.from.membership` names no table to read the memberships from, so the tenant test would search no table. \" +\n \"Write `membership: { table: \\\"<slug of the memberships table>\\\", userField, tenantField }`.\"\n );\n ok = false;\n }\n }\n if (!ok) return undefined;\n const out: TenantDescriptor = { field: column.key, from: tenant.from };\n if (tenant.bypassRoles !== undefined) out.bypassRoles = [...tenant.bypassRoles];\n return out;\n}\n\nfunction checkSearch(table: string, search: SearchConfig, byKey: ReadonlyMap<string, ColumnDescriptor>): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const refuse = (message: string) => problems.push({ table, key: \"search\", message });\n if (!Array.isArray(search.fields) || search.fields.length === 0) {\n refuse(\"`search.fields` lists no field. Name the text columns to index, e.g. `search: { fields: [\\\"title\\\"] }`.\");\n return problems;\n }\n for (const entry of search.fields) {\n const path = typeof entry === \"string\" ? entry : entry.path;\n const [head, ...rest] = path.split(\".\");\n const column = byKey.get(head);\n if (!column) {\n refuse(`\\`search.fields\\` names \"${path}\", and \"${head}\" is no column key of the table. Name a column from \\`columns\\`.`);\n continue;\n }\n if (rest.length > 0 && column.type.kind !== \"json\" && column.type.kind !== \"jsonb\") {\n refuse(`\\`search.fields\\` names the path \"${path}\", and \"${head}\" is \\`${columnTypeLabel(column.type)}\\`, not a JSON column. A dotted path reads into a \\`col.jsonb()\\` document.`);\n }\n if (column.private || column.access?.read !== undefined) {\n refuse(\n `\"${path}\" is named in \\`search.fields\\` and also restricted by \\`${column.private ? \".private()\" : \"access.read\"}\\`. ` +\n \"The search index is one generated column shared by every caller, so the field would stay matchable \" +\n \"to callers who can never see its value — recoverable a term at a time. Remove it from \" +\n \"`search.fields`, or drop the read restriction.\"\n );\n }\n }\n return problems;\n}\n\n/** The columns every auth table has whether it declares them or not, by key and SQL name. */\nconst AUTH_TABLE_NAMES = [\n \"id\", \"email\", \"displayName\", \"display_name\", \"photoURL\", \"photo_url\", \"roles\", \"passwordHash\", \"password_hash\",\n \"emailVerified\", \"email_verified\", \"emailVerificationToken\", \"email_verification_token\",\n \"emailVerificationSentAt\", \"email_verification_sent_at\", \"metadata\", \"createdAt\", \"created_at\", \"updatedAt\", \"updated_at\",\n \"isAnonymous\", \"is_anonymous\", \"tokensValidAfter\", \"tokens_valid_after\"\n];\n\nfunction checkRules(\n table: string,\n rls: RlsDescriptor,\n columns: readonly ColumnDescriptor[],\n relations: readonly RelationDescriptor[],\n auth: boolean\n): SchemaDefinitionProblem[] {\n const names = new Set<string>();\n for (const column of columns) {\n names.add(column.key);\n names.add(column.column);\n }\n for (const relation of relations) {\n if (relation.kind === \"belongsTo\") names.add(relation.name);\n }\n if (auth) for (const name of AUTH_TABLE_NAMES) names.add(name);\n return rls.rules.flatMap((rule, index) => [\n ...ruleShapeProblems(rule, rule.name ? `rule \"${rule.name}\"` : `rule #${index}`)\n .map(message => ({ table, key: `rls[${index}]`, message })),\n ...checkRuleFields(table, rule, index, { names })\n ]);\n}\n\n// ── Across tables ────────────────────────────────────────────────────────────\n\nfunction checkTablesTogether(prepared: readonly PreparedDef[]): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n const names = new Map<string, PreparedDef>();\n const slugs = new Map<string, PreparedDef>();\n const tables = new Map<string, PreparedDef>();\n let authTable: PreparedDef | undefined;\n for (const entry of prepared) {\n const sameName = names.get(entry.name);\n if (sameName) {\n problems.push({ table: entry.name, message: `two definitions are named \"${entry.name}\". Each table and view needs its own name.` });\n } else {\n names.set(entry.name, entry);\n }\n const sameSlug = slugs.get(entry.slug);\n if (sameSlug && sameSlug !== sameName) {\n problems.push({\n table: entry.name,\n message:\n `its slug \"${entry.slug}\" is also the slug of \"${sameSlug.name}\". The slug is the table's API path, ` +\n \"its SDK accessor and what scopes name. Give one of them its own `slug`.\"\n });\n } else if (!sameSlug) {\n slugs.set(entry.slug, entry);\n }\n const qualified = `${entry.schema}.${entry.table}`;\n const sameTable = tables.get(qualified);\n if (sameTable && sameTable !== sameName && sameTable !== sameSlug) {\n problems.push({\n table: entry.name,\n message:\n `it resolves to the SQL table \\`${qualified}\\`, which \"${sameTable.name}\" resolves to too. A table has ` +\n \"one owner. Give one of them another `table` or `schema`.\"\n });\n } else if (!sameTable) {\n tables.set(qualified, entry);\n }\n if (entry.kind === \"table\" && isAuthTableDef(entry.def)) {\n if (authTable) {\n problems.push({\n table: entry.name,\n message:\n `is a second \\`defineAuthTable\\` — \"${authTable.name}\" is already the table users are stored in. ` +\n \"A project has one user store; make this one a `defineTable`.\"\n });\n } else {\n authTable = entry;\n }\n }\n }\n return problems;\n}\n\nfunction claimJunction(\n junctions: Map<string, JunctionClaim>,\n through: string,\n source: PreparedDef,\n relationName: string,\n sourceKey: string,\n targetKey: string,\n target: PreparedDef,\n refuse: (message: string, key?: string) => void\n): void {\n const keys = JSON.stringify([[sourceKey, source.table], [targetKey, target.table]].sort());\n const owner = `the relation \"${relationName}\" of \"${source.name}\" (\"${sourceKey}\" → ${source.table}, \"${targetKey}\" → ${target.table})`;\n const first = junctions.get(through);\n if (!first) {\n junctions.set(through, { keys, owner, table: source.table });\n return;\n }\n if (first.keys === keys) return;\n refuse(\n `two many-to-many relations resolve to the junction table \"${through}\" with different key columns: ` +\n `${first.owner} and ${owner}. Only one table is created, so one of them would read and write columns ` +\n `that do not exist. Give this one its own junction — \\`through: \"${source.table}_${relationName}\"\\` — or, if ` +\n \"both are meant to be one link, declare it once.\",\n relationName\n );\n}\n\n/**\n * Identifiers that are distinct as written and one name once Postgres keeps\n * their first 63 bytes: tables, views, junction tables and enum types share a\n * namespace per schema (every table owns a row type of its name), and the\n * columns of one table share another. Also: one enum type name given two\n * different lists of values.\n */\nfunction checkStoredIdentifiers(descriptors: readonly TableDescriptor[], prepared: readonly PreparedDef[]): SchemaDefinitionProblem[] {\n const problems: SchemaDefinitionProblem[] = [];\n interface Claim { full: string; what: string; table: string; values?: readonly string[] }\n const relationsClaims = new Map<string, Claim>();\n const claim = (schema: string, full: string, what: string, table: string, values?: readonly string[], key?: string): void => {\n const stored = `${schema}.${toPostgresIdentifier(full)}`;\n const first = relationsClaims.get(stored);\n if (!first) {\n relationsClaims.set(stored, { full, what, table, values });\n return;\n }\n if (first.full === full) {\n const bothEnums = first.values !== undefined && values !== undefined;\n if (bothEnums && first.values && values && (first.values.length !== values.length || first.values.some((v, i) => v !== values[i]))) {\n problems.push({\n table,\n key,\n message:\n `the enum type \"${schema}\".\"${full}\" is given the values (${values.join(\", \")}) here and ` +\n `(${first.values.join(\", \")}) by ${first.what}. Columns sharing a named enum type must list the ` +\n \"same values, in the same order. Make them agree, or give one column its own type `name`.\"\n });\n }\n // A junction both sides declare, an enum type two columns share,\n // and a duplicate table (refused on its own) are one name on purpose.\n if (bothEnums || first.values === undefined && values === undefined) return;\n }\n problems.push({\n table,\n key,\n message:\n `${what} and ${first.what} both become \"${schema}\".\"${toPostgresIdentifier(full)}\" in Postgres, which keeps ` +\n \"only the first 63 bytes of an identifier — and tables, views, junction tables and enum types share \" +\n \"one namespace. The push would fail with \\\"already exists\\\". Give one of them a shorter name (a \" +\n \"`table`, a `.column()`, or an enum `name`).\"\n });\n };\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n claim(descriptor.schema, descriptor.table, `${descriptor.kind} \"${descriptor.table}\"`, entry.name);\n });\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n claim(JUNCTION_TABLE_SCHEMA, relation.through.table, `junction table \"${relation.through.table}\"`, entry.name, undefined, relation.name);\n }\n });\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n if (descriptor.kind !== \"table\") return;\n const enumOf = (column: ColumnDescriptor, table: string, schema: string, key: string): void => {\n const type = column.type.kind === \"array\" ? column.type.of : column.type;\n if (type.kind !== \"enum\") return;\n // A column referencing an enum key uses the key table's type.\n if (column.derived) return;\n const name = deriveEnumTypeName(type, table, column.column);\n claim(schema, name, `the enum type of \"${entry.name}.${key}\"`, entry.name, type.values, key);\n };\n for (const column of descriptor.columns) enumOf(column, descriptor.table, descriptor.schema, column.key);\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n for (const column of relation.through.pivot) enumOf(column, relation.through.table, JUNCTION_TABLE_SCHEMA, `${relation.name}.pivot.${column.key}`);\n }\n });\n descriptors.forEach((descriptor, index) => {\n const entry = prepared[index];\n const seen = new Map<string, ColumnDescriptor>();\n for (const column of descriptor.columns) {\n const stored = toPostgresIdentifier(column.column);\n const first = seen.get(stored);\n if (!first) {\n seen.set(stored, column);\n continue;\n }\n problems.push({\n table: entry.name,\n key: column.key,\n message: first.column === column.column\n ? `\"${column.key}\" and \"${first.key}\" both resolve to the SQL column \"${column.column}\" (a column is its ` +\n \"`.column()`, or its key in snake_case), so the table would declare it twice. Rename one, or give \" +\n \"it its own `.column(\\\"…\\\")`.\"\n : `\"${column.key}\" and \"${first.key}\" resolve to the columns \"${column.column}\" and \"${first.column}\", ` +\n `which are one name — \"${stored}\" — once Postgres keeps the first 63 bytes. Give one a shorter \\`.column()\\`.`\n });\n }\n });\n return problems;\n}\n","/**\n * From table definitions to what the server runs on: `CompiledTable[]`.\n *\n * `compileTables` produces the wire-safe descriptors; this adds, per table,\n * the server-only parts the descriptor cannot carry — the table's hooks, its\n * columns' field-level hooks (addressed by column key and nested path) and the\n * auth table's lifecycle hooks — collected from the very definitions that were\n * compiled, so the two halves cannot describe different tables.\n *\n * @module\n */\nimport type {\n AnyTableDef,\n AnyViewDef,\n ColumnDef,\n CompiledAuthHooks,\n CompiledTable,\n CompiledTransform,\n DefaultRls,\n JsonShapeDef,\n TableDescriptor,\n TableHooks,\n TransformNode,\n JsonPathStep\n} from \"@rebasepro/types\";\nimport { isAuthTableDef, isColumnBuilder } from \"@rebasepro/types\";\n\nimport { compileTables } from \"./compile-tables\";\nimport { SchemaDefinitionError, type SchemaDefinitionProblem } from \"./errors\";\nimport { keyTypeProblem } from \"./validate-tables\";\nimport { tableDefsFromDescriptors, type TableDefsFromDescriptorsOptions } from \"./descriptor-to-def\";\n\n/**\n * Options of {@link compileSchema}.\n *\n * @group Schema\n */\nexport interface CompileSchemaOptions {\n /**\n * The project's `defaultRls` (exported from `backend/schema/index.ts`):\n * what every `rls: \"inherit\"` table takes. Without it, `\"inherit\"` is\n * refused.\n */\n defaultRls?: DefaultRls;\n}\n\n/**\n * Compile table and view definitions into the tables the server runs on.\n *\n * The descriptors are exactly `compileTables(defs, options)` — same order,\n * same errors: every problem in every definition is collected into one\n * `SchemaDefinitionError`. Each comes back with the definition it was compiled\n * from and the server-only parts of that definition: `hooks`, the field-level\n * hooks of its columns as {@link TransformNode} trees by column key, and, for\n * a `defineAuthTable`, `onCreateUser` / `onResetPassword`.\n *\n * Pure: nothing is registered, nothing is called.\n *\n * @group Schema\n */\nexport function compileSchema(\n defs: readonly (AnyTableDef | AnyViewDef)[],\n options: CompileSchemaOptions = {}\n): CompiledTable[] {\n const descriptors = compileTables(defs, options.defaultRls !== undefined ? { defaultRls: options.defaultRls } : {});\n // `compileTables` throws unless every definition compiled, and returns them\n // in input order: descriptor i is definition i.\n return descriptors.map((descriptor, index) => compiledTable(defs[index], descriptor));\n}\n\n/**\n * Tables the server runs on for descriptors nobody authored — what\n * introspection reads from a database no project declared.\n *\n * Each descriptor is kept exactly as given (its row-level security is the\n * catalogue's, its key what the database holds, possibly none); the\n * definition beside it is the one {@link tableDefsFromDescriptors} states for\n * it, so a reader of `def` sees the same table. Such a table declares no hooks.\n *\n * A table keyed on a column no row can be addressed by — a JSON document,\n * binary data, a vector, a list — is refused (a {@link SchemaDefinitionError}\n * naming it), as a declared one is; introspection drops it with that reason.\n *\n * @param options Passed to {@link tableDefsFromDescriptors}: introspection\n * replaces each `rls` with `\"admin-only\"`, because Rebase generates no policy\n * for a table it did not declare.\n *\n * @group Schema\n */\nexport function compileDescribedTables(\n descriptors: readonly TableDescriptor[],\n options: TableDefsFromDescriptorsOptions = {}\n): CompiledTable[] {\n const problems: SchemaDefinitionProblem[] = [];\n for (const descriptor of descriptors) {\n for (const column of descriptor.columns) {\n if (!descriptor.primaryKey.includes(column.key)) continue;\n const problem = keyTypeProblem(column.type, column.semantic);\n if (problem !== undefined) problems.push({ table: descriptor.name, key: column.key, message: problem });\n }\n }\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n const defs = tableDefsFromDescriptors(descriptors, options);\n return descriptors.map((descriptor, index) => ({ descriptor, def: defs[index] }));\n}\n\n/**\n * Every field-level hook of a compiled table, flattened: one entry per hook,\n * with its column key and the path inside the column's value. Columns in the\n * table's physical order; inside a column, the column's own hook first, then\n * its nested ones depth first.\n *\n * @group Schema\n */\nexport function listTransforms(table: CompiledTable): CompiledTransform[] {\n const out: CompiledTransform[] = [];\n if (!table.transforms) return out;\n const visit = (column: string, node: TransformNode, path: JsonPathStep[]): void => {\n if (node.transform) out.push({ column, path, transform: node.transform });\n for (const [field, child] of Object.entries(node.fields ?? {})) visit(column, child, [...path, { field }]);\n if (node.items) visit(column, node.items, [...path, { items: true }]);\n for (const [variant, child] of Object.entries(node.variants ?? {})) visit(column, child, [...path, { variant }]);\n };\n const transforms = table.transforms;\n for (const column of table.descriptor.columns) {\n const node = transforms[column.key];\n if (node) visit(column.key, node, []);\n }\n return out;\n}\n\n// ── One table ────────────────────────────────────────────────────────────────\n\n/**\n * One compiled table from a definition and the descriptor it compiled to: the\n * server-only parts collected from `def` beside `descriptor`. What\n * {@link compileSchema} does per table, for a caller that compiled the\n * descriptor itself (`compileTable` with a resolver of its own).\n *\n * @group Schema\n */\nexport function compiledTable(def: AnyTableDef | AnyViewDef, descriptor: TableDescriptor): CompiledTable {\n const compiled: CompiledTable = { descriptor, def };\n const hooks = hooksOf(def);\n if (hooks) compiled.hooks = hooks;\n const transforms = transformsOf(def);\n if (transforms) compiled.transforms = transforms;\n if (isAuthTableDef(def)) {\n const auth: CompiledAuthHooks = {};\n if (typeof def.auth.onCreateUser === \"function\") auth.onCreateUser = def.auth.onCreateUser;\n if (typeof def.auth.onResetPassword === \"function\") auth.onResetPassword = def.auth.onResetPassword;\n if (auth.onCreateUser || auth.onResetPassword) compiled.auth = auth;\n }\n return compiled;\n}\n\n/** The table's hooks, or `undefined` when it declares none. A view has read hooks only. */\nfunction hooksOf(def: AnyTableDef | AnyViewDef): TableHooks | undefined {\n const declared: TableHooks | undefined = def.config.hooks;\n if (!declared) return undefined;\n const hooks: TableHooks = { ...declared };\n return Object.values(hooks).some(hook => typeof hook === \"function\") ? hooks : undefined;\n}\n\n/** The transform tree of every column that declares a field-level hook, by column key. */\nfunction transformsOf(def: AnyTableDef | AnyViewDef): Record<string, TransformNode> | undefined {\n const out: Record<string, TransformNode> = {};\n for (const [key, builder] of Object.entries(def.config.columns)) {\n if (!isColumnBuilder(builder)) continue;\n const node = columnNode(builder.def);\n if (node) out[key] = node;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** The node for one column: its own hook, its JSON shape's and its array element's. */\nfunction columnNode(def: ColumnDef): TransformNode | undefined {\n const node: TransformNode = {};\n if (hasHook(def.transform)) node.transform = def.transform;\n if (def.json) {\n const shape = shapeNode(def.json);\n if (shape) Object.assign(node, shape);\n }\n if (def.element) {\n const items = columnNode(def.element);\n if (items) node.items = items;\n }\n return isEmpty(node) ? undefined : node;\n}\n\n/** The node for one position of a JSON shape. */\nfunction shapeNode(shape: JsonShapeDef): TransformNode | undefined {\n const node: TransformNode = {};\n if (hasHook(shape.transform)) node.transform = shape.transform;\n switch (shape.kind) {\n case \"object\": {\n const fields: Record<string, TransformNode> = {};\n for (const [key, field] of Object.entries(shape.fields)) {\n const child = shapeNode(field);\n if (child) fields[key] = child;\n }\n if (Object.keys(fields).length > 0) node.fields = fields;\n break;\n }\n case \"array\": {\n const items = shapeNode(shape.of);\n if (items) node.items = items;\n break;\n }\n case \"oneOf\": {\n const variants: Record<string, TransformNode> = {};\n for (const [name, variant] of Object.entries(shape.variants)) {\n const child = shapeNode(variant);\n if (child) variants[name] = child;\n }\n if (Object.keys(variants).length > 0) node.variants = variants;\n break;\n }\n default:\n break;\n }\n return isEmpty(node) ? undefined : node;\n}\n\nfunction hasHook(transform: ColumnDef[\"transform\"]): transform is NonNullable<ColumnDef[\"transform\"]> {\n return transform !== undefined && (typeof transform.beforeSave === \"function\" || typeof transform.afterRead === \"function\");\n}\n\nfunction isEmpty(node: TransformNode): boolean {\n return !node.transform && !node.fields && !node.items && !node.variants;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { fileURLToPath, pathToFileURL } from \"url\";\nimport {\n LEGACY_LAYOUT_REMEDY,\n isTableDef,\n isViewDef,\n type AnyTableDef,\n type AnyViewDef,\n type CompiledTable,\n type DefaultRls,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { SchemaDefinitionError, compileSchema, compileTables, type SchemaDefinitionProblem } from \"@rebasepro/common\";\n\n/**\n * The one definition of \"the tables\".\n *\n * Every door that reads a project's `backend/schema` — server boot, the stock\n * runtime, `rebase db generate`, `db push`, the doctor, SDK generation — calls\n * {@link loadBackendSchema}, so they cannot disagree about which tables exist\n * or which of them are protected. A definition that would leave a table\n * unprotected stops all of them the same way.\n */\n\n/** The module names that make a directory a schema: its `index`. */\nconst INDEX_FILES = [\"index.ts\", \"index.mts\", \"index.js\", \"index.mjs\"] as const;\nconst MODULE_EXTENSIONS = [\".ts\", \".mts\", \".js\", \".mjs\"] as const;\n\n/**\n * A `backend/schema` directory, imported and checked.\n *\n * @group Schema\n */\nexport interface LoadedSchema {\n /** The schema directory, absolute. */\n dir: string;\n /**\n * The index module the definitions were read from, absolute. Empty when the\n * directory has no index — the project declares no tables, and the runtime\n * introspects the database instead.\n */\n indexFile: string;\n /**\n * Every table and view the index exports, each once, in the order the\n * index module's namespace lists them (an ES module namespace lists its\n * exports by name; a CommonJS build in declaration order).\n */\n defs: (AnyTableDef | AnyViewDef)[];\n /** The `defaultRls` the index exports: what `rls: \"inherit\"` resolves to. */\n defaultRls?: DefaultRls;\n}\n\n/**\n * Options of {@link loadBackendSchema}.\n *\n * @group Schema\n */\nexport interface LoadBackendSchemaOptions {\n /**\n * The project root, where a legacy `config/collections` directory would\n * be. Defaults to two levels above `dir` (`<root>/backend/schema`).\n * `false` skips that check — for a built bundle, whose layout the\n * manifest's format version already vouches for.\n */\n projectRoot?: string | false;\n /**\n * How a module of the directory is imported: the index and every sibling\n * module go through it. Defaults to a plain `import()`.\n *\n * The default is right wherever a loader already handles TypeScript — the\n * server under tsx, the stock runtime reading a compiled bundle, a test\n * runner. A CLI process is not running under a TypeScript loader, and a\n * schema module's relative imports are extensionless (`./users`), which\n * Node's own type stripping cannot resolve; such a caller passes an\n * importer that can (the CLI passes jiti). Whatever it returns must be the\n * module's namespace: the definitions are read off its exports.\n */\n importModule?: SchemaModuleImporter;\n}\n\n/**\n * A module importer for {@link LoadBackendSchemaOptions.importModule}: takes an\n * absolute file path, returns the module's exports.\n *\n * @group Schema\n */\nexport type SchemaModuleImporter = (file: string) => Promise<Record<string, unknown>>;\n\n/**\n * The schema directory could not be read: a module failed to import, the\n * project is still on the `config/collections` layout, or the index does not\n * export what its siblings define.\n *\n * Distinct from {@link SchemaDefinitionError}, which says a definition is\n * wrong; this says the files could not be turned into definitions at all.\n *\n * @group Schema\n */\nexport class SchemaLoadError extends Error {\n\n readonly code = \"SCHEMA_LOAD_FAILED\";\n\n constructor(\n message: string,\n /** The file the failure is about, absolute, when there is one. */\n readonly file?: string,\n options?: { cause?: unknown }\n ) {\n super(message, options);\n this.name = \"SchemaLoadError\";\n }\n}\n\n/**\n * Whether an error is a {@link SchemaLoadError}, from this copy of the package\n * or another.\n *\n * @group Schema\n */\nexport function isSchemaLoadError(error: unknown): error is SchemaLoadError {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"SCHEMA_LOAD_FAILED\";\n}\n\nasync function nativeImport(file: string): Promise<Record<string, unknown>> {\n // A plain import(), so the tsx loader (or the runtime's own resolution of a\n // compiled bundle) resolves `.ts` and workspace specifiers.\n return await import(pathToFileURL(file).href);\n}\n\n/**\n * What Node's ESM loader needs when it failed on a relative import written\n * without its extension (`export { users } from \"./users\"` in a compiled\n * `index.js`): one sentence naming the import and its fix. Undefined for any\n * other failure — including a module that is missing under every extension,\n * where the extension is not what is wrong.\n */\nfunction missingExtensionHint(error: unknown): string | undefined {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ERR_MODULE_NOT_FOUND\") return undefined;\n // Node names the module it looked for, resolved: `Cannot find module '/app/dist/schema/users' imported from /app/dist/schema/index.js`.\n const match = /Cannot find module '([^']+)' imported from ([^\\n]+)/.exec(error.message);\n if (!match) return undefined;\n const asPath = (text: string): string => (text.startsWith(\"file:\") ? fileURLToPath(text) : text);\n const missing = asPath(match[1]);\n const importer = asPath(match[2].trim());\n if (!path.isAbsolute(missing) || path.extname(missing) !== \"\") return undefined;\n const found = [\".js\", \".ts\", \".mjs\", \".mts\"].find(extension => fs.existsSync(missing + extension));\n if (found === undefined) return undefined;\n let written = path.relative(path.dirname(importer), missing).split(path.sep).join(\"/\");\n if (!written.startsWith(\"../\")) written = `./${written}`;\n const extension = found === \".mjs\" || found === \".mts\" ? \".mjs\" : \".js\";\n return `The import \\`${written}\\` in ${path.basename(importer)} has no extension, which Node's ESM loader needs on a relative import: ` +\n `write \\`${written}${extension}\\` in the source, or build with \\`rebase build\\`, which adds it.`;\n}\n\nasync function importOrThrow(importModule: SchemaModuleImporter, file: string, role: string): Promise<Record<string, unknown>> {\n try {\n return await importModule(file);\n } catch (error) {\n const hint = missingExtensionHint(error);\n throw new SchemaLoadError(\n `Could not import ${file} (${role}).\\n\\n` +\n `${error instanceof Error ? error.message : String(error)}\\n\\n` +\n (hint !== undefined ? `${hint}\\n\\n` : \"\") +\n \"Every module in backend/schema must import cleanly: a table that cannot be read is a route \" +\n \"without policies, or policies without a route. Fix the file, or delete it.\",\n file,\n { cause: error }\n );\n }\n}\n\n/** A legacy collection: a plain object with `properties`, the shape `defineCollection` returned. */\nfunction isLegacyCollection(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null || isTableDef(value) || isViewDef(value)) return false;\n if (!(\"properties\" in value) || typeof value.properties !== \"object\" || value.properties === null) return false;\n return (\"slug\" in value && typeof value.slug === \"string\") || (\"name\" in value && typeof value.name === \"string\");\n}\n\nfunction legacyLayoutError(what: string, file?: string): SchemaLoadError {\n return new SchemaLoadError(\n `${what}. This runtime reads tables from backend/schema (\\`defineTable\\`, \\`defineAuthTable\\`, ` +\n `\\`defineView\\`); \\`defineCollection\\` and config/collections are no longer read. To migrate: ` +\n `${LEGACY_LAYOUT_REMEDY}.`,\n file\n );\n}\n\n/** Every module file under `dir` other than its index, depth first, sorted, for a stable error order. */\nfunction siblingModules(dir: string): string[] {\n const out: string[] = [];\n const walk = (current: string, top: boolean): void => {\n const entries = fs.readdirSync(current, { withFileTypes: true })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n for (const entry of entries) {\n // Dotfiles are never modules (macOS AppleDouble sidecars `._x.ts`\n // are binary blobs whose names end in .ts).\n if (entry.name.startsWith(\".\")) continue;\n const full = path.join(current, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\" || entry.name === \"__tests__\") continue;\n walk(full, false);\n continue;\n }\n if (!entry.isFile()) continue;\n if (!MODULE_EXTENSIONS.some(ext => entry.name.endsWith(ext))) continue;\n if (/\\.d\\.[mc]?ts$/.test(entry.name) || /\\.(test|spec)\\./.test(entry.name)) continue;\n if (top && (INDEX_FILES as readonly string[]).includes(entry.name)) continue;\n out.push(full);\n }\n };\n walk(dir, true);\n return out;\n}\n\nfunction isDefaultRls(value: unknown): value is DefaultRls {\n return value === \"admin-only\" || (Array.isArray(value) && value.length > 0);\n}\n\n/**\n * Import a project's `backend/schema` directory.\n *\n * - Reads `<dir>/index.(ts|mts|js|mjs)` and collects every export that is a\n * `defineTable` / `defineAuthTable` / `defineView` result, and `defaultRls`.\n * - The index is authoritative: every other module under `dir` is imported\n * too, and one defining a table or view the index does not export is\n * refused. A table with policies generated but no route — or a route with\n * no policies — is the bug that prevents.\n * - A module that fails to import is a {@link SchemaLoadError} naming the file;\n * nothing is ever skipped.\n * - A project still on the legacy layout (a `config/collections` directory, or\n * `defineCollection` results exported) is refused with the codemod to run.\n * - Validates by compiling: every problem with every definition (no `rls`,\n * `rls: []`, `\"inherit\"` without `defaultRls`, no primary key, a relation to\n * a table that is not exported…) is thrown together as one\n * {@link SchemaDefinitionError}.\n *\n * Returns the definitions, not lowered: see {@link compileLoadedSchema}. A\n * directory that does not exist, or has no index, declares no tables\n * (`defs: []`) — unless a sibling module defines one.\n *\n * @group Schema\n */\nexport async function loadBackendSchema(dir: string, options: LoadBackendSchemaOptions = {}): Promise<LoadedSchema> {\n const resolved = path.resolve(dir);\n const importModule = options.importModule ?? nativeImport;\n\n if (resolved.split(path.sep).join(\"/\").endsWith(\"/config/collections\")) {\n throw legacyLayoutError(`${resolved} is a config/collections directory`, resolved);\n }\n if (options.projectRoot !== false) {\n const projectRoot = path.resolve(options.projectRoot ?? path.join(resolved, \"..\", \"..\"));\n const legacyDir = path.join(projectRoot, \"config\", \"collections\");\n if (fs.existsSync(legacyDir) && fs.statSync(legacyDir).isDirectory()) {\n // With the tables already written, the codemod has run: it leaves\n // config/collections for `--check` until its author deletes it. Telling\n // that author to run the codemod sends them round the loop again.\n if (INDEX_FILES.some(name => fs.existsSync(path.join(resolved, name)))) {\n throw new SchemaLoadError(\n `The project has ${resolved} and still has ${legacyDir}, which the migration leaves in place ` +\n \"for `rebase migrate collections-to-tables --check`. Remove what Rebase used to read from config/ \" +\n \"once you no longer need that check — `git rm -r config/collections`, and config/index.ts, \" +\n \"config/resources.ts and config/storage.ts if the migration moved them — then run this again.\",\n legacyDir\n );\n }\n throw legacyLayoutError(`The project still has ${legacyDir}`, legacyDir);\n }\n }\n\n if (!fs.existsSync(resolved)) {\n return { dir: resolved, indexFile: \"\", defs: [] };\n }\n if (!fs.statSync(resolved).isDirectory()) {\n throw new SchemaLoadError(\n `${resolved} is a file. The schema is a directory whose index exports the tables: point at backend/schema.`,\n resolved\n );\n }\n\n const indexName = INDEX_FILES.find(name => fs.existsSync(path.join(resolved, name)));\n const indexFile = indexName ? path.join(resolved, indexName) : \"\";\n\n const defs: (AnyTableDef | AnyViewDef)[] = [];\n let defaultRls: DefaultRls | undefined;\n if (indexFile) {\n const mod = await importOrThrow(importModule, indexFile, \"the schema index\");\n for (const [name, value] of Object.entries(mod)) {\n if (isTableDef(value) || isViewDef(value)) {\n if (!defs.includes(value)) defs.push(value);\n continue;\n }\n if (name === \"defaultRls\") {\n if (value !== undefined && !isDefaultRls(value)) {\n throw new SchemaDefinitionError([{\n table: \"defaultRls\",\n message:\n `exported from ${indexFile} is ${JSON.stringify(value)}. It must be \\`\"admin-only\"\\` or a ` +\n \"non-empty list of rules — what every `rls: \\\"inherit\\\"` table takes. (`\\\"inherit\\\"` and `[]` \" +\n \"are not postures a default can have.)\"\n }]);\n }\n if (value !== undefined) defaultRls = value;\n continue;\n }\n if (isLegacyCollection(value) || ((name === \"collections\" || name === \"backendCollections\") && Array.isArray(value))) {\n throw legacyLayoutError(`${indexFile} exports \\`${name}\\`, a collection`, indexFile);\n }\n }\n }\n\n // The index is authoritative: a definition anywhere else that it does not\n // export is refused, every one of them reported at once.\n const exported = new Set<unknown>(defs);\n const exportedNames = new Set(defs.map(def => `${def.brand}:${def.name}`));\n const problems: SchemaDefinitionProblem[] = [];\n for (const file of siblingModules(resolved)) {\n const mod = await importOrThrow(importModule, file, \"a schema module\");\n const relative = path.relative(resolved, file);\n for (const [name, value] of Object.entries(mod)) {\n if (isLegacyCollection(value)) {\n throw legacyLayoutError(`${file} exports \\`${name}\\`, a collection (\\`defineCollection\\`)`, file);\n }\n if (!isTableDef(value) && !isViewDef(value)) continue;\n // The same object reached twice through two module instances is\n // still the exported definition; match those by kind and name.\n if (exported.has(value) || exportedNames.has(`${value.brand}:${value.name}`)) continue;\n const kind = isViewDef(value) ? \"view\" : \"table\";\n problems.push({\n table: value.name,\n message:\n `is a ${kind} defined in ${relative} (export \\`${name}\\`) that ${indexFile ? path.basename(indexFile) : \"no index\"} ` +\n `does not export. Only what backend/schema/index exports is served and protected: add ` +\n `\\`export { ${name} } from \"./${relative.replace(/\\.[mc]?[jt]s$/, \"\")}\";\\` to the index, or delete the definition.`\n });\n }\n }\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n\n // Fail closed, for every caller: compiling is the validation.\n compileTables(defs, defaultRls !== undefined ? { defaultRls } : {});\n\n return { dir: resolved, indexFile, defs, ...(defaultRls !== undefined ? { defaultRls } : {}) };\n}\n\n/**\n * A loaded schema compiled, the same way for every caller.\n *\n * @group Schema\n */\nexport interface CompiledSchema {\n /**\n * The compiled tables, in definition order: each descriptor with its\n * hooks, field-level hooks and definition. What the data driver runs on.\n */\n tables: CompiledTable[];\n /** The descriptors, in definition order: `tables[i].descriptor`. */\n descriptors: TableDescriptor[];\n}\n\n/**\n * Compile table and view definitions to {@link CompiledSchema.tables} and their\n * descriptors. Boot, the runtime and the CLI all compile through this.\n *\n * @group Schema\n */\nexport function compileSchemaDefs(\n defs: readonly (AnyTableDef | AnyViewDef)[],\n defaultRls?: DefaultRls\n): CompiledSchema {\n const options = defaultRls !== undefined ? { defaultRls } : {};\n const tables = compileSchema(defs, options);\n return { tables, descriptors: tables.map(table => table.descriptor) };\n}\n\n/**\n * {@link compileSchemaDefs} over what {@link loadBackendSchema} returned.\n *\n * @group Schema\n */\nexport function compileLoadedSchema(loaded: LoadedSchema): CompiledSchema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