@rebasepro/server 0.33.0 → 0.33.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-B3p3aUX-.js → GCSStorageController-kCv5MH2B.js} +3 -3
- package/dist/{GCSStorageController-B3p3aUX-.js.map → GCSStorageController-kCv5MH2B.js.map} +1 -1
- package/dist/{S3StorageController-C9LjuMhL.js → S3StorageController-DqK533Sl.js} +3 -3
- package/dist/{S3StorageController-C9LjuMhL.js.map → S3StorageController-DqK533Sl.js.map} +1 -1
- package/dist/{access-BxkEYQh1.js → access-CRQBlEZY.js} +4 -4
- package/dist/{access-BxkEYQh1.js.map → access-CRQBlEZY.js.map} +1 -1
- package/dist/auth/api-keys/api-key-routes.d.ts +10 -1
- package/dist/auth/scope-routes.d.ts +7 -0
- package/dist/{auth-Bfwjg4Bg.js → auth-BanB_pZj.js} +18 -16
- package/dist/{auth-Bfwjg4Bg.js.map → auth-BanB_pZj.js.map} +1 -1
- package/dist/{backup-g2ohsDe0.js → backup-CVNce2jz.js} +6 -6
- package/dist/{backup-g2ohsDe0.js.map → backup-CVNce2jz.js.map} +1 -1
- package/dist/{branch-routes-DtNtc0Vh.js → branch-routes-aLDaGOD1.js} +2 -2
- package/dist/{branch-routes-DtNtc0Vh.js.map → branch-routes-aLDaGOD1.js.map} +1 -1
- package/dist/{contract-routes-CZTlAP7p.js → contract-routes-a4ZbN1h3.js} +3 -3
- package/dist/{contract-routes-CZTlAP7p.js.map → contract-routes-a4ZbN1h3.js.map} +1 -1
- package/dist/{cron-loader-BBP0kBIl.js → cron-loader-CWhyA5eR.js} +2 -2
- package/dist/{cron-loader-BBP0kBIl.js.map → cron-loader-CWhyA5eR.js.map} +1 -1
- package/dist/{cron-routes-Du03uJ7K.js → cron-routes-CMGAz1my.js} +4 -4
- package/dist/{cron-routes-Du03uJ7K.js.map → cron-routes-CMGAz1my.js.map} +1 -1
- package/dist/{cron-scheduler-CopTWKYB.js → cron-scheduler-DQBdkkfb.js} +2 -2
- package/dist/{cron-scheduler-CopTWKYB.js.map → cron-scheduler-DQBdkkfb.js.map} +1 -1
- package/dist/{cron-store-FGaZOdMf.js → cron-store-CjUydRyp.js} +2 -2
- package/dist/{cron-store-FGaZOdMf.js.map → cron-store-CjUydRyp.js.map} +1 -1
- package/dist/{filter-dialect-XtPJOCbD.js → filter-dialect-nsQ2ozPY.js} +2 -2
- package/dist/{filter-dialect-XtPJOCbD.js.map → filter-dialect-nsQ2ozPY.js.map} +1 -1
- package/dist/{function-loader-D3YEHF6E.js → function-loader-Cihj_r86.js} +2 -2
- package/dist/{function-loader-D3YEHF6E.js.map → function-loader-Cihj_r86.js.map} +1 -1
- package/dist/{function-routes-DNDFIa7t.js → function-routes-CWaldgEj.js} +2 -2
- package/dist/{function-routes-DNDFIa7t.js.map → function-routes-CWaldgEj.js.map} +1 -1
- package/dist/{history-recorder-C5RkbKS2.js → history-recorder-B8TJMEfO.js} +2 -2
- package/dist/{history-recorder-C5RkbKS2.js.map → history-recorder-B8TJMEfO.js.map} +1 -1
- package/dist/index.es.js +63 -59
- package/dist/index.es.js.map +1 -1
- package/dist/{jobs-CFUwQTao.js → jobs-IJX3fE3X.js} +2 -2
- package/dist/{jobs-CFUwQTao.js.map → jobs-IJX3fE3X.js.map} +1 -1
- package/dist/{jwt-CqhXs8Iz.js → jwt-BuEprb39.js} +3 -3
- package/dist/{jwt-CqhXs8Iz.js.map → jwt-BuEprb39.js.map} +1 -1
- package/dist/{keys-Btt6ZNqF.js → keys-C8gpPIOG.js} +2 -2
- package/dist/{keys-Btt6ZNqF.js.map → keys-C8gpPIOG.js.map} +1 -1
- package/dist/{load-schema-CSEXeduP.js → load-schema-BvRxAuaD.js} +6 -3
- package/dist/{load-schema-CSEXeduP.js.map → load-schema-BvRxAuaD.js.map} +1 -1
- package/dist/{logs-routes-C3CLYP-n.js → logs-routes-BAq2ZxuY.js} +2 -2
- package/dist/{logs-routes-C3CLYP-n.js.map → logs-routes-BAq2ZxuY.js.map} +1 -1
- package/dist/{offline-ET6xI1ZO-BQpLQ7wh.js → offline-ET6xI1ZO-CIdB1ilf.js} +4 -4
- package/dist/{offline-ET6xI1ZO-BQpLQ7wh.js.map → offline-ET6xI1ZO-CIdB1ilf.js.map} +1 -1
- package/dist/{offline-store-DtmBwmKE-C9ba2NJv.js → offline-store-DtmBwmKE-CzyvC_Zj.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-C9ba2NJv.js.map → offline-store-DtmBwmKE-CzyvC_Zj.js.map} +1 -1
- package/dist/{openapi-generator-CAhJiwBm.js → openapi-generator-CCLtAJ2s.js} +2 -2
- package/dist/{openapi-generator-CAhJiwBm.js.map → openapi-generator-CCLtAJ2s.js.map} +1 -1
- package/dist/{project-root-CIrVZi-r.js → project-root-CuCOXvbk.js} +2 -2
- package/dist/{project-root-CIrVZi-r.js.map → project-root-CuCOXvbk.js.map} +1 -1
- package/dist/{proxy-clweqa43.js → proxy-DUUXXoQo.js} +2 -2
- package/dist/{proxy-clweqa43.js.map → proxy-DUUXXoQo.js.map} +1 -1
- package/dist/{query-parser-Cd70kZO8.js → query-parser-C9l1eFov.js} +3 -3
- package/dist/{query-parser-Cd70kZO8.js.map → query-parser-C9l1eFov.js.map} +1 -1
- package/dist/{request-timeout-cC3HT1Pf.js → request-timeout-DOu8ItLQ.js} +2 -2
- package/dist/{request-timeout-cC3HT1Pf.js.map → request-timeout-DOu8ItLQ.js.map} +1 -1
- package/dist/{rls-simulator-routes-DI2sYaQt.js → rls-simulator-routes-DIAjffhq.js} +3 -3
- package/dist/{rls-simulator-routes-DI2sYaQt.js.map → rls-simulator-routes-DIAjffhq.js.map} +1 -1
- package/dist/schema/index.js.map +1 -1
- package/dist/{schema-editor-routes-BxN0Q85n.js → schema-editor-routes-qWGWBPi0.js} +4 -4
- package/dist/{schema-editor-routes-BxN0Q85n.js.map → schema-editor-routes-qWGWBPi0.js.map} +1 -1
- package/dist/{schema-tables-DKFg6vMV.js → schema-tables-BneB2KZ7.js} +3 -3
- package/dist/{schema-tables-DKFg6vMV.js.map → schema-tables-BneB2KZ7.js.map} +1 -1
- package/dist/{schema-tables-routes-BfsNG4c4.js → schema-tables-routes-BBZJK8_S.js} +4 -4
- package/dist/{schema-tables-routes-BfsNG4c4.js.map → schema-tables-routes-BBZJK8_S.js.map} +1 -1
- package/dist/{securityRuleToConditions-Bk5zRSoa.js → securityRuleToConditions-Cj5ZR7TS.js} +2 -2
- package/dist/{securityRuleToConditions-Bk5zRSoa.js.map → securityRuleToConditions-Cj5ZR7TS.js.map} +1 -1
- package/dist/{selection-BOnbJvXD.js → selection-BB8ejqa2.js} +2 -2
- package/dist/{selection-BOnbJvXD.js.map → selection-BB8ejqa2.js.map} +1 -1
- package/dist/{sql-export-routes-B3oqb1Jw.js → sql-export-routes-CPXI3qZ7.js} +2 -2
- package/dist/{sql-export-routes-B3oqb1Jw.js.map → sql-export-routes-CPXI3qZ7.js.map} +1 -1
- package/dist/{src-CNZB3fuE.js → src-BdPKCs9u.js} +4 -2
- package/dist/src-BdPKCs9u.js.map +1 -0
- package/dist/{table-source-editor-DCJgZEz9.js → table-source-editor-D3m_VMwN.js} +6 -3
- package/dist/table-source-editor-D3m_VMwN.js.map +1 -0
- package/package.json +5 -5
- package/dist/src-CNZB3fuE.js.map +0 -1
- package/dist/table-source-editor-DCJgZEz9.js.map +0 -1
package/dist/schema/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../types/src/types/filter-operators.ts","../../../types/src/types/policy.ts","../../../types/src/types/rls-functions.ts","../../../types/src/types/data_source.ts","../../../types/src/types/resources.ts","../../../types/src/types/resource_kinds.ts","../../../types/src/types/scopes.ts","../../../types/src/schema/column_options.ts","../../../types/src/schema/json.ts","../../../types/src/schema/columns.ts","../../../types/src/schema/relations.ts","../../../types/src/schema/table.ts"],"sourcesContent":["/**\n * Canonical filter operators and REST wire-format mappings.\n *\n * `WhereFilterOp` is THE operator type used at every layer — from React\n * components through the SDK, server, and down to the database driver.\n *\n * PostgREST short-codes (`eq`, `gt`, `cs`, …) exist **only** at the\n * HTTP wire boundary, handled by `serializeFilter` / `deserializeFilter`\n * in `@rebasepro/common`.\n *\n * ┌──────────────────────┬───────────────┬──────────────────────────────┐\n * │ Canonical │ REST short │ Meaning │\n * ├──────────────────────┼───────────────┼──────────────────────────────┤\n * │ \"==\" │ \"eq\" │ Equal │\n * │ \"!=\" │ \"neq\" │ Not equal │\n * │ \">\" │ \"gt\" │ Greater than │\n * │ \">=\" │ \"gte\" │ Greater than or equal │\n * │ \"<\" │ \"lt\" │ Less than │\n * │ \"<=\" │ \"lte\" │ Less than or equal │\n * │ \"in\" │ \"in\" │ Value in list │\n * │ \"not-in\" │ \"nin\" │ Value not in list │\n * │ \"array-contains\" │ \"cs\" │ Array contains element │\n * │ \"array-contains-any\" │ \"csa\" │ Array contains any of │\n * │ \"array-contains-all\" │ \"csall\" │ Array contains all of │\n * │ \"array-contained-by\" │ \"cd\" │ Array holds only elements of │\n * │ \"like\" │ \"like\" │ SQL LIKE (case-sensitive) │\n * │ \"ilike\" │ \"ilike\" │ SQL ILIKE (case-insensitive) │\n * │ \"not-like\" │ \"nlike\" │ NOT LIKE (case-sensitive) │\n * │ \"not-ilike\" │ \"nilike\" │ NOT ILIKE (case-insensitive) │\n * │ \"is-null\" │ \"isnull\" │ Field IS NULL │\n * │ \"is-not-null\" │ \"notnull\" │ Field IS NOT NULL │\n * └──────────────────────┴───────────────┴──────────────────────────────┘\n *\n * Pattern matching (`like`/`ilike`) uses SQL wildcard syntax: `%` matches any\n * sequence of characters, `_` matches a single character. Firestore has no\n * native pattern matching and rejects these operators (use `searchString` instead).\n *\n * @module\n */\n\n/**\n * Where NULLs sort relative to real values on one key.\n *\n * Absent means the convention Postgres itself applies and the driver writes\n * out: `NULLS LAST` ascending, `NULLS FIRST` descending. That convention was\n * hardcoded and unstateable — a \"newest first\" list put every row with no date\n * at the very top, and the only way out was to add a `is-not-null` filter and\n * lose those rows entirely.\n *\n * The keyset comparison honours whatever is chosen here, so a cursor over a\n * nullable key stays correct under either placement.\n *\n * @group Models\n */\nexport type NullsPlacement = \"first\" | \"last\";\n\n/**\n * Canonical sort representation: `[fieldName, direction]`, optionally with a\n * {@link NullsPlacement}.\n *\n * Used in `FindParams.orderBy`, `collection.sort`, and `FilterPreset.sort`.\n * The colon-string form (`\"field:direction\"`, or `\"field:direction:nulls\"`)\n * exists only at the HTTP wire boundary, handled by `serializeOrderBy` /\n * `deserializeOrderBy` in `@rebasepro/common`.\n *\n * The third slot is optional so every `[field, direction]` written before it\n * existed is still exactly this type, and every `const [field, direction] =`\n * destructure still reads what it always read.\n *\n * @group Models\n */\nexport type OrderByTuple<Key extends string = string> = [Key, \"asc\" | \"desc\", NullsPlacement?];\n\n/**\n * One sort key, or several applied in order of significance.\n *\n * ```ts\n * orderBy: [\"created_at\", \"desc\"] // one key\n * orderBy: [[\"roles\", \"asc\"], [\"created_at\", \"desc\"]] // roles, then newest first\n * ```\n *\n * The two forms are told apart by whether the first element is itself an\n * array, so a single tuple never needs wrapping and every existing caller\n * keeps working unchanged. `normalizeOrderBy` in `@rebasepro/common` collapses\n * both to the list form, which is what every layer below the call site speaks.\n *\n * Ties on the last key are broken by the row id, so a multi-key sort is a\n * total order and pages over it neither repeat nor skip rows.\n *\n * @group Models\n */\nexport type OrderBySpec<Key extends string = string> =\n | OrderBySortTuple<Key>\n | OrderBySortTuple<Key>[];\n\n/**\n * A sort key: a field name, or an aggregate over a to-many relation.\n *\n * @group Models\n */\nexport type SortKey<Key extends string = string> = Key | RelationAggregateSort;\n\n/**\n * `[sortKey, direction]` — the authoring form of {@link OrderByTuple}, which\n * additionally accepts a {@link RelationAggregateSort} object.\n *\n * The object never reaches a driver: `normalizeOrderBy` in `@rebasepro/common`\n * encodes it to its string spelling on the way down, and everything below that\n * point speaks plain `OrderByTuple`. See {@link RelationAggregateSort} for why\n * the wire form is a string.\n *\n * @group Models\n */\nexport type OrderBySortTuple<Key extends string = string> = [SortKey<Key>, \"asc\" | \"desc\", NullsPlacement?];\n\n/**\n * The aggregate functions a relation sort can apply.\n *\n * Five, and no `array_agg`/`string_agg`: an aggregate used as a sort key has to\n * produce something with an order, and these are the ones that do.\n *\n * @group Models\n */\nexport type RelationAggregateFn = \"min\" | \"max\" | \"count\" | \"sum\" | \"avg\";\n\n/**\n * Order rows by an aggregate over the rows a to-many relation reaches —\n * \"candidates, oldest waiting first\", \"clients, busiest first\".\n *\n * ```ts\n * // The date of each candidate's earliest open application.\n * orderBy: [[{ relation: \"applications\", field: \"created_at\", agg: \"min\" }, \"asc\"]]\n *\n * // How many applications each candidate has.\n * orderBy: [[{ relation: \"applications\", agg: \"count\" }, \"desc\"]]\n * ```\n *\n * This is the half of a queue that cannot be worked around client-side. A\n * *filter* over a relation can be approximated by denormalising a flag onto the\n * row; an *ordering* cannot be approximated at all once the result set is\n * paged, because the client only ever holds one page and the page was chosen by\n * the wrong order.\n *\n * Rows the relation reaches nothing from sort last ascending and first\n * descending — the placement Postgres gives a `NULL`, stated rather than\n * inherited, because the keyset comparison behind cursor paging has to agree\n * with it exactly. Ties are broken by the row id, so the order is total and\n * paging over it neither repeats nor skips.\n *\n * Compiled by the driver into a correlated subquery, so it is subject to the\n * reader's own row-level security on the target table: a related row the reader\n * cannot see does not contribute to the aggregate. Offered only where\n * {@link DataSourceCapabilities.relationAggregateSorts} says the driver can\n * compile it.\n *\n * @group Models\n */\nexport interface RelationAggregateSort {\n /** The to-many relation to aggregate over, by its name on this collection. */\n relation: string;\n\n /** The aggregate to apply. */\n agg: RelationAggregateFn;\n\n /**\n * The column of the *target* to aggregate. Required by every function\n * except `count`, which counts the related rows themselves when it is\n * omitted — and counts the rows whose column is non-null when it is not.\n */\n field?: string;\n}\n\n/** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */\nconst RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\\(([^().]+)(?:\\.([^()]+))?\\)$/;\n\n/**\n * A {@link RelationAggregateSort} as a single string — `min(applications.created_at)`,\n * `count(applications)`.\n *\n * The wire form is a string because every layer below the call site already is\n * one: `OrderByTuple` is `[string, direction]`, the REST parameter is\n * `?orderBy=key:direction`, the driver contract takes `orderBy?: string |\n * OrderByTuple[]`, and a cursor names its keys by string. `_score` established\n * the same pattern — a sort key that is not a column, spelled as one — and this\n * reuses it rather than widening five signatures to carry an object that would\n * be flattened at the end anyway.\n *\n * SQL's own spelling, so the key reads as what it compiles to. Neither `:` nor\n * `,` appears in it, which is what keeps it safe in the colon-delimited wire\n * shorthand.\n *\n * @group Models\n */\nexport function encodeRelationAggregateSort(sort: RelationAggregateSort): string {\n return `${sort.agg}(${sort.relation}${sort.field ? `.${sort.field}` : \"\"})`;\n}\n\n/**\n * Read the string spelling back, or `undefined` if it is not one.\n *\n * `undefined` rather than a throw: this is asked of *every* sort key to find\n * out which kind it is, and an ordinary column name is not an error.\n *\n * @group Models\n */\nexport function parseRelationAggregateSort(key: string): RelationAggregateSort | undefined {\n const match = RELATION_AGGREGATE_SORT_PATTERN.exec(key);\n if (!match) return undefined;\n const [, agg, relation, field] = match;\n // `min()` and friends have nothing to aggregate without a column, and a\n // key that parses to a half-built sort would resolve to no expression and\n // be dropped — leaving the rows unsorted while the caller believes\n // otherwise. `count` is the one function that means something on its own.\n if (!field && agg !== \"count\") return undefined;\n return { agg: agg as RelationAggregateFn, relation, ...(field && { field }) };\n}\n\n/** Is this sort key the object form rather than a field name? */\nexport function isRelationAggregateSort(key: unknown): key is RelationAggregateSort {\n return typeof key === \"object\" && key !== null &&\n typeof (key as RelationAggregateSort).relation === \"string\" &&\n typeof (key as RelationAggregateSort).agg === \"string\";\n}\n\n/** A sort key in the single-string form every layer below the call site speaks. */\nexport function sortKeyToString(key: SortKey): string {\n return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;\n}\n\n/**\n * Canonical filter operators supported across all database backends.\n * Each DB driver translates these to its native query format.\n *\n * @group Models\n */\nexport type WhereFilterOp =\n | \"<\"\n | \"<=\"\n | \"==\"\n | \"!=\"\n | \">=\"\n | \">\"\n | \"array-contains\"\n | \"in\"\n | \"not-in\"\n | \"array-contains-any\"\n | \"array-contains-all\"\n | \"array-contained-by\"\n | \"like\"\n | \"ilike\"\n | \"not-like\"\n | \"not-ilike\"\n | \"is-null\"\n | \"is-not-null\";\n\n/**\n * Used to define filters applied in collections.\n *\n * A single condition is a tuple `[operator, value]`.\n * Multiple conditions on the same field use an array of tuples.\n *\n * @example\n * // Single condition per field\n * { status: [\"==\", \"active\"], price: [\">=\", 9.99] }\n *\n * // Multiple conditions on one field\n * { age: [[\">=\", 18], [\"<\", 65]] }\n *\n * // Array operators\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { tags: [\"array-contains\", \"featured\"] }\n *\n * // Pattern matching (SQL wildcards: % and _)\n * { name: [\"ilike\", \"%john%\"] }\n * { slug: [\"like\", \"post-%\"] }\n *\n * // Null checks (the value is ignored; `null` is conventional, and an\n * // untyped caller may leave it out: `[\"is-null\"]`)\n * { deleted_at: [\"is-null\", null] }\n * { published_at: [\"is-not-null\", null] }\n *\n * @group Models\n */\nexport type FilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][]>>;\n\n/**\n * The field names a query may address on a row type: every column, plus a\n * dotted path reaching inside one — or *through a relation* to a column of the\n * related row.\n *\n * A dotted path is not checked at all, in either direction. That is a\n * deliberate loosening, and it is worth being exact about what it costs. The\n * root used to be checked: `\"meta.tag\"` required a `meta` column. It cannot\n * stay checked, because the other thing a dotted path now means is\n * `\"applications.status\"` — and `applications` is a *relation*, which comes\n * from the collection's `relations` and is not a column of `M` at all. There is\n * nothing in a generated row type that could validate one. `FindParams.include`\n * is `string[]` for exactly this reason and says so.\n *\n * So the guarantee moves rather than disappears: an unresolvable path is a 400\n * from the driver, not a silently dropped condition. See\n * `UnknownFilterFieldsMode` in `@rebasepro/server-postgres` — dropping a filter\n * key *widens* the read to every row, which is why that resolution fails\n * closed. A typo'd relation path is refused at runtime with the target\n * collection's real column list in the message.\n *\n * A JSON path — `metadata->>tier` — is admitted on the same terms and for the\n * same reason. It addresses a key *inside* a `json`/`jsonb` column, so nothing\n * in a generated row type describes it either; the driver resolves it and\n * refuses what it cannot. It has no dot, so the dotted branch above never\n * covered it, and every documented `?metadata->>tier=eq.gold` filter was a\n * compile error on a typed client while working perfectly over HTTP.\n *\n * Undotted keys are unaffected and still checked against `keyof M`.\n *\n * When `M` is left at its default `Record<string, unknown>`, `keyof M` is\n * `string` and this collapses to `string`, so every query stays permissive.\n * That is what keeps an untyped `createRebaseClient()` behaving exactly as it\n * did before the row type was threaded through.\n *\n * @group Models\n */\nexport type FieldPath<M extends Record<string, unknown> = Record<string, unknown>> =\n | Extract<keyof M, string>\n | NonColumnFieldPath;\n\n/**\n * A field key that is not a column: a relation path (`author.name`) or a JSON\n * path (`metadata->>tier`).\n *\n * The fluent builder needs this on its own, where `FindParams` does not. Its\n * `where(column, operator, value)` types the value against `M[column]`, which\n * only means something for a real column — so paths take a second overload\n * whose value is `unknown`. Keying that overload on the *shape* of a path,\n * rather than on \"everything that is not a column\", is what keeps a real column\n * with a wrong value type from falling through to it and being accepted: a\n * mistyped column name has neither a dot nor a `->>`, so it matches neither\n * overload and is still refused.\n *\n * @group Models\n */\nexport type NonColumnFieldPath =\n | `${string}.${string}`\n | `${string}->>${string}`\n | CaseFoldedFieldPath;\n\n/**\n * A text column compared in one case: `lower(artist)` or `upper(code)`. Every\n * operator applies to the folded value, so the values written beside it are\n * written in that case — `{ \"lower(artist)\": [\"in\", [\"abba\", \"queen\"]] }`\n * matches \"ABBA\" and \"Queen\". Compiled to `lower(artist)`, which an index on\n * that expression serves. The same spelling an aggregate's `groupBy` uses.\n *\n * @group Models\n */\nexport type CaseFoldedFieldPath = `lower(${string})` | `upper(${string})`;\n\n/**\n * Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or\n * `undefined` for any other key.\n *\n * @group Models\n */\nexport function parseCaseFoldedFieldPath(key: string): { fn: \"lower\" | \"upper\"; field: string } | undefined {\n const match = /^(lower|upper)\\(\\s*([^()\\s]+)\\s*\\)$/.exec(key);\n return match ? { fn: match[1] as \"lower\" | \"upper\", field: match[2] } : undefined;\n}\n\n/**\n * Relaxed filter type that also accepts pre-serialized PostgREST strings.\n * **Internal only** — used at the wire-format boundary\n * (`serializeFilter` / `deserializeFilter` in `@rebasepro/common`).\n *\n * Application code, UI components, and SDK consumers should use\n * {@link FilterValues} instead.\n *\n * @internal\n */\nexport type WireFilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][] | string>>;\n\n/**\n * PostgREST short-code operators. Wire format only — these never appear\n * in application code. Used by `serializeFilter`/`deserializeFilter`\n * in `@rebasepro/common`.\n */\nexport type RestFilterOp =\n | \"eq\" | \"neq\"\n | \"gt\" | \"gte\"\n | \"lt\" | \"lte\"\n | \"in\" | \"nin\"\n | \"cs\" | \"csa\" | \"csall\" | \"cd\"\n | \"like\" | \"ilike\"\n | \"nlike\" | \"nilike\"\n | \"isnull\" | \"notnull\";\n\n/** Maps canonical operators to their REST short-code equivalents. */\nexport const CANONICAL_TO_REST: Readonly<Record<WhereFilterOp, RestFilterOp>> = {\n \"==\": \"eq\",\n \"!=\": \"neq\",\n \">\": \"gt\",\n \">=\": \"gte\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \"in\": \"in\",\n \"not-in\": \"nin\",\n \"array-contains\": \"cs\",\n \"array-contains-any\": \"csa\",\n \"array-contains-all\": \"csall\",\n \"array-contained-by\": \"cd\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"not-like\": \"nlike\",\n \"not-ilike\": \"nilike\",\n \"is-null\": \"isnull\",\n \"is-not-null\": \"notnull\"\n};\n\n/** Maps REST short-code operators to their canonical equivalents. */\nexport const REST_TO_CANONICAL: Readonly<Record<RestFilterOp, WhereFilterOp>> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"csall\": \"array-contains-all\",\n \"cd\": \"array-contained-by\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"nlike\": \"not-like\",\n \"nilike\": \"not-ilike\",\n \"isnull\": \"is-null\",\n \"notnull\": \"is-not-null\"\n};\n\n/**\n * Operators that test for null/not-null and therefore ignore their value.\n * Codecs normalize the value of these conditions to `null`.\n */\nexport const NULL_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"is-null\", \"is-not-null\"\n]);\n\n/**\n * Operators whose operand is a **list** of values rather than one value.\n *\n * On the wire that list is always parenthesised — `in.(draft,review)` — which\n * is what lets the REST codec tell `?status=in.(a,b)` (the operator) from\n * `?status=in.progress` (a value that happens to start with an operator's\n * name). See `deserializeSingle` in `@rebasepro/common`.\n *\n * @group Models\n */\nexport const LIST_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"in\", \"not-in\", \"array-contains-any\", \"array-contains-all\", \"array-contained-by\"\n]);\n\n/**\n * Every canonical operator, in a stable order. Useful for engine capability\n * declarations ({@link DataSourceCapabilities.filterOperators}) and for\n * building operator subsets.\n * @group Models\n */\nexport const ALL_WHERE_FILTER_OPS: readonly WhereFilterOp[] = [\n \"<\", \"<=\", \"==\", \"!=\", \">=\", \">\",\n \"in\", \"not-in\",\n \"array-contains\", \"array-contains-any\", \"array-contains-all\", \"array-contained-by\",\n \"like\", \"ilike\", \"not-like\", \"not-ilike\",\n \"is-null\", \"is-not-null\"\n];\n\n/** All canonical operator strings for runtime validation. */\nconst CANONICAL_OPS: ReadonlySet<string> = new Set<WhereFilterOp>(ALL_WHERE_FILTER_OPS);\n\n/**\n * The REST table as a `Map`, because the key `toCanonicalOp` is handed comes\n * off the wire.\n *\n * Indexed as a plain object, every `Object.prototype` member answered:\n * `toCanonicalOp(\"valueOf\")` returned the inherited *function* as though it\n * were a `WhereFilterOp`, and every caller here treats a defined result as\n * \"known operator\". Same defect the REST codec's own lookup tables were\n * converted away from in `filter-dialect.ts`; this is the copy that survived\n * one package over, and it now sits under the operator validation the REST\n * parser does, which would otherwise have admitted `[\"constructor\", x]`.\n */\nconst REST_OP_LOOKUP: ReadonlyMap<string, WhereFilterOp> = new Map<string, WhereFilterOp>(\n Object.entries(REST_TO_CANONICAL) as [string, WhereFilterOp][]\n);\n\n/**\n * Resolve any operator string (canonical or REST short-code) to its\n * canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.\n *\n * @example\n * toCanonicalOp(\"==\") // \"==\"\n * toCanonicalOp(\"eq\") // \"==\"\n * toCanonicalOp(\"cs\") // \"array-contains\"\n * toCanonicalOp(\"xyz\") // undefined\n */\nexport function toCanonicalOp(op: string): WhereFilterOp | undefined {\n if (CANONICAL_OPS.has(op)) return op as WhereFilterOp;\n return REST_OP_LOOKUP.get(op);\n}\n","/**\n * Structured, engine-agnostic policy expressions.\n *\n * A {@link PolicyExpression} is the single source of truth for a row-level\n * security condition. It is compiled to Postgres `USING`/`WITH CHECK` SQL\n * (authoritative enforcement) and independently evaluated in JavaScript (to\n * drive the admin UI). Because both the SQL and the JS decision derive from\n * the *same* expression, the UI matches database enforcement by construction —\n * no drift between two hand-written implementations.\n *\n * The only escape hatch that cannot be evaluated client-side is the\n * {@link RawPolicyExpression} node (`{ kind: \"raw\" }`): it preserves full\n * PostgreSQL power but, being arbitrary SQL, is treated as *unknown* by the\n * JavaScript evaluator (never silently allowed) and reflected exactly in the UI\n * via server-computed capability flags.\n *\n * @group Models\n */\nexport type PolicyExpression =\n | TruePolicyExpression\n | FalsePolicyExpression\n | AndPolicyExpression\n | OrPolicyExpression\n | NotPolicyExpression\n | ComparePolicyExpression\n | RolesOverlapPolicyExpression\n | RolesContainPolicyExpression\n | AuthenticatedPolicyExpression\n | RegisteredPolicyExpression\n | ServerContextPolicyExpression\n | ExistsInPolicyExpression\n | RawPolicyExpression;\n\n/**\n * The id a request without a logged-in user reports as `rebase.uid()`.\n *\n * A user-context request always sets `app.uid`: blank would read back as\n * `NULL`, and `NULL` is how the trusted server context is recognised, so an\n * anonymous visitor would be promoted to server privileges. The driver\n * therefore substitutes this sentinel at the single chokepoint where the GUC\n * is set.\n *\n * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a\n * tautology on the user path** — it is true for anonymous visitors too. Use\n * {@link policy.authenticated} to mean \"signed in\", and\n * {@link policy.serverContext} to mean \"the trusted server context\". Do not\n * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one\n * literal is not enough.\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_ID = \"anonymous\";\n\n/**\n * Every uid that has ever meant \"nobody is signed in\" — newest first.\n *\n * There are two because there were two. The types, the policy compiler, the\n * JavaScript evaluator and the linter were all built on\n * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated\n * callers as `'anon'` — so `policy.authenticated()`, which compiled to\n * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The\n * sanctioned way to write \"signed in\" granted to everyone, and the linter\n * flagged the spelling that actually worked as a foreign convention.\n *\n * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here\n * because policies outlive the server that generated them: a database still\n * holding policies from before the fix, or a project whose server has not been\n * upgraded yet, must not become a grant in either direction. Compile against\n * this list, not against a single literal.\n *\n * No real user id is ever one of these, so a match is always \"not signed in\".\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_IDS: readonly string[] = [ANONYMOUS_USER_ID, \"anon\"];\n\n/**\n * Whether a uid stands for \"no one is signed in\", in any spelling rebase has\n * used. `null`/`undefined` is the trusted server context, not an anonymous\n * caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.\n *\n * @group Models\n */\nexport function isAnonymousUid(uid: string | null | undefined): boolean {\n return typeof uid === \"string\" && ANONYMOUS_USER_IDS.includes(uid);\n}\n\n/** Always allows. Compiles to `true`. @group Models */\nexport interface TruePolicyExpression {\n kind: \"true\";\n}\n\n/** Always denies. Compiles to `false`. @group Models */\nexport interface FalsePolicyExpression {\n kind: \"false\";\n}\n\n/** Logical AND — every operand must pass. @group Models */\nexport interface AndPolicyExpression {\n kind: \"and\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical OR — at least one operand must pass. @group Models */\nexport interface OrPolicyExpression {\n kind: \"or\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical negation. @group Models */\nexport interface NotPolicyExpression {\n kind: \"not\";\n operand: PolicyExpression;\n}\n\n/** Comparison operators available to {@link ComparePolicyExpression}. @group Models */\nexport type PolicyCompareOperator = \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\";\n\n/**\n * Compares two operands, e.g. `owner_id = rebase.uid()`.\n * @group Models\n */\nexport interface ComparePolicyExpression {\n kind: \"compare\";\n op: PolicyCompareOperator;\n left: PolicyOperand;\n right: PolicyOperand;\n}\n\n/**\n * True when the user holds *at least one* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') && ARRAY[...]`.\n * @group Models\n */\nexport interface RolesOverlapPolicyExpression {\n kind: \"rolesOverlap\";\n roles: readonly string[];\n}\n\n/**\n * True when the user holds *all* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') @> ARRAY[...]`.\n * @group Models\n */\nexport interface RolesContainPolicyExpression {\n kind: \"rolesContain\";\n roles: readonly string[];\n}\n\n/**\n * True when a signed-in user is making the request. Compiles to\n * `rebase.uid() IS NOT NULL AND rebase.uid() <> 'anonymous'`.\n *\n * Both halves are load-bearing. `IS NOT NULL` excludes the server context;\n * the {@link ANONYMOUS_USER_ID} comparison excludes anonymous visitors, who\n * *do* carry a non-null `rebase.uid()`. Checking only `IS NOT NULL` grants to\n * everyone — see {@link ANONYMOUS_USER_ID}.\n *\n * `policy.not(policy.authenticated())` therefore means \"anonymous visitor or\n * the server context\". To single out the server context, use\n * {@link ServerContextPolicyExpression}.\n * @group Models\n */\nexport interface AuthenticatedPolicyExpression {\n kind: \"authenticated\";\n}\n\n/**\n * True for a signed-in caller who has an ACCOUNT — not a guest.\n *\n * The distinction {@link AuthenticatedPolicyExpression} cannot make. Anonymous\n * SIGN-IN (`POST /auth/anonymous`) mints a real user row with a real uid and a\n * real session, so such a caller is \"authenticated\" by every test that looks at\n * `rebase.uid()`: same shape, same default role, indistinguishable inside a\n * policy. On a deployment with anonymous sign-in enabled, every rule meaning\n * \"a signed-in person\" therefore also meant \"anybody at all\", since pressing\n * Continue as guest needs no email, no password and no agreement to anything.\n *\n * Note the two senses of \"anonymous\", which is the reason this was easy to\n * miss. {@link ANONYMOUS_USER_ID} is the sentinel for a request carrying NO\n * session, and `authenticated()` already excludes it. A guest is the other\n * thing: a session with nobody behind it. This node excludes both.\n *\n * Compiles to `authenticated() AND NOT rebase.is_anonymous()`.\n *\n * Use it wherever a rule is about a person who could be held responsible for\n * something — writing a review, joining an organization, spending money. Use\n * `authenticated()` where a guest is genuinely welcome, which is what\n * anonymous sign-in is for: a cart before checkout, a draft before signup.\n * @group Models\n */\nexport interface RegisteredPolicyExpression {\n kind: \"registered\";\n}\n\n/**\n * True only in the trusted **server context** — the built-in flows that run\n * without a user (signup, migrations, `dataAsAdmin`) set no user GUC, so\n * `rebase.uid()` is `NULL` for them and only for them. Compiles to\n * `rebase.uid() IS NULL`.\n *\n * This is what lets the owner connection satisfy a policy even under FORCE RLS.\n * It is deliberately a primitive rather than `not(authenticated())`: the two\n * meant the same thing while `authenticated` ignored {@link ANONYMOUS_USER_ID},\n * and conflating them is what turns a server-only grant into an anonymous one.\n *\n * The JavaScript evaluator always returns `false` for this node — a client is\n * never the server context.\n * @group Models\n */\nexport interface ServerContextPolicyExpression {\n kind: \"serverContext\";\n}\n\n/**\n * Membership / relational access: true when at least one row exists in another\n * table (a join/membership table) matching `where`. This is what lets you\n * scope reads to \"rows whose team the caller belongs to\" without an N+1\n * per-row lookup — it compiles to a single correlated `EXISTS` subquery.\n *\n * Inside `where`, {@link FieldPolicyOperand} (`policy.field`) references a column\n * of the joined table, while {@link OuterFieldPolicyOperand}\n * (`policy.outerField`) references a column of the row being checked (the outer\n * table under RLS). Combine with {@link AuthUidPolicyOperand} to correlate to\n * the caller.\n *\n * @example\n * ```ts\n * // documents visible only to members of the document's team:\n * policy.existsIn({\n * table: \"team_members\",\n * where: policy.and(\n * policy.compare(policy.field(\"team_id\"), \"eq\", policy.outerField(\"team_id\")),\n * policy.compare(policy.field(\"user_id\"), \"eq\", policy.authUid()),\n * ),\n * })\n * // → EXISTS (SELECT 1 FROM team_members _ex0\n * // WHERE _ex0.team_id = documents.team_id AND _ex0.user_id = rebase.uid())\n * ```\n *\n * Postgres-authoritative: like {@link RawPolicyExpression}, the JavaScript\n * evaluator treats it as *unknown* (it cannot run a subquery client-side), so\n * enforcement is always the database's.\n * @group Models\n */\nexport interface ExistsInPolicyExpression {\n kind: \"existsIn\";\n /**\n * The table to search (the join / membership table), by its slug.\n *\n * Spelled `collection` before tables replaced collections in the backend\n * vocabulary. A policy's name hashes the rule as written, so the name\n * hash still reads this field as `collection` (see `getPolicyNameHash`).\n */\n table: string;\n /** Condition evaluated against the joined table's rows. */\n where: PolicyExpression;\n}\n\n/**\n * A raw PostgreSQL boolean expression — the full-power escape hatch.\n *\n * Columns can be referenced as `{column_name}`. This is Postgres-only and\n * **server-authoritative**: the JavaScript evaluator cannot evaluate arbitrary\n * SQL, so it treats this node as *unknown* rather than guessing.\n * @group Models\n */\nexport interface RawPolicyExpression {\n kind: \"raw\";\n sql: string;\n}\n\n/**\n * An operand referenced by a {@link ComparePolicyExpression}.\n * @group Models\n */\nexport type PolicyOperand =\n | FieldPolicyOperand\n | OuterFieldPolicyOperand\n | LiteralPolicyOperand\n | AuthUidPolicyOperand\n | AuthRolesPolicyOperand\n | AuthClaimPolicyOperand;\n\n/** A column value on the row being evaluated. @group Models */\nexport interface FieldPolicyOperand {\n kind: \"field\";\n /** The property/column name (resolved to its DB column when compiled). */\n name: string;\n}\n\n/**\n * A column value on the *outer* row when used inside {@link ExistsInPolicyExpression}\n * — i.e. the row the RLS policy is being evaluated for, referenced from within the\n * subquery. Outside an `existsIn` it is equivalent to {@link FieldPolicyOperand}.\n * @group Models\n */\nexport interface OuterFieldPolicyOperand {\n kind: \"outerField\";\n /** The property/column name on the outer table. */\n name: string;\n}\n\n/** A constant value. @group Models */\nexport interface LiteralPolicyOperand {\n kind: \"literal\";\n value: string | number | boolean | null;\n}\n\n/** The current user's id — compiles to `rebase.uid()`. @group Models */\nexport interface AuthUidPolicyOperand {\n kind: \"authUid\";\n}\n\n/**\n * The current user's roles as an array — compiles to\n * `string_to_array(rebase.roles(), ',')`.\n * @group Models\n */\nexport interface AuthRolesPolicyOperand {\n kind: \"authRoles\";\n}\n\n/**\n * A named claim on the caller's session token — compiles to\n * `NULLIF(rebase.jwt() ->> '<name>', '')`.\n *\n * The operand multi-tenancy is built on, and the reason it is an operand rather\n * than a {@link RawPolicyExpression}: a claim arrives as **text**, and the\n * column it is compared against usually is not. `org_id = rebase.jwt() ->>\n * 'org_id'` on a `uuid` column is not a policy that denies — it is\n * `CREATE POLICY` failing with \"operator does not exist: uuid = text\", and a\n * table left with RLS enabled and no policy denies every row. Casting the\n * *column* to text instead compiles, but takes the index off the one predicate\n * that is ANDed into every read of the table.\n *\n * As an operand the compiler can see both sides: it casts the claim to the\n * column's type, guarded so a malformed claim denies rather than raising\n * `invalid input syntax` on every query, and the column keeps its index.\n *\n * An absent claim, and a claim set to the empty string, are both NULL — and a\n * comparison against NULL is never true, so a caller carrying no claim sees no\n * rows rather than all of them.\n *\n * Only *custom* claims are reachable. `uid`, `roles`, `aal` and `isAnonymous`\n * are identity claims written after the custom ones when a token is minted,\n * precisely so a claims hook cannot assert them; they have their own operands\n * ({@link AuthUidPolicyOperand}, {@link AuthRolesPolicyOperand}) and naming one\n * here is refused.\n *\n * Postgres-authoritative: the JavaScript evaluator reports *unknown* rather\n * than reproducing Postgres's cast semantics (uuid case folding, numeric\n * widening) a second time and getting them subtly wrong.\n * @group Models\n */\nexport interface AuthClaimPolicyOperand {\n kind: \"authClaim\";\n /** The claim's name on the token, e.g. `\"org_id\"`. */\n name: string;\n}\n\n// ── Shorthand conditions ─────────────────────────────────────────────\n\n/**\n * A value a {@link PolicyShorthand} compares a column with.\n * @group Models\n */\nexport type PolicyShorthandValue = string | number | boolean | null;\n\n/**\n * The plain-object form of a row condition: `{ status: \"published\" }`.\n *\n * Every key is a column key of the table and every value a literal; the\n * condition holds when **each** column equals its value (an AND of\n * equalities), and a `null` value means the column `IS NULL`. It is what\n * `policy.and(policy.compare(policy.field(k), \"eq\", policy.literal(v)), …)`\n * spells longhand, and compiles to the same SQL — except `null`, which no\n * comparison can express (`x = NULL` is never true) and which therefore\n * compiles to `x IS NULL`.\n *\n * - **No key may be named `kind`.** `kind` is how a {@link PolicyExpression}\n * is recognised at runtime, so `{ kind: \"true\" }` would be read as the\n * expression that grants everything. The type refuses it and so does the\n * compiler; compare a column called `kind` with the longhand form.\n * - **At least one key.** `{}` would be an AND of nothing, which is `true`;\n * the compiler refuses it — write `policy.true()` if every row is meant.\n * - The keys are checked against the table when the rule is compiled: a key\n * that names no column is refused, with the table and the key in the error.\n *\n * Use {@link isPolicyShorthand} to tell it apart from a `PolicyExpression`.\n *\n * @example\n * { operation: \"select\", access: \"public\", condition: { status: \"published\" } }\n * { operation: \"select\", condition: { orgId: \"acme\", deletedAt: null } }\n *\n * @group Models\n */\nexport type PolicyShorthand = { readonly [column: string]: PolicyShorthandValue } & { readonly kind?: never };\n\n/**\n * What a rule's `condition` / `check` accepts: a structured\n * {@link PolicyExpression}, or the {@link PolicyShorthand} object form.\n * @group Models\n */\nexport type PolicyCondition = PolicyExpression | PolicyShorthand;\n\n/**\n * Every `kind` a {@link PolicyExpression} node can have — the discriminator\n * {@link isPolicyShorthand} and {@link isPolicyExpressionKind} read.\n * @group Models\n */\nexport const POLICY_EXPRESSION_KINDS: readonly PolicyExpression[\"kind\"][] = [\n \"true\", \"false\", \"and\", \"or\", \"not\", \"compare\", \"rolesOverlap\", \"rolesContain\",\n \"authenticated\", \"registered\", \"serverContext\", \"existsIn\", \"raw\"\n];\n\n/**\n * Whether `kind` names a {@link PolicyExpression} node.\n * @group Models\n */\nexport function isPolicyExpressionKind(kind: unknown): kind is PolicyExpression[\"kind\"] {\n return typeof kind === \"string\" && (POLICY_EXPRESSION_KINDS as readonly string[]).includes(kind);\n}\n\nconst isShorthandValue = (value: unknown): value is PolicyShorthandValue =>\n value === null || typeof value === \"string\" || typeof value === \"boolean\"\n || (typeof value === \"number\" && Number.isFinite(value));\n\n/**\n * Whether a rule's `condition` / `check` is a {@link PolicyShorthand} rather\n * than a {@link PolicyExpression}.\n *\n * True only for a plain object with at least one key, none of them `kind`,\n * whose every value is a string, a finite number, a boolean or `null`. Every\n * expression node carries `kind`, so no expression is ever taken for a\n * shorthand — and an object that has a `kind` key is never taken for a\n * shorthand either, whatever its value: such an object is ambiguous (a column\n * called `kind`, or a misspelt node) and the compiler refuses it rather than\n * guessing.\n *\n * @group Models\n */\nexport function isPolicyShorthand(value: unknown): value is PolicyShorthand {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return false;\n if (Object.prototype.hasOwnProperty.call(value, \"kind\")) return false;\n const entries = Object.entries(value);\n return entries.length > 0 && entries.every(([, v]) => isShorthandValue(v));\n}\n\n// ── Constructor helpers ──────────────────────────────────────────────\n// Small, dependency-free builders so callers (and the desugaring in\n// `@rebasepro/common`) can assemble expressions without object-literal noise.\n\n/** @group Models */\nexport const policy = {\n true: (): TruePolicyExpression => ({ kind: \"true\" }),\n false: (): FalsePolicyExpression => ({ kind: \"false\" }),\n and: (...operands: readonly PolicyExpression[]): AndPolicyExpression => ({ kind: \"and\",\noperands: operands as PolicyExpression[] }),\n or: (...operands: readonly PolicyExpression[]): OrPolicyExpression => ({ kind: \"or\",\noperands: operands as PolicyExpression[] }),\n not: (operand: PolicyExpression): NotPolicyExpression => ({ kind: \"not\",\noperand }),\n compare: (left: PolicyOperand, op: PolicyCompareOperator, right: PolicyOperand): ComparePolicyExpression =>\n ({ kind: \"compare\",\nop,\nleft,\nright }),\n rolesOverlap: (roles: readonly string[]): RolesOverlapPolicyExpression => ({ kind: \"rolesOverlap\",\nroles: roles as string[] }),\n rolesContain: (roles: readonly string[]): RolesContainPolicyExpression => ({ kind: \"rolesContain\",\nroles: roles as string[] }),\n authenticated: (): AuthenticatedPolicyExpression => ({ kind: \"authenticated\" }),\n registered: (): RegisteredPolicyExpression => ({ kind: \"registered\" }),\n serverContext: (): ServerContextPolicyExpression => ({ kind: \"serverContext\" }),\n existsIn: (args: { table: string; where: PolicyExpression }): ExistsInPolicyExpression =>\n ({ kind: \"existsIn\",\ntable: args.table,\nwhere: args.where }),\n raw: (sql: string): RawPolicyExpression => ({ kind: \"raw\",\nsql }),\n field: (name: string): FieldPolicyOperand => ({ kind: \"field\",\nname }),\n outerField: (name: string): OuterFieldPolicyOperand => ({ kind: \"outerField\",\nname }),\n literal: (value: string | number | boolean | null): LiteralPolicyOperand => ({ kind: \"literal\",\nvalue }),\n authUid: (): AuthUidPolicyOperand => ({ kind: \"authUid\" }),\n authRoles: (): AuthRolesPolicyOperand => ({ kind: \"authRoles\" }),\n authClaim: (name: string): AuthClaimPolicyOperand => ({ kind: \"authClaim\",\nname })\n};\n","/**\n * The SQL helper functions RLS policies call, and the schema they live in.\n *\n * ## One schema, and it is ours\n *\n * Rebase creates exactly one schema in a project's database: `rebase`. These\n * three functions live in it alongside the framework's own tables, and that is\n * the whole contract — a reader can look at a database and know precisely which\n * namespace belongs to the framework and that nothing else was touched.\n *\n * It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called\n * `auth`, which is Supabase's name, chosen so that a developer who had written\n * Supabase RLS would recognise `auth.uid()`. The familiarity was real but the\n * name was not Rebase's to take, and taking it had a concrete cost: pointing\n * Rebase at a database that already had a Supabase `auth` schema meant\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's\n * `RETURNS uuid`, which Postgres rejects outright —\n *\n * ERROR: cannot change return type of existing function\n * HINT: Use DROP FUNCTION auth.uid() first.\n *\n * — and the failure landed inside a catch-all that logged a warning and carried\n * on, leaving a database with auth tables, no helper functions, and policies\n * calling functions that did not exist. Under `rebase db migrate` the same\n * statements aborted the migration instead.\n *\n * `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`\n * schema untouched and gains a `rebase` one, which is what a gradual migration\n * needs.\n *\n * ## Why functions at all, rather than inlining `current_setting`\n *\n * Because the indirection has already been spent once. `uid()` resolves\n * `app.uid` and falls back to the pre-rename `app.user_id`, so that during a\n * rolling deploy — old and new pods serving one database — both eras resolve\n * the principal. That was a single `CREATE OR REPLACE`. Inlined into policy\n * bodies it would have been a rewrite of every policy on every table.\n *\n * ## Why the name is not configurable\n *\n * A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so\n * these strings are written into every policy in every database Rebase has\n * provisioned. Everything that reads policies back — the SQL-to-policy parser\n * behind the admin UI, the drift checker, `rls-check` — would have to know the\n * configured value to recognise its own output. One frozen name is the feature.\n */\n\n/** The schema Rebase owns. The only schema Rebase creates. */\nexport const REBASE_SCHEMA = \"rebase\";\n\n/**\n * The principal of the current request, as text, or NULL in the server context.\n *\n * Never NULL for a user request — an anonymous one carries\n * {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for\n * the trusted server plane and `IS NOT NULL` a tautology.\n */\nexport const RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;\n/**\n * Is the caller one of this database's request roles? What a permissive\n * policy is ANDed with under `rls.policyTarget: \"requestRole\"`, so another\n * application's role holding a grant on the table gets nothing from it.\n * `current_user` is passed in — inside the function, which reads the recorded\n * roles with its owner's rights, `current_user` would be the owner — and the\n * sub-select makes it one evaluation per statement, not one per row.\n */\nexport const RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;\n\n/** The request's roles as a comma-separated string, for `string_to_array`. */\nexport const RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;\n\n/**\n * The Postgres role that policies granting only the server context or admins\n * are written `TO`: the injected `<table>_default_admin_*` baseline, and any\n * permissive rule whose every clause requires one of the two (`roles: [\"admin\"]`).\n *\n * Postgres ORs the permissive policies that apply to the current role. Written\n * `TO public`, the baseline applied to every signed-in user too, as\n * `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement\n * constant arm cannot use the owner index, so a user's owner-scoped list or\n * count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`\n * this role, the policy is not in a user's plan at all.\n *\n * It holds no privilege and cannot log in: being in it only decides which\n * policies apply, and those still test `rebase.uid() IS NULL` or the `admin`\n * role. Admin requests switch to a request role that inherits it\n * ({@link adminRequestRoleFor}); a connection that is itself subject to RLS\n * inherits it for the server context. One fixed name, so the policy text is the\n * same in every deployment and every generated migration. FROZEN.\n */\nexport const REBASE_ADMIN_ROLE = \"rebase_admin\";\n\n/**\n * The role the admin request roles ({@link adminRequestRoleFor}) inherit and\n * nothing else does, so an admin-only grant can apply to admin REQUESTS alone.\n *\n * {@link REBASE_ADMIN_ROLE} cannot do that job: the connection inherits it for\n * the server context, and so would any process on it that does not switch\n * roles. Its policies therefore keep their test (`rebase.uid() IS NULL` or the\n * `admin` role) — and any policy expression that is not a constant is a\n * security barrier, behind which Postgres will not evaluate a non-leakproof\n * operator as an index condition. An admin's `tags && $1`, `name ~ $1` or\n * jsonb filter scanned the whole table where the owner's used the index.\n *\n * Each admin-only grant gets a companion `TO` this role `USING (true)`.\n * Postgres folds the OR of the permissive policies to `true` for a member, the\n * barrier goes, and an admin request plans as the owner's does; restrictive\n * policies still apply. Membership is the boundary: only the admin request\n * roles hold it, granted `WITH INHERIT TRUE, SET FALSE`, and only from\n * PostgreSQL 16, whose per-grant INHERIT keeps the connection (which holds\n * those roles `WITH INHERIT FALSE`) out. A boot that finds the connection with\n * its privileges revokes every membership, and the companions admit nobody.\n * One fixed name, as {@link REBASE_ADMIN_ROLE}. FROZEN.\n */\nexport const REBASE_ADMIN_REQUEST_ROLE = \"rebase_admin_request\";\n\n/**\n * The role an admin request runs as, for a signed-in request role: it inherits\n * that role (its grants and every policy written for it) and\n * {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared\n * `rebase_admin` itself, because roles belong to the cluster: a project with a\n * request role of its own (`rls.requestRole`) would otherwise share its admin\n * access with every other project on the cluster. FROZEN derivation.\n */\nexport function adminRequestRoleFor(requestRole: string): string {\n return `${requestRole}_admin`;\n}\n\n/**\n * Whether a request with these roles passes `rolesOverlap([\"admin\"])` — the\n * test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the\n * comma-joined `app.user_roles`, so a role name with a comma in it is split\n * exactly as Postgres splits it.\n */\nexport function holdsAdminRole(roles: readonly string[]): boolean {\n return roles.join(\",\").split(\",\").includes(\"admin\");\n}\n\n/**\n * Whether the caller is a GUEST — signed in through anonymous sign-in rather\n * than with an account.\n *\n * A different question from {@link ANONYMOUS_USER_ID}, and the two are easy to\n * confuse: that sentinel means \"no session at all\", while this means \"a session\n * with nobody behind it\". Anonymous sign-in mints a real user row with a real\n * uid, so before this reached the database the two kinds of caller were one\n * principal inside every policy.\n */\nexport const RLS_IS_ANONYMOUS_SQL = `${REBASE_SCHEMA}.is_anonymous()`;\n\n/** The request's JWT claims as `jsonb`, or `{}`. */\nexport const RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;\n\n/**\n * The pre-1.0 spellings, for recognising policies and hand-written SQL that\n * predate the move.\n *\n * Kept because policies outlive the server that wrote them: a database migrated\n * by an older release still holds `auth.uid()` in its policy bodies until the\n * next push or boot recompiles them, and anything that reads policies back has\n * to recognise both eras or report the framework's own output as foreign drift.\n * Also used to give a project whose `securityRules` contain raw `auth.uid()` a\n * message naming the replacement, instead of a parse failure.\n */\nexport const LEGACY_RLS_SCHEMA = \"auth\";\nexport const LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;\nexport const LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;\nexport const LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;\n\n/**\n * Rewrites the pre-1.0 function calls in a fragment of policy SQL.\n *\n * Deliberately anchored on a word boundary and the schema qualifier, so a column\n * called `auth_uid` or a table named `auth` is left alone.\n */\nexport function rewriteLegacyRlsFunctions(sql: string): string {\n return sql.replace(\n /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/gi,\n (_match, fn: string) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`\n );\n}\n\n/** Whether a fragment of SQL still calls the pre-1.0 functions. */\nexport function usesLegacyRlsFunctions(sql: string): boolean {\n return /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/i.test(sql);\n}\n","import { ALL_WHERE_FILTER_OPS, WhereFilterOp } from \"./filter-operators\";\n\n/**\n * Describes the capabilities and features supported by a data source (driver).\n *\n * Each driver (Postgres, Firebase, etc.) declares which features it\n * supports. The admin uses this descriptor to:\n * - Show/hide editor tabs (e.g. Relations for SQL, Subcollections for Firebase)\n * - Filter the property type picker (e.g. `relation` for SQL, `reference` for Firebase)\n * - Toggle driver-specific form controls (e.g. `columnType` for SQL)\n *\n * @group Models\n */\nexport interface DataSourceCapabilities {\n /** Unique driver key (e.g. \"postgres\", \"firestore\") */\n key: string;\n\n /** Human-readable label for the UI (e.g. \"PostgreSQL\", \"Firebase / Firestore\") */\n label: string;\n\n // ── Feature flags ─────────────────────────────────────────────────\n /** Does this source support SQL-style relations (JOINs)? */\n supportsRelations: boolean;\n\n /** Does this source support nested subcollections? */\n supportsSubcollections: boolean;\n\n /** Does this source support Row Level Security policies? */\n supportsRLS: boolean;\n\n /** Does this source support document references (Firebase-style)? */\n supportsReferences: boolean;\n\n /** Does this source support SQL column type annotations? */\n supportsColumnTypes: boolean;\n\n /** Does this source support real-time listeners? */\n supportsRealtime: boolean;\n\n /**\n * Does this source store vectors natively?\n *\n * `VectorProperty` carries a `dimensions` and is pgvector-shaped. It was\n * the one driver-specific property kind with no flag to gate it, so unlike\n * every other field in this descriptor there was not even a runtime answer\n * to appeal to — a Firestore collection could declare an embedding column\n * and no driver would do anything with it.\n */\n supportsVectors: boolean;\n\n /**\n * Canonical filter operators this engine can execute.\n *\n * The admin UI intersects this set with the property-type defaults and\n * any per-property narrowing (`property.ui.filterOperators`) to decide\n * which operators to offer in filter fields — so an engine that cannot\n * run `ilike` (e.g. Firestore) never shows a \"Contains\" filter that\n * would throw at query time.\n */\n filterOperators: readonly WhereFilterOp[];\n\n /**\n * Relation kinds this engine's driver can compile into a filter.\n *\n * Only `belongsTo` puts a column on the row being filtered; the others are\n * answered with a correlated subquery over the junction or the target\n * table, which not every driver can build. An engine with no relations at\n * all declares none.\n *\n * The admin uses this to decide whether a relation column offers a filter\n * control. Offering one an engine cannot answer is not cosmetic: a driver\n * that drops the key it cannot resolve *widens* the read to every row, and\n * one that fails closed answers a control the admin itself put on screen\n * with a 400.\n *\n * Optional, so a third-party driver registered before this existed still\n * compiles. Omitted means {@link DEFAULT_FILTERABLE_RELATION_KINDS} — the\n * one kind that is a plain column comparison, which every relational\n * driver can do. The subquery kinds are a real capability and have to be\n * claimed rather than assumed: assuming them wrongly is the widening.\n */\n filterableRelationKinds?: readonly string[];\n\n /**\n * Can a filter address a *column of the related row* — `applications.status`\n * — rather than only the related row's id?\n *\n * A separate capability from {@link filterableRelationKinds} because it is\n * a separate subquery: the id filter stops at the junction, one of these\n * reaches the target table and compares one of its columns. A driver can\n * do the first and not the second.\n *\n * Optional and defaulting to **false**, for the reason the relation kinds\n * default narrow: an unclaimed capability that the admin assumes is there\n * produces a control whose query the driver answers by dropping the key —\n * and a dropped filter key widens the read to every row.\n *\n * Meaningless without {@link supportsRelations}; a driver with no relations\n * has nothing to reach through.\n */\n supportsRelationFieldFilters?: boolean;\n\n /**\n * Can a sort key be an aggregate over a to-many relation — \"oldest waiting\n * first\", \"busiest first\"?\n *\n * Compiled as a correlated scalar subquery in `ORDER BY`, which a document\n * store cannot express at all. Optional and defaulting to **false**.\n *\n * A wrongly claimed sort capability fails differently from a wrongly\n * claimed filter one, and worse in one respect: a driver that cannot\n * resolve the key drops the `ORDER BY` and answers 200 with rows in\n * whatever order the database pleased, which reads as a sorted list. Paging\n * over that repeats and skips rows.\n */\n relationAggregateSorts?: boolean;\n\n // ── Admin capability flags ───────────────────────────────────────\n /** Does this source support SQL admin operations (SQL editor, EXPLAIN, etc.)? */\n supportsSQLAdmin: boolean;\n\n /** Does this source support schema admin (unmapped tables, table metadata)? */\n supportsSchemaAdmin: boolean;\n}\n\n/**\n * Subset of DataSourceCapabilities containing only feature flags.\n * Useful when you only need to check capabilities without UI metadata.\n * @group Models\n */\nexport type DataSourceFeatures = Omit<DataSourceCapabilities, \"key\" | \"label\">;\n\n/**\n * The default data-source key, used when a collection does not name a\n * `dataSource`. Shared by the frontend router and the backend driver\n * registry so both agree on \"the default database\".\n * @group Models\n */\nexport const DEFAULT_DATA_SOURCE_KEY = \"(default)\";\n\n/**\n * How the *frontend* reaches a data source.\n *\n * - `\"server\"` — through the Rebase backend (the `RebaseClient`). The backend\n * holds the actual database adapter and routes by data-source key. This is\n * the default and covers Postgres, the only server engine.\n * - `\"direct\"` — straight from the client to the external backend via its own\n * SDK driver (e.g. Firestore). The Rebase backend is not in the data path.\n * - `\"custom\"` — a developer-supplied {@link DataDriver}, transport unspecified.\n *\n * @group Models\n */\nexport type DataSourceTransport = \"server\" | \"direct\" | \"custom\";\n\n/**\n * Declarative definition of a data source — a named place data lives.\n *\n * Declared once and shared front and back: the frontend uses it to decide\n * transport (client vs direct driver), the backend uses the same `key` to\n * resolve a database adapter, and the editor derives capabilities from\n * `engine`. Collections reference a definition by its `key` via\n * `collection.dataSource`.\n *\n * @group Models\n */\nexport interface DataSourceDefinition {\n /**\n * Unique identifier for this data source. Collections point at it via\n * `dataSource`. Defaults to {@link DEFAULT_DATA_SOURCE_KEY}.\n */\n key: string;\n\n /**\n * The engine backing this data source (e.g. `\"postgres\"`,\n * `\"firestore\"`, or a custom id). Determines the\n * {@link DataSourceCapabilities} surfaced in the editor.\n */\n engine: string;\n\n /**\n * How the frontend reaches this source. Optional — when omitted it is\n * inferred: `\"direct\"` if the definition carries a client-side driver,\n * `\"server\"` otherwise.\n */\n transport?: DataSourceTransport;\n\n /**\n * The physical database/schema/Firestore-database within the engine.\n * Threaded to drivers/adapters as the existing `databaseId` runtime\n * parameter. Defaults to the engine's own default.\n */\n databaseId?: string;\n\n /** Human-readable label for the UI. */\n label?: string;\n}\n\n/**\n * The resolved data source for a collection: the single source of truth that\n * the frontend router, backend registry, and editor all derive from.\n * Produced by `resolveDataSource(collection, registry)`.\n *\n * @group Models\n */\nexport interface ResolvedDataSource {\n /** Data-source key (routing key, shared front + back). */\n key: string;\n /** Engine backing the source (drives capabilities). */\n engine: string;\n /** Frontend transport. */\n transport: DataSourceTransport;\n /** Within-engine instance, if any (the `databaseId` runtime param). */\n databaseId?: string;\n /** Capabilities derived from {@link engine}. */\n capabilities: DataSourceCapabilities;\n}\n\n/**\n * Relation kinds assumed filterable when a driver does not say.\n *\n * `belongsTo` alone: its filter is a comparison on a column of the row being\n * filtered, the one shape that needs no query construction a driver might not\n * have. Everything else is a correlated subquery over another table.\n *\n * @group Models\n */\nexport const DEFAULT_FILTERABLE_RELATION_KINDS: readonly string[] = [\"belongsTo\"];\n\n// ── Built-in driver capabilities ─────────────────────────────────────\n\n/** @group Models */\nexport const POSTGRES_CAPABILITIES: DataSourceCapabilities = {\n key: \"postgres\",\n label: \"PostgreSQL\",\n supportsRelations: true,\n supportsSubcollections: false,\n supportsRLS: true,\n supportsReferences: false,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // `via` is absent: its join path is authored source → target with no\n // stated inverse, so the driver has nothing to reverse into a filter.\n filterableRelationKinds: [\"belongsTo\", \"manyToMany\", \"hasMany\", \"hasOne\"],\n supportsRelationFieldFilters: true,\n relationAggregateSorts: true,\n supportsSQLAdmin: true,\n supportsSchemaAdmin: true\n};\n\n/** @group Models */\nexport const FIREBASE_CAPABILITIES: DataSourceCapabilities = {\n key: \"firestore\",\n label: \"Firebase / Firestore\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: true,\n supportsVectors: false,\n // Firestore has no SQL pattern matching — the driver throws on the LIKE\n // family, so the UI must never offer it.\n filterOperators: ALL_WHERE_FILTER_OPS.filter(op =>\n op !== \"like\" && op !== \"ilike\" && op !== \"not-like\" && op !== \"not-ilike\"\n // Firestore matches one element or any of a list; no query asks for all of them, or for none outside one.\n && op !== \"array-contains-all\" && op !== \"array-contained-by\"),\n // No relations at all — a document store links by reference. Nothing to\n // reach through, so neither of the two relation-reaching features either.\n filterableRelationKinds: [],\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: false,\n supportsSchemaAdmin: false\n};\n\n/**\n * Fallback capabilities when the driver is unknown.\n * Enables everything so nothing is hidden unexpectedly.\n * @group Models\n */\nexport const DEFAULT_CAPABILITIES: DataSourceCapabilities = {\n key: \"(default)\",\n label: \"Default\",\n supportsRelations: true,\n supportsSubcollections: true,\n supportsRLS: true,\n supportsReferences: true,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // The exception to this descriptor's \"enable everything\" rule. The other\n // flags hide a tab or a picker when they are wrong; this one decides\n // whether a query is sent that an unknown driver may answer by dropping\n // the condition — which returns every row rather than none.\n filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,\n // Narrow for the same reason, and more sharply. An unknown driver that is\n // assumed to compile these answers by dropping the key: the filter widens\n // the read to every row, and the sort comes back unordered while looking\n // sorted. Both have to be claimed.\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: true,\n supportsSchemaAdmin: true\n};\n\nconst BUILT_IN_CAPABILITIES: ReadonlyMap<string, DataSourceCapabilities> = new Map([\n [\"postgres\", POSTGRES_CAPABILITIES],\n [\"firestore\", FIREBASE_CAPABILITIES],\n [\"(default)\", DEFAULT_CAPABILITIES]\n]);\n\n/**\n * Capabilities registered at runtime, on `globalThis` rather than in a module\n * local: a third-party driver inlines its own copy of this package and\n * registers through it, while the app and the server read through theirs. A\n * module local made the registration land in a copy nobody else reads.\n * See `module-state-across-copies.test.ts`.\n */\nconst REGISTERED_CAPABILITIES_KEY = Symbol.for(\"@rebasepro/types.dataSourceCapabilities.v1\");\n\ntype GlobalWithCapabilities = typeof globalThis & {\n [REGISTERED_CAPABILITIES_KEY]?: Map<string, DataSourceCapabilities>;\n};\n\nfunction registeredCapabilities(): Map<string, DataSourceCapabilities> {\n const g = globalThis as GlobalWithCapabilities;\n let registered = g[REGISTERED_CAPABILITIES_KEY];\n if (!registered) {\n registered = new Map();\n g[REGISTERED_CAPABILITIES_KEY] = registered;\n }\n return registered;\n}\n\n/**\n * Look up capabilities for a given engine key.\n * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.\n * @group Models\n */\nexport function getDataSourceCapabilities(engine?: string): DataSourceCapabilities {\n if (!engine) return POSTGRES_CAPABILITIES; // postgres is the default engine\n return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;\n}\n\n/**\n * Register custom capabilities for a third-party driver.\n * @group Models\n */\nexport function registerDataSourceCapabilities(capabilities: DataSourceCapabilities): void {\n registeredCapabilities().set(capabilities.key, capabilities);\n}\n","/**\n * The resource graph: one declaration site for every named thing a project needs.\n *\n * ## The rule\n *\n * **Every named resource is declared with a constructor in config code.** A\n * database, a bucket, a topic and whatever kind comes next are all spelled the\n * same way, so \"where do I declare my second one\" has one answer instead of one\n * answer per kind.\n *\n * ```ts\n * export const main = database(\"main\");\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * export const signups = topic<SignupEvent>(\"signups\");\n * ```\n *\n * ## Declaration is not binding\n *\n * A declaration says a resource *exists* and what shape it has. It never says\n * how to reach it — that is a property of the environment, not of the project,\n * and it differs between a laptop, a self-hosted box and a tenant in the cloud.\n * Binding lives in `@rebasepro/server`'s boot path, where each kind registers\n * the resolver that reads its environment variables, keyed off the logical\n * name declared here.\n *\n * This split is the whole point. Before it, storage topology was hand-written\n * into `rebase.json` while database topology lived in TypeScript, and the\n * boundary between them was a fact about what the control plane could read\n * before a build — a platform implementation detail that a developer had no way\n * to derive. Worse, storage could be declared in *both* places, and the merge\n * silently kept the JSON's engine and discarded the code's.\n *\n * ## Why a registry rather than a fixed union\n *\n * Kinds register themselves. Adding pub/sub, a cache or a search index must not\n * require editing a manifest schema, a validator and three switch statements —\n * that cost is exactly why the last two kinds ended up in different homes.\n */\n\n/** How a client reaches a resource. */\nexport type ResourceTransport =\n /** Through the backend. The default, and the only one that needs no client SDK. */\n | \"server\"\n /** A provider SDK talks to the resource directly; the backend is not in the path. */\n | \"direct\";\n\n/**\n * A resource kind, as registered.\n *\n * `engines` is an allowlist rather than documentation. An unrecognised engine\n * used to be a free string that passed every check and failed later, further\n * from the typo that caused it — `\"s2\"` for `\"s3\"` reached the runtime. Anything\n * genuinely outside the list is spelled `custom:<id>`, which says so at the call\n * site instead of looking like a typo.\n */\nexport interface ResourceKindSpec {\n /** The kind's name, as it appears in a declaration and in the graph. */\n kind: string;\n /**\n * Which definition of this kind this is. Bump it whenever anything else in\n * the spec changes.\n *\n * Two copies of this package can meet in one process — a published driver\n * inlines it into its dist, and the runtime image ships its own — and the\n * registry is shared between them on purpose. Without a revision the only\n * thing the registry can do with two specs that differ is refuse, and a\n * refusal at driver load is a pod that never boots: every bundle built with\n * a driver older than the change dies on the first image that carries it.\n * With one, the higher revision wins whichever copy loads first, and the\n * older copy is told so. Missing means 0, which is what every copy shipped\n * before revisions existed reports.\n *\n * Only copies that know about revisions honour them. A copy published\n * BEFORE they existed still compares the whole literal and throws, so a\n * kind that has shipped in such a copy cannot change its literal at all —\n * not even to add this field. Correct those kinds with `amendResourceKind`.\n */\n revision?: number;\n /** Engines this kind ships with. `custom:<id>` is always additionally valid. */\n engines: readonly string[];\n /** Used when a declaration names none. */\n defaultEngine: string;\n /**\n * Environment variable base names this kind binds from, in the order a\n * binder should try them. A resource keyed `analytics` reads\n * `<BASE>__ANALYTICS`; the default-keyed resource reads `<BASE>` unsuffixed,\n * so a single-resource project configured the obvious way declares nothing.\n */\n envBases: readonly string[];\n /**\n * The subset of `envBases` that matters for a given engine.\n *\n * The binder reads every base and takes whichever is set — harmless, and it\n * keeps binding tolerant. A GENERATOR cannot be that relaxed: `rebase eject\n * infra` writing S3_BUCKET, GCS_BUCKET, STORAGE_BUCKET and\n * STORAGE_PUBLIC_URL for a `local` bucket hands somebody four variables of\n * which three are noise, and a config file full of irrelevant keys is one\n * nobody reads carefully.\n *\n * Keyed by engine; an engine with no entry falls back to all of them, which\n * is the honest answer for one this package has never heard of.\n */\n envBasesByEngine?: Readonly<Record<string, readonly string[]>>;\n /** Option keys this kind accepts beyond the common ones, for validation. */\n optionKeys?: readonly string[];\n /**\n * Whether a project implicitly has one of these even when it declares\n * nothing. True for databases — a backend without one is not a backend —\n * and false for topics, where zero is the normal number.\n */\n implicitDefault?: boolean;\n}\n\n/** The key a resource takes when a project declares only one of its kind. */\nexport const DEFAULT_RESOURCE_KEY = \"(default)\";\n\n/** A declared resource, as it appears in the graph. */\nexport interface ResourceDeclaration {\n kind: string;\n /** Unique within its kind. What a binder looks up and what an env suffix is built from. */\n key: string;\n engine: string;\n transport: ResourceTransport;\n label?: string;\n /** Kind-specific options, validated against the kind's `optionKeys`. */\n options: Readonly<Record<string, unknown>>;\n /**\n * What in the project reaches this resource, as `<what>:<name>` — a\n * `collection:posts` routed to a database, a `property:posts.cover` stored\n * in a bucket, a `function:report` importing a handle.\n *\n * Recorded by the derive step, never by a constructor: a declaration says\n * a resource exists, and only a reader that has evaluated the rest of the\n * project can say who uses it. It is the map a host needs to split a\n * monolith into units later, and the map a console needs to answer \"what\n * breaks if I remove this\". Absent when nothing was recorded, which is\n * different from an empty list.\n */\n usedBy?: readonly string[];\n}\n\n/**\n * The value a constructor returns.\n *\n * Carries its own declaration so config code can hold it and pass it around,\n * and stringifies to its key so it drops into the places that still take one.\n * Collections name a data source by string today; a handle works there without\n * the collection API having to change, which keeps this a config redesign\n * rather than a rewrite of the data layer.\n */\nexport interface ResourceHandle extends ResourceDeclaration {\n toString(): string;\n}\n\nconst BRAND = Symbol.for(\"@rebasepro/types.resource\");\n\n/** Whether a value is a resource handle rather than a plain string key. */\nexport function isResourceHandle(value: unknown): value is ResourceHandle {\n return typeof value === \"object\" && value !== null && BRAND in value;\n}\n\n/**\n * A reference to a resource where a key is expected: the handle a constructor\n * returned, or the key spelled as a string.\n *\n * The handle is the point. `dataSource: analytics` is the same name spelled\n * once — rename the export and every use follows, jump-to-definition lands on\n * the declaration, and the derive step can record who uses what. The string\n * form stays because a key has to survive serialisation: the runtime and the\n * admin UI read collections as plain data, where a handle cannot travel.\n */\nexport type ResourceRef = string | ResourceHandle;\n\n/** The key a resource reference names, whether it is a handle or already a key. */\nexport function resourceKeyOf(ref: ResourceRef): string {\n return isResourceHandle(ref) ? ref.key : ref;\n}\n\n/**\n * Replace every resource handle inside a value with its key, deeply.\n *\n * Applied where authored config becomes data: `defineCollection`, the\n * collection loaders, the derive step. Past that point a collection is plain\n * data that serialises, compares with `===` and reaches the admin UI over the\n * wire, so a handle must not survive into it. Plain objects and arrays are\n * walked; anything else — a function, a Date, a class instance — is a leaf and\n * is returned as it is, which is what keeps callbacks and validators intact.\n */\nexport function resolveResourceRefs<T>(value: T): T {\n if (isResourceHandle(value)) return value.key as T;\n // Identity-preserving: a value with no handle inside comes back as the\n // same object, not a copy. Collections point at each other through\n // `target: () => authors`, and a loader that cloned every collection would\n // leave those closures returning the originals while everything else\n // held the copies. A collection that `defineCollection` already\n // normalised passes through here untouched.\n if (Array.isArray(value)) {\n let changed = false;\n const out = value.map(item => {\n const next = resolveResourceRefs(item);\n if (next !== item) changed = true;\n return next;\n });\n return (changed ? out : value) as T;\n }\n if (value !== null && typeof value === \"object\") {\n const proto = Object.getPrototypeOf(value);\n if (proto === Object.prototype || proto === null) {\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const next = resolveResourceRefs(v);\n if (next !== v) changed = true;\n out[k] = next;\n }\n return (changed ? out : value) as T;\n }\n }\n return value;\n}\n\n/**\n * The process-wide registry.\n *\n * Keyed off `globalThis` through a shared symbol rather than held in a module\n * local, because a module local is per *copy* of this package. A project that\n * ends up with two copies of `@rebasepro/types` — which a partially-linked\n * `node_modules` produces, and which has already caused a phantom\n * \"JWT secret not configured\" bug in this repo — would otherwise register into\n * one registry and read from the other, and see an empty graph with nothing\n * anywhere to explain it.\n *\n * `declarations` is that shared map, and stays shared: it is what a project\n * writes and what every copy has to be able to read.\n *\n * `kinds` is NOT, and the distinction is the whole point of `KINDS_KEY` below.\n */\ninterface Registry {\n /** Kinds this copy and its peers agree on — the versioned map. */\n kinds: Map<string, ResourceKindSpec>;\n /** Kinds written by a copy that predates the versioned map. Read-only here. */\n legacyKinds: Map<string, ResourceKindSpec>;\n declarations: Map<string, ResourceDeclaration>;\n}\n\nconst GLOBAL_KEY = Symbol.for(\"@rebasepro/types.resourceRegistry\");\n\n/**\n * Where kinds live, versioned — and why the version is in the symbol.\n *\n * Sharing one kinds map across copies means the copy that registers SECOND is\n * the one that runs the comparison. That copy is whatever the bundle happens to\n * carry, which for a driver is a build of this package frozen at its release —\n * so the rule enforced is the rule that shipped THEN, not the one written here.\n *\n * `revision` (390bb03cd, applied to `database` in 346df48e2) was supposed to\n * settle a disagreement between two copies, and it settles it only when the\n * copy doing the arithmetic knows what `revision` is. 0.17.0–0.17.3 do not:\n * they deep-equal the spec and throw. The runtime registers at import and a\n * driver is imported after it, so the old copy is always second, always the\n * judge, and always throws — verified by the bundle corpus on 2026-09-07,\n * which reported v0.17.3's message verbatim (\"Two packages cannot define the\n * same kind.\", no revision clause) while the runtime it ran on was 0.18.\n *\n * So copies that understand `revision` keep their kinds here, under a symbol\n * no released copy looks at, and the legacy map is left to whoever still wants\n * it. An old copy then registers into a map nobody contests, finds no existing\n * entry, and cannot throw — in any load order, which is what the previous fix\n * only claimed. Bumping this suffix again is how a future change to the\n * REGISTRATION PROTOCOL is made; a change to a kind's own definition is still\n * `revision`, among peers that share this map.\n */\nconst KINDS_KEY = Symbol.for(\"@rebasepro/types.resourceKinds.v2\");\n\nfunction registry(): Registry {\n const g = globalThis as Record<symbol, unknown>;\n let shared = g[GLOBAL_KEY] as { kinds: Map<string, ResourceKindSpec>; declarations: Map<string, ResourceDeclaration> } | undefined;\n if (!shared) {\n // `kinds` is created but never written by this copy: an older copy's\n // own `registry()` returns this object as-is once it exists, and would\n // throw on `undefined.get` if the property were absent.\n shared = { kinds: new Map(), declarations: new Map() };\n g[GLOBAL_KEY] = shared;\n }\n let kinds = g[KINDS_KEY] as Map<string, ResourceKindSpec> | undefined;\n if (!kinds) {\n kinds = new Map();\n g[KINDS_KEY] = kinds;\n }\n return { kinds, legacyKinds: shared.kinds, declarations: shared.declarations };\n}\n\n/**\n * Every kind visible to this copy: the versioned map, plus anything only a\n * legacy copy registered.\n *\n * The fallback is not for Rebase's own kinds — this copy defines all of those —\n * but for a third-party driver built against an older `@rebasepro/types` that\n * registers a kind of its own. Dropping it would make that kind invisible and\n * turn `declareResource` into \"unknown resource kind\" for something genuinely\n * registered.\n */\nfunction visibleKinds(): Map<string, ResourceKindSpec> {\n const { kinds, legacyKinds } = registry();\n if (legacyKinds.size === 0) return kinds;\n const merged = new Map(legacyKinds);\n for (const [k, v] of kinds) merged.set(k, v);\n return merged;\n}\n\n/**\n * Corrections this copy applies on top of a registered kind.\n *\n * Deliberately a module local — per COPY of this package — where the registry\n * above is deliberately shared. A published driver inlines this package into\n * its dist, and the copy it carries compares the shared registry's entry for a\n * kind against its own literal by `JSON.stringify` and throws if they differ\n * (see `registerResourceKind` before revisions existed). That code is in the\n * field and cannot be changed, so the registered literal of any kind that has\n * ever shipped is frozen: change one enumerable key and every bundle built with\n * an older driver dies at driver load on the next image. What a kind actually\n * binds can still be corrected — here, read through `resourceKind()` and\n * everything built on it, invisible to the older copy, which keeps binding the\n * way it did when it was published.\n */\ntype KindAmendment = Partial<Pick<ResourceKindSpec, \"envBases\" | \"envBasesByEngine\" | \"optionKeys\">>;\nconst amendments = new Map<string, KindAmendment>();\n\n/**\n * Correct a registered kind without touching its registered literal.\n *\n * Use this, never an edit to the literal, for a kind that has shipped in a\n * published package. The amendment applies to reads through this copy only.\n */\nexport function amendResourceKind(kind: string, amendment: KindAmendment): void {\n amendments.set(kind, { ...amendments.get(kind), ...amendment });\n}\n\n/** A registered kind as this copy sees it: the shared literal plus this copy's amendments. */\nfunction effectiveKind(spec: ResourceKindSpec): ResourceKindSpec {\n const amendment = amendments.get(spec.kind);\n return amendment ? { ...spec, ...amendment } : spec;\n}\n\n/** `kind:key`, the graph's primary key. */\nfunction declarationId(kind: string, key: string): string {\n return `${kind}:${key}`;\n}\n\n/**\n * Register a resource kind.\n *\n * Idempotent for an identical spec. When a spec for the same kind is already\n * registered and differs, the `revision` decides: the higher one is kept and\n * the other copy is warned about, in either load order. Two different specs at\n * the SAME revision are a genuine conflict — two packages defining one kind, or\n * a change that forgot to bump — and still throw.\n *\n * Both copies in that comparison are peers on `KINDS_KEY`, which is what makes\n * the rule enforceable: a copy old enough not to know `revision` writes to the\n * legacy map instead and never reaches this function's arithmetic. Registering\n * a kind an older copy already put in the legacy map is therefore not a\n * conflict — it is the ordinary case, and `visibleKinds` prefers this one.\n */\nexport function registerResourceKind(spec: ResourceKindSpec): void {\n const kinds = registry().kinds;\n const existing = kinds.get(spec.kind);\n if (!existing) {\n kinds.set(spec.kind, spec);\n return;\n }\n if (JSON.stringify(existing) === JSON.stringify(spec)) return;\n\n const have = existing.revision ?? 0;\n const incoming = spec.revision ?? 0;\n if (have === incoming) {\n throw new Error(\n `Resource kind \"${spec.kind}\" is already registered with a different definition at revision ${have}. ` +\n \"Two packages cannot define the same kind; a newer definition of the same kind must carry a higher `revision`.\"\n );\n }\n const [kept, dropped] = incoming > have ? [spec, existing] : [existing, spec];\n if (kept === spec) kinds.set(spec.kind, spec);\n // No logger below @rebasepro/server, and this runs in browsers too.\n console.warn(\n `[resources] Resource kind \"${spec.kind}\" is registered twice, at revisions ${dropped.revision ?? 0} and ` +\n `${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types ` +\n \"inlined in a driver built before the kind changed — rebuild the project with a current driver to remove it.\"\n );\n}\n\n/** Every registered kind, for validators and for `rebase doctor`. */\nexport function resourceKinds(): ResourceKindSpec[] {\n return [...visibleKinds().values()].map(effectiveKind);\n}\n\n/** One registered kind, or undefined. */\nexport function resourceKind(kind: string): ResourceKindSpec | undefined {\n const spec = visibleKinds().get(kind);\n return spec && effectiveKind(spec);\n}\n\n/** Options every kind accepts. */\nexport interface DeclareOptions {\n engine?: string;\n transport?: ResourceTransport;\n label?: string;\n [option: string]: unknown;\n}\n\nconst COMMON_OPTION_KEYS = [\"engine\", \"transport\", \"label\"] as const;\n\n/** Whether an engine is one the kind knows, or an explicit `custom:` opt-out. */\nexport function isValidEngine(spec: ResourceKindSpec, engine: string): boolean {\n return engine.startsWith(\"custom:\") || spec.engines.includes(engine);\n}\n\n/**\n * Declare a resource. The primitive every kind's constructor is built from.\n *\n * Redeclaring the same `kind:key` with a *different* shape throws rather than\n * merging. Merging is what the old storage path did, and it silently discarded\n * one of the two engines — a declaration accepted and then ignored, which is\n * the failure this whole model exists to remove. Redeclaring it identically is\n * fine: a config module evaluated twice must not be an error.\n */\nexport function declareResource(\n kind: string,\n key: string = DEFAULT_RESOURCE_KEY,\n options: DeclareOptions = {}\n): ResourceHandle {\n const spec = resourceKind(kind);\n if (!spec) {\n const known = [...visibleKinds().keys()].sort().join(\", \") || \"none\";\n throw new Error(\n `Unknown resource kind \"${kind}\". Registered kinds: ${known}. ` +\n \"Call registerResourceKind() before declaring one.\"\n );\n }\n\n if (!key || typeof key !== \"string\" || key.trim() === \"\") {\n throw new Error(`A ${kind} needs a non-empty key.`);\n }\n\n const engine = options.engine ?? spec.defaultEngine;\n if (!isValidEngine(spec, engine)) {\n throw new Error(\n `Unknown ${kind} engine \"${engine}\" for \"${key}\". ` +\n `Known engines: ${spec.engines.join(\", \")}. ` +\n `An engine this build does not ship is spelled \"custom:${engine}\", ` +\n \"which says so at the call site rather than failing later.\"\n );\n }\n\n const allowed = new Set<string>([...COMMON_OPTION_KEYS, ...(spec.optionKeys ?? [])]);\n const unknown = Object.keys(options).filter(k => !allowed.has(k));\n if (unknown.length > 0) {\n throw new Error(\n `Unknown option(s) on ${kind} \"${key}\": ${unknown.join(\", \")}. ` +\n `A ${kind} accepts: ${[...allowed].sort().join(\", \")}.`\n );\n }\n\n const extra: Record<string, unknown> = {};\n for (const k of spec.optionKeys ?? []) {\n if (options[k] !== undefined) extra[k] = options[k];\n }\n\n const declaration: ResourceDeclaration = {\n kind,\n key,\n engine,\n transport: options.transport ?? \"server\",\n ...(options.label !== undefined ? { label: options.label } : {}),\n options: Object.freeze(extra)\n };\n\n const id = declarationId(kind, key);\n const previous = registry().declarations.get(id);\n if (previous) {\n if (JSON.stringify(previous) !== JSON.stringify(declaration)) {\n throw new Error(\n `${kind} \"${key}\" is declared twice with different configuration. ` +\n \"Declare it once and export it — two declarations of one resource is \" +\n \"the ambiguity this model exists to remove, so it is refused rather \" +\n \"than merged.\"\n );\n }\n } else {\n registry().declarations.set(id, declaration);\n }\n\n const handle = {\n ...declaration,\n toString() { return key; },\n [BRAND]: true as const\n };\n return handle as ResourceHandle;\n}\n\n/** Every declared resource, in declaration order, optionally filtered by kind. */\nexport function declaredResources(kind?: string): ResourceDeclaration[] {\n const all = [...registry().declarations.values()];\n return kind ? all.filter(r => r.kind === kind) : all;\n}\n\n/**\n * Forget every declaration, keeping registered kinds.\n *\n * For tests and for a CLI that evaluates more than one project in a process.\n * Kinds survive because they are registered by module import, which will not\n * happen a second time.\n */\nexport function resetDeclaredResources(): void {\n registry().declarations.clear();\n}\n\n/**\n * The env-var suffix a resource's bindings use: `__ANALYTICS` for `analytics`,\n * and nothing at all for the default-keyed one.\n *\n * The default takes no suffix so that a project with one database configured\n * through plain `DATABASE_URL` keeps working having declared nothing — the\n * overwhelmingly common project must not have to say so.\n */\nexport function resourceEnvSuffix(key: string): string {\n if (key === DEFAULT_RESOURCE_KEY) return \"\";\n return `__${key.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\").replace(/^_+|_+$/g, \"\")}`;\n}\n\n/**\n * Two resources of a kind whose keys differ but whose env suffixes do not.\n *\n * `media-files` and `media_files` both become `__MEDIA_FILES`, so one would\n * silently read the other's configuration. Returned rather than thrown so the\n * caller can report it with the rest of a validation pass.\n */\nexport function findEnvSuffixCollision(keys: readonly string[]): { a: string; b: string; suffix: string } | null {\n const seen = new Map<string, string>();\n for (const key of keys) {\n const suffix = resourceEnvSuffix(key);\n const previous = seen.get(suffix);\n if (previous !== undefined && previous !== key) return { a: previous, b: key, suffix };\n seen.set(suffix, key);\n }\n return null;\n}\n\n/**\n * The whole graph, as recorded in a manifest and read by a host.\n *\n * `version` is the graph format, not the project's. A host reading a graph it\n * does not understand must say so rather than provision half of it.\n */\nexport interface ResourceGraph {\n version: 1;\n resources: ResourceDeclaration[];\n}\n\n/** The current graph format version. */\nexport const RESOURCE_GRAPH_VERSION = 1 as const;\n\n/**\n * Build a graph from the current declarations, sorted for a stable diff.\n *\n * `usedBy` maps a `kind:key` id to the things that reach it. The derive step\n * supplies it after evaluating collections; a runtime building the graph at\n * boot passes nothing and gets declarations alone, which is all it binds from.\n */\nexport function buildResourceGraph(usedBy?: ReadonlyMap<string, readonly string[]>): ResourceGraph {\n const resources = declaredResources().slice().sort(\n (a, b) => a.kind.localeCompare(b.kind) || a.key.localeCompare(b.key)\n ).map(r => {\n const users = usedBy?.get(declarationId(r.kind, r.key));\n return users && users.length > 0 ? { ...r, usedBy: [...users].sort() } : r;\n });\n return { version: RESOURCE_GRAPH_VERSION, resources };\n}\n\n/** `kind:key`, the id `usedBy` maps are keyed by. Exported for the derive step. */\nexport function resourceId(kind: string, key: string): string {\n return declarationId(kind, key);\n}\n\n/**\n * The environment variables worth writing for a resource, given its engine.\n *\n * Falls back to every base the kind reads when the engine is unknown — a\n * `custom:` engine gets the full list rather than an empty one, because\n * guessing narrow would silently omit the variable it actually needs.\n */\nexport function envBasesForResource(declaration: ResourceDeclaration): readonly string[] {\n const spec = resourceKind(declaration.kind);\n if (!spec) return [];\n return spec.envBasesByEngine?.[declaration.engine] ?? spec.envBases;\n}\n","/**\n * The kinds Rebase ships, and the constructors a project declares them with.\n *\n * Each kind is registered rather than hardcoded, so a fourth one arrives\n * without editing a manifest schema, a validator and a switch statement. That\n * cost is precisely why databases and buckets ended up declared in different\n * files with different rules — the cheapest thing to do was always to bolt the\n * new kind onto whichever home was nearest.\n *\n * A kind owns its engine list. `custom:<id>` is always accepted, so a build\n * that ships an engine this package has never heard of says so at the call site\n * instead of looking like a typo of one that exists.\n */\nimport {\n DEFAULT_RESOURCE_KEY,\n declareResource,\n declaredResources,\n amendResourceKind,\n registerResourceKind,\n type DeclareOptions,\n type ResourceDeclaration,\n type ResourceHandle\n} from \"./resources\";\nimport { DEFAULT_DATA_SOURCE_KEY, type DataSourceDefinition } from \"./data_source\";\nimport { DEFAULT_STORAGE_SOURCE_KEY, type OrphanSweepOptions, type StorageSourceDefinition } from \"./storage_source\";\n\n// ── database ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // There is no single frozen literal for this kind, which is why it carries a\n // revision. 0.17.0 and 0.17.1 shipped `optionKeys: [\"databaseId\",\n // \"migrations\"]`; 0.17.2 added \"extensions\" to the literal itself, before the\n // rule against that existed. So two different objects are inlined in drivers\n // that are in the field, and no choice of literal can equal both: a runtime\n // that matched one threw `already registered with a different definition` at\n // the other and refused to boot. Two tenants crash-looped for six and a half\n // days on exactly that.\n //\n // `revision` is what resolves it. An older copy — whichever literal it\n // carries — is at revision 0, loses to this one, and warns instead of\n // throwing. Corrections still go in the amendment below; this number moves\n // only when the literal itself has to, and every published copy predating the\n // move is thereby handled.\n //\n // The same goes for `engines`. Only \"postgres\" has a server driver — MongoDB\n // support was removed after 0.30.1 — but \"mongodb\" stays in this list because\n // removing it is an edit to the literal every published copy compares. The\n // server refuses a `database()` declared with an engine it has no driver\n // for, naming the engine, so the stale entry cannot be booted.\n revision: 1,\n kind: \"database\",\n engines: [\"postgres\", \"mongodb\", \"firestore\", \"sqlite\"],\n defaultEngine: \"postgres\",\n envBases: [\"DATABASE_URL\", \"REBASE_DRIVER\", \"REBASE_DB_POOL_MAX\"],\n optionKeys: [\"databaseId\", \"migrations\", \"extensions\"],\n implicitDefault: true\n});\n// What a database actually binds from. The 0.17.3 list named two variables\n// the resolver never read and omitted five it does (25f1a97e3).\namendResourceKind(\"database\", {\n // `rls` added by amendment, never to the literal above: every published\n // copy compares that literal, and an edit to it is what took two tenants\n // down for six days (see the comment on `revision`).\n optionKeys: [\"databaseId\", \"migrations\", \"extensions\", \"rls\"],\n envBases: [\n \"DATABASE_URL\",\n \"DATABASE_READ_URL\",\n \"DATABASE_DIRECT_URL\",\n \"DATABASE_POOLED\",\n \"ADMIN_CONNECTION_STRING\",\n \"REBASE_DRIVER\",\n \"DB_POOL_MAX\",\n \"DB_POOL_IDLE_TIMEOUT\",\n \"DB_POOL_CONNECT_TIMEOUT\"\n ]\n});\n\n/** Options a database accepts beyond the common ones. */\nexport interface DatabaseOptions extends DeclareOptions {\n /**\n * The physical database or schema within the engine, when it differs from\n * the engine's own default. Threaded to drivers as `databaseId`.\n */\n databaseId?: string;\n /** Directory of migration files, relative to the config directory. */\n migrations?: string;\n /**\n * Server extensions Rebase may install on this database.\n *\n * A permission, not a request: naming one grants leave to run\n * `CREATE EXTENSION IF NOT EXISTS <name>`, and Rebase issues it only when\n * something in the schema actually needs it. Naming an extension nothing\n * needs installs nothing.\n *\n * It has to be said out loud because installing an extension is a decision\n * with a deployment behind it — the image has to ship the library, the role\n * has to be allowed to install it, and a managed provider has to have it on\n * an allow-list. Rebase cannot see any of that from inside the connection,\n * so the answer comes from whoever chose the database.\n *\n * Today `vector` is the one that matters: a `{ type: \"vector\" }` property\n * compiles to a `VECTOR(n)` column, which does not exist until pgvector is\n * installed. Without this, Rebase creates the column and lets Postgres\n * refuse, naming the option.\n *\n * ```ts\n * export const main = database({ extensions: [\"vector\"] });\n * ```\n *\n * `pg_trgm` and `unaccent` are not on this list and need no permission: a\n * `search` block installs them unasked, because they are contrib modules\n * present in every Postgres distribution. pgvector is a separate build that\n * a stock `postgres:18` does not carry.\n */\n extensions?: string[];\n /**\n * How row-level security runs on this database — the request role and\n * everything around it. Every default is what Rebase did before the option\n * existed. Declared here rather than only on the driver because the policy\n * settings shape the SQL `rebase db generate` writes, and the CLI reads\n * this declaration as the server does. The `REBASE_RLS_*` variables win.\n *\n * ```ts\n * export const main = database({ rls: { requestRole: \"acme_user\" } });\n * ```\n *\n * See `PostgresRlsConfig` in `@rebasepro/server-postgres` for each setting,\n * and the forms only code can give (a function for the role or identity).\n */\n rls?: DatabaseRlsOptions;\n}\n\n/**\n * The data-only `rls` settings a database declaration takes. The driver's own\n * `rls` block (`PostgresRlsConfig`) accepts these and the function forms.\n */\nexport interface DatabaseRlsOptions {\n requestRole?: string | { anonymous: string; signedIn: string };\n provisionRole?: \"auto\" | \"never\";\n grants?: \"schema\" | \"managed\" | \"none\";\n policyTarget?: \"public\" | \"requestRole\";\n adminPolicies?: \"adminRole\" | \"public\";\n defaultPolicies?: boolean;\n inheritRoles?: string[];\n identity?: \"rebase\" | \"supabase\";\n sharedRole?: \"warn\" | \"refuse\" | \"ignore\";\n}\n\n/** A database handle. Collections point at it via `dataSource`. */\nexport type DatabaseHandle = ResourceHandle;\n\n/**\n * Declare a database.\n *\n * ```ts\n * export const main = database(); // the default one\n * export const analytics = database(\"analytics\"); // reads DATABASE_URL__ANALYTICS\n * export const withPgv = database({ extensions: [\"vector\"] }); // the default one, configured\n * ```\n *\n * The third form exists because the default database has no name to pass, and\n * the alternative was `database(\"(default)\", { … })` — writing out an internal\n * sentinel to reach the options. A key is a string and options are an object,\n * so the two can never be confused for one another.\n */\nexport function database(options?: DatabaseOptions): DatabaseHandle;\nexport function database(key?: string, options?: DatabaseOptions): DatabaseHandle;\nexport function database(\n keyOrOptions: string | DatabaseOptions = DEFAULT_RESOURCE_KEY,\n options: DatabaseOptions = {}\n): DatabaseHandle {\n return typeof keyOrOptions === \"string\"\n ? declareResource(\"database\", keyOrOptions, options)\n : declareResource(\"database\", DEFAULT_RESOURCE_KEY, keyOrOptions);\n}\n\n/**\n * The extensions the project's databases gave Rebase leave to install.\n *\n * A flat union rather than a per-database answer, because the surfaces that ask\n * — `rebase db push` and the boot schema-ensure — drive one connection and\n * generate one `schema.sql` for every collection regardless of `dataSource`.\n * Splitting the permission by data source would be a distinction the rest of\n * that pipeline does not make, and a false precision is worse than none.\n *\n * Empty for a project that declared nothing, which is every project that has\n * not opted in — so this reads as a refusal by default, on purpose.\n */\nexport function declaredDatabaseExtensions(): readonly string[] {\n const names = new Set<string>();\n for (const declaration of declaredResources(\"database\")) {\n const declared = declaration.options.extensions;\n if (!Array.isArray(declared)) continue;\n for (const name of declared) {\n if (typeof name === \"string\" && name.trim()) names.add(name.trim());\n }\n }\n return [...names].sort();\n}\n\n/** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */\nexport function declaredDatabaseRls(key: string = DEFAULT_DATA_SOURCE_KEY): DatabaseRlsOptions {\n const declaration = declaredResources(\"database\").find((d) => d.key === key);\n const rls = declaration?.options.rls;\n return rls && typeof rls === \"object\" ? rls as DatabaseRlsOptions : {};\n}\n\n/**\n * The policy settings every compile path must agree on — the boot's policy\n * ensure, `rebase db generate`, the drift check — read from the one place all\n * of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /\n * `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults\n * are what Rebase compiled before these existed, except `adminPolicies`, whose\n * default (`\"adminRole\"`) changed what the server-or-admin policies are `TO`.\n *\n * Browser-safe: where there is no `process`, only the declaration counts.\n */\nexport function declaredRlsPolicyShape(dataSource: string = DEFAULT_DATA_SOURCE_KEY): {\n policyTarget: \"public\" | \"requestRole\";\n adminPolicies: \"adminRole\" | \"public\";\n defaultPolicies: boolean;\n} {\n const declared = declaredDatabaseRls(dataSource);\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();\n const envAdmin = env?.REBASE_RLS_ADMIN_POLICIES?.trim();\n const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();\n return {\n policyTarget: envTarget === \"requestRole\" || envTarget === \"public\"\n ? envTarget\n : declared.policyTarget === \"requestRole\" ? \"requestRole\" : \"public\",\n adminPolicies: envAdmin === \"adminRole\" || envAdmin === \"public\"\n ? envAdmin\n : declared.adminPolicies === \"public\" ? \"public\" : \"adminRole\",\n defaultPolicies: envDefaults === \"false\" ? false : envDefaults === \"true\" ? true : declared.defaultPolicies !== false\n };\n}\n\n// ── bucket ───────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // FROZEN at the 0.17.3 literal, for the reason given on `database`.\n kind: \"bucket\",\n engines: [\"local\", \"s3\", \"gcs\", \"azure\", \"firebase\"],\n defaultEngine: \"local\",\n envBases: [\"S3_BUCKET\", \"GCS_BUCKET\", \"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n envBasesByEngine: {\n local: [\"STORAGE_BUCKET\"],\n s3: [\"S3_BUCKET\", \"STORAGE_ENDPOINT\", \"STORAGE_REGION\", \"STORAGE_PUBLIC_URL\"],\n gcs: [\"GCS_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n azure: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n firebase: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"]\n },\n optionKeys: [\"publicRead\", \"prefix\", \"account\"],\n implicitDefault: false\n});\n// What a bucket actually binds from, per engine (25f1a97e3), plus `default`:\n// the registry no longer promotes a lone named bucket, so a project needs a way\n// to say which one serves unqualified uploads. The literal above is frozen, so\n// the new option key arrives here.\namendResourceKind(\"bucket\", {\n // `orphanSweep` arrived the same way, after `default`.\n optionKeys: [\"publicRead\", \"prefix\", \"account\", \"default\", \"orphanSweep\"],\n envBases: [\n \"STORAGE_TYPE\",\n \"STORAGE_PATH\",\n \"S3_BUCKET\",\n \"S3_REGION\",\n \"S3_ACCESS_KEY_ID\",\n \"S3_SECRET_ACCESS_KEY\",\n \"S3_ENDPOINT\",\n \"S3_FORCE_PATH_STYLE\",\n \"GCS_BUCKET\",\n \"GCS_PROJECT_ID\",\n \"GCS_KEY_FILENAME\",\n // The largest file the source accepts, read for every engine.\n \"STORAGE_MAX_FILE_SIZE\"\n ],\n envBasesByEngine: {\n local: [\"STORAGE_TYPE\", \"STORAGE_PATH\", \"STORAGE_MAX_FILE_SIZE\"],\n s3: [\n \"STORAGE_TYPE\",\n \"S3_BUCKET\",\n \"S3_REGION\",\n \"S3_ACCESS_KEY_ID\",\n \"S3_SECRET_ACCESS_KEY\",\n \"S3_ENDPOINT\",\n \"S3_FORCE_PATH_STYLE\",\n \"STORAGE_MAX_FILE_SIZE\"\n ],\n gcs: [\"STORAGE_TYPE\", \"GCS_BUCKET\", \"GCS_PROJECT_ID\", \"GCS_KEY_FILENAME\", \"STORAGE_MAX_FILE_SIZE\"],\n azure: [],\n firebase: []\n }\n});\n\n/** Options a bucket accepts beyond the common ones. */\nexport interface BucketOptions extends DeclareOptions {\n /**\n * Whether objects are world-readable by default.\n *\n * Declared rather than inferred from the engine, because the two have\n * disagreed before: a private object served through a cacheable public URL\n * is a data leak that nothing errors on.\n */\n publicRead?: boolean;\n /**\n * @deprecated Never applied: every object lands at the root of its bucket,\n * whatever this says, so two sources declaring one bucket share one\n * namespace. Give each source a bucket of its own (`S3_BUCKET__<KEY>`,\n * `GCS_BUCKET__<KEY>`, or `STORAGE_PATH__<KEY>` for a local one), or put\n * the folder in each storage property's `storagePath`. The backend warns\n * once at boot when it is set. Will be removed in a future release.\n */\n prefix?: string;\n /**\n * Serve unqualified uploads — a storage property with no `storageSource` —\n * from this bucket.\n *\n * Without it, declaring `bucket(\"media\")` leaves the default source where\n * it was: on its own `STORAGE_PATH` / `./uploads`, or the bucket the\n * unsuffixed `S3_BUCKET` / `GCS_BUCKET` names. Mark a named bucket to make\n * it the default instead; the files the default held before stay where\n * they are and are no longer served through it.\n */\n default?: boolean;\n /**\n * The credential set this bucket signs with, when several share one.\n *\n * `bucket(\"media\", { engine: \"s3\", account: \"minio\" })` keeps reading its own\n * `S3_BUCKET__MEDIA` — the bucket name is what distinguishes one source from\n * another and never falls back — while the provider-level variables\n * (`S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ENDPOINT`, `S3_REGION`,\n * `S3_FORCE_PATH_STYLE`) fall back to `__MINIO` when no per-key value is set.\n *\n * Fifteen buckets on one install go from ninety variables to eighteen, and\n * rotating the key becomes one edit. A per-bucket value still wins, so a\n * single source can move to another provider without breaking the rest off\n * their shared account.\n */\n account?: string;\n /**\n * Delete, on a schedule, the files in this bucket that no row names:\n * `true` for the defaults, or `{ olderThanHours, schedule }`. See\n * {@link OrphanSweepOptions}.\n *\n * ```ts\n * export const voice = bucket(\"voice\", { engine: \"gcs\", orphanSweep: { olderThanHours: 72 } });\n * ```\n */\n orphanSweep?: boolean | OrphanSweepOptions;\n}\n\n/** A bucket handle. Storage properties point at it via `storageSource`. */\nexport type BucketHandle = ResourceHandle;\n\n/**\n * Declare a bucket.\n *\n * ```ts\n * export const uploads = bucket({ engine: \"s3\" }); // the default one\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * ```\n *\n * `transport: \"direct\"` means a provider SDK talks to the bucket and the\n * backend is not in the upload path.\n *\n * The options-only form exists for the same reason `database`'s does: the\n * default bucket has no name to pass, and without it the only way to configure\n * one was `bucket(\"(default)\", { … })` — writing out an internal sentinel to\n * reach the options. Passing options where a key belongs used to throw \"a\n * bucket needs a non-empty key\", which names neither the mistake nor the fix.\n */\nexport function bucket(options?: BucketOptions): BucketHandle;\nexport function bucket(key?: string, options?: BucketOptions): BucketHandle;\nexport function bucket(\n keyOrOptions: string | BucketOptions = DEFAULT_RESOURCE_KEY,\n options: BucketOptions = {}\n): BucketHandle {\n return typeof keyOrOptions === \"string\"\n ? declareResource(\"bucket\", keyOrOptions, options)\n : declareResource(\"bucket\", DEFAULT_RESOURCE_KEY, keyOrOptions);\n}\n\n// ── topic ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // FROZEN at the 0.17.3 literal, for the reason given on `database`.\n kind: \"topic\",\n // `jobs` is the durable local implementation: a topic fans out to one job\n // row per subscription, so each subscriber retries on its own schedule and\n // a failure is a row somebody can look at rather than a lost message.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [\"REBASE_TOPIC_URL\"],\n optionKeys: [\"delivery\", \"maxAttempts\"],\n implicitDefault: false\n});\n// Nothing. A topic on the `jobs` engine is rows in the project's own database\n// and binds from no variable of its own. The literal above says\n// `REBASE_TOPIC_URL` — a name nothing in either repository read, which\n// `rebase status` then printed as a variable somebody could set — and it has to\n// keep saying it, because a driver ≤ 0.17.3 compares that object and throws.\n// The gate in `resource-env-bases.test.ts` covers every registered kind through\n// the amended view, so a phantom name fails a build rather than reaching a\n// developer.\namendResourceKind(\"topic\", { envBases: [] });\n\n/**\n * How hard the runtime tries to deliver.\n *\n * Only `at-least-once` is implemented, and it is the honest name for what a\n * retrying queue does: a handler must tolerate seeing the same event twice.\n * `at-most-once` is listed so a future transport can offer it without the\n * option changing shape, and is refused today rather than silently upgraded.\n */\nexport type TopicDelivery = \"at-least-once\" | \"at-most-once\";\n\n/** Options a topic accepts beyond the common ones. */\nexport interface TopicOptions extends DeclareOptions {\n delivery?: TopicDelivery;\n /** Attempts per subscription before a message is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a subscription does with an event.\n *\n * `attempt` counts from 1. Worth branching on: the first delivery and the\n * fourth are the same call, but the fourth is where it is worth logging loudly.\n * `signal` is aborted when the attempt runs past the job queue's `timeoutMs`.\n */\nexport type TopicHandler<T> = (\n event: T,\n context: { attempt: number; topic: string; subscription: string; signal: AbortSignal }\n) => Promise<void> | void;\n\n/** A declared subscription, as recorded in the graph and wired at boot. */\nexport interface TopicSubscription<T = unknown> {\n topic: string;\n name: string;\n handler: TopicHandler<T>;\n maxAttempts?: number;\n}\n\n/**\n * What a topic publishes through.\n *\n * Installed by `@rebasepro/server` at boot. Absent — in the CLI evaluating\n * config to derive the graph, or in a unit test — publishing throws a message\n * naming the cause, rather than resolving and dropping the event. A publish\n * that silently does nothing is the failure mode a queue exists to prevent.\n */\nexport interface TopicRuntime {\n publish(topic: string, event: unknown): Promise<void>;\n}\n\n/**\n * Declared handlers and installed runtimes, for topics and queues — on\n * `globalThis` under a shared symbol, never in module locals.\n *\n * A module local is one per COPY of this package, and two copies in one\n * process is the normal layout rather than an accident: `@rebasepro/server`\n * inlines this package into its own dist, while `config/resources.ts` imports\n * it from `node_modules`. With locals, a project's `.handler()` and\n * `.subscription()` went into the project's copy and the worker read the\n * server's empty one (`Job queue started {\"tasks\":0}`), and the runtime the\n * server installed was invisible to the project's `enqueue`/`publish` — so\n * every queue and topic threw \"no runtime is installed\" inside a running\n * backend. The CLI deriving the graph had the same split. Same mechanism and\n * reasoning as `registry()` in resources.ts; `module-state-across-copies.test.ts`\n * loads two copies to hold it, and scans for any other module-level state that\n * would split the same way.\n *\n * The version is in the symbol: a change to this object's SHAPE takes a new\n * suffix, so no copy ever reads a shape it does not know.\n */\nconst WORK_KEY = Symbol.for(\"@rebasepro/types.workRegistry.v1\");\n\ninterface WorkRegistry {\n topicRuntime: TopicRuntime | null;\n subscriptions: TopicSubscription[];\n queueRuntime: QueueRuntime | null;\n queueConsumers: Map<string, QueueConsumer>;\n}\n\ntype GlobalWithWork = typeof globalThis & { [WORK_KEY]?: WorkRegistry };\n\nfunction work(): WorkRegistry {\n const g = globalThis as GlobalWithWork;\n let shared = g[WORK_KEY];\n if (!shared) {\n shared = { topicRuntime: null, subscriptions: [], queueRuntime: null, queueConsumers: new Map() };\n g[WORK_KEY] = shared;\n }\n return shared;\n}\n\n/**\n * Where `@rebasepro/server` publishes its client once it has booted (its\n * `singleton.ts`). Read only to tell the two causes of a missing runtime apart.\n */\nconst SERVER_INSTANCE_SLOT = Symbol.for(\"@rebasepro/server:singleton-instance\");\n\ntype GlobalWithServer = typeof globalThis & { [SERVER_INSTANCE_SLOT]?: unknown };\n\n/**\n * Why there is no runtime to send through, as far as this process can tell.\n *\n * Outside a backend — the CLI evaluating config, a script, a unit test — the\n * answer is that there is nothing to deliver to. Inside one it is not: the\n * backend installs a runtime at boot for what `config/resources.ts` declared,\n * so a missing one there means boot never saw the declaration, or the backend\n * carries a copy of this package too old to share the slot it installs into.\n * Saying \"outside a backend\" to somebody whose backend is running sends them\n * looking for the wrong thing.\n */\nfunction missingRuntimeCause(kind: \"queue\" | \"topic\"): string {\n const backendUp = (globalThis as GlobalWithServer)[SERVER_INSTANCE_SLOT] != null;\n if (!backendUp) {\n return \"This works inside a running Rebase backend; this looks like code running outside one \" +\n \"(a build, a script, or a test without a harness).\";\n }\n return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot ` +\n `when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not ` +\n \"read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads — keep \" +\n \"@rebasepro/server and @rebasepro/types on the same version.\";\n}\n\n/** Install the transport topics publish through. Called by the server at boot. */\nexport function setTopicRuntime(runtime: TopicRuntime | null): void {\n work().topicRuntime = runtime;\n}\n\n/** Every declared subscription, for the worker to wire and the graph to record. */\nexport function declaredSubscriptions(topic?: string): TopicSubscription[] {\n const { subscriptions } = work();\n return topic ? subscriptions.filter(s => s.topic === topic) : subscriptions.slice();\n}\n\n/** Forget declared subscriptions. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredSubscriptions(): void {\n work().subscriptions.length = 0;\n}\n\n/** A topic handle, carrying its payload type. */\nexport interface TopicHandle<T> extends ResourceHandle {\n /**\n * Publish an event.\n *\n * Resolves once the event is durably recorded for every subscription, not\n * once they have run. Enqueued inside a transaction that rolls back, it was\n * never published.\n */\n publish(event: T): Promise<void>;\n /**\n * Declare a subscription.\n *\n * The name is its identity: it is what the job row records, what a retry\n * counts against, and what a second subscription must not collide with.\n */\n subscription(name: string, handler: TopicHandler<T>, options?: { maxAttempts?: number }): void;\n}\n\n/**\n * Declare a topic.\n *\n * ```ts\n * export const signups = topic<{ userId: string }>(\"signups\");\n * signups.subscription(\"send-welcome\", async (event) => { … });\n * await signups.publish({ userId });\n * ```\n */\nexport function topic<T = unknown>(key: string, options: TopicOptions = {}): TopicHandle<T> {\n if (options.delivery === \"at-most-once\") {\n throw new Error(\n `Topic \"${key}\" asks for at-most-once delivery, which no shipped transport implements. ` +\n \"The durable queue behind topics retries, so it is at-least-once and a handler must \" +\n \"tolerate seeing an event twice. Refused rather than quietly given the other guarantee.\"\n );\n }\n const handle = declareResource(\"topic\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async publish(event: T): Promise<void> {\n const runtime = work().topicRuntime;\n if (!runtime) {\n throw new Error(\n `Cannot publish to topic \"${key}\": no topic runtime is installed. ${missingRuntimeCause(\"topic\")}`\n );\n }\n await runtime.publish(key, event);\n },\n subscription(name: string, handler: TopicHandler<T>, subOptions: { maxAttempts?: number } = {}): void {\n if (!name || name.trim() === \"\") {\n throw new Error(`A subscription on topic \"${key}\" needs a non-empty name.`);\n }\n const { subscriptions } = work();\n if (subscriptions.some(s => s.topic === key && s.name === name)) {\n throw new Error(\n `Topic \"${key}\" already has a subscription named \"${name}\". ` +\n \"The name is what a job row records and what a retry counts against, so two \" +\n \"cannot share one.\"\n );\n }\n subscriptions.push({\n topic: key,\n name,\n handler: handler as TopicHandler<unknown>,\n ...(subOptions.maxAttempts !== undefined ? { maxAttempts: subOptions.maxAttempts } : {})\n });\n }\n } as TopicHandle<T>;\n}\n\n// ── cron ─────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"cron\",\n // The in-process scheduler, claiming each slot in `rebase.cron_claims` so\n // several instances of one deployment run a slot once. It is the only\n // engine because it is the only one that exists; an external scheduler\n // (a platform's cron, a Kubernetes CronJob) would be a second engine that\n // triggers the same handler over HTTP, and it can register itself.\n engines: [\"scheduler\"],\n defaultEngine: \"scheduler\",\n // Code, not configuration: a cron binds from no variable. It is in the\n // graph so a host knows a project's schedules BEFORE running it, which is\n // what lets a console show them and a placement decision read them.\n envBases: [],\n optionKeys: [\"schedule\", \"timezone\", \"description\", \"enabled\", \"timeoutSeconds\", \"catchUpWindowSeconds\"],\n implicitDefault: false\n});\n\n/** What a cron declaration records, beyond its handler. */\nexport interface CronResourceOptions extends DeclareOptions {\n /** Five-field cron expression, e.g. `0 3 * * *`. */\n schedule: string;\n /**\n * IANA zone the schedule is read in, e.g. `Europe/Madrid`.\n *\n * Without it the schedule is read in the process's own zone, which is\n * whatever the host happens to be set to — UTC in nearly every container,\n * the developer's own on a laptop. \"3 AM\" then means two different hours\n * either side of a deploy. Naming the zone makes the declaration mean one\n * thing everywhere.\n */\n timezone?: string;\n description?: string;\n enabled?: boolean;\n timeoutSeconds?: number;\n catchUpWindowSeconds?: number;\n}\n\n/**\n * Declare a cron, as the scheduler's `defineCron` does on its way through.\n *\n * Projects do not call this: `defineCron` in `@rebasepro/server` does, so a\n * cron file is both the handler and the declaration — one file, one name, and\n * the graph derived from it says what a host needs to know without evaluating\n * the handler. Exported so the derive step and the scheduler spell the\n * declaration identically.\n */\nexport function declareCron(name: string, options: CronResourceOptions): ResourceHandle {\n if (typeof options.schedule !== \"string\" || options.schedule.trim() === \"\") {\n throw new Error(`Cron \"${name}\" needs a schedule — a five-field cron expression such as \"0 3 * * *\".`);\n }\n return declareResource(\"cron\", name, options);\n}\n\n// ── function ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"function\",\n // Mounted by this runtime at `/api/functions/<name>`. A host that runs a\n // function elsewhere — an edge runtime, say — is a second engine, and the\n // bundle's `portable` analysis already says which ones could move.\n engines: [\"http\"],\n defaultEngine: \"http\",\n envBases: [],\n optionKeys: [\"portable\", \"requires\", \"file\"],\n implicitDefault: false\n});\n\n/**\n * What a function declaration records.\n *\n * Recorded by the derive step from the bundler's static analysis rather than\n * by evaluating the function module: a function's handler is a Hono app that\n * only needs to exist at request time, and evaluating it at build time would\n * run its module-scope code in a process with none of its environment.\n */\nexport interface FunctionResourceOptions extends DeclareOptions {\n /** Path inside the project, so a host can point at the file. */\n file?: string;\n /** `false` when the source imports a Node built-in or a package that needs one. */\n portable?: boolean;\n /** Why it is not portable — one short phrase per reason. */\n requires?: string[];\n}\n\n/** Declare a function. Called by the derive step, not by projects. */\nexport function declareFunction(name: string, options: FunctionResourceOptions = {}): ResourceHandle {\n return declareResource(\"function\", name, options);\n}\n\n// ── queue ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"queue\",\n // Same durable queue topics ride on: a row per job, claimed with\n // `FOR UPDATE SKIP LOCKED`, retried on a backoff, kept when it gives up.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [],\n optionKeys: [\"maxAttempts\"],\n implicitDefault: false\n});\n\n/** Options a queue accepts beyond the common ones. */\nexport interface QueueOptions extends DeclareOptions {\n /** Attempts before a job is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a queue's handler receives. `attempt` counts from 1; `signal` is\n * aborted when the attempt runs past the job queue's `timeoutMs`.\n */\nexport type QueueHandler<T> = (\n payload: T,\n context: { attempt: number; queue: string; jobId: string; signal: AbortSignal }\n) => Promise<void> | void;\n\n/** Per-job options at enqueue time. */\nexport interface QueueEnqueueOptions {\n /** Earliest time the job may run. Defaults to now. */\n runAt?: Date;\n /** Attempts for this job, overriding the queue's. */\n maxAttempts?: number;\n}\n\n/**\n * What a queue enqueues through.\n *\n * Installed by `@rebasepro/server` at boot, alongside the topic runtime.\n * Absent — config evaluated by the CLI, a unit test — enqueueing throws with\n * the cause named, rather than resolving and dropping the job.\n */\nexport interface QueueRuntime {\n enqueue(queue: string, payload: unknown, options?: QueueEnqueueOptions): Promise<{ id: string }>;\n}\n\n/** Install the transport queues enqueue through. Called by the server at boot. */\nexport function setQueueRuntime(runtime: QueueRuntime | null): void {\n work().queueRuntime = runtime;\n}\n\n/** A queue's handler, as recorded for the worker to wire. */\nexport interface QueueConsumer<T = unknown> {\n queue: string;\n handler: QueueHandler<T>;\n}\n\n/** Every declared queue handler, for the worker to wire. */\nexport function declaredQueueConsumers(): QueueConsumer[] {\n return [...work().queueConsumers.values()];\n}\n\n/** Forget declared queue handlers. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredQueueConsumers(): void {\n work().queueConsumers.clear();\n}\n\n/** A queue handle, carrying its payload type. */\nexport interface QueueHandle<T> extends ResourceHandle {\n /**\n * Put a job on the queue.\n *\n * Resolves once the job is durably recorded, not once it has run. A row\n * insert, so enqueued inside a transaction that rolls back it was never\n * enqueued.\n */\n enqueue(payload: T, options?: QueueEnqueueOptions): Promise<{ id: string }>;\n /**\n * Declare the handler.\n *\n * One per queue: a queue is a work list with one consumer, which is what\n * separates it from a topic. Work that several things must react to is a\n * topic with several subscriptions.\n */\n handler(fn: QueueHandler<T>): void;\n}\n\n/**\n * Declare a queue.\n *\n * ```ts\n * export const thumbnails = queue<{ key: string }>(\"thumbnails\");\n * thumbnails.handler(async ({ key }) => { … });\n * await thumbnails.enqueue({ key }, { runAt: new Date(Date.now() + 60_000) });\n * ```\n *\n * The difference from a topic is the number of consumers: a queue has one, a\n * topic fans out to every subscription. Both ride on the durable job queue, so\n * declaring either turns it on.\n */\nexport function queue<T = unknown>(key: string, options: QueueOptions = {}): QueueHandle<T> {\n const handle = declareResource(\"queue\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async enqueue(payload: T, enqueueOptions?: QueueEnqueueOptions): Promise<{ id: string }> {\n const runtime = work().queueRuntime;\n if (!runtime) {\n throw new Error(\n `Cannot enqueue on queue \"${key}\": no queue runtime is installed. ${missingRuntimeCause(\"queue\")}`\n );\n }\n return runtime.enqueue(key, payload, enqueueOptions);\n },\n handler(fn: QueueHandler<T>): void {\n const { queueConsumers } = work();\n if (queueConsumers.has(key)) {\n throw new Error(\n `Queue \"${key}\" already has a handler. A queue has exactly one consumer; ` +\n \"work that several things react to is a topic with several subscriptions.\"\n );\n }\n queueConsumers.set(key, { queue: key, handler: fn as QueueHandler<unknown> });\n }\n } as QueueHandle<T>;\n}\n\n// ── Handing declarations to the readers ──────────────────────────────────────\n\n/**\n * One declaration, as the data layer's definition.\n *\n * There is exactly one of these per kind, and everything that needs a\n * definition goes through it — the frontend, the managed runtime's boot path,\n * and an ejected project's own entrypoint. That is not tidiness: the mapping\n * used to exist twice, once here and once in `@rebasepro/server`'s\n * `graphToStorageSources`, and the two disagreed. The server's copy carried a\n * bucket's `account`; this one dropped it, so a bucket declared with shared\n * credentials resolved them on the managed runtime and resolved *nothing* in an\n * ejected backend — the source was skipped and every upload to it answered 501.\n *\n * A field-by-field map is one line away from that failure at all times, so\n * there is now one line to keep right instead of two to keep equal.\n */\nexport function resourceToDataSource(declaration: ResourceDeclaration): DataSourceDefinition {\n return {\n // The graph and the data layer spell \"the unnamed one\" identically\n // today, but they are separate constants and nothing stops them\n // drifting. Mapped explicitly so a divergence is a compile error rather\n // than a default database that silently fails to bind.\n key: declaration.key === DEFAULT_RESOURCE_KEY ? DEFAULT_DATA_SOURCE_KEY : declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.databaseId === \"string\"\n ? { databaseId: declaration.options.databaseId }\n : {}),\n ...(declaration.label !== undefined ? { label: declaration.label } : {})\n };\n}\n\n/** One declaration, as the storage layer's definition. See {@link resourceToDataSource}. */\nexport function resourceToStorageSource(declaration: ResourceDeclaration): StorageSourceDefinition {\n return {\n key: declaration.key === DEFAULT_RESOURCE_KEY ? DEFAULT_STORAGE_SOURCE_KEY : declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n // Carried, or the declaration's `account` is accepted at the call site\n // and lost on the way to the reader — a declared option that does\n // nothing, which is the exact failure this whole model exists to remove.\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n ...(declaration.options.default === true ? { default: true } : {}),\n ...orphanSweepOf(declaration.options.orphanSweep),\n ...(declaration.label !== undefined ? { label: declaration.label } : {})\n };\n}\n\n/**\n * A bucket's `orphanSweep` option as a definition carries it: `true` is the\n * defaults, an object keeps only the fields of the right type. The runtime\n * checks the values (the grace-period floor, the schedule) and refuses a bad\n * one loudly; this only refuses to invent one.\n */\nfunction orphanSweepOf(option: unknown): { orphanSweep?: OrphanSweepOptions } {\n if (option === true) return { orphanSweep: {} };\n if (!option || typeof option !== \"object\") return {};\n const { olderThanHours, schedule } = option as Record<string, unknown>;\n return {\n orphanSweep: {\n ...(typeof olderThanHours === \"number\" ? { olderThanHours } : {}),\n ...(typeof schedule === \"string\" ? { schedule } : {})\n }\n };\n}\n\n/**\n * The declared databases, as definitions.\n *\n * Both the frontend and a project's own backend entrypoint read this. The\n * frontend needs to know which sources exist and how they are reached — a\n * `direct`-transport source is one the browser talks to itself — and it imports\n * the same config package the backend does. Without these it would mean writing\n * the list a second time, by hand, next to the declarations, which is precisely\n * the two-homes problem this model removed everywhere else.\n *\n * ```tsx\n * import \"../config/resources\"; // registers them\n * import { declaredDataSources, declaredStorageSources } from \"@rebasepro/types\";\n *\n * <Rebase dataSources={declaredDataSources()} storageSources={declaredStorageSources()} />\n * ```\n *\n * The import is what registers them, so a bundler that drops an unused module\n * would leave this empty — hence the side-effect import above rather than a\n * bare re-export.\n */\nexport function declaredDataSources(): DataSourceDefinition[] {\n return declaredResources(\"database\").map(resourceToDataSource);\n}\n\n/** The declared buckets, as definitions. */\nexport function declaredStorageSources(): StorageSourceDefinition[] {\n return declaredResources(\"bucket\").map(resourceToStorageSource);\n}\n","/**\n * Scopes — what a credential may do, named `resource:action`.\n *\n * One vocabulary for every way of reaching a Rebase backend: a person's\n * session, a service key, a personal key and an OAuth token for `/mcp` all\n * answer \"may this caller do X?\" with the same strings, so a grant reads the\n * same on a key, on a role and on a consent screen.\n *\n * A scope may carry a target — `data:read:posts` is `data:read` on the `posts`\n * collection only. The unqualified scope covers every target. Only the data\n * plane and app scopes take targets; see {@link SCOPE_TARGETS}.\n *\n * Two planes, held differently:\n *\n * - **The data plane** (`data:*`, `storage:*`, `functions:invoke`). Every\n * signed-in person holds all of it, because what a person may do with data\n * is decided row by row by the collection's `securityRules` and by storage\n * policies, never by a scope. On a key or a token these scopes narrow: a key\n * holding `data:read:posts` reaches nothing else, whatever RLS would allow.\n * - **The admin plane** (everything else). Nobody holds it implicitly. The\n * `admin` role holds all of it; any other role holds what the app declares\n * for it under `auth.roles` on the users collection.\n *\n * Apps declare their own scopes too (`auth.scopes`), named the same way —\n * `project:deploy`. Every signed-in person holds every app scope: like the data\n * plane, the function behind it decides whether the person may act, and the\n * scope exists so a key can be narrowed to that one action.\n *\n * @module\n */\n\n/** @group Auth */\nexport const DATA_PLANE_SCOPES = [\n \"data:read\",\n \"data:write\",\n \"data:delete\",\n \"storage:read\",\n \"storage:write\",\n \"storage:delete\",\n \"functions:invoke\"\n] as const;\n\n/** @group Auth */\nexport const ADMIN_SCOPES = [\n \"users:read\",\n \"users:write\",\n \"schema:read\",\n \"schema:write\",\n \"database:read\",\n \"database:write\",\n \"backups:read\",\n \"cron:read\",\n \"cron:write\",\n \"logs:read\",\n \"keys:read\",\n \"keys:write\"\n] as const;\n\n/** @group Auth */\nexport type DataPlaneScope = (typeof DATA_PLANE_SCOPES)[number];\n/** @group Auth */\nexport type AdminScope = (typeof ADMIN_SCOPES)[number];\n/** @group Auth */\nexport type BuiltInScope = DataPlaneScope | AdminScope;\n\n/** Every scope Rebase itself defines, in display order. @group Auth */\nexport const BUILT_IN_SCOPES: readonly BuiltInScope[] = [...DATA_PLANE_SCOPES, ...ADMIN_SCOPES];\n\n/**\n * Scopes no key may hold.\n *\n * A key that could manage keys could mint its own successor, widen itself, or\n * revoke the keys other integrations run on — and revoking it would undo none\n * of that. Managing keys is for a person (or the service key).\n *\n * @group Auth\n */\nexport const KEY_MANAGEMENT_SCOPES: readonly AdminScope[] = [\"keys:read\", \"keys:write\"];\n\n/** The one built-in role. It holds every scope and is the RLS `admin` role. @group Auth */\nexport const ADMIN_ROLE = \"admin\";\n\n/** What a scope's target names. @group Auth */\nexport type ScopeTargetKind = \"collection\" | \"bucket\" | \"function\";\n\n/**\n * The built-in scopes that accept a target, and what the target names.\n *\n * - `data:*` — a collection slug\n * - `storage:*` — a storage source id (`(default)` for the default source)\n * - `functions:invoke` — a custom function's name\n *\n * @group Auth\n */\nexport const SCOPE_TARGETS: Readonly<Partial<Record<BuiltInScope, ScopeTargetKind>>> = {\n \"data:read\": \"collection\",\n \"data:write\": \"collection\",\n \"data:delete\": \"collection\",\n \"storage:read\": \"bucket\",\n \"storage:write\": \"bucket\",\n \"storage:delete\": \"bucket\",\n \"functions:invoke\": \"function\"\n};\n\n/** A scope's wording, for the screens that ask a person to grant it. @group Auth */\nexport interface ScopeDescription {\n /** Short, imperative: what a holder may do. */\n label: string;\n /** One sentence on what that reaches, including anything surprising. */\n description: string;\n}\n\n/** @group Auth */\nexport const BUILT_IN_SCOPE_DESCRIPTIONS: Readonly<Record<BuiltInScope, ScopeDescription>> = {\n \"data:read\": {\n label: \"Read data\",\n description: \"Read rows from tables, through the caller's row-level security.\"\n },\n \"data:write\": {\n label: \"Create and update data\",\n description: \"Create and update rows in tables, through the caller's row-level security.\"\n },\n \"data:delete\": {\n label: \"Delete data\",\n description: \"Delete rows from tables, through the caller's row-level security.\"\n },\n \"storage:read\": {\n label: \"Read files\",\n description: \"List and download stored files.\"\n },\n \"storage:write\": {\n label: \"Upload files\",\n description: \"Upload files and create folders.\"\n },\n \"storage:delete\": {\n label: \"Delete files\",\n description: \"Delete stored files.\"\n },\n \"functions:invoke\": {\n label: \"Call functions\",\n description: \"Call the backend's custom functions. A function can do anything its code does.\"\n },\n \"users:read\": {\n label: \"See users\",\n description: \"List user accounts and their roles.\"\n },\n \"users:write\": {\n label: \"Manage users\",\n description: \"Create, edit and delete accounts, reset passwords and second factors, and assign roles up to the holder's own.\"\n },\n \"schema:read\": {\n label: \"See the schema\",\n description: \"Read the schema, plan schema changes and run the RLS audit.\"\n },\n \"schema:write\": {\n label: \"Change the schema\",\n description: \"Apply schema changes: edits schema files and alters the database.\"\n },\n \"database:read\": {\n label: \"Inspect the database\",\n description: \"List databases, tables, Postgres roles and branches.\"\n },\n \"database:write\": {\n label: \"Run SQL\",\n description: \"Run SQL as the database owner, outside row-level security, and create or delete branches.\"\n },\n \"backups:read\": {\n label: \"Download backups\",\n description: \"List and download database backups — every row, outside row-level security.\"\n },\n \"cron:read\": {\n label: \"See cron jobs\",\n description: \"List cron jobs and read their run history.\"\n },\n \"cron:write\": {\n label: \"Run cron jobs\",\n description: \"Trigger cron jobs and switch them on or off.\"\n },\n \"logs:read\": {\n label: \"Read server logs\",\n description: \"Read the server's request and application logs.\"\n },\n \"keys:read\": {\n label: \"See service keys\",\n description: \"List the project's service keys. Never grantable to a key.\"\n },\n \"keys:write\": {\n label: \"Manage service keys\",\n description: \"Create, change and revoke the project's service keys. Never grantable to a key.\"\n }\n};\n\n/**\n * An app-declared scope, under `auth.scopes` on the users collection.\n *\n * @example\n * ```ts\n * auth: {\n * enabled: true,\n * scopes: {\n * \"project:deploy\": { label: \"Deploy projects\", target: \"project\" }\n * }\n * }\n * ```\n *\n * @group Auth\n */\nexport interface ScopeDefinition {\n /** Short, imperative: what a holder may do. Shown wherever the scope is granted. */\n label: string;\n /** One sentence on what that reaches. */\n description?: string;\n /**\n * What a target names, when the scope accepts one — `\"project\"` lets a\n * key hold `project:deploy:<id>`. Unset, the scope takes no target.\n */\n target?: string;\n}\n\n/**\n * An app-declared role, under `auth.roles` on the users collection.\n *\n * A role is a name the database sees (RLS policies match it) and a bundle of\n * admin-plane and app scopes. Data-plane scopes are not role scopes: what a\n * person may do with data is the collection's `securityRules`, so listing\n * `data:write` here would read as a grant it is not, and is refused.\n *\n * @example\n * ```ts\n * auth: {\n * enabled: true,\n * roles: {\n * support: { name: \"Support\", scopes: [\"users:read\", \"users:write\", \"logs:read\"] },\n * developer: { name: \"Developer\", scopes: [\"schema:read\", \"database:read\", \"logs:read\", \"cron:read\"] }\n * }\n * }\n * ```\n *\n * @group Auth\n */\nexport interface RoleDefinition {\n /** Display name. Defaults to the role id. */\n name?: string;\n /** One sentence on who holds it. */\n description?: string;\n /** Admin-plane and app scopes the role holds. */\n scopes: readonly string[];\n}\n\n/**\n * The declared access model: the app's own scopes and roles beside the\n * built-in ones. What `scopesForRoles` and `validateScopes` read.\n *\n * @group Auth\n */\nexport interface AccessModel {\n roles: Readonly<Record<string, RoleDefinition>>;\n scopes: Readonly<Record<string, ScopeDefinition>>;\n}\n\n/** The access model of an app that declares nothing: built-ins only. @group Auth */\nexport const EMPTY_ACCESS_MODEL: AccessModel = { roles: {}, scopes: {} };\n\n/** A scope string split into its scope and optional target. @group Auth */\nexport interface ParsedScope {\n /** `resource:action`. */\n scope: string;\n /** The one collection, bucket, function or app resource it is narrowed to. */\n target?: string;\n}\n\nconst SCOPE_PART = /^[a-z][a-z0-9-]*$/;\n\n/**\n * Split `resource:action[:target]`. Returns null for anything else.\n *\n * The target is everything after the second colon, so a target may itself\n * contain colons. Resource and action are lower-case words.\n *\n * @group Auth\n */\nexport function parseScope(value: string): ParsedScope | null {\n if (typeof value !== \"string\") return null;\n const first = value.indexOf(\":\");\n if (first < 0) return null;\n const second = value.indexOf(\":\", first + 1);\n const resource = value.slice(0, first);\n const action = second < 0 ? value.slice(first + 1) : value.slice(first + 1, second);\n if (!SCOPE_PART.test(resource) || !SCOPE_PART.test(action)) return null;\n if (second < 0) return { scope: `${resource}:${action}` };\n const target = value.slice(second + 1);\n if (target.length === 0 || /\\s/.test(target)) return null;\n return { scope: `${resource}:${action}`, target };\n}\n\n/** @group Auth */\nexport function isBuiltInScope(scope: string): scope is BuiltInScope {\n return (BUILT_IN_SCOPES as readonly string[]).includes(scope);\n}\n\n/** @group Auth */\nexport function isDataPlaneScope(scope: string): scope is DataPlaneScope {\n return (DATA_PLANE_SCOPES as readonly string[]).includes(scope);\n}\n\n/** @group Auth */\nexport function isAdminScope(scope: string): scope is AdminScope {\n return (ADMIN_SCOPES as readonly string[]).includes(scope);\n}\n\n/** Does this list of roles include the built-in `admin` role? @group Auth */\nexport function hasAdminRole(roles: readonly string[] | null | undefined): boolean {\n return !!roles?.includes(ADMIN_ROLE);\n}\n\n/**\n * Why `name` cannot be written as a role, or `undefined` when it can.\n *\n * No naming pattern is imposed — an app may call its roles anything. What is\n * refused is a name that would be read back as *other* roles: a role travels as\n * one element of a Postgres `text[]` and as one entry of the comma-joined\n * `app.user_roles` setting that RLS policies split with\n * `string_to_array(…, ',')`. Written as `\"support,admin\"`, a role comes back as\n * `admin`; braces, quotes and backslashes are array-literal syntax, so they are\n * refused too, as are empty names and control characters.\n *\n * @group Auth\n */\nexport function roleNameProblem(name: unknown): string | undefined {\n if (typeof name !== \"string\") return \"is not a string\";\n if (name.trim() === \"\") return \"is empty\";\n if (/[,{}\"\\\\]/.test(name)) return \"contains , { } \\\" or \\\\\";\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(name)) return \"contains a control character\";\n return undefined;\n}\n\n/**\n * Does a set of held scopes grant `scope`, optionally on one `target`?\n *\n * The unqualified grant covers every target. A qualified grant covers its own\n * target only, and never answers an unqualified question: a key holding\n * `data:read:posts` is not asked \"may you read data?\" and told yes.\n *\n * @group Auth\n */\nexport function scopeGrants(held: readonly string[], scope: string, target?: string): boolean {\n for (const entry of held) {\n if (entry === scope) return true;\n if (target !== undefined && entry === `${scope}:${target}`) return true;\n }\n return false;\n}\n\n/**\n * Does a set of held scopes grant `scope` on at least one target?\n *\n * For a surface that lists what is reachable — the collections an MCP client\n * may query — and filters per item afterwards.\n *\n * @group Auth\n */\nexport function scopeGrantsAny(held: readonly string[], scope: string): boolean {\n const prefix = `${scope}:`;\n return held.some(entry => entry === scope || entry.startsWith(prefix));\n}\n\n/**\n * The targets a held set narrows `scope` to: `\"all\"` when it holds the\n * unqualified scope, otherwise the listed targets (possibly none).\n *\n * @group Auth\n */\nexport function scopeTargets(held: readonly string[], scope: string): \"all\" | string[] {\n const prefix = `${scope}:`;\n const targets: string[] = [];\n for (const entry of held) {\n if (entry === scope) return \"all\";\n if (entry.startsWith(prefix)) targets.push(entry.slice(prefix.length));\n }\n return targets;\n}\n\n/**\n * Every scope a person holding `roles` has.\n *\n * The data plane and every app scope always; the whole admin plane with the\n * `admin` role; otherwise each declared role's scopes. A role nobody declared\n * adds nothing — it may still mean something to an RLS policy.\n *\n * @group Auth\n */\nexport function scopesForRoles(roles: readonly string[] | null | undefined, model: AccessModel = EMPTY_ACCESS_MODEL): string[] {\n const held = new Set<string>([...DATA_PLANE_SCOPES, ...Object.keys(model.scopes)]);\n if (hasAdminRole(roles)) {\n for (const scope of ADMIN_SCOPES) held.add(scope);\n return [...held];\n }\n for (const role of roles ?? []) {\n const definition = Object.prototype.hasOwnProperty.call(model.roles, role) ? model.roles[role] : undefined;\n for (const scope of definition?.scopes ?? []) held.add(scope);\n }\n return [...held];\n}\n\n/**\n * Every scope this access model knows, unqualified: the built-ins, then the\n * app's own.\n *\n * @group Auth\n */\nexport function knownScopes(model: AccessModel = EMPTY_ACCESS_MODEL): string[] {\n return [...BUILT_IN_SCOPES, ...Object.keys(model.scopes)];\n}\n\n/** Does this scope accept a target? @group Auth */\nexport function scopeAcceptsTarget(scope: string, model: AccessModel = EMPTY_ACCESS_MODEL): boolean {\n if (isBuiltInScope(scope)) return SCOPE_TARGETS[scope] !== undefined;\n const definition = Object.prototype.hasOwnProperty.call(model.scopes, scope) ? model.scopes[scope] : undefined;\n return definition?.target !== undefined;\n}\n\n/** How a scope string failed to validate. @group Auth */\nexport interface ScopeProblem {\n scope: string;\n reason: \"malformed\" | \"unknown\" | \"target-not-accepted\";\n}\n\n/**\n * Check a list of scope strings against an access model. Returns the\n * problems, empty when every entry is a known scope with an acceptable target.\n *\n * @group Auth\n */\nexport function validateScopes(values: readonly unknown[], model: AccessModel = EMPTY_ACCESS_MODEL): ScopeProblem[] {\n const known = new Set(knownScopes(model));\n const problems: ScopeProblem[] = [];\n for (const value of values) {\n const text = typeof value === \"string\" ? value : String(value);\n const parsed = typeof value === \"string\" ? parseScope(value) : null;\n if (!parsed) {\n problems.push({ scope: text, reason: \"malformed\" });\n } else if (!known.has(parsed.scope)) {\n problems.push({ scope: text, reason: \"unknown\" });\n } else if (parsed.target !== undefined && !scopeAcceptsTarget(parsed.scope, model)) {\n problems.push({ scope: text, reason: \"target-not-accepted\" });\n }\n }\n return problems;\n}\n\n/**\n * The entries of `requested` that `held` does not cover — what a credential\n * would hold beyond its minter. Empty means the request is within reach.\n *\n * `data:read:posts` is covered by `data:read`; `data:read` is not covered by\n * `data:read:posts`.\n *\n * @group Auth\n */\nexport function scopesBeyond(requested: readonly string[], held: readonly string[]): string[] {\n return requested.filter(entry => {\n const parsed = parseScope(entry);\n if (!parsed) return true;\n return !scopeGrants(held, parsed.scope, parsed.target);\n });\n}\n\n/**\n * Narrow `requested` to what `held` covers, entry by entry. What a personal\n * key holds today when its owner has lost a role since it was minted.\n *\n * @group Auth\n */\nexport function intersectScopes(requested: readonly string[], held: readonly string[]): string[] {\n const beyond = new Set(scopesBeyond(requested, held));\n return requested.filter(entry => !beyond.has(entry));\n}\n\n/**\n * How a scope is worded for a person: the built-in description, the app's\n * declared label, or the raw string when nothing describes it. A target is\n * named after the label.\n *\n * @group Auth\n */\nexport function describeScope(value: string, model: AccessModel = EMPTY_ACCESS_MODEL): ScopeDescription {\n const parsed = parseScope(value);\n if (!parsed) return { label: value, description: \"\" };\n let base: ScopeDescription | undefined;\n if (isBuiltInScope(parsed.scope)) {\n base = BUILT_IN_SCOPE_DESCRIPTIONS[parsed.scope];\n } else if (Object.prototype.hasOwnProperty.call(model.scopes, parsed.scope)) {\n const definition = model.scopes[parsed.scope];\n base = { label: definition.label, description: definition.description ?? \"\" };\n }\n const label = base?.label ?? parsed.scope;\n return {\n label: parsed.target !== undefined ? `${label}: ${parsed.target}` : label,\n description: base?.description ?? \"\"\n };\n}\n\n/** A role as a person managing access sees it. @group Auth */\nexport interface RoleSummary {\n id: string;\n name: string;\n description?: string;\n /** Admin-plane and app scopes. The `admin` role lists every admin-plane scope. */\n scopes: string[];\n /** True for `admin`, which the app does not declare. */\n builtIn: boolean;\n}\n\n/** A scope as a screen that grants it lists it. @group Auth */\nexport interface ScopeSummary {\n scope: string;\n label: string;\n description: string;\n /** What a target names, when the scope takes one. */\n target?: string;\n /** `data`, `admin` or `app`: which plane the scope belongs to. */\n plane: \"data\" | \"admin\" | \"app\";\n}\n\n/** The roles of an access model, `admin` first. @group Auth */\nexport function summarizeRoles(model: AccessModel = EMPTY_ACCESS_MODEL): RoleSummary[] {\n return [\n { id: ADMIN_ROLE, name: \"Admin\", description: \"Holds every scope. Row-level security does not limit it: it reads, changes and deletes every row.\", scopes: [...ADMIN_SCOPES], builtIn: true },\n ...Object.entries(model.roles).map(([id, definition]) => ({\n id,\n name: definition.name ?? id,\n ...(definition.description ? { description: definition.description } : {}),\n scopes: [...definition.scopes],\n builtIn: false\n }))\n ];\n}\n\n/** Every scope of an access model, described, in display order. @group Auth */\nexport function summarizeScopes(model: AccessModel = EMPTY_ACCESS_MODEL): ScopeSummary[] {\n const builtIn: ScopeSummary[] = BUILT_IN_SCOPES.map(scope => ({\n scope,\n ...BUILT_IN_SCOPE_DESCRIPTIONS[scope],\n ...(SCOPE_TARGETS[scope] ? { target: SCOPE_TARGETS[scope] } : {}),\n plane: isDataPlaneScope(scope) ? \"data\" : \"admin\"\n }));\n const app: ScopeSummary[] = Object.entries(model.scopes).map(([scope, definition]) => ({\n scope,\n label: definition.label,\n description: definition.description ?? \"\",\n ...(definition.target ? { target: definition.target } : {}),\n plane: \"app\"\n }));\n return [...builtIn, ...app];\n}\n","import { resourceKeyOf } from \"../types/resources\";\nimport type { ResourceRef } from \"../types/resources\";\n\n/**\n * Who may read and who may write one column, by role.\n *\n * A list that is absent leaves that direction to the table's `rls`. An empty\n * list closes it to every caller, the server's own code aside. Enforced on\n * every door — REST, realtime, MCP, caller SQL, includes, filters and sorts —\n * never only in the panel.\n *\n * @group Schema\n */\nexport interface ColumnAccess {\n /** Roles that receive the column on a read. */\n read?: readonly string[];\n /** Roles that may write the column. */\n write?: readonly string[];\n}\n\n/**\n * Per-role access in its stored form, checked: `read` and `write` must each be\n * a list of non-empty role names, and nothing else may be given.\n *\n * Checked at runtime because a JavaScript caller writing\n * `.access({ read: \"admin\" })` would otherwise have the string spread into\n * one role per character, silently.\n *\n * @param where What is being configured, for the error: `column \"title\"`.\n *\n * @group Schema\n */\nexport function normalizeColumnAccess(access: unknown, where: string): ColumnAccess {\n const expected = \"Write `{ read?: [\\\"role\\\", …], write?: [\\\"role\\\", …] }`.\";\n if (typeof access !== \"object\" || access === null || Array.isArray(access)) {\n throw new Error(`The access of ${where} must be an object of role lists, got ${JSON.stringify(access)}. ${expected}`);\n }\n const stored: ColumnAccess = {};\n for (const [key, value] of Object.entries(access)) {\n if (key !== \"read\" && key !== \"write\") {\n throw new Error(`The access of ${where} has an unknown key \"${key}\". ${expected}`);\n }\n if (value === undefined) continue;\n if (!Array.isArray(value) || value.some(role => typeof role !== \"string\" || role.length === 0)) {\n throw new Error(`\\`access.${key}\\` of ${where} must be a list of role names, got ${JSON.stringify(value)}. ${expected}`);\n }\n const roles: string[] = value.filter((role): role is string => typeof role === \"string\");\n stored[key] = roles;\n }\n return stored;\n}\n\n/**\n * A value the server writes into a column on its own: the time, or the caller.\n *\n * @group Schema\n */\nexport interface ColumnStamp {\n /** `create` stamps on insert only; `update` stamps on every write. */\n on: \"create\" | \"update\";\n /** `now` is the current instant; `user` is the id of the caller. */\n value: \"now\" | \"user\";\n}\n\n/**\n * The DEFAULT of a column.\n *\n * - `literal` — a value, written as a DDL default and applied by the driver on\n * create, so every writer gets the same row.\n * - `sql` — an expression Postgres evaluates.\n * - `random-uuid` — `gen_random_uuid()`.\n * - `identity` — `GENERATED BY DEFAULT AS IDENTITY`.\n * - `database` — the database holds a default Rebase does not state and must\n * not drop; a create may omit the column.\n *\n * @group Schema\n */\nexport type ColumnDefault =\n | { kind: \"literal\"; value: unknown }\n | { kind: \"sql\"; expression: string }\n | { kind: \"random-uuid\" }\n | { kind: \"identity\" }\n | { kind: \"database\" };\n\n/** What every `.validate()` accepts. */\nexport interface BaseValidation {\n /** The API error when a `.notNull()` column is missing from a create. */\n requiredMessage?: string;\n}\n\n/**\n * Validation of a text column, checked by the API before a write.\n *\n * @group Schema\n */\nexport interface StringValidation extends BaseValidation {\n /** Minimum length. */\n min?: number;\n /** Maximum length. */\n max?: number;\n /** Exact length. */\n length?: number;\n /** A pattern the value must match. A `RegExp` is kept as its source and flags. */\n matches?: string | RegExp;\n /** Flags of `matches`, when it was given as a string. */\n matchesFlags?: string;\n /** The API error when `matches` fails. */\n matchesMessage?: string;\n /** The value must be an e-mail address. */\n email?: boolean;\n /** The value must be a URL. */\n url?: boolean;\n /** Lower-case the value before it is stored. */\n lowercase?: boolean;\n /** Upper-case the value before it is stored. */\n uppercase?: boolean;\n /** Trim surrounding whitespace before the value is stored. */\n trim?: boolean;\n}\n\n/**\n * Validation of a numeric column, checked by the API before a write.\n *\n * @group Schema\n */\nexport interface NumberValidation extends BaseValidation {\n /** Inclusive lower bound. */\n min?: number;\n /** Inclusive upper bound. */\n max?: number;\n /** Exclusive upper bound. */\n lessThan?: number;\n /** Exclusive lower bound. */\n moreThan?: number;\n /** The value must be greater than zero. */\n positive?: boolean;\n /** The value must be less than zero. */\n negative?: boolean;\n /** The value must be a whole number. */\n integer?: boolean;\n}\n\n/**\n * Validation of a temporal column. Bounds are ISO strings.\n *\n * @group Schema\n */\nexport interface DateValidation extends BaseValidation {\n /** Earliest accepted value. */\n min?: string | Date;\n /** Latest accepted value. */\n max?: string | Date;\n}\n\n/**\n * Validation of an array column.\n *\n * @group Schema\n */\nexport interface ArrayValidation extends BaseValidation {\n /** Fewest items accepted. */\n minItems?: number;\n /** Most items accepted. */\n maxItems?: number;\n /** Refuse an array holding the same value twice. */\n uniqueItems?: boolean;\n /**\n * For a JSON array of objects (`json.array(json.object({...}))`): refuse\n * two items with the same value in any one of these fields — each field\n * is unique across the items on its own (`[\"sku\"]`: no SKU twice). The\n * fields are keys of the item object; anything else is refused when the\n * schema compiles.\n */\n uniqueBy?: string[];\n}\n\n/**\n * Every validation rule a column can carry, as stored on its definition and\n * served on the wire: patterns are strings, date bounds are ISO strings.\n *\n * @group Schema\n */\nexport interface ColumnValidation {\n /** The API error when a `.notNull()` column is missing from a create. */\n requiredMessage?: string;\n /**\n * Lower bound: minimum length of text, inclusive minimum of a number, earliest\n * accepted value of a temporal column (an ISO string).\n */\n min?: number | string;\n /**\n * Upper bound: maximum length of text, inclusive maximum of a number, latest\n * accepted value of a temporal column (an ISO string).\n */\n max?: number | string;\n /** Exact length of a text value. */\n length?: number;\n /** A pattern a text value must match: a `RegExp`'s source, its flags in `matchesFlags`. */\n matches?: string;\n /** Flags of `matches` (`\"i\"`, `\"u\"`, …). No flags when omitted. */\n matchesFlags?: string;\n /** The API error when `matches` fails. */\n matchesMessage?: string;\n /** A text value must be an e-mail address. */\n email?: boolean;\n /** A text value must be a URL. */\n url?: boolean;\n /** Lower-case a text value before it is stored. */\n lowercase?: boolean;\n /** Upper-case a text value before it is stored. */\n uppercase?: boolean;\n /** Trim surrounding whitespace from a text value before it is stored. */\n trim?: boolean;\n /** Exclusive upper bound of a number. */\n lessThan?: number;\n /** Exclusive lower bound of a number. */\n moreThan?: number;\n /** A number must be greater than zero. */\n positive?: boolean;\n /** A number must be less than zero. */\n negative?: boolean;\n /** A number must be a whole number. */\n integer?: boolean;\n /** Fewest items an array accepts. */\n minItems?: number;\n /** Most items an array accepts. */\n maxItems?: number;\n /** Refuse an array holding the same value twice. */\n uniqueItems?: boolean;\n /** Fields of a JSON array's object items, each unique across the items. See {@link ArrayValidation.uniqueBy}. */\n uniqueBy?: string[];\n}\n\n/** The rules a builder method accepts, before they are normalized. */\nexport type ValidationInput = StringValidation | NumberValidation | DateValidation | ArrayValidation | BaseValidation;\n\nconst isoOf = (value: string | Date): string => (value instanceof Date ? value.toISOString() : value);\n\n/**\n * Validation rules in their stored form: a `RegExp` becomes its source and\n * flags, a `Date` bound becomes an ISO string. What a builder keeps is then\n * exactly what the wire carries.\n *\n * @group Schema\n */\nexport function normalizeValidation(rules: ValidationInput): ColumnValidation {\n const out: ColumnValidation = {};\n for (const [key, value] of Object.entries(rules)) {\n if (value === undefined) continue;\n if (key === \"matches\" && value instanceof RegExp) {\n out.matches = value.source;\n if (value.flags) out.matchesFlags = value.flags;\n continue;\n }\n if ((key === \"min\" || key === \"max\") && (value instanceof Date)) {\n out[key] = isoOf(value);\n continue;\n }\n // A list is copied, so the stored rules do not alias the caller's array.\n Object.assign(out, { [key]: Array.isArray(value) ? [...value] : value });\n }\n return out;\n}\n\n/**\n * How an image is resized before it is stored.\n *\n * @group Schema\n */\nexport interface StorageImageResize {\n /**\n * Largest width in pixels; a wider image is scaled down proportionally. No\n * width limit when omitted.\n */\n maxWidth?: number;\n /**\n * Largest height in pixels; a taller image is scaled down proportionally. No\n * height limit when omitted.\n */\n maxHeight?: number;\n /**\n * How the image fits `maxWidth` × `maxHeight`: `contain` (the default) scales\n * it to fit inside, keeping its aspect ratio; `cover` scales it to fill the box,\n * keeping its aspect ratio, and may crop.\n */\n mode?: \"contain\" | \"cover\";\n /** The stored image's format. `original` (the default) keeps the uploaded one. */\n format?: \"original\" | \"jpeg\" | \"png\" | \"webp\";\n /**\n * Quality of a lossy output (JPEG, WebP), 0–100: higher is sharper and larger.\n * 80 when omitted.\n */\n quality?: number;\n}\n\n/**\n * What `col.storage()` and `json.storage()` take.\n *\n * @group Schema\n */\nexport interface StorageOptions {\n /** The bucket, declared in `backend/resources.ts`. The default bucket when omitted. */\n source?: ResourceRef;\n /** Where files go, as a path template: `\"posts/heroes/\"`, `\"users/{id}/\"`. */\n path: string;\n /** MIME types accepted, with wildcards: `[\"image/*\", \"application/pdf\"]`. */\n accept?: readonly string[];\n /** Largest file accepted, in bytes or as `\"10MB\"`. */\n maxBytes?: number | string;\n /** Resize images before storing them. */\n imageResize?: StorageImageResize;\n /** Files are readable without a signed URL. */\n public?: boolean;\n /** The stored file name, as a template. The uploaded name when omitted. */\n fileName?: string;\n /** Metadata stored with every file. */\n metadata?: Record<string, unknown>;\n /** Store the bucket URL in front of the path. */\n includeBucketUrl?: boolean;\n /** Store the download URL instead of the path. */\n storeUrl?: boolean;\n}\n\n/**\n * The storage rules of a column, as stored and served: the bucket by its key,\n * the size limit in bytes.\n *\n * @group Schema\n */\nexport interface ColumnStorage {\n source?: string;\n path: string;\n accept?: readonly string[];\n maxBytes?: number;\n imageResize?: StorageImageResize;\n public?: boolean;\n fileName?: string;\n metadata?: Record<string, unknown>;\n includeBucketUrl?: boolean;\n storeUrl?: boolean;\n}\n\nconst BYTE_UNITS: Record<string, number> = {\n b: 1,\n kb: 1024,\n mb: 1024 ** 2,\n gb: 1024 ** 3,\n tb: 1024 ** 4\n};\n\n/**\n * A size in bytes, from a number or from `\"10MB\"` / `\"512 kb\"` / `\"1.5GB\"`.\n *\n * Binary multiples (1 MB = 1,048,576 bytes), the unit a storage limit is\n * enforced in. Throws on anything else: a limit that silently parsed to `NaN`\n * is a limit that is never applied.\n *\n * @group Schema\n */\nexport function parseByteSize(size: number | string): number {\n if (typeof size === \"number\") {\n if (!Number.isFinite(size) || size < 0) throw new Error(`A byte size must be a non-negative number, got ${size}.`);\n return size;\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|tb)?\\s*$/i.exec(size);\n if (!match) {\n throw new Error(`Cannot read \"${size}\" as a byte size. Write a number of bytes, or a size such as \"10MB\".`);\n }\n const unit = (match[2] ?? \"b\").toLowerCase();\n return Math.round(Number(match[1]) * BYTE_UNITS[unit]);\n}\n\n/**\n * Storage options in their stored form.\n *\n * @group Schema\n */\nexport function normalizeStorage(options: StorageOptions): ColumnStorage {\n if (typeof options.path !== \"string\" || options.path.length === 0) {\n throw new Error(\"A storage column needs a `path`: where its files go, e.g. `col.storage({ path: \\\"posts/heroes/\\\" })`.\");\n }\n const out: ColumnStorage = { path: options.path };\n if (options.source !== undefined) out.source = resourceKeyOf(options.source);\n if (options.accept !== undefined) out.accept = [...options.accept];\n if (options.maxBytes !== undefined) out.maxBytes = parseByteSize(options.maxBytes);\n if (options.imageResize !== undefined) out.imageResize = { ...options.imageResize };\n if (options.public !== undefined) out.public = options.public;\n if (options.fileName !== undefined) out.fileName = options.fileName;\n if (options.metadata !== undefined) out.metadata = { ...options.metadata };\n if (options.includeBucketUrl !== undefined) out.includeBucketUrl = options.includeBucketUrl;\n if (options.storeUrl !== undefined) out.storeUrl = options.storeUrl;\n return out;\n}\n\n/**\n * The distance a vector index is built for.\n *\n * `ip` is the inner product (pgvector's `vector_ip_ops`).\n *\n * @group Schema\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"ip\";\n\n/**\n * The approximate-nearest-neighbour index of a `col.vector()` column.\n *\n * @group Schema\n */\nexport interface VectorIndexOptions {\n /** `hnsw` (the default) or `ivfflat`. */\n method?: \"hnsw\" | \"ivfflat\";\n /** The distance, or several: one index is built per metric. `cosine` by default. */\n metric?: VectorMetric | readonly VectorMetric[];\n /** HNSW: connections per layer. */\n m?: number;\n /** HNSW: size of the candidate list while building. */\n efConstruction?: number;\n /** IVFFlat: number of lists. */\n lists?: number;\n}\n","import type {\n ArrayValidation,\n BaseValidation,\n ColumnStorage,\n ColumnValidation,\n DateValidation,\n NumberValidation,\n StorageOptions,\n StringValidation,\n ValidationInput\n} from \"./column_options\";\nimport { normalizeStorage, normalizeValidation } from \"./column_options\";\nimport type { ColumnTransform } from \"./hooks\";\n\n/** What every node of a JSON shape may carry. */\ninterface JsonNodeBase {\n /** The key must be present in the document. */\n required?: boolean;\n /** The value written when the key is absent on create. */\n default?: unknown;\n /** What the value is, for OpenAPI and MCP. */\n description?: string;\n}\n\ntype JsonNode<Extra> = Extra & JsonNodeBase & (\n | {\n kind: \"string\";\n validate?: ColumnValidation;\n oneOf?: readonly string[];\n storage?: ColumnStorage;\n /**\n * The server writes the caller's user id into the field: on create\n * only (`\"createUser\"`, `.onCreateUser()`) or on every write\n * (`\"updateUser\"`, `.onUpdateUser()`).\n */\n stamp?: \"createUser\" | \"updateUser\";\n /** `\"user\"`: the field holds a user's id (`.userId()`). */\n semantic?: \"user\";\n }\n | { kind: \"number\"; validate?: ColumnValidation; oneOf?: readonly number[] }\n | { kind: \"boolean\" }\n | {\n kind: \"date\";\n validate?: ColumnValidation;\n /**\n * The server writes the current time into the field: on create only\n * (`\"create\"`, `.onCreateNow()`) or on every write (`\"update\"`,\n * `.onUpdateNow()`).\n */\n stamp?: \"create\" | \"update\";\n }\n | { kind: \"geopoint\" }\n | { kind: \"object\"; fields: Record<string, JsonNode<Extra>>; additional?: boolean }\n | { kind: \"array\"; of: JsonNode<Extra>; validate?: ColumnValidation }\n | { kind: \"oneOf\"; typeField: string; valueField: string; variants: Record<string, JsonNode<Extra>> }\n | { kind: \"unknown\" }\n);\n\n/**\n * The shape of a `json`/`jsonb` document, as served on the wire.\n *\n * It is what lets the server validate a nested field, stamp a nested date,\n * find the files a document references, and search a JSON path — and what lets\n * the panel build a form for the document without being told how.\n *\n * @group Schema\n */\nexport type JsonShape = JsonNode<unknown>;\n\n/**\n * A {@link JsonShape} as authored: the same tree, with field-level hooks on\n * its nodes. Hooks stay on the server.\n *\n * @group Schema\n */\nexport type JsonShapeDef = JsonNode<{ transform?: ColumnTransform }>;\n\n/**\n * The kind of one node of a JSON shape.\n *\n * @group Schema\n */\nexport type JsonKind = JsonShape[\"kind\"];\n\n/** A point on Earth, as a JSON document stores it. */\nexport interface JsonGeoPoint {\n /** Degrees north of the equator, −90 to 90 (south is negative). */\n latitude: number;\n /** Degrees east of Greenwich, −180 to 180 (west is negative). */\n longitude: number;\n}\n\ntype JsonValidationFor<K extends JsonKind> =\n K extends \"string\" ? StringValidation :\n K extends \"number\" ? NumberValidation :\n K extends \"date\" ? DateValidation :\n K extends \"array\" ? ArrayValidation :\n BaseValidation;\n\n/**\n * The value a JSON field's `.transform()` hooks receive and return: the\n * field's type, plus `undefined` while the field is not `.required()`.\n *\n * Read when `.transform()` is called: `.required().transform(…)` receives\n * `TData`, `.transform(…).required()` keeps `TData | undefined`.\n *\n * @group Schema\n */\nexport type JsonTransformValue<TData, TRequired extends boolean> = TRequired extends true ? TData : TData | undefined;\n\n/** The brand every JSON field builder carries, so one built by another copy of this package is still recognised. */\nexport const JSON_FIELD_BRAND = \"rebase.json-field\";\n\n/**\n * One field of a JSON document: `json.string()`, `json.object({...})`, ….\n *\n * Immutable: every modifier returns a new field.\n *\n * @group Schema\n */\nexport class JsonField<TData, TKind extends JsonKind = JsonKind, TRequired extends boolean = false> {\n\n /** Type-level only: the TypeScript type of the value. */\n declare readonly $data: TData;\n /** Type-level only: the node kind. */\n declare readonly $kind: TKind;\n /** Type-level only: whether the key must be present. */\n declare readonly $required: TRequired;\n\n readonly brand = JSON_FIELD_BRAND;\n\n constructor(\n /** The shape this field describes. */\n readonly shape: JsonShapeDef\n ) {}\n\n private with<D, K extends JsonKind, R extends boolean>(patch: Partial<JsonNodeBase> & Record<string, unknown>): JsonField<D, K, R> {\n return new JsonField<D, K, R>(Object.assign({}, this.shape, patch));\n }\n\n /** The key must be present in the document. */\n required(): JsonField<TData, TKind, true> {\n return this.with<TData, TKind, true>({ required: true });\n }\n\n /** The value written when the key is absent on create. */\n default(value: TData): JsonField<TData, TKind, TRequired> {\n return this.with<TData, TKind, TRequired>({ default: value });\n }\n\n /** What the value is, for OpenAPI and MCP. */\n describe(description: string): JsonField<TData, TKind, TRequired> {\n return this.with<TData, TKind, TRequired>({ description });\n }\n\n /** Rules the API checks before a write. */\n validate(rules: JsonValidationFor<TKind>): JsonField<TData, TKind, TRequired> {\n const input: ValidationInput = rules;\n return this.with<TData, TKind, TRequired>({ validate: normalizeValidation(input) });\n }\n\n /** A closed set of accepted values. */\n oneOf<const V extends readonly TData[], K extends \"string\" | \"number\">(\n this: JsonField<TData, K, TRequired>,\n values: V\n ): JsonField<V[number], K, TRequired> {\n return this.with<V[number], K, TRequired>({ oneOf: [...values] });\n }\n\n /** The server writes the current time into the field when the row is created. */\n onCreateNow(this: JsonField<string, \"date\", TRequired>): JsonField<string, \"date\", TRequired> {\n return this.with<string, \"date\", TRequired>({ stamp: \"create\" });\n }\n\n /** The server writes the current time into the field on every write. */\n onUpdateNow(this: JsonField<string, \"date\", TRequired>): JsonField<string, \"date\", TRequired> {\n return this.with<string, \"date\", TRequired>({ stamp: \"update\" });\n }\n\n /** The server writes the caller's user id into the field when the row is created. */\n onCreateUser(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n return this.with<string, \"string\", TRequired>({ stamp: \"createUser\" });\n }\n\n /** The server writes the caller's user id into the field on every write. */\n onUpdateUser(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n return this.with<string, \"string\", TRequired>({ stamp: \"updateUser\" });\n }\n\n /**\n * The field holds the id of a user. The panel offers a user picker for it,\n * and callers who may write the table may look users up to fill it.\n * Only on `json.string()`; anything else throws.\n */\n userId(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n if (this.shape.kind !== \"string\" || this.shape.storage !== undefined) {\n const what = this.shape.kind === \"string\" ? \"`json.storage()`\" : `a \\`json.${this.shape.kind}()\\` field`;\n throw new Error(`\\`.userId()\\` on ${what}: a user's id is held by \\`json.string()\\`.`);\n }\n return this.with<string, \"string\", TRequired>({ semantic: \"user\" });\n }\n\n /**\n * Field-level hooks. They run on the server only.\n *\n * The value is `TData | undefined` on a field not (yet) marked\n * `.required()` — the key can be absent from the document — and `TData` on\n * one that is; see {@link JsonTransformValue}. Chain `.required()` before\n * `.transform()` to get the narrower type.\n */\n transform(transform: ColumnTransform<JsonTransformValue<TData, TRequired>>): JsonField<TData, TKind, TRequired> {\n const erased: ColumnTransform = transform;\n return this.with<TData, TKind, TRequired>({ transform: erased });\n }\n}\n\n/** Any JSON field, whatever it holds. */\nexport type AnyJsonField = JsonField<unknown, JsonKind, boolean>;\n\n/** The TypeScript type a JSON field holds. */\nexport type JsonDataOf<F> = F extends JsonField<infer T, JsonKind, boolean> ? T : never;\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The TypeScript type of a `json.object({...})`: required keys required, the rest optional. */\nexport type JsonObjectOf<S extends Record<string, AnyJsonField>> = Simplify<\n { [K in keyof S as S[K] extends JsonField<unknown, JsonKind, true> ? K : never]: JsonDataOf<S[K]> } &\n { [K in keyof S as S[K] extends JsonField<unknown, JsonKind, true> ? never : K]?: JsonDataOf<S[K]> }\n>;\n\n/** One block of a `json.oneOf(...)`: its discriminator and its value. */\nexport type JsonOneOfOf<\n S extends Record<string, AnyJsonField>,\n TypeField extends string,\n ValueField extends string\n> = { [K in keyof S]: Simplify<Record<TypeField, K> & Record<ValueField, JsonDataOf<S[K]>>> }[keyof S];\n\nconst shapesOf = (fields: Record<string, AnyJsonField>): Record<string, JsonShapeDef> => {\n const out: Record<string, JsonShapeDef> = {};\n for (const [key, field] of Object.entries(fields)) out[key] = field.shape;\n return out;\n};\n\n/**\n * Builders for the shape of a `json`/`jsonb` document.\n *\n * ```ts\n * metadata: col.jsonb(json.object({\n * seoTitle: json.string().validate({ max: 60 }),\n * canonicalUrl: json.string().validate({ url: true }),\n * })),\n * content: col.jsonb(json.array(json.oneOf({\n * text: json.string(),\n * image: json.storage({ path: \"posts/content/\" }),\n * }))),\n * ```\n *\n * `col.jsonb().$type<T>()` on its own types the document statically; a shape also\n * tells the server what is inside it.\n *\n * @group Schema\n */\nexport const json = {\n /** A string. */\n string(): JsonField<string, \"string\"> {\n return new JsonField<string, \"string\">({ kind: \"string\" });\n },\n /** A number. */\n number(): JsonField<number, \"number\"> {\n return new JsonField<number, \"number\">({ kind: \"number\" });\n },\n /** A boolean. */\n boolean(): JsonField<boolean, \"boolean\"> {\n return new JsonField<boolean, \"boolean\">({ kind: \"boolean\" });\n },\n /** An instant, stored as an ISO string. */\n date(): JsonField<string, \"date\"> {\n return new JsonField<string, \"date\">({ kind: \"date\" });\n },\n /** A point on Earth: `{ latitude, longitude }`. */\n geopoint(): JsonField<JsonGeoPoint, \"geopoint\"> {\n return new JsonField<JsonGeoPoint, \"geopoint\">({ kind: \"geopoint\" });\n },\n /** The path of a stored file. Counted by the orphan sweep like a `col.storage()` column. */\n storage(options: StorageOptions): JsonField<string, \"string\"> {\n return new JsonField<string, \"string\">({ kind: \"string\", storage: normalizeStorage(options) });\n },\n /** An object with known keys. `additional: true` also accepts keys it does not name. */\n object<S extends Record<string, AnyJsonField>>(\n fields: S,\n options: { additional?: boolean } = {}\n ): JsonField<JsonObjectOf<S>, \"object\"> {\n const shape: JsonShapeDef = { kind: \"object\", fields: shapesOf(fields) };\n if (options.additional) shape.additional = true;\n return new JsonField<JsonObjectOf<S>, \"object\">(shape);\n },\n /** An array of one shape. */\n array<F extends AnyJsonField>(of: F): JsonField<JsonDataOf<F>[], \"array\"> {\n return new JsonField<JsonDataOf<F>[], \"array\">({ kind: \"array\", of: of.shape });\n },\n /**\n * A typed block: `{ type: \"<variant>\", value: <its shape> }`. The keys are\n * `type` and `value` unless `typeField` / `valueField` say otherwise.\n */\n oneOf<\n S extends Record<string, AnyJsonField>,\n const TypeField extends string = \"type\",\n const ValueField extends string = \"value\"\n >(\n variants: S,\n options: { typeField?: TypeField; valueField?: ValueField } = {}\n ): JsonField<JsonOneOfOf<S, TypeField, ValueField>, \"oneOf\"> {\n return new JsonField<JsonOneOfOf<S, TypeField, ValueField>, \"oneOf\">({\n kind: \"oneOf\",\n typeField: options.typeField ?? \"type\",\n valueField: options.valueField ?? \"value\",\n variants: shapesOf(variants)\n });\n },\n /** Anything. */\n unknown(): JsonField<unknown, \"unknown\"> {\n return new JsonField<unknown, \"unknown\">({ kind: \"unknown\" });\n }\n};\n\n/**\n * Whether a value is a JSON field builder, from this copy of the package or\n * another.\n *\n * @group Schema\n */\nexport function isJsonField(value: unknown): value is AnyJsonField {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === JSON_FIELD_BRAND;\n}\n\n/**\n * A JSON shape without its hooks: what the wire carries.\n *\n * @group Schema\n */\nexport function describeJsonShape(shape: JsonShapeDef): JsonShape {\n const { transform: _transform, ...rest } = shape;\n void _transform;\n switch (rest.kind) {\n case \"object\": {\n const fields: Record<string, JsonShape> = {};\n for (const [key, field] of Object.entries(rest.fields)) fields[key] = describeJsonShape(field);\n return { ...rest, fields };\n }\n case \"array\":\n return { ...rest, of: describeJsonShape(rest.of) };\n case \"oneOf\": {\n const variants: Record<string, JsonShape> = {};\n for (const [key, variant] of Object.entries(rest.variants)) variants[key] = describeJsonShape(variant);\n return { ...rest, variants };\n }\n default:\n return rest;\n }\n}\n","import type { ColumnKind, ColumnType, NumericColumnKind, TemporalColumnKind, TextColumnKind } from \"./column_type\";\nimport type {\n ArrayValidation,\n BaseValidation,\n ColumnAccess,\n ColumnDefault,\n ColumnStamp,\n ColumnStorage,\n ColumnValidation,\n DateValidation,\n NumberValidation,\n StorageOptions,\n StringValidation,\n ValidationInput,\n VectorIndexOptions\n} from \"./column_options\";\nimport { normalizeColumnAccess, normalizeStorage, normalizeValidation } from \"./column_options\";\nimport type { ColumnTransform } from \"./hooks\";\nimport type { JsonField, JsonGeoPoint, JsonKind, JsonShapeDef } from \"./json\";\n\n/**\n * Every Drizzle spelling Rebase refuses, with the instruction it shows.\n *\n * Each text is used twice: as a string-literal *type* placed where the\n * developer wrote the refused thing (a `this` parameter, a config key, an\n * argument), so TypeScript prints the instruction verbatim; and as the message\n * thrown at run time, for a JavaScript caller the types do not reach. See\n * `drizzle-alignment.md` for the table of Drizzle spellings.\n *\n * @group Schema\n */\nexport const DRIZZLE_REFUSALS = {\n /** `col.timestamp()` without `withTimezone: true`: Drizzle's timestamp WITHOUT time zone. */\n timestamp: \"Rebase stores instants as timestamptz: write `col.timestamp({ withTimezone: true })`. For a timestamp without time zone write `col.custom({ dataType: \\\"timestamp\\\" })`.\",\n /** `col.timestamp({ mode: \"date\" })`: Drizzle's Date-typed mode. */\n timestampMode: \"Rebase serves a timestamp as an ISO string: leave `mode` out or write `mode: \\\"string\\\"`.\",\n /** `col.timestamp({ precision })`. */\n timestampPrecision: \"Rebase does not state a timestamp's precision: leave `precision` out, or write `col.custom({ dataType: \\\"timestamp(3) with time zone\\\" })`.\",\n /** `col.date({ mode: \"date\" })`: Drizzle's Date-typed mode. */\n dateMode: \"Rebase serves a date as a `YYYY-MM-DD` string: leave `mode` out or write `mode: \\\"string\\\"`.\",\n /** `col.time({ withTimezone: true })`: a `timetz`. */\n timeZone: \"`col.time()` is a time without time zone: leave `withTimezone` out, or write `col.custom({ dataType: \\\"timetz\\\" })`.\",\n /** `col.time({ precision })`. */\n timePrecision: \"Rebase does not state a time's precision: leave `precision` out, or write `col.custom({ dataType: \\\"time(3)\\\" })`.\",\n /** `col.numeric({ mode: \"string\" | \"bigint\" })`: our value is a JSON number. */\n numericMode: \"Rebase reads and writes numeric as a JSON number: leave `mode` out or write `mode: \\\"number\\\"`. For exact decimals kept as text write `col.text()`.\",\n /** `col.bigint({ mode: \"bigint\" })`: our value is a JSON number. */\n bigintMode: \"Rebase serves bigint as a JSON number: write `{ mode: \\\"number\\\" }`. For exact 64-bit values write `col.numeric()` or `col.text()`.\",\n /** `col.varchar(\"name\")` / `col.varchar({ enum })` without a length. */\n varcharLength: \"`col.varchar()` needs a length (a bare varchar is unbounded in Postgres and Drizzle): write `col.varchar({ length: 255 })`, or `col.text()` for text of any length.\",\n /** `col.char(\"name\")` / `col.char({ enum })` without a length. */\n charLength: \"`col.char()` needs a length (a bare char is char(1) in Postgres and Drizzle): write `col.char({ length: 2 })`.\",\n /** `.generatedAlwaysAsIdentity()`: the planner creates BY DEFAULT identities only. */\n identityAlways: \"Rebase creates identity columns GENERATED BY DEFAULT: write `.generatedByDefaultAsIdentity()`.\",\n /** `.generatedByDefaultAsIdentity({ … })`: sequence options. */\n identityOptions: \"Rebase does not take sequence options: write `.generatedByDefaultAsIdentity()` with no argument.\",\n /** `.references(() => …)`: a foreign key is a `rel.belongsTo`. */\n references: \"A foreign key is a relation in Rebase: write `relations: { author: rel.belongsTo(() => users, { localKey: \\\"author_id\\\", onDelete: \\\"cascade\\\" }) }`. The relation's key is what `include` names.\",\n /** `.$defaultFn()` / `.$default()`: a run-time default function. */\n defaultFn: \"Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`…`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`.\",\n /** `.$onUpdate()` / `.$onUpdateFn()`: a run-time update function. */\n onUpdateFn: \"Rebase's schema is data, not code: write `.onUpdateNow()` for the time, `.onUpdateUser()` for the caller; anything else belongs in `hooks.beforeSave`.\",\n /** `.unique(name, { nulls })`: a named or NULLS NOT DISTINCT constraint. */\n uniqueName: \"Rebase derives constraint names and keeps NULLs distinct: write `.unique()`, or a unique index under `indexes`.\",\n /** `.generatedAlwaysAs(value)` with something other than a `sql` expression. */\n generatedValue: \"`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`…`)`.\",\n /** `.array(size)`. */\n arraySize: \"Postgres ignores array sizes: write `.array()`.\",\n /** `.notNull()` & co. before `.array()`. */\n arrayOrder: \"`.notNull()`, a default, `.primaryKey()`, `.readOnly()` and `.private()` before `.array()` would describe each item: write them after it, as in `col.text().array().notNull()`.\",\n /** `.array().array()`. */\n arrayOfArray: \"An array of arrays is not supported: use `col.jsonb()` for nested lists.\",\n /** `sql` with an interpolation. */\n sqlInterpolation: \"`sql` writes its text into the DDL verbatim: write the expression inline, without `${…}`.\",\n /** `col.bigint()` / `col.bigserial()` without `{ mode }`. */\n bigintModeMissing: \"`col.bigint()` and `col.bigserial()` take Drizzle's `{ mode: \\\"number\\\" }`: write `col.bigint({ mode: \\\"number\\\" })`.\",\n /** `col.numeric(10, 2)`: positional precision and scale. */\n numericPositional: \"`col.numeric()` takes a config object: write `col.numeric({ precision: 10, scale: 2 })`.\",\n /** `col.vector(1536)`: positional dimensions. */\n vectorPositional: \"`col.vector()` takes a config object: write `col.vector({ dimensions: 1536 })`.\",\n /** `col.enum(values, { name })`: a named enum type. */\n enumName: \"A named Postgres enum type is declared once with `pgEnum`: write `const postStatus = pgEnum(\\\"post_status\\\", [...])`, then `postStatus()` in the column.\",\n /** `col.custom(\"inet\")`: a lone string is the SQL column name. */\n customDataType: \"`col.custom()` names its Postgres type in a config object: write `col.custom({ dataType: \\\"inet\\\" })`, or `col.custom(\\\"ip\\\", { dataType: \\\"inet\\\" })` with a SQL column name.\",\n /** `pgEnum(name, { A: \"a\" })`: Drizzle's object form. */\n pgEnumObject: \"`pgEnum(name, values)` takes the list of labels: write `pgEnum(\\\"post_status\\\", [\\\"draft\\\", \\\"published\\\"])`.\"\n} as const;\n\ntype Refusal = typeof DRIZZLE_REFUSALS;\n\n/** The message of a Drizzle column type Rebase names only through `col.custom()`. */\ntype UnsupportedType<T extends string> =\n `Rebase has no \\`col.${T}()\\`: write \\`col.custom({ dataType: \"${T}\" })\\`. The value passes through as the driver returns it (a string).`;\n\nfunction unsupportedMessage<T extends string>(type: T): UnsupportedType<T> {\n return `Rebase has no \\`col.${type}()\\`: write \\`col.custom({ dataType: \"${type}\" })\\`. The value passes through as the driver returns it (a string).`;\n}\n\n/** The brand of a {@link sql} expression. */\nexport const SQL_BRAND = \"rebase.sql\";\n\n/**\n * A SQL expression written with the {@link sql} tag: `sql\\`now()\\``.\n *\n * @group Schema\n */\nexport interface SqlTemplate {\n /** Marks a value as written with the {@link sql} tag. */\n readonly brand: typeof SQL_BRAND;\n /** The expression, exactly as written between the backticks. */\n readonly text: string;\n}\n\n/**\n * A SQL expression for a default or a generated column, as Drizzle writes it:\n * `.default(sql\\`gen_short_id()\\`)`, `.generatedAlwaysAs(sql\\`lower(email)\\`)`.\n *\n * The text goes into the DDL verbatim, so it takes no interpolation: write the\n * expression inline.\n *\n * @group Schema\n */\nexport function sql(strings: TemplateStringsArray, ...values: Refusal[\"sqlInterpolation\"][]): SqlTemplate {\n if (values.length > 0 || strings.length !== 1) throw new Error(DRIZZLE_REFUSALS.sqlInterpolation);\n const text = strings[0] ?? strings.raw[0];\n if (text.trim().length === 0) throw new Error(\"`sql``` is empty: write the expression, e.g. sql`now()`.\");\n return { brand: SQL_BRAND, text };\n}\n\n/**\n * Whether a value is a {@link sql} expression, from this copy of the package or another.\n *\n * @group Schema\n */\nexport function isSqlTemplate(value: unknown): value is SqlTemplate {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === SQL_BRAND &&\n \"text\" in value && typeof value.text === \"string\";\n}\n\n/**\n * Everything a column builder has been told, as data.\n *\n * Wire-safe except for `transform` and the hooks inside `json`, which stay on\n * the server.\n *\n * @group Schema\n */\nexport interface ColumnDef {\n /** The Postgres type. */\n type: ColumnType;\n /** The SQL column name, when it is not the snake_case of the key. */\n column?: string;\n notNull: boolean;\n primaryKey: boolean;\n unique: boolean;\n default?: ColumnDefault;\n /** `GENERATED ALWAYS AS (<expression>) STORED`. */\n generatedAs?: string;\n readOnly: boolean;\n private: boolean;\n access?: ColumnAccess;\n stamp?: ColumnStamp;\n validate?: ColumnValidation;\n oneOf?: readonly (string | number)[];\n description?: string;\n storage?: ColumnStorage;\n /**\n * A meaning the Postgres type does not state: `\"geopoint\"` (`col.geopoint()`,\n * a `jsonb` point) or `\"user\"` (`.userId()`, a text or uuid column holding a\n * user's id).\n */\n semantic?: \"geopoint\" | \"user\";\n vectorIndex?: VectorIndexOptions | false;\n /** The shape of a `json`/`jsonb` document. */\n json?: JsonShapeDef;\n /** For an array column: the definition of each item. */\n element?: ColumnDef;\n /** Field-level hooks. Server only. */\n transform?: ColumnTransform;\n}\n\n/**\n * The type-level tag of a builder. A {@link ColumnKind}, or one of the two\n * builders whose meaning the Postgres type alone does not state.\n */\nexport type BuilderKind = ColumnKind | \"storage\" | \"geopoint\";\n\n/**\n * What the type system tracks about a column besides its data type.\n *\n * @group Schema\n */\nexport interface ColumnFlags {\n /** `NOT NULL`: never `null` on a row, required on create unless it has a default. */\n notNull: boolean;\n /** A create may omit it. */\n hasDefault: boolean;\n /** Clients may write it. */\n writable: boolean;\n /** It is served on the wire. */\n exposed: boolean;\n /** Part of the primary key. */\n primaryKey: boolean;\n}\n\n/** The flags of a column no modifier has touched: nullable, required-by-nobody, writable, served. */\nexport interface InitialColumnFlags extends ColumnFlags {\n notNull: false;\n hasDefault: false;\n writable: true;\n exposed: true;\n primaryKey: false;\n}\n\n/**\n * The value a column's `.transform()` hooks receive and return: the column's\n * type, plus `null` while the column is nullable.\n *\n * Read from the flags at the point `.transform()` is called, so the order of\n * the chain matters: `.notNull().transform(…)` (or `.primaryKey()` first)\n * receives `TData`; `.transform(…).notNull()` was typed before the column\n * became `NOT NULL` and keeps receiving `TData | null`. Write `.notNull()`\n * first.\n *\n * @group Schema\n */\nexport type ColumnTransformValue<TData, F extends ColumnFlags> = F[\"notNull\"] extends true ? TData : TData | null;\n\ntype SetFlag<F extends ColumnFlags, K extends keyof ColumnFlags, V extends boolean> = {\n [P in keyof ColumnFlags]: P extends K ? V : F[P]\n};\n\ntype WithDefault<F extends ColumnFlags> = SetFlag<F, \"hasDefault\", true>;\n\n/** The rules `.validate()` accepts for a kind of column. */\nexport type ValidationFor<K extends BuilderKind> =\n K extends TextColumnKind | \"storage\" ? StringValidation :\n K extends NumericColumnKind ? NumberValidation :\n K extends TemporalColumnKind ? DateValidation :\n K extends \"array\" ? ArrayValidation :\n BaseValidation;\n\n/** The value `.default()` accepts: what the column holds; a `Date` too, for a temporal column. */\nexport type DefaultValueFor<TData, K extends BuilderKind> = K extends TemporalColumnKind ? TData | Date : TData;\n\nconst STAMP_METHODS: Record<string, string> = {\n \"create:now\": \".onCreateNow\",\n \"update:now\": \".onUpdateNow\",\n \"create:user\": \".onCreateUser\",\n \"update:user\": \".onUpdateUser\"\n};\n\n/** The brand every column builder carries, so one built by another copy of this package is still recognised. */\nexport const COLUMN_BRAND = \"rebase.column\";\n\nconst baseDef = (type: ColumnType): ColumnDef => ({\n type,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n});\n\n/**\n * One column of a table: `col.text()`, `col.uuid().primaryKey()`, ….\n *\n * Immutable — every modifier returns a new builder — so a column can be shared\n * between tables. Columns are nullable until `.notNull()` or `.primaryKey()`\n * says otherwise, as in SQL.\n *\n * @typeParam TData The TypeScript type of a value on the wire.\n * @typeParam TKind Which builder made it; decides which modifiers apply.\n * @typeParam F What has been said about it so far.\n *\n * @group Schema\n */\nexport class ColumnBuilder<TData, TKind extends BuilderKind = BuilderKind, F extends ColumnFlags = InitialColumnFlags> {\n\n /** Type-level only: the TypeScript type of a value. */\n declare readonly $data: TData;\n /** Type-level only: the builder kind. */\n declare readonly $kind: TKind;\n /** Type-level only: the flags. */\n declare readonly $flags: F;\n\n readonly brand = COLUMN_BRAND;\n\n constructor(\n /** Everything this column has been told. */\n readonly def: ColumnDef\n ) {}\n\n private with<D, K extends BuilderKind, G extends ColumnFlags>(patch: Partial<ColumnDef>): ColumnBuilder<D, K, G> {\n return new ColumnBuilder<D, K, G>({ ...this.def, ...patch });\n }\n\n /**\n * The patch that sets a stamp, refusing a second, different one: a column\n * holds one stamp, so `.onCreateNow().onUpdateNow()` would otherwise keep\n * whichever came last without a word.\n */\n private stamped(stamp: ColumnStamp, method: string): Partial<ColumnDef> {\n const current = this.def.stamp;\n if (current && (current.on !== stamp.on || current.value !== stamp.value)) {\n throw new Error(\n `\\`.${method}()\\` on a column that already has \\`${STAMP_METHODS[`${current.on}:${current.value}`]}()\\`: a column ` +\n \"holds one stamp. `.onUpdateNow()` alone also stamps the row when it is created.\"\n );\n }\n return { stamp };\n }\n\n // ── Every column ─────────────────────────────────────────────────────\n\n /**\n * Types the value without changing the column, as Drizzle's `$type`:\n * `col.jsonb().$type<{ seoTitle?: string }>()`, `col.integer().$type<UserId>()`.\n * Nothing is checked at run time; use `col.jsonb(json.object({...}))` for\n * a shape the server enforces.\n */\n $type<T>(): ColumnBuilder<T, TKind, F> {\n return this.with<T, TKind, F>({});\n }\n\n /** `NOT NULL`. The API requires the column on create unless it has a default. */\n notNull(): ColumnBuilder<TData, TKind, SetFlag<F, \"notNull\", true>> {\n return this.with<TData, TKind, SetFlag<F, \"notNull\", true>>({ notNull: true });\n }\n\n /**\n * Part of the primary key. Several columns marked this way form a composite\n * key, in declaration order.\n */\n primaryKey(): ColumnBuilder<TData, TKind, SetFlag<SetFlag<F, \"notNull\", true>, \"primaryKey\", true>> {\n return this.with<TData, TKind, SetFlag<SetFlag<F, \"notNull\", true>, \"primaryKey\", true>>({\n primaryKey: true,\n notNull: true\n });\n }\n\n /**\n * A single-column `UNIQUE` constraint. Its name is derived; Drizzle's\n * `.unique(name, { nulls })` arguments are refused.\n */\n unique(name?: Refusal[\"uniqueName\"], config?: Refusal[\"uniqueName\"]): ColumnBuilder<TData, TKind, F> {\n if (name !== undefined || config !== undefined) throw new Error(DRIZZLE_REFUSALS.uniqueName);\n return this.with<TData, TKind, F>({ unique: true });\n }\n\n /**\n * A default: a value, written as the column's DDL default and applied by\n * the driver on create, so a row comes out the same whoever inserts it — or\n * an expression Postgres evaluates, `.default(sql\\`gen_short_id()\\`)`.\n */\n default(value: DefaultValueFor<TData, TKind> | SqlTemplate): ColumnBuilder<TData, TKind, WithDefault<F>> {\n if (isSqlTemplate(value)) {\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"sql\", expression: value.text } });\n }\n const stored = value instanceof Date ? value.toISOString() : value;\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"literal\", value: stored } });\n }\n\n /** Refused: Drizzle's run-time default function. See {@link DRIZZLE_REFUSALS}. */\n $defaultFn(this: Refusal[\"defaultFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.defaultFn);\n }\n\n /** Refused: Drizzle's alias of `$defaultFn`. See {@link DRIZZLE_REFUSALS}. */\n $default(this: Refusal[\"defaultFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.defaultFn);\n }\n\n /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */\n $onUpdate(this: Refusal[\"onUpdateFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.onUpdateFn);\n }\n\n /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */\n $onUpdateFn(this: Refusal[\"onUpdateFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.onUpdateFn);\n }\n\n /**\n * Refused: a foreign key is a relation, `rel.belongsTo(() => users, {...})`\n * under `relations`, whose key is what `include` names.\n */\n references(this: Refusal[\"references\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.references);\n }\n\n /**\n * The database already holds a default for this column that Rebase does not\n * state. A create may omit the column, and a schema push leaves the default\n * alone.\n */\n dbDefault(): ColumnBuilder<TData, TKind, WithDefault<F>> {\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"database\" } });\n }\n\n /**\n * `GENERATED ALWAYS AS (<expression>) STORED`, as Drizzle writes it:\n * `.generatedAlwaysAs(sql\\`lower(email)\\`)`. Nobody writes the column.\n */\n generatedAlwaysAs(as: SqlTemplate | (() => SqlTemplate)): ColumnBuilder<TData, TKind, SetFlag<WithDefault<F>, \"writable\", false>> {\n const expression: unknown = typeof as === \"function\" ? as() : as;\n if (!isSqlTemplate(expression)) throw new Error(DRIZZLE_REFUSALS.generatedValue);\n return this.with<TData, TKind, SetFlag<WithDefault<F>, \"writable\", false>>({\n generatedAs: expression.text,\n readOnly: true\n });\n }\n\n /**\n * Client writes are refused on create and update. The database (a default,\n * a trigger) and the server's own code still fill it.\n */\n readOnly(): ColumnBuilder<TData, TKind, SetFlag<F, \"writable\", false>> {\n return this.with<TData, TKind, SetFlag<F, \"writable\", false>>({ readOnly: true });\n }\n\n /**\n * Never leaves the server: absent from every row on the wire, from the SDK\n * and from OpenAPI, and refused in filters and sorts. Hooks and server code\n * still see it.\n */\n private(): ColumnBuilder<TData, TKind, SetFlag<SetFlag<F, \"exposed\", false>, \"writable\", false>> {\n return this.with<TData, TKind, SetFlag<SetFlag<F, \"exposed\", false>, \"writable\", false>>({ private: true });\n }\n\n /**\n * Who may read and who may write the column, by role. Enforced on every\n * door into the table, not only in the panel. `read` and `write` are lists\n * of role names; anything else throws.\n */\n access(access: ColumnAccess): ColumnBuilder<TData, TKind, F> {\n return this.with<TData, TKind, F>({ access: normalizeColumnAccess(access, \"a column (`.access()`)\") });\n }\n\n /** What the column holds, for OpenAPI and MCP tool descriptions. */\n describe(description: string): ColumnBuilder<TData, TKind, F> {\n return this.with<TData, TKind, F>({ description });\n }\n\n /** Rules the API checks before a write. */\n validate(rules: ValidationFor<TKind>): ColumnBuilder<TData, TKind, F> {\n const input: ValidationInput = rules;\n return this.with<TData, TKind, F>({ validate: { ...this.def.validate, ...normalizeValidation(input) } });\n }\n\n /**\n * Field-level hooks: `beforeSave` returns the value to store, `afterRead`\n * the value to serve. They run on the server, for every caller.\n *\n * The value is `TData | null` on a column not (yet) marked `.notNull()` /\n * `.primaryKey()` — a nullable column hands the hook `null` — and `TData`\n * on one that is; see {@link ColumnTransformValue}. Chain `.notNull()`\n * before `.transform()` to get the narrower type.\n */\n transform(transform: ColumnTransform<ColumnTransformValue<TData, F>>): ColumnBuilder<TData, TKind, F> {\n const erased: ColumnTransform = transform;\n return this.with<TData, TKind, F>({ transform: erased });\n }\n\n // ── Text and numbers ─────────────────────────────────────────────────\n\n /**\n * A closed set of accepted values that is *not* a Postgres enum type: the\n * API refuses anything else and the SDK types the column as their union.\n * Use `col.enum()` when the database should enforce it too.\n *\n * On a number column. On a text column write Drizzle's spelling,\n * `col.text({ enum: [...] })`.\n */\n oneOf<const V extends readonly TData[], K extends TextColumnKind | NumericColumnKind>(\n this: ColumnBuilder<TData, K, F>,\n values: V\n ): ColumnBuilder<V[number], K, F> {\n const stored: (string | number)[] = [];\n for (const value of values) {\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n throw new Error(\"`.oneOf()` takes strings or numbers.\");\n }\n stored.push(value);\n }\n return this.with<V[number], K, F>({ oneOf: stored });\n }\n\n // ── uuid ─────────────────────────────────────────────────────────────\n\n /** `DEFAULT gen_random_uuid()`. */\n defaultRandom(this: ColumnBuilder<string, \"uuid\", F>): ColumnBuilder<string, \"uuid\", WithDefault<F>> {\n return this.with<string, \"uuid\", WithDefault<F>>({ default: { kind: \"random-uuid\" } });\n }\n\n // ── Integers ─────────────────────────────────────────────────────────\n\n /** `GENERATED BY DEFAULT AS IDENTITY`. Sequence options are refused. */\n generatedByDefaultAsIdentity<K extends \"smallint\" | \"integer\" | \"bigint\">(\n this: ColumnBuilder<number, K, F>,\n sequence?: Refusal[\"identityOptions\"]\n ): ColumnBuilder<number, K, WithDefault<F>> {\n if (sequence !== undefined) throw new Error(DRIZZLE_REFUSALS.identityOptions);\n return this.with<number, K, WithDefault<F>>({ default: { kind: \"identity\" } });\n }\n\n /** Refused: Rebase creates identity columns `GENERATED BY DEFAULT`. See {@link DRIZZLE_REFUSALS}. */\n generatedAlwaysAsIdentity(this: Refusal[\"identityAlways\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.identityAlways);\n }\n\n // ── Arrays ───────────────────────────────────────────────────────────\n\n /**\n * A Postgres array of this column's type, as Drizzle writes it:\n * `col.text().array()` is `TEXT[]`. What is chained before `.array()`\n * describes each item (`col.text({ enum: [...] }).array()`,\n * `col.integer().validate({ min: 0 }).array()`); column modifiers come\n * after it (`.array().notNull().default([])`). A leading SQL name\n * (`col.text(\"tag_list\").array()`) names the array column.\n */\n array(\n this: F extends InitialColumnFlags\n ? TKind extends \"array\" ? Refusal[\"arrayOfArray\"] : ColumnBuilder<TData, TKind, F>\n : Refusal[\"arrayOrder\"],\n size?: Refusal[\"arraySize\"]\n ): ColumnBuilder<TData[], \"array\"> {\n if (size !== undefined) throw new Error(DRIZZLE_REFUSALS.arraySize);\n if (!isColumnBuilder(this)) throw new Error(\"`.array()` is called on a column builder.\");\n const { column, ...item } = this.def;\n if (item.notNull || item.primaryKey || item.default !== undefined || item.readOnly || item.private) {\n throw new Error(DRIZZLE_REFUSALS.arrayOrder);\n }\n const def = arrayDef(item);\n if (column !== undefined) def.column = column;\n return new ColumnBuilder<TData[], \"array\">(def);\n }\n\n // ── Temporal ─────────────────────────────────────────────────────────\n\n /**\n * `DEFAULT now()`, as Drizzle's `defaultNow()`: a DDL default a client may\n * still override. `.onCreateNow()` is the server stamp the client cannot.\n */\n defaultNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>({ default: { kind: \"sql\", expression: \"now()\" } });\n }\n\n /** The server stamps the current time when the row is created (`DEFAULT now()`). */\n onCreateNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"create\", value: \"now\" }, \"onCreateNow\"));\n }\n\n /**\n * The server stamps the current time on every write: `DEFAULT now()`, a\n * `BEFORE UPDATE` trigger, and the driver's own stamp.\n */\n onUpdateNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"update\", value: \"now\" }, \"onUpdateNow\"));\n }\n\n // ── Acting user ──────────────────────────────────────────────────────\n\n /** The server writes the caller's id when the row is created. */\n onCreateUser<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"create\", value: \"user\" }, \"onCreateUser\"));\n }\n\n /** The server writes the caller's id on every write. */\n onUpdateUser<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"update\", value: \"user\" }, \"onUpdateUser\"));\n }\n\n /**\n * The column holds the id of a user. The panel offers a user picker for it,\n * and callers who may write the table may look users up to fill it (the\n * user picker's read answers them even though row-level security hides\n * other users' rows).\n *\n * Only on `col.text()`, `col.varchar()`, `col.char()` and `col.uuid()`;\n * anything else throws. It declares no foreign key: use\n * `rel.belongsTo(() => users)` when the database should enforce one.\n */\n userId<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, F> {\n const kind = this.def.type.kind;\n if ((kind !== \"text\" && kind !== \"varchar\" && kind !== \"char\" && kind !== \"uuid\") || this.def.storage !== undefined) {\n const what = this.def.storage !== undefined ? \"`col.storage()`\" : `a \\`${kind}\\` column`;\n throw new Error(\n `\\`.userId()\\` on ${what}: a user's id is held by \\`col.text()\\`, \\`col.varchar()\\`, \\`col.char()\\` or \\`col.uuid()\\`.`\n );\n }\n return this.with<string, K, F>({ semantic: \"user\" });\n }\n\n // ── Storage ──────────────────────────────────────────────────────────\n\n /** The column holds several files: `TEXT[]` of paths. */\n multiple(this: ColumnBuilder<string, \"storage\", F>): ColumnBuilder<string[], \"array\", F> {\n const { storage, validate, ...rest } = this.def;\n return new ColumnBuilder<string[], \"array\", F>({\n ...rest,\n type: { kind: \"array\", of: { kind: \"text\" } },\n storage,\n element: { ...baseDef({ kind: \"text\" }), storage, validate }\n });\n }\n}\n\n/** Any column, whatever it holds. */\nexport type AnyColumn = ColumnBuilder<unknown, BuilderKind, ColumnFlags>;\n\n/**\n * The `columns` of a table: builders by key, in physical order.\n *\n * @group Schema\n */\nexport type ColumnsShape = Record<string, AnyColumn>;\n\n/** The SQL column name a builder's leading argument gives, checked. */\nfunction sqlName(name: string | undefined, builder: string): string | undefined {\n if (name === undefined) return undefined;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(`\\`col.${builder}(name, …)\\`: the leading argument is the SQL column name, a non-empty string.`);\n }\n return name;\n}\n\n/** A fresh definition, named by the builder's leading argument when it has one. */\nfunction namedDef(type: ColumnType, name: string | undefined, builder: string): ColumnDef {\n const def = baseDef(type);\n const column = sqlName(name, builder);\n if (column !== undefined) def.column = column;\n return def;\n}\n\n/** Drizzle's `(name?, config?)` arguments, either of which may be left out. */\nfunction nameAndConfig<C>(first: string | C | undefined, second: C | undefined): [string | undefined, C | undefined] {\n return typeof first === \"string\" ? [first, second] : [undefined, first];\n}\n\n/** A config object, checked at run time: JavaScript callers bypass the types. */\nfunction configOf(value: unknown, builder: string): Record<string, unknown> {\n if (value === undefined) return {};\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`\\`col.${builder}()\\` takes an optional SQL column name and a config object, got ${JSON.stringify(value)}.`);\n }\n return { ...value };\n}\n\n/** The definition of an array of `item`: what `col.text().array()` builds. */\nfunction arrayDef(item: ColumnDef): ColumnDef {\n if (item.type.kind === \"array\") throw new Error(DRIZZLE_REFUSALS.arrayOfArray);\n const def = baseDef({ kind: \"array\", of: item.type });\n def.element = item;\n if (item.storage) def.storage = item.storage;\n return def;\n}\n\n/** A list of string labels: an enum's values, Drizzle's `{ enum: [...] }`. */\nfunction labelsOf(values: unknown, where: string): string[] {\n if (!Array.isArray(values) || values.length === 0 || values.some(value => typeof value !== \"string\")) {\n throw new Error(`${where} takes a non-empty list of strings, got ${JSON.stringify(values)}.`);\n }\n return values.filter((value): value is string => typeof value === \"string\");\n}\n\n/** A non-empty list of string labels, as a type. */\ntype Labels = readonly [string, ...string[]];\n\n/** What `col.text()` takes besides the name: Drizzle's `{ enum }`, a closed set of values. */\nexport interface TextConfig<E extends Labels = Labels> {\n /** The values the API accepts; the SDK types the column as their union. A Postgres enum type is `pgEnum`. */\n enum: E;\n}\n\n/** What `col.varchar()` / `col.char()` take besides the name. */\nexport interface StringConfig<E extends Labels = Labels> {\n /** The length in characters. Required: a bare varchar is unbounded and a bare char is char(1). */\n length: number;\n /** The values the API accepts, as `col.text({ enum })`. */\n enum?: E;\n}\n\n/** What `col.numeric()` takes besides the name. */\nexport interface NumericConfig {\n /** Total number of digits. */\n precision?: number;\n /** Digits after the decimal point. Needs a precision. */\n scale?: number;\n /** The value is a JSON number. Drizzle's `\"string\"` and `\"bigint\"` modes are refused. */\n mode?: \"number\" | Refusal[\"numericMode\"];\n}\n\n/** What `col.bigint()` / `col.bigserial()` take besides the name. */\nexport interface BigintConfig {\n /** `\"number\"`: the value is a JSON number. Drizzle's `\"bigint\"` mode is refused. */\n mode: \"number\" | Refusal[\"bigintMode\"];\n}\n\n/** What `col.timestamp()` takes besides the name. */\nexport interface TimestampConfig {\n /** `true`: the column is `TIMESTAMPTZ`, the only timestamp Rebase creates. */\n withTimezone: true;\n /** `\"string\"`: an ISO string on the wire, which it always is. */\n mode?: \"string\" | Refusal[\"timestampMode\"];\n /** Refused: Rebase does not state a timestamp's precision. */\n precision?: Refusal[\"timestampPrecision\"];\n}\n\n/** What `col.date()` takes besides the name. */\nexport interface DateConfig {\n /** `\"string\"`: `YYYY-MM-DD` on the wire, which it always is. */\n mode?: \"string\" | Refusal[\"dateMode\"];\n}\n\n/** What `col.time()` takes besides the name. */\nexport interface TimeConfig {\n /** `false` or omitted: `col.time()` is a time without time zone. */\n withTimezone?: false | Refusal[\"timeZone\"];\n /** Refused: Rebase does not state a time's precision. */\n precision?: Refusal[\"timePrecision\"];\n}\n\n/** What `col.vector()` takes besides the name. */\nexport interface VectorConfig {\n /** The number of dimensions. */\n dimensions: number;\n /** The approximate-nearest-neighbour index: HNSW cosine when omitted, none with `false`. */\n index?: VectorIndexOptions | false;\n}\n\n/** What `col.custom()` takes besides the name. */\nexport interface CustomConfig {\n /** The Postgres type, verbatim: `\"inet\"`, `\"citext\"`, `\"geometry(Point, 4326)\"`. */\n dataType: string;\n}\n\nconst checkMode = (value: unknown, allowed: string, message: string): void => {\n if (value !== undefined && value !== allowed) throw new Error(message);\n};\n\nfunction jsonColumn<T, K extends \"json\" | \"jsonb\">(kind: K, first: string | JsonField<T, JsonKind, boolean> | undefined, second: JsonField<T, JsonKind, boolean> | undefined): ColumnBuilder<T, K> {\n const [name, shape] = nameAndConfig(first, second);\n const def = namedDef({ kind }, name, kind);\n if (shape) def.json = shape.shape;\n return new ColumnBuilder<T, K>(def);\n}\n\nfunction jsonb(name?: string): ColumnBuilder<unknown, \"jsonb\">;\nfunction jsonb<T>(shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\">;\nfunction jsonb<T>(name: string, shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\">;\nfunction jsonb<T>(first?: string | JsonField<T, JsonKind, boolean>, second?: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\"> {\n return jsonColumn<T, \"jsonb\">(\"jsonb\", first, second);\n}\n\nfunction json(name?: string): ColumnBuilder<unknown, \"json\">;\nfunction json<T>(shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\">;\nfunction json<T>(name: string, shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\">;\nfunction json<T>(first?: string | JsonField<T, JsonKind, boolean>, second?: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\"> {\n return jsonColumn<T, \"json\">(\"json\", first, second);\n}\n\nconst lengthOf = (length: unknown, builder: string): number => {\n if (typeof length !== \"number\" || !Number.isInteger(length) || length <= 0) {\n throw new Error(`\\`col.${builder}({ length })\\` takes a positive whole number of characters, got ${String(length)}.`);\n }\n return length;\n};\n\nfunction text(name?: string): ColumnBuilder<string, \"text\">;\nfunction text<const E extends Labels>(config: TextConfig<E>): ColumnBuilder<E[number], \"text\">;\nfunction text<const E extends Labels>(name: string, config: TextConfig<E>): ColumnBuilder<E[number], \"text\">;\nfunction text(first?: string | TextConfig, second?: TextConfig): ColumnBuilder<string, \"text\"> {\n const [name, rawConfig] = nameAndConfig(first, second);\n const config = configOf(rawConfig, \"text\");\n const def = namedDef({ kind: \"text\" }, name, \"text\");\n if (config.enum !== undefined) def.oneOf = labelsOf(config.enum, \"`col.text({ enum })`\");\n return new ColumnBuilder<string, \"text\">(def);\n}\n\n/** `varchar` / `char`: Drizzle's `(name?, { length, enum? })`. A length is required. */\nfunction stringColumn<K extends \"varchar\" | \"char\">(kind: K, first: unknown, second: unknown): ColumnBuilder<string, K> {\n const name = typeof first === \"string\" ? first : undefined;\n const raw = typeof first === \"string\" ? second : first;\n if (raw === undefined || typeof raw === \"number\") throw new Error(kind === \"varchar\" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);\n const config = configOf(raw, kind);\n if (config.length === undefined) throw new Error(kind === \"varchar\" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);\n const length = lengthOf(config.length, kind);\n const def = namedDef(kind === \"varchar\" ? { kind: \"varchar\", length } : { kind: \"char\", length }, name, kind);\n if (config.enum !== undefined) def.oneOf = labelsOf(config.enum, `\\`col.${kind}({ enum })\\``);\n return new ColumnBuilder<string, K>(def);\n}\n\nfunction varchar(config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"varchar\">;\nfunction varchar<const E extends Labels>(config: StringConfig<E> & object): ColumnBuilder<E[number], \"varchar\">;\nfunction varchar(name: string, config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"varchar\">;\nfunction varchar<const E extends Labels>(name: string, config: StringConfig<E> & object): ColumnBuilder<E[number], \"varchar\">;\nfunction varchar(this: Refusal[\"varcharLength\"], ...rest: unknown[]): never;\nfunction varchar(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"varchar\"> {\n return stringColumn(\"varchar\", first, second);\n}\n\nfunction char(config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"char\">;\nfunction char<const E extends Labels>(config: StringConfig<E> & object): ColumnBuilder<E[number], \"char\">;\nfunction char(name: string, config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"char\">;\nfunction char<const E extends Labels>(name: string, config: StringConfig<E> & object): ColumnBuilder<E[number], \"char\">;\nfunction char(this: Refusal[\"charLength\"], ...rest: unknown[]): never;\nfunction char(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"char\"> {\n return stringColumn(\"char\", first, second);\n}\n\nfunction enumColumn<const V extends Labels>(values: V): ColumnBuilder<V[number], \"enum\">;\nfunction enumColumn<const V extends Labels>(name: string, values: V): ColumnBuilder<V[number], \"enum\">;\nfunction enumColumn(this: Refusal[\"enumName\"], values: Labels, options: Readonly<Record<string, unknown>>): never;\nfunction enumColumn(this: unknown, first: string | Labels, second?: unknown): ColumnBuilder<string, \"enum\"> {\n if (typeof first === \"string\") {\n const values = labelsOf(second, \"`col.enum(name, values)`\");\n return new ColumnBuilder<string, \"enum\">(namedDef({ kind: \"enum\", values }, first, \"enum\"));\n }\n if (second !== undefined) throw new Error(DRIZZLE_REFUSALS.enumName);\n if (first.length === 0) throw new Error(\"`col.enum([...])` needs at least one value.\");\n return new ColumnBuilder<string, \"enum\">(baseDef({ kind: \"enum\", values: [...first] }));\n}\n\n/** `numeric`, Drizzle's `(name?, { precision, scale, mode })`. */\nfunction numericColumn(builder: string, first: unknown, second: unknown): ColumnBuilder<number, \"numeric\"> {\n if (typeof first === \"number\" || typeof second === \"number\") throw new Error(DRIZZLE_REFUSALS.numericPositional);\n const name = typeof first === \"string\" ? first : undefined;\n const config = configOf(typeof first === \"string\" ? second : first, builder);\n checkMode(config.mode, \"number\", DRIZZLE_REFUSALS.numericMode);\n const precision: unknown = config.precision;\n const scale: unknown = config.scale;\n if (scale !== undefined && precision === undefined) {\n throw new Error(`\\`col.${builder}({ precision, scale })\\`: a scale needs a precision.`);\n }\n for (const [what, value] of [[\"precision\", precision], [\"scale\", scale]] as const) {\n if (value !== undefined && (typeof value !== \"number\" || !Number.isInteger(value) || value < 0)) {\n throw new Error(`\\`col.${builder}()\\`: \\`${what}\\` is a whole number, got ${String(value)}.`);\n }\n }\n const type: ColumnType = typeof precision !== \"number\"\n ? { kind: \"numeric\" }\n : typeof scale !== \"number\" ? { kind: \"numeric\", precision } : { kind: \"numeric\", precision, scale };\n return new ColumnBuilder<number, \"numeric\">(namedDef(type, name, builder));\n}\n\nfunction numeric(name?: string, config?: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction numeric(config: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction numeric(this: Refusal[\"numericPositional\"], precision: number, scale?: number): never;\nfunction numeric(this: unknown, first?: string | number | NumericConfig, second?: number | NumericConfig): ColumnBuilder<number, \"numeric\"> {\n return numericColumn(\"numeric\", first, second);\n}\n\nfunction decimal(name?: string, config?: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction decimal(config: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction decimal(first?: string | NumericConfig, second?: NumericConfig): ColumnBuilder<number, \"numeric\"> {\n return numericColumn(\"decimal\", first, second);\n}\n\n/** `bigint` / `bigserial`, Drizzle's `(name?, { mode })`. */\nfunction bigColumn<K extends \"bigint\" | \"bigserial\">(kind: K, first: unknown, second: unknown): ColumnBuilder<number, K> {\n const name = typeof first === \"string\" ? first : undefined;\n const raw = typeof first === \"string\" ? second : first;\n if (raw === undefined) throw new Error(DRIZZLE_REFUSALS.bigintModeMissing);\n checkMode(configOf(raw, kind).mode, \"number\", DRIZZLE_REFUSALS.bigintMode);\n return new ColumnBuilder<number, K>(namedDef(kind === \"bigint\" ? { kind: \"bigint\" } : { kind: \"bigserial\" }, name, kind));\n}\n\nfunction bigint(config: BigintConfig): ColumnBuilder<number, \"bigint\">;\nfunction bigint(name: string, config: BigintConfig): ColumnBuilder<number, \"bigint\">;\nfunction bigint(this: Refusal[\"bigintModeMissing\"], ...rest: unknown[]): never;\nfunction bigint(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<number, \"bigint\"> {\n return bigColumn(\"bigint\", first, second);\n}\n\nfunction bigserial(config: BigintConfig): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>;\nfunction bigserial(name: string, config: BigintConfig): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>;\nfunction bigserial(this: Refusal[\"bigintModeMissing\"], ...rest: unknown[]): never;\nfunction bigserial(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>(bigColumn(\"bigserial\", first, second).def);\n}\n\nfunction timestamp(config: TimestampConfig): ColumnBuilder<string, \"timestamptz\">;\nfunction timestamp(name: string, config: TimestampConfig): ColumnBuilder<string, \"timestamptz\">;\nfunction timestamp(this: Refusal[\"timestamp\"], ...rest: unknown[]): never;\nfunction timestamp(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"timestamptz\"> {\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"timestamp\");\n if (config.withTimezone !== true) throw new Error(DRIZZLE_REFUSALS.timestamp);\n checkMode(config.mode, \"string\", DRIZZLE_REFUSALS.timestampMode);\n if (config.precision !== undefined) throw new Error(DRIZZLE_REFUSALS.timestampPrecision);\n return new ColumnBuilder<string, \"timestamptz\">(namedDef({ kind: \"timestamptz\" }, name, \"timestamp\"));\n}\n\nfunction date(name?: string, config?: DateConfig): ColumnBuilder<string, \"date\">;\nfunction date(config: DateConfig): ColumnBuilder<string, \"date\">;\nfunction date(first?: string | DateConfig, second?: DateConfig): ColumnBuilder<string, \"date\"> {\n const [name, raw] = nameAndConfig(first, second);\n checkMode(configOf(raw, \"date\").mode, \"string\", DRIZZLE_REFUSALS.dateMode);\n return new ColumnBuilder<string, \"date\">(namedDef({ kind: \"date\" }, name, \"date\"));\n}\n\nfunction time(name?: string, config?: TimeConfig): ColumnBuilder<string, \"time\">;\nfunction time(config: TimeConfig): ColumnBuilder<string, \"time\">;\nfunction time(first?: string | TimeConfig, second?: TimeConfig): ColumnBuilder<string, \"time\"> {\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"time\");\n if (config.withTimezone !== undefined && config.withTimezone !== false) throw new Error(DRIZZLE_REFUSALS.timeZone);\n if (config.precision !== undefined) throw new Error(DRIZZLE_REFUSALS.timePrecision);\n return new ColumnBuilder<string, \"time\">(namedDef({ kind: \"time\" }, name, \"time\"));\n}\n\nfunction vector(config: VectorConfig): ColumnBuilder<number[], \"vector\">;\nfunction vector(name: string, config: VectorConfig): ColumnBuilder<number[], \"vector\">;\nfunction vector(this: Refusal[\"vectorPositional\"], dimensions: number, ...rest: unknown[]): never;\nfunction vector(this: unknown, first: unknown, second?: unknown): ColumnBuilder<number[], \"vector\"> {\n if (typeof first === \"number\") throw new Error(DRIZZLE_REFUSALS.vectorPositional);\n const name = typeof first === \"string\" ? first : undefined;\n const config = configOf(typeof first === \"string\" ? second : first, \"vector\");\n const dimensions: unknown = config.dimensions;\n const index: unknown = config.index;\n if (typeof dimensions !== \"number\" || !Number.isInteger(dimensions) || dimensions <= 0) {\n throw new Error(`\\`col.vector({ dimensions })\\` takes a positive whole number, got ${String(dimensions)}.`);\n }\n const def = namedDef({ kind: \"vector\", dimensions }, name, \"vector\");\n if (index === false) def.vectorIndex = false;\n else if (typeof index === \"object\" && index !== null) def.vectorIndex = { ...index };\n else if (index !== undefined) throw new Error(\"`col.vector({ index })` takes index options or `false`.\");\n return new ColumnBuilder<number[], \"vector\">(def);\n}\n\nfunction storage(options: StorageOptions): ColumnBuilder<string, \"storage\">;\nfunction storage(name: string, options: StorageOptions): ColumnBuilder<string, \"storage\">;\nfunction storage(first: string | StorageOptions, second?: StorageOptions): ColumnBuilder<string, \"storage\"> {\n const [name, options] = nameAndConfig(first, second);\n if (options === undefined) throw new Error(\"`col.storage()` takes its options: `col.storage({ path: \\\"posts/heroes/\\\" })`.\");\n const def = namedDef({ kind: \"text\" }, name, \"storage\");\n def.storage = normalizeStorage(options);\n return new ColumnBuilder<string, \"storage\">(def);\n}\n\nfunction custom<T = string>(config: CustomConfig): ColumnBuilder<T, \"other\">;\nfunction custom<T = string>(name: string, config: CustomConfig): ColumnBuilder<T, \"other\">;\nfunction custom(this: Refusal[\"customDataType\"], name: string): never;\nfunction custom<T = string>(this: unknown, first: string | CustomConfig, second?: CustomConfig): ColumnBuilder<T, \"other\"> {\n if (typeof first === \"string\" && second === undefined) throw new Error(DRIZZLE_REFUSALS.customDataType);\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"custom\");\n if (typeof config.dataType !== \"string\") {\n throw new Error(\"`col.custom()` names its Postgres type: `col.custom({ dataType: \\\"inet\\\" })`.\");\n }\n return new ColumnBuilder<T, \"other\">(namedDef({ kind: \"other\", sqlType: customSqlType(config.dataType) }, name, \"custom\"));\n}\n\n/** A builder for a Drizzle column type Rebase serves only through `col.custom()`: refused with the spelling. */\nfunction unsupported<T extends string>(type: T): (this: UnsupportedType<T>, ..._args: unknown[]) => never {\n return () => {\n throw new Error(unsupportedMessage(type));\n };\n}\n\n/** A builder that takes only the optional SQL column name. */\nfunction simple<D, K extends ColumnKind>(kind: K & BuilderKind, type: ColumnType): (name?: string) => ColumnBuilder<D, K> {\n return (name?: string) => new ColumnBuilder<D, K>(namedDef(type, name, kind));\n}\n\n/**\n * The column builders, spelled as Drizzle's `pg-core` spells them: the\n * optional SQL column name first, then Drizzle's config object, then the\n * chain.\n *\n * ```ts\n * columns: {\n * id: col.uuid().primaryKey().defaultRandom(),\n * title: col.text().notNull().validate({ min: 3, max: 200 }),\n * slug: col.varchar({ length: 160 }).notNull().unique(),\n * status: postStatus().notNull().default(\"draft\"), // const postStatus = pgEnum(\"post_status\", [...])\n * tags: col.text().array().notNull().default([]),\n * heroImage: col.storage({ path: \"posts/heroes/\", accept: [\"image/*\"], maxBytes: \"10MB\" }),\n * createdAt: col.timestamp({ withTimezone: true }).notNull().defaultNow(),\n * }\n * ```\n *\n * @group Schema\n */\nexport const col = {\n /** `UUID`. */\n uuid: simple<string, \"uuid\">(\"uuid\", { kind: \"uuid\" }),\n /** `TEXT`. `col.text({ enum: [...] })` accepts only those values. */\n text,\n /** `VARCHAR(n)`: `col.varchar({ length: n })`. */\n varchar,\n /** `CHAR(n)`: `col.char({ length: n })`. */\n char,\n /**\n * A Postgres enum type of its own, created as `<table>_<column>`. A type\n * with a stated name, shared by several columns, is `pgEnum(name, values)`.\n */\n enum: enumColumn,\n /** `SMALLINT`. */\n smallint: simple<number, \"smallint\">(\"smallint\", { kind: \"smallint\" }),\n /** `INTEGER`. */\n integer: simple<number, \"integer\">(\"integer\", { kind: \"integer\" }),\n /** `BIGINT`, read and written as a JavaScript number: `col.bigint({ mode: \"number\" })`. */\n bigint,\n /** `SMALLSERIAL`. Prefer `col.smallint().generatedByDefaultAsIdentity()` in a new schema. */\n smallserial(name?: string): ColumnBuilder<number, \"smallserial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"smallserial\", WithDefault<InitialColumnFlags>>(namedDef({ kind: \"smallserial\" }, name, \"smallserial\"));\n },\n /** `SERIAL`. Prefer `col.integer().generatedByDefaultAsIdentity()` in a new schema. */\n serial(name?: string): ColumnBuilder<number, \"serial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"serial\", WithDefault<InitialColumnFlags>>(namedDef({ kind: \"serial\" }, name, \"serial\"));\n },\n /** `BIGSERIAL`: `col.bigserial({ mode: \"number\" })`. Prefer an identity column in a new schema. */\n bigserial,\n /** `REAL`. */\n real: simple<number, \"real\">(\"real\", { kind: \"real\" }),\n /** `DOUBLE PRECISION`. */\n doublePrecision: simple<number, \"doublePrecision\">(\"doublePrecision\", { kind: \"doublePrecision\" }),\n /** `NUMERIC`, `NUMERIC(p)` or `NUMERIC(p, s)`: `col.numeric({ precision, scale })`. A JSON number. */\n numeric,\n /** Drizzle's alias of `col.numeric()`. */\n decimal,\n /** `BOOLEAN`. */\n boolean: simple<boolean, \"boolean\">(\"boolean\", { kind: \"boolean\" }),\n /** `TIMESTAMPTZ`: `col.timestamp({ withTimezone: true })`. An ISO string on the wire. */\n timestamp,\n /** `DATE`. `YYYY-MM-DD` on the wire. */\n date,\n /** `TIME`. `HH:MM:SS` on the wire. */\n time,\n /**\n * `JSONB`. `col.jsonb().$type<T>()` types the document;\n * `col.jsonb(json.object({...}))` also tells the server its shape, so\n * nested fields are validated, stamped and searchable.\n */\n jsonb,\n /** `JSON`. As `col.jsonb`, for a column that must keep the text it was given. */\n json,\n /**\n * `vector(dimensions)` (pgvector): `col.vector({ dimensions: 1536 })`. An\n * HNSW cosine index is created unless `index` says otherwise; `index: false`\n * creates none.\n */\n vector,\n /** `BYTEA`. Base64 on the wire. */\n bytea: simple<string, \"bytea\">(\"bytea\", { kind: \"bytea\" }),\n /** A point on Earth, stored as `JSONB` `{ latitude, longitude }`. */\n geopoint(name?: string): ColumnBuilder<JsonGeoPoint, \"geopoint\"> {\n const def = namedDef({ kind: \"jsonb\" }, name, \"geopoint\");\n def.semantic = \"geopoint\";\n return new ColumnBuilder<JsonGeoPoint, \"geopoint\">(def);\n },\n /**\n * The path of a stored file, as `TEXT` — or several with `.multiple()`. The\n * upload route enforces `accept` and `maxBytes`, and the orphan sweep counts\n * the file as referenced.\n */\n storage,\n /**\n * A column of a Postgres type no other builder names —\n * `col.custom({ dataType: \"inet\" })`, `col.custom({ dataType: \"citext\" })`,\n * `col.custom({ dataType: \"geometry(Point, 4326)\" })`. What\n * `rebase schema introspect` writes for a column of such a type, so a\n * project generated from an existing database keeps it.\n *\n * Rebase names the type in DDL, verbatim, and does nothing else with it: it\n * does not create, alter or drop the type's definition (an extension or a\n * `CREATE TYPE` the database already holds provides it), it does not\n * validate values, and it passes every value through exactly as the\n * driver returns it — a string for most types. `.$type<T>()` types it for\n * the SDK when the driver returns something else.\n */\n custom,\n /** Refused: write `col.custom({ dataType: \"interval\" })`. */\n interval: unsupported(\"interval\"),\n /** Refused: write `col.custom({ dataType: \"inet\" })`. */\n inet: unsupported(\"inet\"),\n /** Refused: write `col.custom({ dataType: \"cidr\" })`. */\n cidr: unsupported(\"cidr\"),\n /** Refused: write `col.custom({ dataType: \"macaddr\" })`. */\n macaddr: unsupported(\"macaddr\"),\n /** Refused: write `col.custom({ dataType: \"macaddr8\" })`. */\n macaddr8: unsupported(\"macaddr8\"),\n /** Refused: write `col.custom({ dataType: \"point\" })`. */\n point: unsupported(\"point\"),\n /** Refused: write `col.custom({ dataType: \"line\" })`. */\n line: unsupported(\"line\"),\n /** Refused: write `col.custom({ dataType: \"halfvec\" })`. */\n halfvec: unsupported(\"halfvec\"),\n /** Refused: write `col.custom({ dataType: \"sparsevec\" })`. */\n sparsevec: unsupported(\"sparsevec\"),\n /** Refused: write `col.custom({ dataType: \"bit\" })`. */\n bit: unsupported(\"bit\")\n};\n\n/**\n * A Postgres enum type with a stated name, as Drizzle declares one: call it in\n * a column, `status: postStatus().notNull()`, or with the SQL column name,\n * `postStatus(\"state\")`.\n *\n * @group Schema\n */\nexport interface PgEnum<V extends Labels> {\n /** A column of this enum type; the optional argument is the SQL column name. */\n (name?: string): ColumnBuilder<V[number], \"enum\">;\n /** The type's name in Postgres. */\n readonly enumName: string;\n /** Its labels, in order. */\n readonly enumValues: V;\n}\n\n/**\n * Declare a Postgres enum type by name, as Drizzle does:\n *\n * ```ts\n * export const postStatus = pgEnum(\"post_status\", [\"draft\", \"published\"]);\n * // columns: { status: postStatus().notNull().default(\"draft\") }\n * ```\n *\n * Every column of it shares the one type. Two declarations of the same name\n * must list the same labels.\n *\n * @group Schema\n */\nexport function pgEnum<const V extends Labels>(enumName: string, values: V): PgEnum<V>;\nexport function pgEnum(this: Refusal[\"pgEnumObject\"], enumName: string, values: Readonly<Record<string, string>>): never;\nexport function pgEnum<const V extends Labels>(this: unknown, enumName: string, values: V | Readonly<Record<string, string>>): PgEnum<V> {\n if (typeof enumName !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(enumName)) {\n throw new Error(`\\`pgEnum(name, values)\\`: the name is a plain SQL identifier, got ${JSON.stringify(enumName)}.`);\n }\n if (!isLabelTuple<V>(values)) throw new Error(DRIZZLE_REFUSALS.pgEnumObject);\n const labels = [...values];\n const factory = (name?: string): ColumnBuilder<V[number], \"enum\"> =>\n new ColumnBuilder<V[number], \"enum\">(namedDef({ kind: \"enum\", values: labels, name: enumName }, name, \"enum\"));\n return Object.assign(factory, { enumName, enumValues: values });\n}\n\nfunction isLabelTuple<V extends Labels>(values: V | Readonly<Record<string, string>>): values is V {\n return Array.isArray(values) && values.length > 0 && values.every(value => typeof value === \"string\");\n}\n\n/**\n * The type name `col.custom()` puts into DDL: trimmed, and refused when it is\n * empty or could end the statement it is written into.\n */\nfunction customSqlType(sqlType: string): string {\n const trimmed = typeof sqlType === \"string\" ? sqlType.trim() : \"\";\n if (trimmed.length === 0) throw new Error(\"`col.custom()` takes the Postgres type, e.g. `col.custom({ dataType: \\\"inet\\\" })`.\");\n if (/;|--|\\/\\*/.test(trimmed)) {\n throw new Error(`\\`col.custom({ dataType: ${JSON.stringify(sqlType)} })\\`: a type name holds no \\`;\\` and no comment.`);\n }\n return trimmed;\n}\n\n/**\n * Whether a value is a column builder, from this copy of the package or\n * another.\n *\n * @group Schema\n */\nexport function isColumnBuilder(value: unknown): value is AnyColumn {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === COLUMN_BRAND;\n}\n","import type { JoinStep, OnAction } from \"../types/relations\";\nimport type { OrderByTuple } from \"../types/filter-operators\";\nimport type { ColumnAccess } from \"./column_options\";\nimport { normalizeColumnAccess } from \"./column_options\";\nimport type { ColumnsShape } from \"./columns\";\n\n/**\n * A relation's target, as written: `() => users`.\n *\n * Typed `() => void` on purpose. A thunk typed by what it returns (generic\n * over the returned table, a structural table type, or `() => unknown`) makes\n * TypeScript resolve the returned table's type while it is still inferring the\n * table being defined, so two tables that point at each other — `posts.author`\n * → `users`, `users.posts` → `posts` — failed with TS7022/TS7024 unless one\n * thunk was annotated. A `void` return is the one form TypeScript never\n * resolves, so mutual and self relations need no annotation, in one file or\n * across files.\n *\n * What the thunk returns is checked when the schema is compiled instead: a\n * thunk that does not return a `defineTable` / `defineView` result is refused\n * by `compileTables`, naming the table and the relation.\n *\n * @group Schema\n */\nexport type TableThunk = () => void;\n\n/** The brand every relation builder result carries. */\nexport const RELATION_BRAND = \"rebase.relation\";\n\ninterface RelationDefBase {\n readonly brand: typeof RELATION_BRAND;\n /**\n * The table it points at, behind a thunk so two tables can point at each\n * other. Typed `() => unknown`: read it through `isTableDef` / `isViewDef`.\n */\n readonly target: () => unknown;\n}\n\n/**\n * Field-level access on a relation, accepted by every `rel.*`: who may read\n * the relation (`include` it, see its key) and who may write a link through it.\n * The same rules a column states with `.access()` / `.private()`, enforced by\n * the server on every door — an `include` the caller may not read is refused,\n * a nested write the caller may not make is refused.\n *\n * @group Schema\n */\nexport interface RelationAccessOptions {\n /**\n * Per-role read and write access to the relation. `read` lists the roles\n * that may include it; `write` the roles that may link or unlink through\n * it. Omitted: whoever the table's `rls` lets read or write the row.\n */\n access?: ColumnAccess;\n /**\n * `true` keeps the relation off the wire entirely: not includable, not in\n * the SDK or OpenAPI. Only server code traverses it. Not combined with\n * `access`.\n */\n private?: boolean;\n}\n\n/**\n * Options of `rel.belongsTo`.\n *\n * @group Schema\n */\nexport interface BelongsToOptions extends RelationAccessOptions {\n /**\n * The SQL column on this table holding the foreign key. `<relation>_id`\n * when omitted. A column in `columns` with this SQL name is bound to;\n * otherwise the column is derived from the target's key.\n */\n localKey?: string;\n /** The derived column is `NOT NULL`. A bound column says so itself. */\n notNull?: boolean;\n /** The derived column is `UNIQUE`, making this side one-to-one. */\n unique?: boolean;\n /** `RESTRICT` when the column is `NOT NULL`, `SET NULL` otherwise. */\n onDelete?: OnAction;\n /**\n * What the foreign key does when the referenced key changes. No `ON UPDATE`\n * clause when omitted, so Postgres's default applies: `NO ACTION`.\n */\n onUpdate?: OnAction;\n /** `false` skips the index on the foreign key that is otherwise created. */\n index?: boolean;\n /** `false` stores the key without a `FOREIGN KEY` constraint. */\n constraint?: boolean;\n}\n\n/**\n * Options of `rel.hasOne` and `rel.hasMany`.\n *\n * @group Schema\n */\nexport interface HasOptions extends RelationAccessOptions {\n /** The SQL column on the target that points back here. Derived from this table's slug when omitted. */\n foreignKey?: string;\n /** The SQL column on this table it points at, when that is not the primary key. */\n sourceKey?: string;\n}\n\n/**\n * Options of `rel.hasMany`.\n *\n * @group Schema\n */\nexport interface HasManyOptions extends HasOptions {\n /** The order related rows come back in when the caller names none. */\n orderBy?: OrderByTuple | readonly OrderByTuple[];\n}\n\n/**\n * Options of `rel.manyToMany`.\n *\n * @group Schema\n */\nexport interface ManyToManyOptions<P extends ColumnsShape = ColumnsShape> extends RelationAccessOptions {\n /** The junction table. The two table names, sorted and joined by `_`, when omitted. */\n through?: string;\n /** The junction column pointing at this table. */\n sourceKey?: string;\n /** The junction column pointing at the target. */\n targetKey?: string;\n /** Extra columns on the junction, read and written as `_pivot`. */\n pivot?: P;\n /** What happens to a link when either row is deleted. `CASCADE` when omitted. */\n onDelete?: OnAction;\n}\n\n/**\n * Options of `rel.via`.\n *\n * @group Schema\n */\nexport interface ViaOptions extends RelationAccessOptions {\n /** The joins from this table to the target, in order. */\n steps: readonly JoinStep[];\n /** `many` when omitted. */\n cardinality?: \"one\" | \"many\";\n}\n\n/** `rel.belongsTo(...)`. */\nexport interface BelongsToDef extends RelationDefBase, BelongsToOptions {\n readonly kind: \"belongsTo\";\n}\n\n/** `rel.hasOne(...)`. */\nexport interface HasOneDef extends RelationDefBase, HasOptions {\n readonly kind: \"hasOne\";\n}\n\n/** `rel.hasMany(...)`. */\nexport interface HasManyDef extends RelationDefBase, HasManyOptions {\n readonly kind: \"hasMany\";\n}\n\n/** `rel.manyToMany(...)`. */\nexport interface ManyToManyDef<P extends ColumnsShape = ColumnsShape> extends RelationDefBase, ManyToManyOptions<P> {\n readonly kind: \"manyToMany\";\n}\n\n/** `rel.via(...)`. */\nexport interface ViaDef extends RelationDefBase, ViaOptions {\n readonly kind: \"via\";\n}\n\n/**\n * A relation as authored: the result of one `rel.*` call.\n *\n * @group Schema\n */\nexport type RelationDef =\n | BelongsToDef\n | HasOneDef\n | HasManyDef\n | ManyToManyDef\n | ViaDef;\n\n/**\n * The `relations` of a table: `rel.*` results by relation name.\n *\n * @group Schema\n */\nexport type RelationsShape = Record<string, RelationDef>;\n\n/** The options with `access` checked and copied: a role list, never a string spread into characters. */\nfunction withCheckedAccess<O extends RelationAccessOptions>(kind: string, options: O): O {\n if (options.access === undefined) return options;\n return { ...options, access: normalizeColumnAccess(options.access, `a relation (\\`rel.${kind}(…, { access })\\`)`) };\n}\n\nfunction belongsTo(target: TableThunk): BelongsToDef;\nfunction belongsTo<const O extends BelongsToOptions>(target: TableThunk, options: O): BelongsToDef & O;\nfunction belongsTo(target: TableThunk, options: BelongsToOptions = {}): BelongsToDef {\n return { ...withCheckedAccess(\"belongsTo\", options), brand: RELATION_BRAND, kind: \"belongsTo\", target };\n}\n\n/**\n * The relation builders. All five kinds; the target is a thunk, so two tables\n * can point at each other whatever order their modules load in — and, being a\n * {@link TableThunk}, without a type annotation on either side.\n *\n * ```ts\n * relations: {\n * author: rel.belongsTo(() => users, { localKey: \"author_id\", notNull: true, onDelete: \"restrict\" }),\n * tags: rel.manyToMany(() => tags, { through: \"posts_tags\", pivot: { sortOrder: col.integer().default(0) } }),\n * }\n * ```\n *\n * @group Schema\n */\nexport const rel = {\n /**\n * This table holds the foreign key. Binds to the column in `columns` whose\n * SQL name is `localKey`, or derives that column and indexes it.\n */\n belongsTo,\n /** The target holds a unique foreign key pointing here. */\n hasOne(target: TableThunk, options: HasOptions = {}): HasOneDef {\n return { ...withCheckedAccess(\"hasOne\", options), brand: RELATION_BRAND, kind: \"hasOne\", target };\n },\n /** The target holds a foreign key pointing here. */\n hasMany(target: TableThunk, options: HasManyOptions = {}): HasManyDef {\n return { ...withCheckedAccess(\"hasMany\", options), brand: RELATION_BRAND, kind: \"hasMany\", target };\n },\n /**\n * Linked through a junction table, which is created with its own row-level\n * security. `pivot` columns are read and written as `_pivot`.\n */\n manyToMany<P extends ColumnsShape = Record<never, never>>(\n target: TableThunk,\n options: ManyToManyOptions<P> = {}\n ): ManyToManyDef<P> {\n return { ...withCheckedAccess(\"manyToMany\", options), brand: RELATION_BRAND, kind: \"manyToMany\", target };\n },\n /** A read-only traversal across several joins. */\n via(target: TableThunk, options: ViaOptions): ViaDef {\n if (!options.steps || options.steps.length === 0) {\n throw new Error(\"`rel.via(target, { steps })` needs at least one join step.\");\n }\n return { ...withCheckedAccess(\"via\", options), brand: RELATION_BRAND, kind: \"via\", target };\n }\n};\n\n/**\n * Whether a value is the result of a `rel.*` call.\n *\n * @group Schema\n */\nexport function isRelationDef(value: unknown): value is RelationDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === RELATION_BRAND;\n}\n","import type { User } from \"../users\";\nimport type { ResourceRef } from \"../types/resources\";\nimport type { SearchConfig } from \"../types/search\";\nimport type { RoleDefinition, ScopeDefinition } from \"../types/scopes\";\nimport type {\n AuthCollectionContext,\n AuthCollectionCreateResult,\n AuthCollectionResetResult\n} from \"../types/auth_hooks\";\nimport type { ColumnsShape } from \"./columns\";\nimport { isColumnBuilder } from \"./columns\";\nimport type { BelongsToDef, RelationsShape } from \"./relations\";\nimport { isRelationDef } from \"./relations\";\nimport type { TableHooks } from \"./hooks\";\nimport type { RlsPosture, TableIndex, TableTenant } from \"./table_options\";\nimport type { InsertOfColumns, RowOfColumns } from \"./infer\";\n\n/** The brand of a `defineTable` / `defineAuthTable` result. */\nexport const TABLE_BRAND = \"rebase.table\";\n/** The brand of a `defineView` result. */\nexport const VIEW_BRAND = \"rebase.view\";\n\n/**\n * What `defineTable` takes besides the name.\n *\n * @group Schema\n */\nexport interface TableConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> {\n /**\n * The name in the API, the SDK and in scopes. The table's name when\n * omitted. Captured as a literal type, so `TableSlugOf<typeof table>` reads it.\n */\n slug?: S;\n /** The SQL table name, when it is not the name the table is defined under. */\n table?: string;\n /** The Postgres schema. `public` when omitted. */\n schema?: string;\n /** A non-default Postgres database, declared in `backend/resources.ts`. */\n database?: ResourceRef;\n /** What the table holds, for OpenAPI and MCP tool descriptions. */\n description?: string;\n /**\n * The columns, in physical order. At least one must be `.primaryKey()`;\n * several form a composite key in declaration order.\n */\n columns: C;\n /** The relations, by name. */\n relations?: R;\n /**\n * The row-level security posture. Required: `\"admin-only\"`, `\"inherit\"`\n * (the project's `defaultRls`), or the rules to generate policies from.\n */\n rls: RlsPosture;\n /**\n * `false` generates only the declared rules, without the injected admin\n * baseline. Refused together with `rls: \"admin-only\"`. `true` keeps the\n * baseline even when the table's database switches it off for every\n * table (`database({ rls: { defaultPolicies: false } })`). Absent, the\n * database's declaration decides.\n */\n defaultPolicies?: boolean;\n /**\n * Scope every row to a tenant: a column key, or a `belongsTo` relation's\n * name, which stands for its foreign-key column (as the compiler reads it).\n */\n tenant?: TableTenant<NoInfer<Extract<keyof C, string> | BelongsToKeys<R>>>;\n /** Deleting stamps a timestamp column instead of removing the row. */\n softDelete?: boolean | { field?: NoInfer<Extract<keyof C, string>> };\n /** Record every write in the history table. */\n history?: boolean;\n /** Full-text search over these columns. */\n search?: SearchConfig;\n /**\n * Indexes, each with the query it serves. The keys are not inferred from:\n * without `NoInfer`, a key naming nothing made TypeScript infer a relation\n * of that name instead of refusing it.\n */\n indexes?: readonly TableIndex<NoInfer<Extract<keyof C, string> | Extract<keyof R, string>>>[];\n /** Server-side lifecycle hooks. */\n hooks?: TableHooks<RowOfColumns<C>, InsertOfColumns<C>, USER>;\n /** `false` accepts writes naming columns the table does not declare. */\n strictWrites?: false;\n /** Opaque data, served with the table's descriptor. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * The names of the `belongsTo` relations in `R`: the relations that own a\n * foreign-key column on this table, and so can stand for it.\n *\n * @group Schema\n */\nexport type BelongsToKeys<R extends RelationsShape> = {\n [K in Extract<keyof R, string>]: R[K] extends BelongsToDef ? K : never\n}[Extract<keyof R, string>];\n\n/**\n * A table as authored: the result of `defineTable`.\n *\n * `N` is the name it was defined under and `S` its slug — the `slug` it was\n * given, or the name when it was given none — both as literal types, so a\n * frontend holding only `typeof posts` knows the slug (`TableSlugOf`).\n *\n * @group Schema\n */\nexport interface TableDef<\n N extends string = string,\n C extends ColumnsShape = ColumnsShape,\n R extends RelationsShape = RelationsShape,\n S extends string = N\n> {\n readonly brand: typeof TABLE_BRAND;\n /** The name it was defined under. */\n readonly name: N;\n /** What it was defined with, as written. */\n readonly config: TableConfig<C, R, User, S>;\n /** Present when defined with `defineAuthTable`. */\n readonly auth?: AuthTableOptions;\n}\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertTableShape(builder: string, name: unknown, config: unknown): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(`\\`${builder}(name, config)\\` needs the table's name as its first argument.`);\n }\n if (typeof config !== \"object\" || config === null) {\n throw new Error(`\\`${builder}(\"${name}\", config)\\` needs a config object.`);\n }\n const columns = \"columns\" in config ? config.columns : undefined;\n if (typeof columns !== \"object\" || columns === null || Object.keys(columns).length === 0) {\n throw new Error(`Table \"${name}\" declares no columns. Add \\`columns: { id: col.uuid().primaryKey().defaultRandom(), … }\\`.`);\n }\n for (const [key, column] of Object.entries(columns)) {\n if (!isColumnBuilder(column)) {\n throw new Error(`Column \"${key}\" of table \"${name}\" is not a \\`col.*\\` builder.`);\n }\n }\n const relations = \"relations\" in config ? config.relations : undefined;\n if (relations !== undefined) {\n if (typeof relations !== \"object\" || relations === null) {\n throw new Error(`\\`relations\\` of table \"${name}\" must be an object of \\`rel.*\\` results.`);\n }\n for (const [key, relation] of Object.entries(relations)) {\n if (!isRelationDef(relation)) {\n throw new Error(`Relation \"${key}\" of table \"${name}\" is not a \\`rel.*\\` result.`);\n }\n if (key in columns) {\n throw new Error(\n `Table \"${name}\" has both a column and a relation named \"${key}\". ` +\n \"A relation's key is what `include` names; give the foreign-key column its own key.\"\n );\n }\n }\n }\n for (const key of [\"schema\", \"table\"] as const) {\n const value: unknown = key in config ? Reflect.get(config, key) : undefined;\n if (value !== undefined && (typeof value !== \"string\" || !IDENTIFIER.test(value))) {\n throw new Error(`\\`${key}\\` of table \"${name}\" must be a plain SQL identifier, got ${JSON.stringify(value)}.`);\n }\n }\n}\n\nfunction assertRlsDeclared(builder: string, name: string, config: object): void {\n const rls = \"rls\" in config ? config.rls : undefined;\n const ok = rls === \"admin-only\" || rls === \"inherit\" || (Array.isArray(rls) && rls.length > 0);\n if (ok) return;\n const detail = Array.isArray(rls)\n ? \"`rls: []` grants nothing and says nothing. Write `rls: \\\"admin-only\\\"` to lock the table to admins.\"\n : \"Every table needs an explicit row-level security posture.\";\n throw new Error(\n `\\`${builder}(\"${name}\", …)\\` has no usable \\`rls\\`. ${detail} ` +\n \"Accepted: `\\\"admin-only\\\"`, `\\\"inherit\\\"` (the `defaultRls` exported from backend/schema/index.ts), \" +\n \"or a non-empty list of rules.\"\n );\n}\n\n/**\n * Define a Postgres table.\n *\n * The name is the SQL table and the API slug; `rls` is mandatory. The result\n * is what the backend reads from `backend/schema/index.ts` — it generates the\n * DDL and the policies, serves the REST, realtime and MCP surfaces, and types\n * the SDK.\n *\n * ```ts\n * export const posts = defineTable(\"posts\", {\n * columns: {\n * id: col.uuid().primaryKey().defaultRandom(),\n * title: col.text().notNull(),\n * },\n * rls: [\n * { operation: \"select\", access: \"public\" },\n * { operations: [\"insert\", \"update\", \"delete\"], roles: [\"editor\"] },\n * ],\n * });\n * ```\n *\n * @group Schema\n */\nexport function defineTable<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: TableConfig<C, R, User, S>): TableDef<N, C, R, S> {\n assertTableShape(\"defineTable\", name, config);\n assertRlsDeclared(\"defineTable\", name, config);\n return { brand: TABLE_BRAND, name, config };\n}\n\n/**\n * The auth half of `defineAuthTable`.\n *\n * @group Schema\n */\nexport interface AuthTableOptions {\n /** The roles a user can hold, each with the scopes it grants. */\n roles?: Record<string, RoleDefinition>;\n /** The scopes an API key or token can be granted. */\n scopes?: Record<string, ScopeDefinition>;\n /** Let users create personal API keys. */\n personalKeys?: boolean;\n /** Runs when an admin creates a user: hash the password, send the invitation. */\n onCreateUser?: (values: Record<string, unknown>, ctx: AuthCollectionContext) => Promise<AuthCollectionCreateResult>;\n /** Runs when an admin resets a user's password. */\n onResetPassword?: (uid: string, ctx: AuthCollectionContext) => Promise<AuthCollectionResetResult>;\n}\n\n/**\n * What `defineAuthTable` takes besides the name.\n *\n * @group Schema\n */\nexport interface AuthTableConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> extends TableConfig<C, R, USER, S> {\n /** Roles, scopes, personal keys and the user-lifecycle hooks. */\n auth?: AuthTableOptions;\n}\n\n/**\n * Define the table users are stored in.\n *\n * A `defineTable` that auth reads and writes: the columns auth needs are added\n * when the table does not declare them, a signed-in user can read their own\n * row, and the privilege columns (`roles`) can only be written by an admin —\n * whatever `rls` says. A project has at most one.\n *\n * @group Schema\n */\nexport function defineAuthTable<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: AuthTableConfig<C, R, User, S>): TableDef<N, C, R, S> {\n assertTableShape(\"defineAuthTable\", name, config);\n assertRlsDeclared(\"defineAuthTable\", name, config);\n const { auth, ...table } = config;\n return { brand: TABLE_BRAND, name, config: table, auth: auth ?? {} };\n}\n\n/**\n * What `defineView` takes besides the name.\n *\n * @group Schema\n */\nexport interface ViewConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> {\n /** The defining `SELECT`. */\n query: string;\n /**\n * `true` stores the rows. Postgres cannot attach row policies to a\n * materialized view, so it is read through a gate that admits `roles`.\n */\n materialized?: boolean;\n /** Who may read a materialized view. `[\"admin\"]` when omitted. Not accepted on a plain view. */\n roles?: readonly string[];\n /** The columns the query returns. `.primaryKey()` marks the ones that identify a row. */\n columns: C;\n /** The name in the API. The view's name when omitted. Captured as a literal type, like a table's. */\n slug?: S;\n /** The SQL view name, when it is not the name the view is defined under. A plain SQL identifier. */\n table?: string;\n /** The Postgres schema. `public` when omitted. */\n schema?: string;\n /** A non-default Postgres database. */\n database?: ResourceRef;\n /** What the view holds, for OpenAPI and MCP. */\n description?: string;\n /** Relations to read through. No constraint is created for a view. */\n relations?: R;\n /** Indexes on a materialized view's stored rows. */\n indexes?: readonly TableIndex<NoInfer<Extract<keyof C, string>>>[];\n /** Read hooks. A view is never written. */\n hooks?: Pick<TableHooks<RowOfColumns<C>, RowOfColumns<C>, USER>, \"beforeQuery\" | \"afterRead\">;\n /** Opaque data, served with the view's descriptor. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * A view as authored: the result of `defineView`.\n *\n * @group Schema\n */\nexport interface ViewDef<\n N extends string = string,\n C extends ColumnsShape = ColumnsShape,\n R extends RelationsShape = RelationsShape,\n S extends string = N\n> {\n readonly brand: typeof VIEW_BRAND;\n /** The name it was defined under. */\n readonly name: N;\n /** What it was defined with, as written. */\n readonly config: ViewConfig<C, R, User, S>;\n}\n\n/**\n * Define a SQL view, served read-only.\n *\n * A plain view is created `WITH (security_invoker = true)`: the row-level\n * security of the tables it reads decides what each caller sees. A\n * materialized view stores its rows, so it is gated by `roles` instead.\n *\n * @group Schema\n */\nexport function defineView<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: ViewConfig<C, R, User, S>): ViewDef<N, C, R, S> {\n assertTableShape(\"defineView\", name, config);\n if (typeof config.query !== \"string\" || config.query.trim().length === 0) {\n throw new Error(`View \"${name}\" needs a \\`query\\`: the SELECT that defines it.`);\n }\n if (config.roles !== undefined && !config.materialized) {\n throw new Error(\n `View \"${name}\" lists \\`roles\\` but is not materialized. A plain view is governed by the row-level ` +\n \"security of the tables it reads; `roles` gates a materialized view only.\"\n );\n }\n return { brand: VIEW_BRAND, name, config };\n}\n\n/**\n * The slug of a table or view, from its type: `TableSlugOf<typeof posts>`.\n *\n * The `slug` it was defined with, or the name it was defined under when it was\n * given none — the table's API path, SDK accessor and what scopes name. Reads\n * any `{ name, config: { slug? } }` structurally, so `import type { posts }`\n * is enough; `string` for a table whose type is not literal.\n *\n * ```ts\n * const posts = defineTable(\"blog_posts\", { slug: \"posts\", … });\n * type S = TableSlugOf<typeof posts>; // \"posts\"\n * ```\n *\n * @group Schema\n */\nexport type TableSlugOf<T extends { readonly name: string }> =\n T extends { readonly config: { readonly slug?: infer S } }\n ? [Exclude<S, undefined>] extends [never]\n ? T[\"name\"]\n : Exclude<S, undefined> extends string ? Exclude<S, undefined> : T[\"name\"]\n : T[\"name\"];\n\n/**\n * A type compared member by member rather than through its type parameters.\n *\n * `TableConfig<C>` names `keyof C` (in `tenant`, `softDelete`, `indexes`), and\n * TypeScript measures a type parameter read through `keyof` as contravariant —\n * so `TableConfig<{ id: … }>` was refused where `TableConfig<ColumnsShape>`\n * was expected, although every member is assignable. Spelling the \"any\" types\n * out structurally makes the compiler compare the members, which is the\n * question actually being asked.\n */\ntype Structural<T> = { [K in keyof T]: T[K] };\n\n/**\n * Any table, whatever its columns: what a list of `defineTable` results is\n * typed as (`compileTables(defs)`, `backend/schema/index.ts`).\n *\n * @group Schema\n */\nexport interface AnyTableDef {\n readonly brand: typeof TABLE_BRAND;\n readonly name: string;\n readonly config: Structural<TableConfig<ColumnsShape, RelationsShape>>;\n readonly auth?: AuthTableOptions;\n}\n\n/**\n * Any view, whatever its columns.\n *\n * @group Schema\n */\nexport interface AnyViewDef {\n readonly brand: typeof VIEW_BRAND;\n readonly name: string;\n readonly config: Structural<ViewConfig<ColumnsShape, RelationsShape>>;\n}\n\n/**\n * Whether a value is the result of `defineTable` or `defineAuthTable`, from\n * this copy of the package or another.\n *\n * @group Schema\n */\nexport function isTableDef(value: unknown): value is AnyTableDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === TABLE_BRAND;\n}\n\n/**\n * Whether a value is the result of `defineAuthTable`.\n *\n * @group Schema\n */\nexport function isAuthTableDef(value: unknown): value is AnyTableDef & { auth: AuthTableOptions } {\n return isTableDef(value) && value.auth !== undefined;\n}\n\n/**\n * Whether a value is the result of `defineView`.\n *\n * @group Schema\n */\nexport function isViewDef(value: unknown): value is AnyViewDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === VIEW_BRAND;\n}\n"],"mappings":";;AAoaA,IAAa,oBAAmE;CAC5E,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,SAAS;CACT,MAAM;CACN,QAAQ;CACR,SAAS;CACT,SAAS;CACT,UAAU;CACV,UAAU;CACV,WAAW;AACf;;;;;;;AA8BA,IAAa,uBAAiD;CAC1D;CAAK;CAAM;CAAM;CAAM;CAAM;CAC7B;CAAM;CACN;CAAkB;CAAsB;CAAsB;CAC9D;CAAQ;CAAS;CAAY;CAC7B;CAAW;AACf;AAG2C,IAAI,IAAmB,oBAAoB;AAc3B,IAAI,IAC3D,OAAO,QAAQ,iBAAiB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M,IAAI,MACN,SAAS,KAAK,gKAElB;CAEJ,OAAO;EAAE,OAAO;EAAY;EAAM;CAAO;AAC7C;;;;;;;AAkEA,SAAgB,WAAW,OAAsC;CAC7D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,WAAW,SAAS,MAAM,UAAA;AACpF;;;;;;AAOA,SAAgB,eAAe,OAAmE;CAC9F,OAAO,WAAW,KAAK,KAAK,MAAM,SAAS,KAAA;AAC/C;;;;;;AAOA,SAAgB,UAAU,OAAqC;CAC3D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,WAAW,SAAS,MAAM,UAAA;AACpF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../types/src/types/filter-operators.ts","../../../types/src/types/policy.ts","../../../types/src/types/rls-functions.ts","../../../types/src/types/data_source.ts","../../../types/src/types/resources.ts","../../../types/src/types/resource_kinds.ts","../../../types/src/types/scopes.ts","../../../types/src/schema/column_options.ts","../../../types/src/schema/json.ts","../../../types/src/schema/columns.ts","../../../types/src/schema/relations.ts","../../../types/src/schema/table.ts"],"sourcesContent":["/**\n * Canonical filter operators and REST wire-format mappings.\n *\n * `WhereFilterOp` is THE operator type used at every layer — from React\n * components through the SDK, server, and down to the database driver.\n *\n * PostgREST short-codes (`eq`, `gt`, `cs`, …) exist **only** at the\n * HTTP wire boundary, handled by `serializeFilter` / `deserializeFilter`\n * in `@rebasepro/common`.\n *\n * ┌──────────────────────┬───────────────┬──────────────────────────────┐\n * │ Canonical │ REST short │ Meaning │\n * ├──────────────────────┼───────────────┼──────────────────────────────┤\n * │ \"==\" │ \"eq\" │ Equal │\n * │ \"!=\" │ \"neq\" │ Not equal │\n * │ \">\" │ \"gt\" │ Greater than │\n * │ \">=\" │ \"gte\" │ Greater than or equal │\n * │ \"<\" │ \"lt\" │ Less than │\n * │ \"<=\" │ \"lte\" │ Less than or equal │\n * │ \"in\" │ \"in\" │ Value in list │\n * │ \"not-in\" │ \"nin\" │ Value not in list │\n * │ \"array-contains\" │ \"cs\" │ Array contains element │\n * │ \"array-contains-any\" │ \"csa\" │ Array contains any of │\n * │ \"array-contains-all\" │ \"csall\" │ Array contains all of │\n * │ \"array-contained-by\" │ \"cd\" │ Array holds only elements of │\n * │ \"like\" │ \"like\" │ SQL LIKE (case-sensitive) │\n * │ \"ilike\" │ \"ilike\" │ SQL ILIKE (case-insensitive) │\n * │ \"not-like\" │ \"nlike\" │ NOT LIKE (case-sensitive) │\n * │ \"not-ilike\" │ \"nilike\" │ NOT ILIKE (case-insensitive) │\n * │ \"is-null\" │ \"isnull\" │ Field IS NULL │\n * │ \"is-not-null\" │ \"notnull\" │ Field IS NOT NULL │\n * └──────────────────────┴───────────────┴──────────────────────────────┘\n *\n * Pattern matching (`like`/`ilike`) uses SQL wildcard syntax: `%` matches any\n * sequence of characters, `_` matches a single character. Firestore has no\n * native pattern matching and rejects these operators (use `searchString` instead).\n *\n * @module\n */\n\n/**\n * Where NULLs sort relative to real values on one key.\n *\n * Absent means the convention Postgres itself applies and the driver writes\n * out: `NULLS LAST` ascending, `NULLS FIRST` descending. That convention was\n * hardcoded and unstateable — a \"newest first\" list put every row with no date\n * at the very top, and the only way out was to add a `is-not-null` filter and\n * lose those rows entirely.\n *\n * The keyset comparison honours whatever is chosen here, so a cursor over a\n * nullable key stays correct under either placement.\n *\n * @group Models\n */\nexport type NullsPlacement = \"first\" | \"last\";\n\n/**\n * Canonical sort representation: `[fieldName, direction]`, optionally with a\n * {@link NullsPlacement}.\n *\n * Used in `FindParams.orderBy`, `collection.sort`, and `FilterPreset.sort`.\n * The colon-string form (`\"field:direction\"`, or `\"field:direction:nulls\"`)\n * exists only at the HTTP wire boundary, handled by `serializeOrderBy` /\n * `deserializeOrderBy` in `@rebasepro/common`.\n *\n * The third slot is optional so every `[field, direction]` written before it\n * existed is still exactly this type, and every `const [field, direction] =`\n * destructure still reads what it always read.\n *\n * @group Models\n */\nexport type OrderByTuple<Key extends string = string> = [Key, \"asc\" | \"desc\", NullsPlacement?];\n\n/**\n * One sort key, or several applied in order of significance.\n *\n * ```ts\n * orderBy: [\"created_at\", \"desc\"] // one key\n * orderBy: [[\"roles\", \"asc\"], [\"created_at\", \"desc\"]] // roles, then newest first\n * ```\n *\n * The two forms are told apart by whether the first element is itself an\n * array, so a single tuple never needs wrapping and every existing caller\n * keeps working unchanged. `normalizeOrderBy` in `@rebasepro/common` collapses\n * both to the list form, which is what every layer below the call site speaks.\n *\n * Ties on the last key are broken by the row id, so a multi-key sort is a\n * total order and pages over it neither repeat nor skip rows.\n *\n * @group Models\n */\nexport type OrderBySpec<Key extends string = string> =\n | OrderBySortTuple<Key>\n | OrderBySortTuple<Key>[];\n\n/**\n * A sort key: a field name, or an aggregate over a to-many relation.\n *\n * @group Models\n */\nexport type SortKey<Key extends string = string> = Key | RelationAggregateSort;\n\n/**\n * `[sortKey, direction]` — the authoring form of {@link OrderByTuple}, which\n * additionally accepts a {@link RelationAggregateSort} object.\n *\n * The object never reaches a driver: `normalizeOrderBy` in `@rebasepro/common`\n * encodes it to its string spelling on the way down, and everything below that\n * point speaks plain `OrderByTuple`. See {@link RelationAggregateSort} for why\n * the wire form is a string.\n *\n * @group Models\n */\nexport type OrderBySortTuple<Key extends string = string> = [SortKey<Key>, \"asc\" | \"desc\", NullsPlacement?];\n\n/**\n * The aggregate functions a relation sort can apply.\n *\n * Five, and no `array_agg`/`string_agg`: an aggregate used as a sort key has to\n * produce something with an order, and these are the ones that do.\n *\n * @group Models\n */\nexport type RelationAggregateFn = \"min\" | \"max\" | \"count\" | \"sum\" | \"avg\";\n\n/**\n * Order rows by an aggregate over the rows a to-many relation reaches —\n * \"candidates, oldest waiting first\", \"clients, busiest first\".\n *\n * ```ts\n * // The date of each candidate's earliest open application.\n * orderBy: [[{ relation: \"applications\", field: \"created_at\", agg: \"min\" }, \"asc\"]]\n *\n * // How many applications each candidate has.\n * orderBy: [[{ relation: \"applications\", agg: \"count\" }, \"desc\"]]\n * ```\n *\n * This is the half of a queue that cannot be worked around client-side. A\n * *filter* over a relation can be approximated by denormalising a flag onto the\n * row; an *ordering* cannot be approximated at all once the result set is\n * paged, because the client only ever holds one page and the page was chosen by\n * the wrong order.\n *\n * Rows the relation reaches nothing from sort last ascending and first\n * descending — the placement Postgres gives a `NULL`, stated rather than\n * inherited, because the keyset comparison behind cursor paging has to agree\n * with it exactly. Ties are broken by the row id, so the order is total and\n * paging over it neither repeats nor skips.\n *\n * Compiled by the driver into a correlated subquery, so it is subject to the\n * reader's own row-level security on the target table: a related row the reader\n * cannot see does not contribute to the aggregate. Offered only where\n * {@link DataSourceCapabilities.relationAggregateSorts} says the driver can\n * compile it.\n *\n * @group Models\n */\nexport interface RelationAggregateSort {\n /** The to-many relation to aggregate over, by its name on this collection. */\n relation: string;\n\n /** The aggregate to apply. */\n agg: RelationAggregateFn;\n\n /**\n * The column of the *target* to aggregate. Required by every function\n * except `count`, which counts the related rows themselves when it is\n * omitted — and counts the rows whose column is non-null when it is not.\n */\n field?: string;\n}\n\n/** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */\nconst RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\\(([^().]+)(?:\\.([^()]+))?\\)$/;\n\n/**\n * A {@link RelationAggregateSort} as a single string — `min(applications.created_at)`,\n * `count(applications)`.\n *\n * The wire form is a string because every layer below the call site already is\n * one: `OrderByTuple` is `[string, direction]`, the REST parameter is\n * `?orderBy=key:direction`, the driver contract takes `orderBy?: string |\n * OrderByTuple[]`, and a cursor names its keys by string. `_score` established\n * the same pattern — a sort key that is not a column, spelled as one — and this\n * reuses it rather than widening five signatures to carry an object that would\n * be flattened at the end anyway.\n *\n * SQL's own spelling, so the key reads as what it compiles to. Neither `:` nor\n * `,` appears in it, which is what keeps it safe in the colon-delimited wire\n * shorthand.\n *\n * @group Models\n */\nexport function encodeRelationAggregateSort(sort: RelationAggregateSort): string {\n return `${sort.agg}(${sort.relation}${sort.field ? `.${sort.field}` : \"\"})`;\n}\n\n/**\n * Read the string spelling back, or `undefined` if it is not one.\n *\n * `undefined` rather than a throw: this is asked of *every* sort key to find\n * out which kind it is, and an ordinary column name is not an error.\n *\n * @group Models\n */\nexport function parseRelationAggregateSort(key: string): RelationAggregateSort | undefined {\n const match = RELATION_AGGREGATE_SORT_PATTERN.exec(key);\n if (!match) return undefined;\n const [, agg, relation, field] = match;\n // `min()` and friends have nothing to aggregate without a column, and a\n // key that parses to a half-built sort would resolve to no expression and\n // be dropped — leaving the rows unsorted while the caller believes\n // otherwise. `count` is the one function that means something on its own.\n if (!field && agg !== \"count\") return undefined;\n return { agg: agg as RelationAggregateFn, relation, ...(field && { field }) };\n}\n\n/** Is this sort key the object form rather than a field name? */\nexport function isRelationAggregateSort(key: unknown): key is RelationAggregateSort {\n return typeof key === \"object\" && key !== null &&\n typeof (key as RelationAggregateSort).relation === \"string\" &&\n typeof (key as RelationAggregateSort).agg === \"string\";\n}\n\n/** A sort key in the single-string form every layer below the call site speaks. */\nexport function sortKeyToString(key: SortKey): string {\n return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;\n}\n\n/**\n * Canonical filter operators supported across all database backends.\n * Each DB driver translates these to its native query format.\n *\n * @group Models\n */\nexport type WhereFilterOp =\n | \"<\"\n | \"<=\"\n | \"==\"\n | \"!=\"\n | \">=\"\n | \">\"\n | \"array-contains\"\n | \"in\"\n | \"not-in\"\n | \"array-contains-any\"\n | \"array-contains-all\"\n | \"array-contained-by\"\n | \"like\"\n | \"ilike\"\n | \"not-like\"\n | \"not-ilike\"\n | \"is-null\"\n | \"is-not-null\";\n\n/**\n * Used to define filters applied in collections.\n *\n * A single condition is a tuple `[operator, value]`.\n * Multiple conditions on the same field use an array of tuples.\n *\n * @example\n * // Single condition per field\n * { status: [\"==\", \"active\"], price: [\">=\", 9.99] }\n *\n * // Multiple conditions on one field\n * { age: [[\">=\", 18], [\"<\", 65]] }\n *\n * // Array operators\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { tags: [\"array-contains\", \"featured\"] }\n *\n * // Pattern matching (SQL wildcards: % and _)\n * { name: [\"ilike\", \"%john%\"] }\n * { slug: [\"like\", \"post-%\"] }\n *\n * // Null checks (the value is ignored; `null` is conventional, and an\n * // untyped caller may leave it out: `[\"is-null\"]`)\n * { deleted_at: [\"is-null\", null] }\n * { published_at: [\"is-not-null\", null] }\n *\n * @group Models\n */\nexport type FilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][]>>;\n\n/**\n * The field names a query may address on a row type: every column, plus a\n * dotted path reaching inside one — or *through a relation* to a column of the\n * related row.\n *\n * A dotted path is not checked at all, in either direction. That is a\n * deliberate loosening, and it is worth being exact about what it costs. The\n * root used to be checked: `\"meta.tag\"` required a `meta` column. It cannot\n * stay checked, because the other thing a dotted path now means is\n * `\"applications.status\"` — and `applications` is a *relation*, which comes\n * from the collection's `relations` and is not a column of `M` at all. There is\n * nothing in a generated row type that could validate one. `FindParams.include`\n * is `string[]` for exactly this reason and says so.\n *\n * So the guarantee moves rather than disappears: an unresolvable path is a 400\n * from the driver, not a silently dropped condition. See\n * `UnknownFilterFieldsMode` in `@rebasepro/server-postgres` — dropping a filter\n * key *widens* the read to every row, which is why that resolution fails\n * closed. A typo'd relation path is refused at runtime with the target\n * collection's real column list in the message.\n *\n * A JSON path — `metadata->>tier` — is admitted on the same terms and for the\n * same reason. It addresses a key *inside* a `json`/`jsonb` column, so nothing\n * in a generated row type describes it either; the driver resolves it and\n * refuses what it cannot. It has no dot, so the dotted branch above never\n * covered it, and every documented `?metadata->>tier=eq.gold` filter was a\n * compile error on a typed client while working perfectly over HTTP.\n *\n * Undotted keys are unaffected and still checked against `keyof M`.\n *\n * When `M` is left at its default `Record<string, unknown>`, `keyof M` is\n * `string` and this collapses to `string`, so every query stays permissive.\n * That is what keeps an untyped `createRebaseClient()` behaving exactly as it\n * did before the row type was threaded through.\n *\n * @group Models\n */\nexport type FieldPath<M extends Record<string, unknown> = Record<string, unknown>> =\n | Extract<keyof M, string>\n | NonColumnFieldPath;\n\n/**\n * A field key that is not a column: a relation path (`author.name`) or a JSON\n * path (`metadata->>tier`).\n *\n * The fluent builder needs this on its own, where `FindParams` does not. Its\n * `where(column, operator, value)` types the value against `M[column]`, which\n * only means something for a real column — so paths take a second overload\n * whose value is `unknown`. Keying that overload on the *shape* of a path,\n * rather than on \"everything that is not a column\", is what keeps a real column\n * with a wrong value type from falling through to it and being accepted: a\n * mistyped column name has neither a dot nor a `->>`, so it matches neither\n * overload and is still refused.\n *\n * @group Models\n */\nexport type NonColumnFieldPath =\n | `${string}.${string}`\n | `${string}->>${string}`\n | CaseFoldedFieldPath;\n\n/**\n * A text column compared in one case: `lower(artist)` or `upper(code)`. Every\n * operator applies to the folded value, so the values written beside it are\n * written in that case — `{ \"lower(artist)\": [\"in\", [\"abba\", \"queen\"]] }`\n * matches \"ABBA\" and \"Queen\". Compiled to `lower(artist)`, which an index on\n * that expression serves. The same spelling an aggregate's `groupBy` uses.\n *\n * @group Models\n */\nexport type CaseFoldedFieldPath = `lower(${string})` | `upper(${string})`;\n\n/**\n * Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or\n * `undefined` for any other key.\n *\n * @group Models\n */\nexport function parseCaseFoldedFieldPath(key: string): { fn: \"lower\" | \"upper\"; field: string } | undefined {\n const match = /^(lower|upper)\\(\\s*([^()\\s]+)\\s*\\)$/.exec(key);\n return match ? { fn: match[1] as \"lower\" | \"upper\", field: match[2] } : undefined;\n}\n\n/**\n * Relaxed filter type that also accepts pre-serialized PostgREST strings.\n * **Internal only** — used at the wire-format boundary\n * (`serializeFilter` / `deserializeFilter` in `@rebasepro/common`).\n *\n * Application code, UI components, and SDK consumers should use\n * {@link FilterValues} instead.\n *\n * @internal\n */\nexport type WireFilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][] | string>>;\n\n/**\n * PostgREST short-code operators. Wire format only — these never appear\n * in application code. Used by `serializeFilter`/`deserializeFilter`\n * in `@rebasepro/common`.\n */\nexport type RestFilterOp =\n | \"eq\" | \"neq\"\n | \"gt\" | \"gte\"\n | \"lt\" | \"lte\"\n | \"in\" | \"nin\"\n | \"cs\" | \"csa\" | \"csall\" | \"cd\"\n | \"like\" | \"ilike\"\n | \"nlike\" | \"nilike\"\n | \"isnull\" | \"notnull\";\n\n/** Maps canonical operators to their REST short-code equivalents. */\nexport const CANONICAL_TO_REST: Readonly<Record<WhereFilterOp, RestFilterOp>> = {\n \"==\": \"eq\",\n \"!=\": \"neq\",\n \">\": \"gt\",\n \">=\": \"gte\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \"in\": \"in\",\n \"not-in\": \"nin\",\n \"array-contains\": \"cs\",\n \"array-contains-any\": \"csa\",\n \"array-contains-all\": \"csall\",\n \"array-contained-by\": \"cd\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"not-like\": \"nlike\",\n \"not-ilike\": \"nilike\",\n \"is-null\": \"isnull\",\n \"is-not-null\": \"notnull\"\n};\n\n/** Maps REST short-code operators to their canonical equivalents. */\nexport const REST_TO_CANONICAL: Readonly<Record<RestFilterOp, WhereFilterOp>> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"csall\": \"array-contains-all\",\n \"cd\": \"array-contained-by\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"nlike\": \"not-like\",\n \"nilike\": \"not-ilike\",\n \"isnull\": \"is-null\",\n \"notnull\": \"is-not-null\"\n};\n\n/**\n * Operators that test for null/not-null and therefore ignore their value.\n * Codecs normalize the value of these conditions to `null`.\n */\nexport const NULL_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"is-null\", \"is-not-null\"\n]);\n\n/**\n * Operators whose operand is a **list** of values rather than one value.\n *\n * On the wire that list is always parenthesised — `in.(draft,review)` — which\n * is what lets the REST codec tell `?status=in.(a,b)` (the operator) from\n * `?status=in.progress` (a value that happens to start with an operator's\n * name). See `deserializeSingle` in `@rebasepro/common`.\n *\n * @group Models\n */\nexport const LIST_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"in\", \"not-in\", \"array-contains-any\", \"array-contains-all\", \"array-contained-by\"\n]);\n\n/**\n * Every canonical operator, in a stable order. Useful for engine capability\n * declarations ({@link DataSourceCapabilities.filterOperators}) and for\n * building operator subsets.\n * @group Models\n */\nexport const ALL_WHERE_FILTER_OPS: readonly WhereFilterOp[] = [\n \"<\", \"<=\", \"==\", \"!=\", \">=\", \">\",\n \"in\", \"not-in\",\n \"array-contains\", \"array-contains-any\", \"array-contains-all\", \"array-contained-by\",\n \"like\", \"ilike\", \"not-like\", \"not-ilike\",\n \"is-null\", \"is-not-null\"\n];\n\n/** All canonical operator strings for runtime validation. */\nconst CANONICAL_OPS: ReadonlySet<string> = new Set<WhereFilterOp>(ALL_WHERE_FILTER_OPS);\n\n/**\n * The REST table as a `Map`, because the key `toCanonicalOp` is handed comes\n * off the wire.\n *\n * Indexed as a plain object, every `Object.prototype` member answered:\n * `toCanonicalOp(\"valueOf\")` returned the inherited *function* as though it\n * were a `WhereFilterOp`, and every caller here treats a defined result as\n * \"known operator\". Same defect the REST codec's own lookup tables were\n * converted away from in `filter-dialect.ts`; this is the copy that survived\n * one package over, and it now sits under the operator validation the REST\n * parser does, which would otherwise have admitted `[\"constructor\", x]`.\n */\nconst REST_OP_LOOKUP: ReadonlyMap<string, WhereFilterOp> = new Map<string, WhereFilterOp>(\n Object.entries(REST_TO_CANONICAL) as [string, WhereFilterOp][]\n);\n\n/**\n * Resolve any operator string (canonical or REST short-code) to its\n * canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.\n *\n * @example\n * toCanonicalOp(\"==\") // \"==\"\n * toCanonicalOp(\"eq\") // \"==\"\n * toCanonicalOp(\"cs\") // \"array-contains\"\n * toCanonicalOp(\"xyz\") // undefined\n */\nexport function toCanonicalOp(op: string): WhereFilterOp | undefined {\n if (CANONICAL_OPS.has(op)) return op as WhereFilterOp;\n return REST_OP_LOOKUP.get(op);\n}\n","/**\n * Structured, engine-agnostic policy expressions.\n *\n * A {@link PolicyExpression} is the single source of truth for a row-level\n * security condition. It is compiled to Postgres `USING`/`WITH CHECK` SQL\n * (authoritative enforcement) and independently evaluated in JavaScript (to\n * drive the admin UI). Because both the SQL and the JS decision derive from\n * the *same* expression, the UI matches database enforcement by construction —\n * no drift between two hand-written implementations.\n *\n * The only escape hatch that cannot be evaluated client-side is the\n * {@link RawPolicyExpression} node (`{ kind: \"raw\" }`): it preserves full\n * PostgreSQL power but, being arbitrary SQL, is treated as *unknown* by the\n * JavaScript evaluator (never silently allowed) and reflected exactly in the UI\n * via server-computed capability flags.\n *\n * @group Models\n */\nexport type PolicyExpression =\n | TruePolicyExpression\n | FalsePolicyExpression\n | AndPolicyExpression\n | OrPolicyExpression\n | NotPolicyExpression\n | ComparePolicyExpression\n | RolesOverlapPolicyExpression\n | RolesContainPolicyExpression\n | AuthenticatedPolicyExpression\n | RegisteredPolicyExpression\n | ServerContextPolicyExpression\n | ExistsInPolicyExpression\n | RawPolicyExpression;\n\n/**\n * The id a request without a logged-in user reports as `rebase.uid()`.\n *\n * A user-context request always sets `app.uid`: blank would read back as\n * `NULL`, and `NULL` is how the trusted server context is recognised, so an\n * anonymous visitor would be promoted to server privileges. The driver\n * therefore substitutes this sentinel at the single chokepoint where the GUC\n * is set.\n *\n * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a\n * tautology on the user path** — it is true for anonymous visitors too. Use\n * {@link policy.authenticated} to mean \"signed in\", and\n * {@link policy.serverContext} to mean \"the trusted server context\". Do not\n * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one\n * literal is not enough.\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_ID = \"anonymous\";\n\n/**\n * Every uid that has ever meant \"nobody is signed in\" — newest first.\n *\n * There are two because there were two. The types, the policy compiler, the\n * JavaScript evaluator and the linter were all built on\n * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated\n * callers as `'anon'` — so `policy.authenticated()`, which compiled to\n * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The\n * sanctioned way to write \"signed in\" granted to everyone, and the linter\n * flagged the spelling that actually worked as a foreign convention.\n *\n * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here\n * because policies outlive the server that generated them: a database still\n * holding policies from before the fix, or a project whose server has not been\n * upgraded yet, must not become a grant in either direction. Compile against\n * this list, not against a single literal.\n *\n * No real user id is ever one of these, so a match is always \"not signed in\".\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_IDS: readonly string[] = [ANONYMOUS_USER_ID, \"anon\"];\n\n/**\n * Whether a uid stands for \"no one is signed in\", in any spelling rebase has\n * used. `null`/`undefined` is the trusted server context, not an anonymous\n * caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.\n *\n * @group Models\n */\nexport function isAnonymousUid(uid: string | null | undefined): boolean {\n return typeof uid === \"string\" && ANONYMOUS_USER_IDS.includes(uid);\n}\n\n/** Always allows. Compiles to `true`. @group Models */\nexport interface TruePolicyExpression {\n kind: \"true\";\n}\n\n/** Always denies. Compiles to `false`. @group Models */\nexport interface FalsePolicyExpression {\n kind: \"false\";\n}\n\n/** Logical AND — every operand must pass. @group Models */\nexport interface AndPolicyExpression {\n kind: \"and\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical OR — at least one operand must pass. @group Models */\nexport interface OrPolicyExpression {\n kind: \"or\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical negation. @group Models */\nexport interface NotPolicyExpression {\n kind: \"not\";\n operand: PolicyExpression;\n}\n\n/** Comparison operators available to {@link ComparePolicyExpression}. @group Models */\nexport type PolicyCompareOperator = \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\";\n\n/**\n * Compares two operands, e.g. `owner_id = rebase.uid()`.\n * @group Models\n */\nexport interface ComparePolicyExpression {\n kind: \"compare\";\n op: PolicyCompareOperator;\n left: PolicyOperand;\n right: PolicyOperand;\n}\n\n/**\n * True when the user holds *at least one* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') && ARRAY[...]`.\n * @group Models\n */\nexport interface RolesOverlapPolicyExpression {\n kind: \"rolesOverlap\";\n roles: readonly string[];\n}\n\n/**\n * True when the user holds *all* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') @> ARRAY[...]`.\n * @group Models\n */\nexport interface RolesContainPolicyExpression {\n kind: \"rolesContain\";\n roles: readonly string[];\n}\n\n/**\n * True when a signed-in user is making the request. Compiles to\n * `rebase.uid() IS NOT NULL AND rebase.uid() <> 'anonymous'`.\n *\n * Both halves are load-bearing. `IS NOT NULL` excludes the server context;\n * the {@link ANONYMOUS_USER_ID} comparison excludes anonymous visitors, who\n * *do* carry a non-null `rebase.uid()`. Checking only `IS NOT NULL` grants to\n * everyone — see {@link ANONYMOUS_USER_ID}.\n *\n * `policy.not(policy.authenticated())` therefore means \"anonymous visitor or\n * the server context\". To single out the server context, use\n * {@link ServerContextPolicyExpression}.\n * @group Models\n */\nexport interface AuthenticatedPolicyExpression {\n kind: \"authenticated\";\n}\n\n/**\n * True for a signed-in caller who has an ACCOUNT — not a guest.\n *\n * The distinction {@link AuthenticatedPolicyExpression} cannot make. Anonymous\n * SIGN-IN (`POST /auth/anonymous`) mints a real user row with a real uid and a\n * real session, so such a caller is \"authenticated\" by every test that looks at\n * `rebase.uid()`: same shape, same default role, indistinguishable inside a\n * policy. On a deployment with anonymous sign-in enabled, every rule meaning\n * \"a signed-in person\" therefore also meant \"anybody at all\", since pressing\n * Continue as guest needs no email, no password and no agreement to anything.\n *\n * Note the two senses of \"anonymous\", which is the reason this was easy to\n * miss. {@link ANONYMOUS_USER_ID} is the sentinel for a request carrying NO\n * session, and `authenticated()` already excludes it. A guest is the other\n * thing: a session with nobody behind it. This node excludes both.\n *\n * Compiles to `authenticated() AND NOT rebase.is_anonymous()`.\n *\n * Use it wherever a rule is about a person who could be held responsible for\n * something — writing a review, joining an organization, spending money. Use\n * `authenticated()` where a guest is genuinely welcome, which is what\n * anonymous sign-in is for: a cart before checkout, a draft before signup.\n * @group Models\n */\nexport interface RegisteredPolicyExpression {\n kind: \"registered\";\n}\n\n/**\n * True only in the trusted **server context** — the built-in flows that run\n * without a user (signup, migrations, `dataAsAdmin`) set no user GUC, so\n * `rebase.uid()` is `NULL` for them and only for them. Compiles to\n * `rebase.uid() IS NULL`.\n *\n * This is what lets the owner connection satisfy a policy even under FORCE RLS.\n * It is deliberately a primitive rather than `not(authenticated())`: the two\n * meant the same thing while `authenticated` ignored {@link ANONYMOUS_USER_ID},\n * and conflating them is what turns a server-only grant into an anonymous one.\n *\n * The JavaScript evaluator always returns `false` for this node — a client is\n * never the server context.\n * @group Models\n */\nexport interface ServerContextPolicyExpression {\n kind: \"serverContext\";\n}\n\n/**\n * Membership / relational access: true when at least one row exists in another\n * table (a join/membership table) matching `where`. This is what lets you\n * scope reads to \"rows whose team the caller belongs to\" without an N+1\n * per-row lookup — it compiles to a single correlated `EXISTS` subquery.\n *\n * Inside `where`, {@link FieldPolicyOperand} (`policy.field`) references a column\n * of the joined table, while {@link OuterFieldPolicyOperand}\n * (`policy.outerField`) references a column of the row being checked (the outer\n * table under RLS). Combine with {@link AuthUidPolicyOperand} to correlate to\n * the caller.\n *\n * @example\n * ```ts\n * // documents visible only to members of the document's team:\n * policy.existsIn({\n * table: \"team_members\",\n * where: policy.and(\n * policy.compare(policy.field(\"team_id\"), \"eq\", policy.outerField(\"team_id\")),\n * policy.compare(policy.field(\"user_id\"), \"eq\", policy.authUid()),\n * ),\n * })\n * // → EXISTS (SELECT 1 FROM team_members _ex0\n * // WHERE _ex0.team_id = documents.team_id AND _ex0.user_id = rebase.uid())\n * ```\n *\n * Postgres-authoritative: like {@link RawPolicyExpression}, the JavaScript\n * evaluator treats it as *unknown* (it cannot run a subquery client-side), so\n * enforcement is always the database's.\n * @group Models\n */\nexport interface ExistsInPolicyExpression {\n kind: \"existsIn\";\n /**\n * The table to search (the join / membership table), by its slug.\n *\n * Spelled `collection` before tables replaced collections in the backend\n * vocabulary. A policy's name hashes the rule as written, so the name\n * hash still reads this field as `collection` (see `getPolicyNameHash`).\n */\n table: string;\n /** Condition evaluated against the joined table's rows. */\n where: PolicyExpression;\n}\n\n/**\n * A raw PostgreSQL boolean expression — the full-power escape hatch.\n *\n * Columns can be referenced as `{column_name}`. This is Postgres-only and\n * **server-authoritative**: the JavaScript evaluator cannot evaluate arbitrary\n * SQL, so it treats this node as *unknown* rather than guessing.\n * @group Models\n */\nexport interface RawPolicyExpression {\n kind: \"raw\";\n sql: string;\n}\n\n/**\n * An operand referenced by a {@link ComparePolicyExpression}.\n * @group Models\n */\nexport type PolicyOperand =\n | FieldPolicyOperand\n | OuterFieldPolicyOperand\n | LiteralPolicyOperand\n | AuthUidPolicyOperand\n | AuthRolesPolicyOperand\n | AuthClaimPolicyOperand;\n\n/** A column value on the row being evaluated. @group Models */\nexport interface FieldPolicyOperand {\n kind: \"field\";\n /** The property/column name (resolved to its DB column when compiled). */\n name: string;\n}\n\n/**\n * A column value on the *outer* row when used inside {@link ExistsInPolicyExpression}\n * — i.e. the row the RLS policy is being evaluated for, referenced from within the\n * subquery. Outside an `existsIn` it is equivalent to {@link FieldPolicyOperand}.\n * @group Models\n */\nexport interface OuterFieldPolicyOperand {\n kind: \"outerField\";\n /** The property/column name on the outer table. */\n name: string;\n}\n\n/** A constant value. @group Models */\nexport interface LiteralPolicyOperand {\n kind: \"literal\";\n value: string | number | boolean | null;\n}\n\n/** The current user's id — compiles to `rebase.uid()`. @group Models */\nexport interface AuthUidPolicyOperand {\n kind: \"authUid\";\n}\n\n/**\n * The current user's roles as an array — compiles to\n * `string_to_array(rebase.roles(), ',')`.\n * @group Models\n */\nexport interface AuthRolesPolicyOperand {\n kind: \"authRoles\";\n}\n\n/**\n * A named claim on the caller's session token — compiles to\n * `NULLIF(rebase.jwt() ->> '<name>', '')`.\n *\n * The operand multi-tenancy is built on, and the reason it is an operand rather\n * than a {@link RawPolicyExpression}: a claim arrives as **text**, and the\n * column it is compared against usually is not. `org_id = rebase.jwt() ->>\n * 'org_id'` on a `uuid` column is not a policy that denies — it is\n * `CREATE POLICY` failing with \"operator does not exist: uuid = text\", and a\n * table left with RLS enabled and no policy denies every row. Casting the\n * *column* to text instead compiles, but takes the index off the one predicate\n * that is ANDed into every read of the table.\n *\n * As an operand the compiler can see both sides: it casts the claim to the\n * column's type, guarded so a malformed claim denies rather than raising\n * `invalid input syntax` on every query, and the column keeps its index.\n *\n * An absent claim, and a claim set to the empty string, are both NULL — and a\n * comparison against NULL is never true, so a caller carrying no claim sees no\n * rows rather than all of them.\n *\n * Only *custom* claims are reachable. `uid`, `roles`, `aal` and `isAnonymous`\n * are identity claims written after the custom ones when a token is minted,\n * precisely so a claims hook cannot assert them; they have their own operands\n * ({@link AuthUidPolicyOperand}, {@link AuthRolesPolicyOperand}) and naming one\n * here is refused.\n *\n * Postgres-authoritative: the JavaScript evaluator reports *unknown* rather\n * than reproducing Postgres's cast semantics (uuid case folding, numeric\n * widening) a second time and getting them subtly wrong.\n * @group Models\n */\nexport interface AuthClaimPolicyOperand {\n kind: \"authClaim\";\n /** The claim's name on the token, e.g. `\"org_id\"`. */\n name: string;\n}\n\n// ── Shorthand conditions ─────────────────────────────────────────────\n\n/**\n * A value a {@link PolicyShorthand} compares a column with.\n * @group Models\n */\nexport type PolicyShorthandValue = string | number | boolean | null;\n\n/**\n * The plain-object form of a row condition: `{ status: \"published\" }`.\n *\n * Every key is a column key of the table and every value a literal; the\n * condition holds when **each** column equals its value (an AND of\n * equalities), and a `null` value means the column `IS NULL`. It is what\n * `policy.and(policy.compare(policy.field(k), \"eq\", policy.literal(v)), …)`\n * spells longhand, and compiles to the same SQL — except `null`, which no\n * comparison can express (`x = NULL` is never true) and which therefore\n * compiles to `x IS NULL`.\n *\n * - **No key may be named `kind`.** `kind` is how a {@link PolicyExpression}\n * is recognised at runtime, so `{ kind: \"true\" }` would be read as the\n * expression that grants everything. The type refuses it and so does the\n * compiler; compare a column called `kind` with the longhand form.\n * - **At least one key.** `{}` would be an AND of nothing, which is `true`;\n * the compiler refuses it — write `policy.true()` if every row is meant.\n * - The keys are checked against the table when the rule is compiled: a key\n * that names no column is refused, with the table and the key in the error.\n *\n * Use {@link isPolicyShorthand} to tell it apart from a `PolicyExpression`.\n *\n * @example\n * { operation: \"select\", access: \"public\", condition: { status: \"published\" } }\n * { operation: \"select\", condition: { orgId: \"acme\", deletedAt: null } }\n *\n * @group Models\n */\nexport type PolicyShorthand = { readonly [column: string]: PolicyShorthandValue } & { readonly kind?: never };\n\n/**\n * What a rule's `condition` / `check` accepts: a structured\n * {@link PolicyExpression}, or the {@link PolicyShorthand} object form.\n * @group Models\n */\nexport type PolicyCondition = PolicyExpression | PolicyShorthand;\n\n/**\n * Every `kind` a {@link PolicyExpression} node can have — the discriminator\n * {@link isPolicyShorthand} and {@link isPolicyExpressionKind} read.\n * @group Models\n */\nexport const POLICY_EXPRESSION_KINDS: readonly PolicyExpression[\"kind\"][] = [\n \"true\", \"false\", \"and\", \"or\", \"not\", \"compare\", \"rolesOverlap\", \"rolesContain\",\n \"authenticated\", \"registered\", \"serverContext\", \"existsIn\", \"raw\"\n];\n\n/**\n * Whether `kind` names a {@link PolicyExpression} node.\n * @group Models\n */\nexport function isPolicyExpressionKind(kind: unknown): kind is PolicyExpression[\"kind\"] {\n return typeof kind === \"string\" && (POLICY_EXPRESSION_KINDS as readonly string[]).includes(kind);\n}\n\nconst isShorthandValue = (value: unknown): value is PolicyShorthandValue =>\n value === null || typeof value === \"string\" || typeof value === \"boolean\"\n || (typeof value === \"number\" && Number.isFinite(value));\n\n/**\n * Whether a rule's `condition` / `check` is a {@link PolicyShorthand} rather\n * than a {@link PolicyExpression}.\n *\n * True only for a plain object with at least one key, none of them `kind`,\n * whose every value is a string, a finite number, a boolean or `null`. Every\n * expression node carries `kind`, so no expression is ever taken for a\n * shorthand — and an object that has a `kind` key is never taken for a\n * shorthand either, whatever its value: such an object is ambiguous (a column\n * called `kind`, or a misspelt node) and the compiler refuses it rather than\n * guessing.\n *\n * @group Models\n */\nexport function isPolicyShorthand(value: unknown): value is PolicyShorthand {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return false;\n if (Object.prototype.hasOwnProperty.call(value, \"kind\")) return false;\n const entries = Object.entries(value);\n return entries.length > 0 && entries.every(([, v]) => isShorthandValue(v));\n}\n\n// ── Constructor helpers ──────────────────────────────────────────────\n// Small, dependency-free builders so callers (and the desugaring in\n// `@rebasepro/common`) can assemble expressions without object-literal noise.\n\n/** @group Models */\nexport const policy = {\n true: (): TruePolicyExpression => ({ kind: \"true\" }),\n false: (): FalsePolicyExpression => ({ kind: \"false\" }),\n and: (...operands: readonly PolicyExpression[]): AndPolicyExpression => ({ kind: \"and\",\noperands: operands as PolicyExpression[] }),\n or: (...operands: readonly PolicyExpression[]): OrPolicyExpression => ({ kind: \"or\",\noperands: operands as PolicyExpression[] }),\n not: (operand: PolicyExpression): NotPolicyExpression => ({ kind: \"not\",\noperand }),\n compare: (left: PolicyOperand, op: PolicyCompareOperator, right: PolicyOperand): ComparePolicyExpression =>\n ({ kind: \"compare\",\nop,\nleft,\nright }),\n rolesOverlap: (roles: readonly string[]): RolesOverlapPolicyExpression => ({ kind: \"rolesOverlap\",\nroles: roles as string[] }),\n rolesContain: (roles: readonly string[]): RolesContainPolicyExpression => ({ kind: \"rolesContain\",\nroles: roles as string[] }),\n authenticated: (): AuthenticatedPolicyExpression => ({ kind: \"authenticated\" }),\n registered: (): RegisteredPolicyExpression => ({ kind: \"registered\" }),\n serverContext: (): ServerContextPolicyExpression => ({ kind: \"serverContext\" }),\n existsIn: (args: { table: string; where: PolicyExpression }): ExistsInPolicyExpression =>\n ({ kind: \"existsIn\",\ntable: args.table,\nwhere: args.where }),\n raw: (sql: string): RawPolicyExpression => ({ kind: \"raw\",\nsql }),\n field: (name: string): FieldPolicyOperand => ({ kind: \"field\",\nname }),\n outerField: (name: string): OuterFieldPolicyOperand => ({ kind: \"outerField\",\nname }),\n literal: (value: string | number | boolean | null): LiteralPolicyOperand => ({ kind: \"literal\",\nvalue }),\n authUid: (): AuthUidPolicyOperand => ({ kind: \"authUid\" }),\n authRoles: (): AuthRolesPolicyOperand => ({ kind: \"authRoles\" }),\n authClaim: (name: string): AuthClaimPolicyOperand => ({ kind: \"authClaim\",\nname })\n};\n","/**\n * The SQL helper functions RLS policies call, and the schema they live in.\n *\n * ## One schema, and it is ours\n *\n * Rebase creates exactly one schema in a project's database: `rebase`. These\n * three functions live in it alongside the framework's own tables, and that is\n * the whole contract — a reader can look at a database and know precisely which\n * namespace belongs to the framework and that nothing else was touched.\n *\n * It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called\n * `auth`, which is Supabase's name, chosen so that a developer who had written\n * Supabase RLS would recognise `auth.uid()`. The familiarity was real but the\n * name was not Rebase's to take, and taking it had a concrete cost: pointing\n * Rebase at a database that already had a Supabase `auth` schema meant\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's\n * `RETURNS uuid`, which Postgres rejects outright —\n *\n * ERROR: cannot change return type of existing function\n * HINT: Use DROP FUNCTION auth.uid() first.\n *\n * — and the failure landed inside a catch-all that logged a warning and carried\n * on, leaving a database with auth tables, no helper functions, and policies\n * calling functions that did not exist. Under `rebase db migrate` the same\n * statements aborted the migration instead.\n *\n * `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`\n * schema untouched and gains a `rebase` one, which is what a gradual migration\n * needs.\n *\n * ## Why functions at all, rather than inlining `current_setting`\n *\n * Because the indirection has already been spent once. `uid()` resolves\n * `app.uid` and falls back to the pre-rename `app.user_id`, so that during a\n * rolling deploy — old and new pods serving one database — both eras resolve\n * the principal. That was a single `CREATE OR REPLACE`. Inlined into policy\n * bodies it would have been a rewrite of every policy on every table.\n *\n * ## Why the name is not configurable\n *\n * A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so\n * these strings are written into every policy in every database Rebase has\n * provisioned. Everything that reads policies back — the SQL-to-policy parser\n * behind the admin UI, the drift checker, `rls-check` — would have to know the\n * configured value to recognise its own output. One frozen name is the feature.\n */\n\n/** The schema Rebase owns. The only schema Rebase creates. */\nexport const REBASE_SCHEMA = \"rebase\";\n\n/**\n * The principal of the current request, as text, or NULL in the server context.\n *\n * Never NULL for a user request — an anonymous one carries\n * {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for\n * the trusted server plane and `IS NOT NULL` a tautology.\n */\nexport const RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;\n/**\n * Is the caller one of this database's request roles? What a permissive\n * policy is ANDed with under `rls.policyTarget: \"requestRole\"`, so another\n * application's role holding a grant on the table gets nothing from it.\n * `current_user` is passed in — inside the function, which reads the recorded\n * roles with its owner's rights, `current_user` would be the owner — and the\n * sub-select makes it one evaluation per statement, not one per row.\n */\nexport const RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;\n\n/** The request's roles as a comma-separated string, for `string_to_array`. */\nexport const RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;\n\n/**\n * The Postgres role that policies granting only the server context or admins\n * are written `TO`: the injected `<table>_default_admin_*` baseline, and any\n * permissive rule whose every clause requires one of the two (`roles: [\"admin\"]`).\n *\n * Postgres ORs the permissive policies that apply to the current role. Written\n * `TO public`, the baseline applied to every signed-in user too, as\n * `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement\n * constant arm cannot use the owner index, so a user's owner-scoped list or\n * count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`\n * this role, the policy is not in a user's plan at all.\n *\n * It holds no privilege and cannot log in: being in it only decides which\n * policies apply, and those still test `rebase.uid() IS NULL` or the `admin`\n * role. Admin requests switch to a request role that inherits it\n * ({@link adminRequestRoleFor}); a connection that is itself subject to RLS\n * inherits it for the server context. One fixed name, so the policy text is the\n * same in every deployment and every generated migration. FROZEN.\n */\nexport const REBASE_ADMIN_ROLE = \"rebase_admin\";\n\n/**\n * The role the admin request roles ({@link adminRequestRoleFor}) inherit and\n * nothing else does, so an admin-only grant can apply to admin REQUESTS alone.\n *\n * {@link REBASE_ADMIN_ROLE} cannot do that job: the connection inherits it for\n * the server context, and so would any process on it that does not switch\n * roles. Its policies therefore keep their test (`rebase.uid() IS NULL` or the\n * `admin` role) — and any policy expression that is not a constant is a\n * security barrier, behind which Postgres will not evaluate a non-leakproof\n * operator as an index condition. An admin's `tags && $1`, `name ~ $1` or\n * jsonb filter scanned the whole table where the owner's used the index.\n *\n * Each admin-only grant gets a companion `TO` this role `USING (true)`.\n * Postgres folds the OR of the permissive policies to `true` for a member, the\n * barrier goes, and an admin request plans as the owner's does; restrictive\n * policies still apply. Membership is the boundary: only the admin request\n * roles hold it, granted `WITH INHERIT TRUE, SET FALSE`, and only from\n * PostgreSQL 16, whose per-grant INHERIT keeps the connection (which holds\n * those roles `WITH INHERIT FALSE`) out. A boot that finds the connection with\n * its privileges revokes every membership, and the companions admit nobody.\n * One fixed name, as {@link REBASE_ADMIN_ROLE}. FROZEN.\n */\nexport const REBASE_ADMIN_REQUEST_ROLE = \"rebase_admin_request\";\n\n/**\n * The role an admin request runs as, for a signed-in request role: it inherits\n * that role (its grants and every policy written for it) and\n * {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared\n * `rebase_admin` itself, because roles belong to the cluster: a project with a\n * request role of its own (`rls.requestRole`) would otherwise share its admin\n * access with every other project on the cluster. FROZEN derivation.\n */\nexport function adminRequestRoleFor(requestRole: string): string {\n return `${requestRole}_admin`;\n}\n\n/**\n * Whether a request with these roles passes `rolesOverlap([\"admin\"])` — the\n * test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the\n * comma-joined `app.user_roles`, so a role name with a comma in it is split\n * exactly as Postgres splits it.\n */\nexport function holdsAdminRole(roles: readonly string[]): boolean {\n return roles.join(\",\").split(\",\").includes(\"admin\");\n}\n\n/**\n * Whether the caller is a GUEST — signed in through anonymous sign-in rather\n * than with an account.\n *\n * A different question from {@link ANONYMOUS_USER_ID}, and the two are easy to\n * confuse: that sentinel means \"no session at all\", while this means \"a session\n * with nobody behind it\". Anonymous sign-in mints a real user row with a real\n * uid, so before this reached the database the two kinds of caller were one\n * principal inside every policy.\n */\nexport const RLS_IS_ANONYMOUS_SQL = `${REBASE_SCHEMA}.is_anonymous()`;\n\n/** The request's JWT claims as `jsonb`, or `{}`. */\nexport const RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;\n\n/**\n * The pre-1.0 spellings, for recognising policies and hand-written SQL that\n * predate the move.\n *\n * Kept because policies outlive the server that wrote them: a database migrated\n * by an older release still holds `auth.uid()` in its policy bodies until the\n * next push or boot recompiles them, and anything that reads policies back has\n * to recognise both eras or report the framework's own output as foreign drift.\n * Also used to give a project whose `securityRules` contain raw `auth.uid()` a\n * message naming the replacement, instead of a parse failure.\n */\nexport const LEGACY_RLS_SCHEMA = \"auth\";\nexport const LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;\nexport const LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;\nexport const LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;\n\n/**\n * Rewrites the pre-1.0 function calls in a fragment of policy SQL.\n *\n * Deliberately anchored on a word boundary and the schema qualifier, so a column\n * called `auth_uid` or a table named `auth` is left alone.\n */\nexport function rewriteLegacyRlsFunctions(sql: string): string {\n return sql.replace(\n /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/gi,\n (_match, fn: string) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`\n );\n}\n\n/** Whether a fragment of SQL still calls the pre-1.0 functions. */\nexport function usesLegacyRlsFunctions(sql: string): boolean {\n return /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/i.test(sql);\n}\n","import { ALL_WHERE_FILTER_OPS, WhereFilterOp } from \"./filter-operators\";\n\n/**\n * Describes the capabilities and features supported by a data source (driver).\n *\n * Each driver (Postgres, Firebase, etc.) declares which features it\n * supports. The admin uses this descriptor to:\n * - Show/hide editor tabs (e.g. Relations for SQL, Subcollections for Firebase)\n * - Filter the property type picker (e.g. `relation` for SQL, `reference` for Firebase)\n * - Toggle driver-specific form controls (e.g. `columnType` for SQL)\n *\n * @group Models\n */\nexport interface DataSourceCapabilities {\n /** Unique driver key (e.g. \"postgres\", \"firestore\") */\n key: string;\n\n /** Human-readable label for the UI (e.g. \"PostgreSQL\", \"Firebase / Firestore\") */\n label: string;\n\n // ── Feature flags ─────────────────────────────────────────────────\n /** Does this source support SQL-style relations (JOINs)? */\n supportsRelations: boolean;\n\n /** Does this source support nested subcollections? */\n supportsSubcollections: boolean;\n\n /** Does this source support Row Level Security policies? */\n supportsRLS: boolean;\n\n /** Does this source support document references (Firebase-style)? */\n supportsReferences: boolean;\n\n /** Does this source support SQL column type annotations? */\n supportsColumnTypes: boolean;\n\n /** Does this source support real-time listeners? */\n supportsRealtime: boolean;\n\n /**\n * Does this source store vectors natively?\n *\n * `VectorProperty` carries a `dimensions` and is pgvector-shaped. It was\n * the one driver-specific property kind with no flag to gate it, so unlike\n * every other field in this descriptor there was not even a runtime answer\n * to appeal to — a Firestore collection could declare an embedding column\n * and no driver would do anything with it.\n */\n supportsVectors: boolean;\n\n /**\n * Canonical filter operators this engine can execute.\n *\n * The admin UI intersects this set with the property-type defaults and\n * any per-property narrowing (`property.ui.filterOperators`) to decide\n * which operators to offer in filter fields — so an engine that cannot\n * run `ilike` (e.g. Firestore) never shows a \"Contains\" filter that\n * would throw at query time.\n */\n filterOperators: readonly WhereFilterOp[];\n\n /**\n * Relation kinds this engine's driver can compile into a filter.\n *\n * Only `belongsTo` puts a column on the row being filtered; the others are\n * answered with a correlated subquery over the junction or the target\n * table, which not every driver can build. An engine with no relations at\n * all declares none.\n *\n * The admin uses this to decide whether a relation column offers a filter\n * control. Offering one an engine cannot answer is not cosmetic: a driver\n * that drops the key it cannot resolve *widens* the read to every row, and\n * one that fails closed answers a control the admin itself put on screen\n * with a 400.\n *\n * Optional, so a third-party driver registered before this existed still\n * compiles. Omitted means {@link DEFAULT_FILTERABLE_RELATION_KINDS} — the\n * one kind that is a plain column comparison, which every relational\n * driver can do. The subquery kinds are a real capability and have to be\n * claimed rather than assumed: assuming them wrongly is the widening.\n */\n filterableRelationKinds?: readonly string[];\n\n /**\n * Can a filter address a *column of the related row* — `applications.status`\n * — rather than only the related row's id?\n *\n * A separate capability from {@link filterableRelationKinds} because it is\n * a separate subquery: the id filter stops at the junction, one of these\n * reaches the target table and compares one of its columns. A driver can\n * do the first and not the second.\n *\n * Optional and defaulting to **false**, for the reason the relation kinds\n * default narrow: an unclaimed capability that the admin assumes is there\n * produces a control whose query the driver answers by dropping the key —\n * and a dropped filter key widens the read to every row.\n *\n * Meaningless without {@link supportsRelations}; a driver with no relations\n * has nothing to reach through.\n */\n supportsRelationFieldFilters?: boolean;\n\n /**\n * Can a sort key be an aggregate over a to-many relation — \"oldest waiting\n * first\", \"busiest first\"?\n *\n * Compiled as a correlated scalar subquery in `ORDER BY`, which a document\n * store cannot express at all. Optional and defaulting to **false**.\n *\n * A wrongly claimed sort capability fails differently from a wrongly\n * claimed filter one, and worse in one respect: a driver that cannot\n * resolve the key drops the `ORDER BY` and answers 200 with rows in\n * whatever order the database pleased, which reads as a sorted list. Paging\n * over that repeats and skips rows.\n */\n relationAggregateSorts?: boolean;\n\n // ── Admin capability flags ───────────────────────────────────────\n /** Does this source support SQL admin operations (SQL editor, EXPLAIN, etc.)? */\n supportsSQLAdmin: boolean;\n\n /** Does this source support schema admin (unmapped tables, table metadata)? */\n supportsSchemaAdmin: boolean;\n}\n\n/**\n * Subset of DataSourceCapabilities containing only feature flags.\n * Useful when you only need to check capabilities without UI metadata.\n * @group Models\n */\nexport type DataSourceFeatures = Omit<DataSourceCapabilities, \"key\" | \"label\">;\n\n/**\n * The default data-source key, used when a collection does not name a\n * `dataSource`. Shared by the frontend router and the backend driver\n * registry so both agree on \"the default database\".\n * @group Models\n */\nexport const DEFAULT_DATA_SOURCE_KEY = \"(default)\";\n\n/**\n * How the *frontend* reaches a data source.\n *\n * - `\"server\"` — through the Rebase backend (the `RebaseClient`). The backend\n * holds the actual database adapter and routes by data-source key. This is\n * the default and covers Postgres, the only server engine.\n * - `\"direct\"` — straight from the client to the external backend via its own\n * SDK driver (e.g. Firestore). The Rebase backend is not in the data path.\n * - `\"custom\"` — a developer-supplied {@link DataDriver}, transport unspecified.\n *\n * @group Models\n */\nexport type DataSourceTransport = \"server\" | \"direct\" | \"custom\";\n\n/**\n * Declarative definition of a data source — a named place data lives.\n *\n * Declared once and shared front and back: the frontend uses it to decide\n * transport (client vs direct driver), the backend uses the same `key` to\n * resolve a database adapter, and the editor derives capabilities from\n * `engine`. Collections reference a definition by its `key` via\n * `collection.dataSource`.\n *\n * @group Models\n */\nexport interface DataSourceDefinition {\n /**\n * Unique identifier for this data source. Collections point at it via\n * `dataSource`. Defaults to {@link DEFAULT_DATA_SOURCE_KEY}.\n */\n key: string;\n\n /**\n * The engine backing this data source (e.g. `\"postgres\"`,\n * `\"firestore\"`, or a custom id). Determines the\n * {@link DataSourceCapabilities} surfaced in the editor.\n */\n engine: string;\n\n /**\n * How the frontend reaches this source. Optional — when omitted it is\n * inferred: `\"direct\"` if the definition carries a client-side driver,\n * `\"server\"` otherwise.\n */\n transport?: DataSourceTransport;\n\n /**\n * The physical database/schema/Firestore-database within the engine.\n * Threaded to drivers/adapters as the existing `databaseId` runtime\n * parameter. Defaults to the engine's own default.\n */\n databaseId?: string;\n\n /** Human-readable label for the UI. */\n label?: string;\n}\n\n/**\n * The resolved data source for a collection: the single source of truth that\n * the frontend router, backend registry, and editor all derive from.\n * Produced by `resolveDataSource(collection, registry)`.\n *\n * @group Models\n */\nexport interface ResolvedDataSource {\n /** Data-source key (routing key, shared front + back). */\n key: string;\n /** Engine backing the source (drives capabilities). */\n engine: string;\n /** Frontend transport. */\n transport: DataSourceTransport;\n /** Within-engine instance, if any (the `databaseId` runtime param). */\n databaseId?: string;\n /** Capabilities derived from {@link engine}. */\n capabilities: DataSourceCapabilities;\n}\n\n/**\n * Relation kinds assumed filterable when a driver does not say.\n *\n * `belongsTo` alone: its filter is a comparison on a column of the row being\n * filtered, the one shape that needs no query construction a driver might not\n * have. Everything else is a correlated subquery over another table.\n *\n * @group Models\n */\nexport const DEFAULT_FILTERABLE_RELATION_KINDS: readonly string[] = [\"belongsTo\"];\n\n// ── Built-in driver capabilities ─────────────────────────────────────\n\n/** @group Models */\nexport const POSTGRES_CAPABILITIES: DataSourceCapabilities = {\n key: \"postgres\",\n label: \"PostgreSQL\",\n supportsRelations: true,\n supportsSubcollections: false,\n supportsRLS: true,\n supportsReferences: false,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // `via` is absent: its join path is authored source → target with no\n // stated inverse, so the driver has nothing to reverse into a filter.\n filterableRelationKinds: [\"belongsTo\", \"manyToMany\", \"hasMany\", \"hasOne\"],\n supportsRelationFieldFilters: true,\n relationAggregateSorts: true,\n supportsSQLAdmin: true,\n supportsSchemaAdmin: true\n};\n\n/** @group Models */\nexport const FIREBASE_CAPABILITIES: DataSourceCapabilities = {\n key: \"firestore\",\n label: \"Firebase / Firestore\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: true,\n supportsVectors: false,\n // Firestore has no SQL pattern matching — the driver throws on the LIKE\n // family, so the UI must never offer it.\n filterOperators: ALL_WHERE_FILTER_OPS.filter(op =>\n op !== \"like\" && op !== \"ilike\" && op !== \"not-like\" && op !== \"not-ilike\"\n // Firestore matches one element or any of a list; no query asks for all of them, or for none outside one.\n && op !== \"array-contains-all\" && op !== \"array-contained-by\"),\n // No relations at all — a document store links by reference. Nothing to\n // reach through, so neither of the two relation-reaching features either.\n filterableRelationKinds: [],\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: false,\n supportsSchemaAdmin: false\n};\n\n/**\n * Fallback capabilities when the driver is unknown.\n * Enables everything so nothing is hidden unexpectedly.\n * @group Models\n */\nexport const DEFAULT_CAPABILITIES: DataSourceCapabilities = {\n key: \"(default)\",\n label: \"Default\",\n supportsRelations: true,\n supportsSubcollections: true,\n supportsRLS: true,\n supportsReferences: true,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // The exception to this descriptor's \"enable everything\" rule. The other\n // flags hide a tab or a picker when they are wrong; this one decides\n // whether a query is sent that an unknown driver may answer by dropping\n // the condition — which returns every row rather than none.\n filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,\n // Narrow for the same reason, and more sharply. An unknown driver that is\n // assumed to compile these answers by dropping the key: the filter widens\n // the read to every row, and the sort comes back unordered while looking\n // sorted. Both have to be claimed.\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: true,\n supportsSchemaAdmin: true\n};\n\nconst BUILT_IN_CAPABILITIES: ReadonlyMap<string, DataSourceCapabilities> = new Map([\n [\"postgres\", POSTGRES_CAPABILITIES],\n [\"firestore\", FIREBASE_CAPABILITIES],\n [\"(default)\", DEFAULT_CAPABILITIES]\n]);\n\n/**\n * Capabilities registered at runtime, on `globalThis` rather than in a module\n * local: a third-party driver inlines its own copy of this package and\n * registers through it, while the app and the server read through theirs. A\n * module local made the registration land in a copy nobody else reads.\n * See `module-state-across-copies.test.ts`.\n */\nconst REGISTERED_CAPABILITIES_KEY = Symbol.for(\"@rebasepro/types.dataSourceCapabilities.v1\");\n\ntype GlobalWithCapabilities = typeof globalThis & {\n [REGISTERED_CAPABILITIES_KEY]?: Map<string, DataSourceCapabilities>;\n};\n\nfunction registeredCapabilities(): Map<string, DataSourceCapabilities> {\n const g = globalThis as GlobalWithCapabilities;\n let registered = g[REGISTERED_CAPABILITIES_KEY];\n if (!registered) {\n registered = new Map();\n g[REGISTERED_CAPABILITIES_KEY] = registered;\n }\n return registered;\n}\n\n/**\n * Look up capabilities for a given engine key.\n * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.\n * @group Models\n */\nexport function getDataSourceCapabilities(engine?: string): DataSourceCapabilities {\n if (!engine) return POSTGRES_CAPABILITIES; // postgres is the default engine\n return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;\n}\n\n/**\n * Register custom capabilities for a third-party driver.\n * @group Models\n */\nexport function registerDataSourceCapabilities(capabilities: DataSourceCapabilities): void {\n registeredCapabilities().set(capabilities.key, capabilities);\n}\n","/**\n * The resource graph: one declaration site for every named thing a project needs.\n *\n * ## The rule\n *\n * **Every named resource is declared with a constructor in config code.** A\n * database, a bucket, a topic and whatever kind comes next are all spelled the\n * same way, so \"where do I declare my second one\" has one answer instead of one\n * answer per kind.\n *\n * ```ts\n * export const main = database(\"main\");\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * export const signups = topic<SignupEvent>(\"signups\");\n * ```\n *\n * ## Declaration is not binding\n *\n * A declaration says a resource *exists* and what shape it has. It never says\n * how to reach it — that is a property of the environment, not of the project,\n * and it differs between a laptop, a self-hosted box and a tenant in the cloud.\n * Binding lives in `@rebasepro/server`'s boot path, where each kind registers\n * the resolver that reads its environment variables, keyed off the logical\n * name declared here.\n *\n * This split is the whole point. Before it, storage topology was hand-written\n * into `rebase.json` while database topology lived in TypeScript, and the\n * boundary between them was a fact about what the control plane could read\n * before a build — a platform implementation detail that a developer had no way\n * to derive. Worse, storage could be declared in *both* places, and the merge\n * silently kept the JSON's engine and discarded the code's.\n *\n * ## Why a registry rather than a fixed union\n *\n * Kinds register themselves. Adding pub/sub, a cache or a search index must not\n * require editing a manifest schema, a validator and three switch statements —\n * that cost is exactly why the last two kinds ended up in different homes.\n */\n\n/** How a client reaches a resource. */\nexport type ResourceTransport =\n /** Through the backend. The default, and the only one that needs no client SDK. */\n | \"server\"\n /** A provider SDK talks to the resource directly; the backend is not in the path. */\n | \"direct\";\n\n/**\n * A resource kind, as registered.\n *\n * `engines` is an allowlist rather than documentation. An unrecognised engine\n * used to be a free string that passed every check and failed later, further\n * from the typo that caused it — `\"s2\"` for `\"s3\"` reached the runtime. Anything\n * genuinely outside the list is spelled `custom:<id>`, which says so at the call\n * site instead of looking like a typo.\n */\nexport interface ResourceKindSpec {\n /** The kind's name, as it appears in a declaration and in the graph. */\n kind: string;\n /**\n * Which definition of this kind this is. Bump it whenever anything else in\n * the spec changes.\n *\n * Two copies of this package can meet in one process — a published driver\n * inlines it into its dist, and the runtime image ships its own — and the\n * registry is shared between them on purpose. Without a revision the only\n * thing the registry can do with two specs that differ is refuse, and a\n * refusal at driver load is a pod that never boots: every bundle built with\n * a driver older than the change dies on the first image that carries it.\n * With one, the higher revision wins whichever copy loads first, and the\n * older copy is told so. Missing means 0, which is what every copy shipped\n * before revisions existed reports.\n *\n * Only copies that know about revisions honour them. A copy published\n * BEFORE they existed still compares the whole literal and throws, so a\n * kind that has shipped in such a copy cannot change its literal at all —\n * not even to add this field. Correct those kinds with `amendResourceKind`.\n */\n revision?: number;\n /** Engines this kind ships with. `custom:<id>` is always additionally valid. */\n engines: readonly string[];\n /** Used when a declaration names none. */\n defaultEngine: string;\n /**\n * Environment variable base names this kind binds from, in the order a\n * binder should try them. A resource keyed `analytics` reads\n * `<BASE>__ANALYTICS`; the default-keyed resource reads `<BASE>` unsuffixed,\n * so a single-resource project configured the obvious way declares nothing.\n */\n envBases: readonly string[];\n /**\n * The subset of `envBases` that matters for a given engine.\n *\n * The binder reads every base and takes whichever is set — harmless, and it\n * keeps binding tolerant. A GENERATOR cannot be that relaxed: `rebase eject\n * infra` writing S3_BUCKET, GCS_BUCKET, STORAGE_BUCKET and\n * STORAGE_PUBLIC_URL for a `local` bucket hands somebody four variables of\n * which three are noise, and a config file full of irrelevant keys is one\n * nobody reads carefully.\n *\n * Keyed by engine; an engine with no entry falls back to all of them, which\n * is the honest answer for one this package has never heard of.\n */\n envBasesByEngine?: Readonly<Record<string, readonly string[]>>;\n /** Option keys this kind accepts beyond the common ones, for validation. */\n optionKeys?: readonly string[];\n /**\n * Whether a project implicitly has one of these even when it declares\n * nothing. True for databases — a backend without one is not a backend —\n * and false for topics, where zero is the normal number.\n */\n implicitDefault?: boolean;\n}\n\n/** The key a resource takes when a project declares only one of its kind. */\nexport const DEFAULT_RESOURCE_KEY = \"(default)\";\n\n/** A declared resource, as it appears in the graph. */\nexport interface ResourceDeclaration {\n kind: string;\n /** Unique within its kind. What a binder looks up and what an env suffix is built from. */\n key: string;\n engine: string;\n transport: ResourceTransport;\n label?: string;\n /** Kind-specific options, validated against the kind's `optionKeys`. */\n options: Readonly<Record<string, unknown>>;\n /**\n * What in the project reaches this resource, as `<what>:<name>` — a\n * `collection:posts` routed to a database, a `property:posts.cover` stored\n * in a bucket, a `function:report` importing a handle.\n *\n * Recorded by the derive step, never by a constructor: a declaration says\n * a resource exists, and only a reader that has evaluated the rest of the\n * project can say who uses it. It is the map a host needs to split a\n * monolith into units later, and the map a console needs to answer \"what\n * breaks if I remove this\". Absent when nothing was recorded, which is\n * different from an empty list.\n */\n usedBy?: readonly string[];\n}\n\n/**\n * The value a constructor returns.\n *\n * Carries its own declaration so config code can hold it and pass it around,\n * and stringifies to its key so it drops into the places that still take one.\n * Collections name a data source by string today; a handle works there without\n * the collection API having to change, which keeps this a config redesign\n * rather than a rewrite of the data layer.\n */\nexport interface ResourceHandle extends ResourceDeclaration {\n toString(): string;\n}\n\nconst BRAND = Symbol.for(\"@rebasepro/types.resource\");\n\n/** Whether a value is a resource handle rather than a plain string key. */\nexport function isResourceHandle(value: unknown): value is ResourceHandle {\n return typeof value === \"object\" && value !== null && BRAND in value;\n}\n\n/**\n * A reference to a resource where a key is expected: the handle a constructor\n * returned, or the key spelled as a string.\n *\n * The handle is the point. `dataSource: analytics` is the same name spelled\n * once — rename the export and every use follows, jump-to-definition lands on\n * the declaration, and the derive step can record who uses what. The string\n * form stays because a key has to survive serialisation: the runtime and the\n * admin UI read collections as plain data, where a handle cannot travel.\n */\nexport type ResourceRef = string | ResourceHandle;\n\n/** The key a resource reference names, whether it is a handle or already a key. */\nexport function resourceKeyOf(ref: ResourceRef): string {\n return isResourceHandle(ref) ? ref.key : ref;\n}\n\n/**\n * Replace every resource handle inside a value with its key, deeply.\n *\n * Applied where authored config becomes data: `defineCollection`, the\n * collection loaders, the derive step. Past that point a collection is plain\n * data that serialises, compares with `===` and reaches the admin UI over the\n * wire, so a handle must not survive into it. Plain objects and arrays are\n * walked; anything else — a function, a Date, a class instance — is a leaf and\n * is returned as it is, which is what keeps callbacks and validators intact.\n */\nexport function resolveResourceRefs<T>(value: T): T {\n if (isResourceHandle(value)) return value.key as T;\n // Identity-preserving: a value with no handle inside comes back as the\n // same object, not a copy. Collections point at each other through\n // `target: () => authors`, and a loader that cloned every collection would\n // leave those closures returning the originals while everything else\n // held the copies. A collection that `defineCollection` already\n // normalised passes through here untouched.\n if (Array.isArray(value)) {\n let changed = false;\n const out = value.map(item => {\n const next = resolveResourceRefs(item);\n if (next !== item) changed = true;\n return next;\n });\n return (changed ? out : value) as T;\n }\n if (value !== null && typeof value === \"object\") {\n const proto = Object.getPrototypeOf(value);\n if (proto === Object.prototype || proto === null) {\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const next = resolveResourceRefs(v);\n if (next !== v) changed = true;\n out[k] = next;\n }\n return (changed ? out : value) as T;\n }\n }\n return value;\n}\n\n/**\n * The process-wide registry.\n *\n * Keyed off `globalThis` through a shared symbol rather than held in a module\n * local, because a module local is per *copy* of this package. A project that\n * ends up with two copies of `@rebasepro/types` — which a partially-linked\n * `node_modules` produces, and which has already caused a phantom\n * \"JWT secret not configured\" bug in this repo — would otherwise register into\n * one registry and read from the other, and see an empty graph with nothing\n * anywhere to explain it.\n *\n * `declarations` is that shared map, and stays shared: it is what a project\n * writes and what every copy has to be able to read.\n *\n * `kinds` is NOT, and the distinction is the whole point of `KINDS_KEY` below.\n */\ninterface Registry {\n /** Kinds this copy and its peers agree on — the versioned map. */\n kinds: Map<string, ResourceKindSpec>;\n /** Kinds written by a copy that predates the versioned map. Read-only here. */\n legacyKinds: Map<string, ResourceKindSpec>;\n declarations: Map<string, ResourceDeclaration>;\n}\n\nconst GLOBAL_KEY = Symbol.for(\"@rebasepro/types.resourceRegistry\");\n\n/**\n * Where kinds live, versioned — and why the version is in the symbol.\n *\n * Sharing one kinds map across copies means the copy that registers SECOND is\n * the one that runs the comparison. That copy is whatever the bundle happens to\n * carry, which for a driver is a build of this package frozen at its release —\n * so the rule enforced is the rule that shipped THEN, not the one written here.\n *\n * `revision` (390bb03cd, applied to `database` in 346df48e2) was supposed to\n * settle a disagreement between two copies, and it settles it only when the\n * copy doing the arithmetic knows what `revision` is. 0.17.0–0.17.3 do not:\n * they deep-equal the spec and throw. The runtime registers at import and a\n * driver is imported after it, so the old copy is always second, always the\n * judge, and always throws — verified by the bundle corpus on 2026-09-07,\n * which reported v0.17.3's message verbatim (\"Two packages cannot define the\n * same kind.\", no revision clause) while the runtime it ran on was 0.18.\n *\n * So copies that understand `revision` keep their kinds here, under a symbol\n * no released copy looks at, and the legacy map is left to whoever still wants\n * it. An old copy then registers into a map nobody contests, finds no existing\n * entry, and cannot throw — in any load order, which is what the previous fix\n * only claimed. Bumping this suffix again is how a future change to the\n * REGISTRATION PROTOCOL is made; a change to a kind's own definition is still\n * `revision`, among peers that share this map.\n */\nconst KINDS_KEY = Symbol.for(\"@rebasepro/types.resourceKinds.v2\");\n\nfunction registry(): Registry {\n const g = globalThis as Record<symbol, unknown>;\n let shared = g[GLOBAL_KEY] as { kinds: Map<string, ResourceKindSpec>; declarations: Map<string, ResourceDeclaration> } | undefined;\n if (!shared) {\n // `kinds` is created but never written by this copy: an older copy's\n // own `registry()` returns this object as-is once it exists, and would\n // throw on `undefined.get` if the property were absent.\n shared = { kinds: new Map(), declarations: new Map() };\n g[GLOBAL_KEY] = shared;\n }\n let kinds = g[KINDS_KEY] as Map<string, ResourceKindSpec> | undefined;\n if (!kinds) {\n kinds = new Map();\n g[KINDS_KEY] = kinds;\n }\n return { kinds, legacyKinds: shared.kinds, declarations: shared.declarations };\n}\n\n/**\n * Every kind visible to this copy: the versioned map, plus anything only a\n * legacy copy registered.\n *\n * The fallback is not for Rebase's own kinds — this copy defines all of those —\n * but for a third-party driver built against an older `@rebasepro/types` that\n * registers a kind of its own. Dropping it would make that kind invisible and\n * turn `declareResource` into \"unknown resource kind\" for something genuinely\n * registered.\n */\nfunction visibleKinds(): Map<string, ResourceKindSpec> {\n const { kinds, legacyKinds } = registry();\n if (legacyKinds.size === 0) return kinds;\n const merged = new Map(legacyKinds);\n for (const [k, v] of kinds) merged.set(k, v);\n return merged;\n}\n\n/**\n * Corrections this copy applies on top of a registered kind.\n *\n * Deliberately a module local — per COPY of this package — where the registry\n * above is deliberately shared. A published driver inlines this package into\n * its dist, and the copy it carries compares the shared registry's entry for a\n * kind against its own literal by `JSON.stringify` and throws if they differ\n * (see `registerResourceKind` before revisions existed). That code is in the\n * field and cannot be changed, so the registered literal of any kind that has\n * ever shipped is frozen: change one enumerable key and every bundle built with\n * an older driver dies at driver load on the next image. What a kind actually\n * binds can still be corrected — here, read through `resourceKind()` and\n * everything built on it, invisible to the older copy, which keeps binding the\n * way it did when it was published.\n */\ntype KindAmendment = Partial<Pick<ResourceKindSpec, \"envBases\" | \"envBasesByEngine\" | \"optionKeys\">>;\nconst amendments = new Map<string, KindAmendment>();\n\n/**\n * Correct a registered kind without touching its registered literal.\n *\n * Use this, never an edit to the literal, for a kind that has shipped in a\n * published package. The amendment applies to reads through this copy only.\n */\nexport function amendResourceKind(kind: string, amendment: KindAmendment): void {\n amendments.set(kind, { ...amendments.get(kind), ...amendment });\n}\n\n/** A registered kind as this copy sees it: the shared literal plus this copy's amendments. */\nfunction effectiveKind(spec: ResourceKindSpec): ResourceKindSpec {\n const amendment = amendments.get(spec.kind);\n return amendment ? { ...spec, ...amendment } : spec;\n}\n\n/** `kind:key`, the graph's primary key. */\nfunction declarationId(kind: string, key: string): string {\n return `${kind}:${key}`;\n}\n\n/**\n * Register a resource kind.\n *\n * Idempotent for an identical spec. When a spec for the same kind is already\n * registered and differs, the `revision` decides: the higher one is kept and\n * the other copy is warned about, in either load order. Two different specs at\n * the SAME revision are a genuine conflict — two packages defining one kind, or\n * a change that forgot to bump — and still throw.\n *\n * Both copies in that comparison are peers on `KINDS_KEY`, which is what makes\n * the rule enforceable: a copy old enough not to know `revision` writes to the\n * legacy map instead and never reaches this function's arithmetic. Registering\n * a kind an older copy already put in the legacy map is therefore not a\n * conflict — it is the ordinary case, and `visibleKinds` prefers this one.\n */\nexport function registerResourceKind(spec: ResourceKindSpec): void {\n const kinds = registry().kinds;\n const existing = kinds.get(spec.kind);\n if (!existing) {\n kinds.set(spec.kind, spec);\n return;\n }\n if (JSON.stringify(existing) === JSON.stringify(spec)) return;\n\n const have = existing.revision ?? 0;\n const incoming = spec.revision ?? 0;\n if (have === incoming) {\n throw new Error(\n `Resource kind \"${spec.kind}\" is already registered with a different definition at revision ${have}. ` +\n \"Two packages cannot define the same kind; a newer definition of the same kind must carry a higher `revision`.\"\n );\n }\n const [kept, dropped] = incoming > have ? [spec, existing] : [existing, spec];\n if (kept === spec) kinds.set(spec.kind, spec);\n // No logger below @rebasepro/server, and this runs in browsers too.\n console.warn(\n `[resources] Resource kind \"${spec.kind}\" is registered twice, at revisions ${dropped.revision ?? 0} and ` +\n `${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types ` +\n \"inlined in a driver built before the kind changed — rebuild the project with a current driver to remove it.\"\n );\n}\n\n/** Every registered kind, for validators and for `rebase doctor`. */\nexport function resourceKinds(): ResourceKindSpec[] {\n return [...visibleKinds().values()].map(effectiveKind);\n}\n\n/** One registered kind, or undefined. */\nexport function resourceKind(kind: string): ResourceKindSpec | undefined {\n const spec = visibleKinds().get(kind);\n return spec && effectiveKind(spec);\n}\n\n/** Options every kind accepts. */\nexport interface DeclareOptions {\n engine?: string;\n transport?: ResourceTransport;\n label?: string;\n [option: string]: unknown;\n}\n\nconst COMMON_OPTION_KEYS = [\"engine\", \"transport\", \"label\"] as const;\n\n/** Whether an engine is one the kind knows, or an explicit `custom:` opt-out. */\nexport function isValidEngine(spec: ResourceKindSpec, engine: string): boolean {\n return engine.startsWith(\"custom:\") || spec.engines.includes(engine);\n}\n\n/**\n * Declare a resource. The primitive every kind's constructor is built from.\n *\n * Redeclaring the same `kind:key` with a *different* shape throws rather than\n * merging. Merging is what the old storage path did, and it silently discarded\n * one of the two engines — a declaration accepted and then ignored, which is\n * the failure this whole model exists to remove. Redeclaring it identically is\n * fine: a config module evaluated twice must not be an error.\n */\nexport function declareResource(\n kind: string,\n key: string = DEFAULT_RESOURCE_KEY,\n options: DeclareOptions = {}\n): ResourceHandle {\n const spec = resourceKind(kind);\n if (!spec) {\n const known = [...visibleKinds().keys()].sort().join(\", \") || \"none\";\n throw new Error(\n `Unknown resource kind \"${kind}\". Registered kinds: ${known}. ` +\n \"Call registerResourceKind() before declaring one.\"\n );\n }\n\n if (!key || typeof key !== \"string\" || key.trim() === \"\") {\n throw new Error(`A ${kind} needs a non-empty key.`);\n }\n\n const engine = options.engine ?? spec.defaultEngine;\n if (!isValidEngine(spec, engine)) {\n throw new Error(\n `Unknown ${kind} engine \"${engine}\" for \"${key}\". ` +\n `Known engines: ${spec.engines.join(\", \")}. ` +\n `An engine this build does not ship is spelled \"custom:${engine}\", ` +\n \"which says so at the call site rather than failing later.\"\n );\n }\n\n const allowed = new Set<string>([...COMMON_OPTION_KEYS, ...(spec.optionKeys ?? [])]);\n const unknown = Object.keys(options).filter(k => !allowed.has(k));\n if (unknown.length > 0) {\n throw new Error(\n `Unknown option(s) on ${kind} \"${key}\": ${unknown.join(\", \")}. ` +\n `A ${kind} accepts: ${[...allowed].sort().join(\", \")}.`\n );\n }\n\n const extra: Record<string, unknown> = {};\n for (const k of spec.optionKeys ?? []) {\n if (options[k] !== undefined) extra[k] = options[k];\n }\n\n const declaration: ResourceDeclaration = {\n kind,\n key,\n engine,\n transport: options.transport ?? \"server\",\n ...(options.label !== undefined ? { label: options.label } : {}),\n options: Object.freeze(extra)\n };\n\n const id = declarationId(kind, key);\n const previous = registry().declarations.get(id);\n if (previous) {\n if (JSON.stringify(previous) !== JSON.stringify(declaration)) {\n throw new Error(\n `${kind} \"${key}\" is declared twice with different configuration. ` +\n \"Declare it once and export it — two declarations of one resource is \" +\n \"the ambiguity this model exists to remove, so it is refused rather \" +\n \"than merged.\"\n );\n }\n } else {\n registry().declarations.set(id, declaration);\n }\n\n const handle = {\n ...declaration,\n toString() { return key; },\n [BRAND]: true as const\n };\n return handle as ResourceHandle;\n}\n\n/** Every declared resource, in declaration order, optionally filtered by kind. */\nexport function declaredResources(kind?: string): ResourceDeclaration[] {\n const all = [...registry().declarations.values()];\n return kind ? all.filter(r => r.kind === kind) : all;\n}\n\n/**\n * Forget every declaration, keeping registered kinds.\n *\n * For tests and for a CLI that evaluates more than one project in a process.\n * Kinds survive because they are registered by module import, which will not\n * happen a second time.\n */\nexport function resetDeclaredResources(): void {\n registry().declarations.clear();\n}\n\n/**\n * The env-var suffix a resource's bindings use: `__ANALYTICS` for `analytics`,\n * and nothing at all for the default-keyed one.\n *\n * The default takes no suffix so that a project with one database configured\n * through plain `DATABASE_URL` keeps working having declared nothing — the\n * overwhelmingly common project must not have to say so.\n */\nexport function resourceEnvSuffix(key: string): string {\n if (key === DEFAULT_RESOURCE_KEY) return \"\";\n return `__${key.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\").replace(/^_+|_+$/g, \"\")}`;\n}\n\n/**\n * Two resources of a kind whose keys differ but whose env suffixes do not.\n *\n * `media-files` and `media_files` both become `__MEDIA_FILES`, so one would\n * silently read the other's configuration. Returned rather than thrown so the\n * caller can report it with the rest of a validation pass.\n */\nexport function findEnvSuffixCollision(keys: readonly string[]): { a: string; b: string; suffix: string } | null {\n const seen = new Map<string, string>();\n for (const key of keys) {\n const suffix = resourceEnvSuffix(key);\n const previous = seen.get(suffix);\n if (previous !== undefined && previous !== key) return { a: previous, b: key, suffix };\n seen.set(suffix, key);\n }\n return null;\n}\n\n/**\n * The whole graph, as recorded in a manifest and read by a host.\n *\n * `version` is the graph format, not the project's. A host reading a graph it\n * does not understand must say so rather than provision half of it.\n */\nexport interface ResourceGraph {\n version: 1;\n resources: ResourceDeclaration[];\n}\n\n/** The current graph format version. */\nexport const RESOURCE_GRAPH_VERSION = 1 as const;\n\n/**\n * Build a graph from the current declarations, sorted for a stable diff.\n *\n * `usedBy` maps a `kind:key` id to the things that reach it. The derive step\n * supplies it after evaluating collections; a runtime building the graph at\n * boot passes nothing and gets declarations alone, which is all it binds from.\n */\nexport function buildResourceGraph(usedBy?: ReadonlyMap<string, readonly string[]>): ResourceGraph {\n const resources = declaredResources().slice().sort(\n (a, b) => a.kind.localeCompare(b.kind) || a.key.localeCompare(b.key)\n ).map(r => {\n const users = usedBy?.get(declarationId(r.kind, r.key));\n return users && users.length > 0 ? { ...r, usedBy: [...users].sort() } : r;\n });\n return { version: RESOURCE_GRAPH_VERSION, resources };\n}\n\n/** `kind:key`, the id `usedBy` maps are keyed by. Exported for the derive step. */\nexport function resourceId(kind: string, key: string): string {\n return declarationId(kind, key);\n}\n\n/**\n * The environment variables worth writing for a resource, given its engine.\n *\n * Falls back to every base the kind reads when the engine is unknown — a\n * `custom:` engine gets the full list rather than an empty one, because\n * guessing narrow would silently omit the variable it actually needs.\n */\nexport function envBasesForResource(declaration: ResourceDeclaration): readonly string[] {\n const spec = resourceKind(declaration.kind);\n if (!spec) return [];\n return spec.envBasesByEngine?.[declaration.engine] ?? spec.envBases;\n}\n","/**\n * The kinds Rebase ships, and the constructors a project declares them with.\n *\n * Each kind is registered rather than hardcoded, so a fourth one arrives\n * without editing a manifest schema, a validator and a switch statement. That\n * cost is precisely why databases and buckets ended up declared in different\n * files with different rules — the cheapest thing to do was always to bolt the\n * new kind onto whichever home was nearest.\n *\n * A kind owns its engine list. `custom:<id>` is always accepted, so a build\n * that ships an engine this package has never heard of says so at the call site\n * instead of looking like a typo of one that exists.\n */\nimport {\n DEFAULT_RESOURCE_KEY,\n declareResource,\n declaredResources,\n amendResourceKind,\n registerResourceKind,\n type DeclareOptions,\n type ResourceDeclaration,\n type ResourceHandle\n} from \"./resources\";\nimport { DEFAULT_DATA_SOURCE_KEY, type DataSourceDefinition } from \"./data_source\";\nimport { DEFAULT_STORAGE_SOURCE_KEY, type OrphanSweepOptions, type StorageSourceDefinition } from \"./storage_source\";\n\n// ── database ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // There is no single frozen literal for this kind, which is why it carries a\n // revision. 0.17.0 and 0.17.1 shipped `optionKeys: [\"databaseId\",\n // \"migrations\"]`; 0.17.2 added \"extensions\" to the literal itself, before the\n // rule against that existed. So two different objects are inlined in drivers\n // that are in the field, and no choice of literal can equal both: a runtime\n // that matched one threw `already registered with a different definition` at\n // the other and refused to boot. Two tenants crash-looped for six and a half\n // days on exactly that.\n //\n // `revision` is what resolves it. An older copy — whichever literal it\n // carries — is at revision 0, loses to this one, and warns instead of\n // throwing. Corrections still go in the amendment below; this number moves\n // only when the literal itself has to, and every published copy predating the\n // move is thereby handled.\n //\n // The same goes for `engines`. Only \"postgres\" has a server driver — MongoDB\n // support was removed after 0.30.1 — but \"mongodb\" stays in this list because\n // removing it is an edit to the literal every published copy compares. The\n // server refuses a `database()` declared with an engine it has no driver\n // for, naming the engine, so the stale entry cannot be booted.\n revision: 1,\n kind: \"database\",\n engines: [\"postgres\", \"mongodb\", \"firestore\", \"sqlite\"],\n defaultEngine: \"postgres\",\n envBases: [\"DATABASE_URL\", \"REBASE_DRIVER\", \"REBASE_DB_POOL_MAX\"],\n optionKeys: [\"databaseId\", \"migrations\", \"extensions\"],\n implicitDefault: true\n});\n// What a database actually binds from. The 0.17.3 list named two variables\n// the resolver never read and omitted five it does (25f1a97e3).\namendResourceKind(\"database\", {\n // `rls` added by amendment, never to the literal above: every published\n // copy compares that literal, and an edit to it is what took two tenants\n // down for six days (see the comment on `revision`).\n optionKeys: [\"databaseId\", \"migrations\", \"extensions\", \"rls\"],\n envBases: [\n \"DATABASE_URL\",\n \"DATABASE_READ_URL\",\n \"DATABASE_DIRECT_URL\",\n \"DATABASE_POOLED\",\n \"ADMIN_CONNECTION_STRING\",\n \"REBASE_DRIVER\",\n \"DB_POOL_MAX\",\n \"DB_POOL_IDLE_TIMEOUT\",\n \"DB_POOL_CONNECT_TIMEOUT\"\n ]\n});\n\n/** Options a database accepts beyond the common ones. */\nexport interface DatabaseOptions extends DeclareOptions {\n /**\n * The physical database or schema within the engine, when it differs from\n * the engine's own default. Threaded to drivers as `databaseId`.\n */\n databaseId?: string;\n /** Directory of migration files, relative to the config directory. */\n migrations?: string;\n /**\n * Server extensions Rebase may install on this database.\n *\n * A permission, not a request: naming one grants leave to run\n * `CREATE EXTENSION IF NOT EXISTS <name>`, and Rebase issues it only when\n * something in the schema actually needs it. Naming an extension nothing\n * needs installs nothing.\n *\n * It has to be said out loud because installing an extension is a decision\n * with a deployment behind it — the image has to ship the library, the role\n * has to be allowed to install it, and a managed provider has to have it on\n * an allow-list. Rebase cannot see any of that from inside the connection,\n * so the answer comes from whoever chose the database.\n *\n * Today `vector` is the one that matters: a `{ type: \"vector\" }` property\n * compiles to a `VECTOR(n)` column, which does not exist until pgvector is\n * installed. Without this, Rebase creates the column and lets Postgres\n * refuse, naming the option.\n *\n * ```ts\n * export const main = database({ extensions: [\"vector\"] });\n * ```\n *\n * `pg_trgm` and `unaccent` are not on this list and need no permission: a\n * `search` block installs them unasked, because they are contrib modules\n * present in every Postgres distribution. pgvector is a separate build that\n * a stock `postgres:18` does not carry.\n */\n extensions?: string[];\n /**\n * How row-level security runs on this database — the request role and\n * everything around it. Every default is what Rebase did before the option\n * existed. Declared here rather than only on the driver because the policy\n * settings shape the SQL `rebase db generate` writes, and the CLI reads\n * this declaration as the server does. The `REBASE_RLS_*` variables win.\n *\n * ```ts\n * export const main = database({ rls: { requestRole: \"acme_user\" } });\n * ```\n *\n * See `PostgresRlsConfig` in `@rebasepro/server-postgres` for each setting,\n * and the forms only code can give (a function for the role or identity).\n */\n rls?: DatabaseRlsOptions;\n}\n\n/**\n * The data-only `rls` settings a database declaration takes. The driver's own\n * `rls` block (`PostgresRlsConfig`) accepts these and the function forms.\n */\nexport interface DatabaseRlsOptions {\n requestRole?: string | { anonymous: string; signedIn: string };\n provisionRole?: \"auto\" | \"never\";\n grants?: \"schema\" | \"managed\" | \"none\";\n policyTarget?: \"public\" | \"requestRole\";\n adminPolicies?: \"adminRole\" | \"public\";\n defaultPolicies?: boolean;\n /**\n * `false` serves this database's declared tables even when it does not\n * enforce their `rls` (row-level security off, declared policies\n * missing): for a database whose schema something else owns and whose\n * access the app enforces. A table's own `rlsRequired` wins. Default\n * `true`: such a table is withheld (503 TABLE_WITHHELD).\n */\n required?: boolean;\n inheritRoles?: string[];\n identity?: \"rebase\" | \"supabase\";\n sharedRole?: \"warn\" | \"refuse\" | \"ignore\";\n}\n\n/** A database handle. Collections point at it via `dataSource`. */\nexport type DatabaseHandle = ResourceHandle;\n\n/**\n * Declare a database.\n *\n * ```ts\n * export const main = database(); // the default one\n * export const analytics = database(\"analytics\"); // reads DATABASE_URL__ANALYTICS\n * export const withPgv = database({ extensions: [\"vector\"] }); // the default one, configured\n * ```\n *\n * The third form exists because the default database has no name to pass, and\n * the alternative was `database(\"(default)\", { … })` — writing out an internal\n * sentinel to reach the options. A key is a string and options are an object,\n * so the two can never be confused for one another.\n */\nexport function database(options?: DatabaseOptions): DatabaseHandle;\nexport function database(key?: string, options?: DatabaseOptions): DatabaseHandle;\nexport function database(\n keyOrOptions: string | DatabaseOptions = DEFAULT_RESOURCE_KEY,\n options: DatabaseOptions = {}\n): DatabaseHandle {\n return typeof keyOrOptions === \"string\"\n ? declareResource(\"database\", keyOrOptions, options)\n : declareResource(\"database\", DEFAULT_RESOURCE_KEY, keyOrOptions);\n}\n\n/**\n * The extensions the project's databases gave Rebase leave to install.\n *\n * A flat union rather than a per-database answer, because the surfaces that ask\n * — `rebase db push` and the boot schema-ensure — drive one connection and\n * generate one `schema.sql` for every collection regardless of `dataSource`.\n * Splitting the permission by data source would be a distinction the rest of\n * that pipeline does not make, and a false precision is worse than none.\n *\n * Empty for a project that declared nothing, which is every project that has\n * not opted in — so this reads as a refusal by default, on purpose.\n */\nexport function declaredDatabaseExtensions(): readonly string[] {\n const names = new Set<string>();\n for (const declaration of declaredResources(\"database\")) {\n const declared = declaration.options.extensions;\n if (!Array.isArray(declared)) continue;\n for (const name of declared) {\n if (typeof name === \"string\" && name.trim()) names.add(name.trim());\n }\n }\n return [...names].sort();\n}\n\n/** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */\nexport function declaredDatabaseRls(key: string = DEFAULT_DATA_SOURCE_KEY): DatabaseRlsOptions {\n const declaration = declaredResources(\"database\").find((d) => d.key === key);\n const rls = declaration?.options.rls;\n return rls && typeof rls === \"object\" ? rls as DatabaseRlsOptions : {};\n}\n\n/**\n * The policy settings every compile path must agree on — the boot's policy\n * ensure, `rebase db generate`, the drift check — read from the one place all\n * of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /\n * `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults\n * are what Rebase compiled before these existed, except `adminPolicies`, whose\n * default (`\"adminRole\"`) changed what the server-or-admin policies are `TO`.\n *\n * Browser-safe: where there is no `process`, only the declaration counts.\n */\nexport function declaredRlsPolicyShape(dataSource: string = DEFAULT_DATA_SOURCE_KEY): {\n policyTarget: \"public\" | \"requestRole\";\n adminPolicies: \"adminRole\" | \"public\";\n defaultPolicies: boolean;\n} {\n const declared = declaredDatabaseRls(dataSource);\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();\n const envAdmin = env?.REBASE_RLS_ADMIN_POLICIES?.trim();\n const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();\n return {\n policyTarget: envTarget === \"requestRole\" || envTarget === \"public\"\n ? envTarget\n : declared.policyTarget === \"requestRole\" ? \"requestRole\" : \"public\",\n adminPolicies: envAdmin === \"adminRole\" || envAdmin === \"public\"\n ? envAdmin\n : declared.adminPolicies === \"public\" ? \"public\" : \"adminRole\",\n defaultPolicies: envDefaults === \"false\" ? false : envDefaults === \"true\" ? true : declared.defaultPolicies !== false\n };\n}\n\n// ── bucket ───────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // FROZEN at the 0.17.3 literal, for the reason given on `database`.\n kind: \"bucket\",\n engines: [\"local\", \"s3\", \"gcs\", \"azure\", \"firebase\"],\n defaultEngine: \"local\",\n envBases: [\"S3_BUCKET\", \"GCS_BUCKET\", \"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n envBasesByEngine: {\n local: [\"STORAGE_BUCKET\"],\n s3: [\"S3_BUCKET\", \"STORAGE_ENDPOINT\", \"STORAGE_REGION\", \"STORAGE_PUBLIC_URL\"],\n gcs: [\"GCS_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n azure: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n firebase: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"]\n },\n optionKeys: [\"publicRead\", \"prefix\", \"account\"],\n implicitDefault: false\n});\n// What a bucket actually binds from, per engine (25f1a97e3), plus `default`:\n// the registry no longer promotes a lone named bucket, so a project needs a way\n// to say which one serves unqualified uploads. The literal above is frozen, so\n// the new option key arrives here.\namendResourceKind(\"bucket\", {\n // `orphanSweep` arrived the same way, after `default`.\n optionKeys: [\"publicRead\", \"prefix\", \"account\", \"default\", \"orphanSweep\"],\n envBases: [\n \"STORAGE_TYPE\",\n \"STORAGE_PATH\",\n \"S3_BUCKET\",\n \"S3_REGION\",\n \"S3_ACCESS_KEY_ID\",\n \"S3_SECRET_ACCESS_KEY\",\n \"S3_ENDPOINT\",\n \"S3_FORCE_PATH_STYLE\",\n \"GCS_BUCKET\",\n \"GCS_PROJECT_ID\",\n \"GCS_KEY_FILENAME\",\n // The largest file the source accepts, read for every engine.\n \"STORAGE_MAX_FILE_SIZE\"\n ],\n envBasesByEngine: {\n local: [\"STORAGE_TYPE\", \"STORAGE_PATH\", \"STORAGE_MAX_FILE_SIZE\"],\n s3: [\n \"STORAGE_TYPE\",\n \"S3_BUCKET\",\n \"S3_REGION\",\n \"S3_ACCESS_KEY_ID\",\n \"S3_SECRET_ACCESS_KEY\",\n \"S3_ENDPOINT\",\n \"S3_FORCE_PATH_STYLE\",\n \"STORAGE_MAX_FILE_SIZE\"\n ],\n gcs: [\"STORAGE_TYPE\", \"GCS_BUCKET\", \"GCS_PROJECT_ID\", \"GCS_KEY_FILENAME\", \"STORAGE_MAX_FILE_SIZE\"],\n azure: [],\n firebase: []\n }\n});\n\n/** Options a bucket accepts beyond the common ones. */\nexport interface BucketOptions extends DeclareOptions {\n /**\n * Whether objects are world-readable by default.\n *\n * Declared rather than inferred from the engine, because the two have\n * disagreed before: a private object served through a cacheable public URL\n * is a data leak that nothing errors on.\n */\n publicRead?: boolean;\n /**\n * @deprecated Never applied: every object lands at the root of its bucket,\n * whatever this says, so two sources declaring one bucket share one\n * namespace. Give each source a bucket of its own (`S3_BUCKET__<KEY>`,\n * `GCS_BUCKET__<KEY>`, or `STORAGE_PATH__<KEY>` for a local one), or put\n * the folder in each storage property's `storagePath`. The backend warns\n * once at boot when it is set. Will be removed in a future release.\n */\n prefix?: string;\n /**\n * Serve unqualified uploads — a storage property with no `storageSource` —\n * from this bucket.\n *\n * Without it, declaring `bucket(\"media\")` leaves the default source where\n * it was: on its own `STORAGE_PATH` / `./uploads`, or the bucket the\n * unsuffixed `S3_BUCKET` / `GCS_BUCKET` names. Mark a named bucket to make\n * it the default instead; the files the default held before stay where\n * they are and are no longer served through it.\n */\n default?: boolean;\n /**\n * The credential set this bucket signs with, when several share one.\n *\n * `bucket(\"media\", { engine: \"s3\", account: \"minio\" })` keeps reading its own\n * `S3_BUCKET__MEDIA` — the bucket name is what distinguishes one source from\n * another and never falls back — while the provider-level variables\n * (`S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ENDPOINT`, `S3_REGION`,\n * `S3_FORCE_PATH_STYLE`) fall back to `__MINIO` when no per-key value is set.\n *\n * Fifteen buckets on one install go from ninety variables to eighteen, and\n * rotating the key becomes one edit. A per-bucket value still wins, so a\n * single source can move to another provider without breaking the rest off\n * their shared account.\n */\n account?: string;\n /**\n * Delete, on a schedule, the files in this bucket that no row names:\n * `true` for the defaults, or `{ olderThanHours, schedule }`. See\n * {@link OrphanSweepOptions}.\n *\n * ```ts\n * export const voice = bucket(\"voice\", { engine: \"gcs\", orphanSweep: { olderThanHours: 72 } });\n * ```\n */\n orphanSweep?: boolean | OrphanSweepOptions;\n}\n\n/** A bucket handle. Storage properties point at it via `storageSource`. */\nexport type BucketHandle = ResourceHandle;\n\n/**\n * Declare a bucket.\n *\n * ```ts\n * export const uploads = bucket({ engine: \"s3\" }); // the default one\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * ```\n *\n * `transport: \"direct\"` means a provider SDK talks to the bucket and the\n * backend is not in the upload path.\n *\n * The options-only form exists for the same reason `database`'s does: the\n * default bucket has no name to pass, and without it the only way to configure\n * one was `bucket(\"(default)\", { … })` — writing out an internal sentinel to\n * reach the options. Passing options where a key belongs used to throw \"a\n * bucket needs a non-empty key\", which names neither the mistake nor the fix.\n */\nexport function bucket(options?: BucketOptions): BucketHandle;\nexport function bucket(key?: string, options?: BucketOptions): BucketHandle;\nexport function bucket(\n keyOrOptions: string | BucketOptions = DEFAULT_RESOURCE_KEY,\n options: BucketOptions = {}\n): BucketHandle {\n return typeof keyOrOptions === \"string\"\n ? declareResource(\"bucket\", keyOrOptions, options)\n : declareResource(\"bucket\", DEFAULT_RESOURCE_KEY, keyOrOptions);\n}\n\n// ── topic ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // FROZEN at the 0.17.3 literal, for the reason given on `database`.\n kind: \"topic\",\n // `jobs` is the durable local implementation: a topic fans out to one job\n // row per subscription, so each subscriber retries on its own schedule and\n // a failure is a row somebody can look at rather than a lost message.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [\"REBASE_TOPIC_URL\"],\n optionKeys: [\"delivery\", \"maxAttempts\"],\n implicitDefault: false\n});\n// Nothing. A topic on the `jobs` engine is rows in the project's own database\n// and binds from no variable of its own. The literal above says\n// `REBASE_TOPIC_URL` — a name nothing in either repository read, which\n// `rebase status` then printed as a variable somebody could set — and it has to\n// keep saying it, because a driver ≤ 0.17.3 compares that object and throws.\n// The gate in `resource-env-bases.test.ts` covers every registered kind through\n// the amended view, so a phantom name fails a build rather than reaching a\n// developer.\namendResourceKind(\"topic\", { envBases: [] });\n\n/**\n * How hard the runtime tries to deliver.\n *\n * Only `at-least-once` is implemented, and it is the honest name for what a\n * retrying queue does: a handler must tolerate seeing the same event twice.\n * `at-most-once` is listed so a future transport can offer it without the\n * option changing shape, and is refused today rather than silently upgraded.\n */\nexport type TopicDelivery = \"at-least-once\" | \"at-most-once\";\n\n/** Options a topic accepts beyond the common ones. */\nexport interface TopicOptions extends DeclareOptions {\n delivery?: TopicDelivery;\n /** Attempts per subscription before a message is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a subscription does with an event.\n *\n * `attempt` counts from 1. Worth branching on: the first delivery and the\n * fourth are the same call, but the fourth is where it is worth logging loudly.\n * `signal` is aborted when the attempt runs past the job queue's `timeoutMs`.\n */\nexport type TopicHandler<T> = (\n event: T,\n context: { attempt: number; topic: string; subscription: string; signal: AbortSignal }\n) => Promise<void> | void;\n\n/** A declared subscription, as recorded in the graph and wired at boot. */\nexport interface TopicSubscription<T = unknown> {\n topic: string;\n name: string;\n handler: TopicHandler<T>;\n maxAttempts?: number;\n}\n\n/**\n * What a topic publishes through.\n *\n * Installed by `@rebasepro/server` at boot. Absent — in the CLI evaluating\n * config to derive the graph, or in a unit test — publishing throws a message\n * naming the cause, rather than resolving and dropping the event. A publish\n * that silently does nothing is the failure mode a queue exists to prevent.\n */\nexport interface TopicRuntime {\n publish(topic: string, event: unknown): Promise<void>;\n}\n\n/**\n * Declared handlers and installed runtimes, for topics and queues — on\n * `globalThis` under a shared symbol, never in module locals.\n *\n * A module local is one per COPY of this package, and two copies in one\n * process is the normal layout rather than an accident: `@rebasepro/server`\n * inlines this package into its own dist, while `config/resources.ts` imports\n * it from `node_modules`. With locals, a project's `.handler()` and\n * `.subscription()` went into the project's copy and the worker read the\n * server's empty one (`Job queue started {\"tasks\":0}`), and the runtime the\n * server installed was invisible to the project's `enqueue`/`publish` — so\n * every queue and topic threw \"no runtime is installed\" inside a running\n * backend. The CLI deriving the graph had the same split. Same mechanism and\n * reasoning as `registry()` in resources.ts; `module-state-across-copies.test.ts`\n * loads two copies to hold it, and scans for any other module-level state that\n * would split the same way.\n *\n * The version is in the symbol: a change to this object's SHAPE takes a new\n * suffix, so no copy ever reads a shape it does not know.\n */\nconst WORK_KEY = Symbol.for(\"@rebasepro/types.workRegistry.v1\");\n\ninterface WorkRegistry {\n topicRuntime: TopicRuntime | null;\n subscriptions: TopicSubscription[];\n queueRuntime: QueueRuntime | null;\n queueConsumers: Map<string, QueueConsumer>;\n}\n\ntype GlobalWithWork = typeof globalThis & { [WORK_KEY]?: WorkRegistry };\n\nfunction work(): WorkRegistry {\n const g = globalThis as GlobalWithWork;\n let shared = g[WORK_KEY];\n if (!shared) {\n shared = { topicRuntime: null, subscriptions: [], queueRuntime: null, queueConsumers: new Map() };\n g[WORK_KEY] = shared;\n }\n return shared;\n}\n\n/**\n * Where `@rebasepro/server` publishes its client once it has booted (its\n * `singleton.ts`). Read only to tell the two causes of a missing runtime apart.\n */\nconst SERVER_INSTANCE_SLOT = Symbol.for(\"@rebasepro/server:singleton-instance\");\n\ntype GlobalWithServer = typeof globalThis & { [SERVER_INSTANCE_SLOT]?: unknown };\n\n/**\n * Why there is no runtime to send through, as far as this process can tell.\n *\n * Outside a backend — the CLI evaluating config, a script, a unit test — the\n * answer is that there is nothing to deliver to. Inside one it is not: the\n * backend installs a runtime at boot for what `config/resources.ts` declared,\n * so a missing one there means boot never saw the declaration, or the backend\n * carries a copy of this package too old to share the slot it installs into.\n * Saying \"outside a backend\" to somebody whose backend is running sends them\n * looking for the wrong thing.\n */\nfunction missingRuntimeCause(kind: \"queue\" | \"topic\"): string {\n const backendUp = (globalThis as GlobalWithServer)[SERVER_INSTANCE_SLOT] != null;\n if (!backendUp) {\n return \"This works inside a running Rebase backend; this looks like code running outside one \" +\n \"(a build, a script, or a test without a harness).\";\n }\n return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot ` +\n `when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not ` +\n \"read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads — keep \" +\n \"@rebasepro/server and @rebasepro/types on the same version.\";\n}\n\n/** Install the transport topics publish through. Called by the server at boot. */\nexport function setTopicRuntime(runtime: TopicRuntime | null): void {\n work().topicRuntime = runtime;\n}\n\n/** Every declared subscription, for the worker to wire and the graph to record. */\nexport function declaredSubscriptions(topic?: string): TopicSubscription[] {\n const { subscriptions } = work();\n return topic ? subscriptions.filter(s => s.topic === topic) : subscriptions.slice();\n}\n\n/** Forget declared subscriptions. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredSubscriptions(): void {\n work().subscriptions.length = 0;\n}\n\n/** A topic handle, carrying its payload type. */\nexport interface TopicHandle<T> extends ResourceHandle {\n /**\n * Publish an event.\n *\n * Resolves once the event is durably recorded for every subscription, not\n * once they have run. Enqueued inside a transaction that rolls back, it was\n * never published.\n */\n publish(event: T): Promise<void>;\n /**\n * Declare a subscription.\n *\n * The name is its identity: it is what the job row records, what a retry\n * counts against, and what a second subscription must not collide with.\n */\n subscription(name: string, handler: TopicHandler<T>, options?: { maxAttempts?: number }): void;\n}\n\n/**\n * Declare a topic.\n *\n * ```ts\n * export const signups = topic<{ userId: string }>(\"signups\");\n * signups.subscription(\"send-welcome\", async (event) => { … });\n * await signups.publish({ userId });\n * ```\n */\nexport function topic<T = unknown>(key: string, options: TopicOptions = {}): TopicHandle<T> {\n if (options.delivery === \"at-most-once\") {\n throw new Error(\n `Topic \"${key}\" asks for at-most-once delivery, which no shipped transport implements. ` +\n \"The durable queue behind topics retries, so it is at-least-once and a handler must \" +\n \"tolerate seeing an event twice. Refused rather than quietly given the other guarantee.\"\n );\n }\n const handle = declareResource(\"topic\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async publish(event: T): Promise<void> {\n const runtime = work().topicRuntime;\n if (!runtime) {\n throw new Error(\n `Cannot publish to topic \"${key}\": no topic runtime is installed. ${missingRuntimeCause(\"topic\")}`\n );\n }\n await runtime.publish(key, event);\n },\n subscription(name: string, handler: TopicHandler<T>, subOptions: { maxAttempts?: number } = {}): void {\n if (!name || name.trim() === \"\") {\n throw new Error(`A subscription on topic \"${key}\" needs a non-empty name.`);\n }\n const { subscriptions } = work();\n if (subscriptions.some(s => s.topic === key && s.name === name)) {\n throw new Error(\n `Topic \"${key}\" already has a subscription named \"${name}\". ` +\n \"The name is what a job row records and what a retry counts against, so two \" +\n \"cannot share one.\"\n );\n }\n subscriptions.push({\n topic: key,\n name,\n handler: handler as TopicHandler<unknown>,\n ...(subOptions.maxAttempts !== undefined ? { maxAttempts: subOptions.maxAttempts } : {})\n });\n }\n } as TopicHandle<T>;\n}\n\n// ── cron ─────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"cron\",\n // The in-process scheduler, claiming each slot in `rebase.cron_claims` so\n // several instances of one deployment run a slot once. It is the only\n // engine because it is the only one that exists; an external scheduler\n // (a platform's cron, a Kubernetes CronJob) would be a second engine that\n // triggers the same handler over HTTP, and it can register itself.\n engines: [\"scheduler\"],\n defaultEngine: \"scheduler\",\n // Code, not configuration: a cron binds from no variable. It is in the\n // graph so a host knows a project's schedules BEFORE running it, which is\n // what lets a console show them and a placement decision read them.\n envBases: [],\n optionKeys: [\"schedule\", \"timezone\", \"description\", \"enabled\", \"timeoutSeconds\", \"catchUpWindowSeconds\"],\n implicitDefault: false\n});\n\n/** What a cron declaration records, beyond its handler. */\nexport interface CronResourceOptions extends DeclareOptions {\n /** Five-field cron expression, e.g. `0 3 * * *`. */\n schedule: string;\n /**\n * IANA zone the schedule is read in, e.g. `Europe/Madrid`.\n *\n * Without it the schedule is read in the process's own zone, which is\n * whatever the host happens to be set to — UTC in nearly every container,\n * the developer's own on a laptop. \"3 AM\" then means two different hours\n * either side of a deploy. Naming the zone makes the declaration mean one\n * thing everywhere.\n */\n timezone?: string;\n description?: string;\n enabled?: boolean;\n timeoutSeconds?: number;\n catchUpWindowSeconds?: number;\n}\n\n/**\n * Declare a cron, as the scheduler's `defineCron` does on its way through.\n *\n * Projects do not call this: `defineCron` in `@rebasepro/server` does, so a\n * cron file is both the handler and the declaration — one file, one name, and\n * the graph derived from it says what a host needs to know without evaluating\n * the handler. Exported so the derive step and the scheduler spell the\n * declaration identically.\n */\nexport function declareCron(name: string, options: CronResourceOptions): ResourceHandle {\n if (typeof options.schedule !== \"string\" || options.schedule.trim() === \"\") {\n throw new Error(`Cron \"${name}\" needs a schedule — a five-field cron expression such as \"0 3 * * *\".`);\n }\n return declareResource(\"cron\", name, options);\n}\n\n// ── function ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"function\",\n // Mounted by this runtime at `/api/functions/<name>`. A host that runs a\n // function elsewhere — an edge runtime, say — is a second engine, and the\n // bundle's `portable` analysis already says which ones could move.\n engines: [\"http\"],\n defaultEngine: \"http\",\n envBases: [],\n optionKeys: [\"portable\", \"requires\", \"file\"],\n implicitDefault: false\n});\n\n/**\n * What a function declaration records.\n *\n * Recorded by the derive step from the bundler's static analysis rather than\n * by evaluating the function module: a function's handler is a Hono app that\n * only needs to exist at request time, and evaluating it at build time would\n * run its module-scope code in a process with none of its environment.\n */\nexport interface FunctionResourceOptions extends DeclareOptions {\n /** Path inside the project, so a host can point at the file. */\n file?: string;\n /** `false` when the source imports a Node built-in or a package that needs one. */\n portable?: boolean;\n /** Why it is not portable — one short phrase per reason. */\n requires?: string[];\n}\n\n/** Declare a function. Called by the derive step, not by projects. */\nexport function declareFunction(name: string, options: FunctionResourceOptions = {}): ResourceHandle {\n return declareResource(\"function\", name, options);\n}\n\n// ── queue ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"queue\",\n // Same durable queue topics ride on: a row per job, claimed with\n // `FOR UPDATE SKIP LOCKED`, retried on a backoff, kept when it gives up.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [],\n optionKeys: [\"maxAttempts\"],\n implicitDefault: false\n});\n\n/** Options a queue accepts beyond the common ones. */\nexport interface QueueOptions extends DeclareOptions {\n /** Attempts before a job is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a queue's handler receives. `attempt` counts from 1; `signal` is\n * aborted when the attempt runs past the job queue's `timeoutMs`.\n */\nexport type QueueHandler<T> = (\n payload: T,\n context: { attempt: number; queue: string; jobId: string; signal: AbortSignal }\n) => Promise<void> | void;\n\n/** Per-job options at enqueue time. */\nexport interface QueueEnqueueOptions {\n /** Earliest time the job may run. Defaults to now. */\n runAt?: Date;\n /** Attempts for this job, overriding the queue's. */\n maxAttempts?: number;\n}\n\n/**\n * What a queue enqueues through.\n *\n * Installed by `@rebasepro/server` at boot, alongside the topic runtime.\n * Absent — config evaluated by the CLI, a unit test — enqueueing throws with\n * the cause named, rather than resolving and dropping the job.\n */\nexport interface QueueRuntime {\n enqueue(queue: string, payload: unknown, options?: QueueEnqueueOptions): Promise<{ id: string }>;\n}\n\n/** Install the transport queues enqueue through. Called by the server at boot. */\nexport function setQueueRuntime(runtime: QueueRuntime | null): void {\n work().queueRuntime = runtime;\n}\n\n/** A queue's handler, as recorded for the worker to wire. */\nexport interface QueueConsumer<T = unknown> {\n queue: string;\n handler: QueueHandler<T>;\n}\n\n/** Every declared queue handler, for the worker to wire. */\nexport function declaredQueueConsumers(): QueueConsumer[] {\n return [...work().queueConsumers.values()];\n}\n\n/** Forget declared queue handlers. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredQueueConsumers(): void {\n work().queueConsumers.clear();\n}\n\n/** A queue handle, carrying its payload type. */\nexport interface QueueHandle<T> extends ResourceHandle {\n /**\n * Put a job on the queue.\n *\n * Resolves once the job is durably recorded, not once it has run. A row\n * insert, so enqueued inside a transaction that rolls back it was never\n * enqueued.\n */\n enqueue(payload: T, options?: QueueEnqueueOptions): Promise<{ id: string }>;\n /**\n * Declare the handler.\n *\n * One per queue: a queue is a work list with one consumer, which is what\n * separates it from a topic. Work that several things must react to is a\n * topic with several subscriptions.\n */\n handler(fn: QueueHandler<T>): void;\n}\n\n/**\n * Declare a queue.\n *\n * ```ts\n * export const thumbnails = queue<{ key: string }>(\"thumbnails\");\n * thumbnails.handler(async ({ key }) => { … });\n * await thumbnails.enqueue({ key }, { runAt: new Date(Date.now() + 60_000) });\n * ```\n *\n * The difference from a topic is the number of consumers: a queue has one, a\n * topic fans out to every subscription. Both ride on the durable job queue, so\n * declaring either turns it on.\n */\nexport function queue<T = unknown>(key: string, options: QueueOptions = {}): QueueHandle<T> {\n const handle = declareResource(\"queue\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async enqueue(payload: T, enqueueOptions?: QueueEnqueueOptions): Promise<{ id: string }> {\n const runtime = work().queueRuntime;\n if (!runtime) {\n throw new Error(\n `Cannot enqueue on queue \"${key}\": no queue runtime is installed. ${missingRuntimeCause(\"queue\")}`\n );\n }\n return runtime.enqueue(key, payload, enqueueOptions);\n },\n handler(fn: QueueHandler<T>): void {\n const { queueConsumers } = work();\n if (queueConsumers.has(key)) {\n throw new Error(\n `Queue \"${key}\" already has a handler. A queue has exactly one consumer; ` +\n \"work that several things react to is a topic with several subscriptions.\"\n );\n }\n queueConsumers.set(key, { queue: key, handler: fn as QueueHandler<unknown> });\n }\n } as QueueHandle<T>;\n}\n\n// ── Handing declarations to the readers ──────────────────────────────────────\n\n/**\n * One declaration, as the data layer's definition.\n *\n * There is exactly one of these per kind, and everything that needs a\n * definition goes through it — the frontend, the managed runtime's boot path,\n * and an ejected project's own entrypoint. That is not tidiness: the mapping\n * used to exist twice, once here and once in `@rebasepro/server`'s\n * `graphToStorageSources`, and the two disagreed. The server's copy carried a\n * bucket's `account`; this one dropped it, so a bucket declared with shared\n * credentials resolved them on the managed runtime and resolved *nothing* in an\n * ejected backend — the source was skipped and every upload to it answered 501.\n *\n * A field-by-field map is one line away from that failure at all times, so\n * there is now one line to keep right instead of two to keep equal.\n */\nexport function resourceToDataSource(declaration: ResourceDeclaration): DataSourceDefinition {\n return {\n // The graph and the data layer spell \"the unnamed one\" identically\n // today, but they are separate constants and nothing stops them\n // drifting. Mapped explicitly so a divergence is a compile error rather\n // than a default database that silently fails to bind.\n key: declaration.key === DEFAULT_RESOURCE_KEY ? DEFAULT_DATA_SOURCE_KEY : declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.databaseId === \"string\"\n ? { databaseId: declaration.options.databaseId }\n : {}),\n ...(declaration.label !== undefined ? { label: declaration.label } : {})\n };\n}\n\n/** One declaration, as the storage layer's definition. See {@link resourceToDataSource}. */\nexport function resourceToStorageSource(declaration: ResourceDeclaration): StorageSourceDefinition {\n return {\n key: declaration.key === DEFAULT_RESOURCE_KEY ? DEFAULT_STORAGE_SOURCE_KEY : declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n // Carried, or the declaration's `account` is accepted at the call site\n // and lost on the way to the reader — a declared option that does\n // nothing, which is the exact failure this whole model exists to remove.\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n ...(declaration.options.default === true ? { default: true } : {}),\n ...orphanSweepOf(declaration.options.orphanSweep),\n ...(declaration.label !== undefined ? { label: declaration.label } : {})\n };\n}\n\n/**\n * A bucket's `orphanSweep` option as a definition carries it: `true` is the\n * defaults, an object keeps only the fields of the right type. The runtime\n * checks the values (the grace-period floor, the schedule) and refuses a bad\n * one loudly; this only refuses to invent one.\n */\nfunction orphanSweepOf(option: unknown): { orphanSweep?: OrphanSweepOptions } {\n if (option === true) return { orphanSweep: {} };\n if (!option || typeof option !== \"object\") return {};\n const { olderThanHours, schedule } = option as Record<string, unknown>;\n return {\n orphanSweep: {\n ...(typeof olderThanHours === \"number\" ? { olderThanHours } : {}),\n ...(typeof schedule === \"string\" ? { schedule } : {})\n }\n };\n}\n\n/**\n * The declared databases, as definitions.\n *\n * Both the frontend and a project's own backend entrypoint read this. The\n * frontend needs to know which sources exist and how they are reached — a\n * `direct`-transport source is one the browser talks to itself — and it imports\n * the same config package the backend does. Without these it would mean writing\n * the list a second time, by hand, next to the declarations, which is precisely\n * the two-homes problem this model removed everywhere else.\n *\n * ```tsx\n * import \"../config/resources\"; // registers them\n * import { declaredDataSources, declaredStorageSources } from \"@rebasepro/types\";\n *\n * <Rebase dataSources={declaredDataSources()} storageSources={declaredStorageSources()} />\n * ```\n *\n * The import is what registers them, so a bundler that drops an unused module\n * would leave this empty — hence the side-effect import above rather than a\n * bare re-export.\n */\nexport function declaredDataSources(): DataSourceDefinition[] {\n return declaredResources(\"database\").map(resourceToDataSource);\n}\n\n/** The declared buckets, as definitions. */\nexport function declaredStorageSources(): StorageSourceDefinition[] {\n return declaredResources(\"bucket\").map(resourceToStorageSource);\n}\n","/**\n * Scopes — what a credential may do, named `resource:action`.\n *\n * One vocabulary for every way of reaching a Rebase backend: a person's\n * session, a service key, a personal key and an OAuth token for `/mcp` all\n * answer \"may this caller do X?\" with the same strings, so a grant reads the\n * same on a key, on a role and on a consent screen.\n *\n * A scope may carry a target — `data:read:posts` is `data:read` on the `posts`\n * collection only. The unqualified scope covers every target. Only the data\n * plane and app scopes take targets; see {@link SCOPE_TARGETS}.\n *\n * Two planes, held differently:\n *\n * - **The data plane** (`data:*`, `storage:*`, `functions:invoke`). Every\n * signed-in person holds all of it, because what a person may do with data\n * is decided row by row by the collection's `securityRules` and by storage\n * policies, never by a scope. On a key or a token these scopes narrow: a key\n * holding `data:read:posts` reaches nothing else, whatever RLS would allow.\n * - **The admin plane** (everything else). Nobody holds it implicitly. The\n * `admin` role holds all of it; any other role holds what the app declares\n * for it under `auth.roles` on the users collection.\n *\n * Apps declare their own scopes too (`auth.scopes`), named the same way —\n * `project:deploy`. Every signed-in person holds every app scope: like the data\n * plane, the function behind it decides whether the person may act, and the\n * scope exists so a key can be narrowed to that one action.\n *\n * @module\n */\n\n/** @group Auth */\nexport const DATA_PLANE_SCOPES = [\n \"data:read\",\n \"data:write\",\n \"data:delete\",\n \"storage:read\",\n \"storage:write\",\n \"storage:delete\",\n \"functions:invoke\"\n] as const;\n\n/** @group Auth */\nexport const ADMIN_SCOPES = [\n \"users:read\",\n \"users:write\",\n \"schema:read\",\n \"schema:write\",\n \"database:read\",\n \"database:write\",\n \"backups:read\",\n \"cron:read\",\n \"cron:write\",\n \"logs:read\",\n \"keys:read\",\n \"keys:write\"\n] as const;\n\n/** @group Auth */\nexport type DataPlaneScope = (typeof DATA_PLANE_SCOPES)[number];\n/** @group Auth */\nexport type AdminScope = (typeof ADMIN_SCOPES)[number];\n/** @group Auth */\nexport type BuiltInScope = DataPlaneScope | AdminScope;\n\n/** Every scope Rebase itself defines, in display order. @group Auth */\nexport const BUILT_IN_SCOPES: readonly BuiltInScope[] = [...DATA_PLANE_SCOPES, ...ADMIN_SCOPES];\n\n/**\n * Scopes no key may hold.\n *\n * A key that could manage keys could mint its own successor, widen itself, or\n * revoke the keys other integrations run on — and revoking it would undo none\n * of that. Managing keys is for a person (or the service key).\n *\n * @group Auth\n */\nexport const KEY_MANAGEMENT_SCOPES: readonly AdminScope[] = [\"keys:read\", \"keys:write\"];\n\n/** The one built-in role. It holds every scope and is the RLS `admin` role. @group Auth */\nexport const ADMIN_ROLE = \"admin\";\n\n/** What a scope's target names. @group Auth */\nexport type ScopeTargetKind = \"collection\" | \"bucket\" | \"function\";\n\n/**\n * The built-in scopes that accept a target, and what the target names.\n *\n * - `data:*` — a collection slug\n * - `storage:*` — a storage source id (`(default)` for the default source)\n * - `functions:invoke` — a custom function's name\n *\n * @group Auth\n */\nexport const SCOPE_TARGETS: Readonly<Partial<Record<BuiltInScope, ScopeTargetKind>>> = {\n \"data:read\": \"collection\",\n \"data:write\": \"collection\",\n \"data:delete\": \"collection\",\n \"storage:read\": \"bucket\",\n \"storage:write\": \"bucket\",\n \"storage:delete\": \"bucket\",\n \"functions:invoke\": \"function\"\n};\n\n/** A scope's wording, for the screens that ask a person to grant it. @group Auth */\nexport interface ScopeDescription {\n /** Short, imperative: what a holder may do. */\n label: string;\n /** One sentence on what that reaches, including anything surprising. */\n description: string;\n}\n\n/** @group Auth */\nexport const BUILT_IN_SCOPE_DESCRIPTIONS: Readonly<Record<BuiltInScope, ScopeDescription>> = {\n \"data:read\": {\n label: \"Read data\",\n description: \"Read rows from tables, through the caller's row-level security.\"\n },\n \"data:write\": {\n label: \"Create and update data\",\n description: \"Create and update rows in tables, through the caller's row-level security.\"\n },\n \"data:delete\": {\n label: \"Delete data\",\n description: \"Delete rows from tables, through the caller's row-level security.\"\n },\n \"storage:read\": {\n label: \"Read files\",\n description: \"List and download stored files.\"\n },\n \"storage:write\": {\n label: \"Upload files\",\n description: \"Upload files and create folders.\"\n },\n \"storage:delete\": {\n label: \"Delete files\",\n description: \"Delete stored files.\"\n },\n \"functions:invoke\": {\n label: \"Call functions\",\n description: \"Call the backend's custom functions. A function can do anything its code does.\"\n },\n \"users:read\": {\n label: \"See users\",\n description: \"List user accounts and their roles.\"\n },\n \"users:write\": {\n label: \"Manage users\",\n description: \"Create, edit and delete accounts, reset passwords and second factors, and assign roles up to the holder's own.\"\n },\n \"schema:read\": {\n label: \"See the schema\",\n description: \"Read the schema, plan schema changes and run the RLS audit.\"\n },\n \"schema:write\": {\n label: \"Change the schema\",\n description: \"Apply schema changes: edits schema files and alters the database.\"\n },\n \"database:read\": {\n label: \"Inspect the database\",\n description: \"List databases, tables, Postgres roles and branches.\"\n },\n \"database:write\": {\n label: \"Run SQL\",\n description: \"Run SQL as the database owner, outside row-level security, and create or delete branches.\"\n },\n \"backups:read\": {\n label: \"Download backups\",\n description: \"List and download database backups — every row, outside row-level security.\"\n },\n \"cron:read\": {\n label: \"See cron jobs\",\n description: \"List cron jobs and read their run history.\"\n },\n \"cron:write\": {\n label: \"Run cron jobs\",\n description: \"Trigger cron jobs and switch them on or off.\"\n },\n \"logs:read\": {\n label: \"Read server logs\",\n description: \"Read the server's request and application logs.\"\n },\n \"keys:read\": {\n label: \"See service keys\",\n description: \"List the project's service keys. Never grantable to a key.\"\n },\n \"keys:write\": {\n label: \"Manage service keys\",\n description: \"Create, change and revoke the project's service keys. Never grantable to a key.\"\n }\n};\n\n/**\n * An app-declared scope, under `auth.scopes` on the users collection.\n *\n * @example\n * ```ts\n * auth: {\n * enabled: true,\n * scopes: {\n * \"project:deploy\": { label: \"Deploy projects\", target: \"project\" }\n * }\n * }\n * ```\n *\n * @group Auth\n */\nexport interface ScopeDefinition {\n /** Short, imperative: what a holder may do. Shown wherever the scope is granted. */\n label: string;\n /** One sentence on what that reaches. */\n description?: string;\n /**\n * What a target names, when the scope accepts one — `\"project\"` lets a\n * key hold `project:deploy:<id>`. Unset, the scope takes no target.\n */\n target?: string;\n}\n\n/**\n * An app-declared role, under `auth.roles` on the users collection.\n *\n * A role is a name the database sees (RLS policies match it) and a bundle of\n * admin-plane and app scopes. Data-plane scopes are not role scopes: what a\n * person may do with data is the collection's `securityRules`, so listing\n * `data:write` here would read as a grant it is not, and is refused.\n *\n * @example\n * ```ts\n * auth: {\n * enabled: true,\n * roles: {\n * support: { name: \"Support\", scopes: [\"users:read\", \"users:write\", \"logs:read\"] },\n * developer: { name: \"Developer\", scopes: [\"schema:read\", \"database:read\", \"logs:read\", \"cron:read\"] }\n * }\n * }\n * ```\n *\n * @group Auth\n */\nexport interface RoleDefinition {\n /** Display name. Defaults to the role id. */\n name?: string;\n /** One sentence on who holds it. */\n description?: string;\n /** Admin-plane and app scopes the role holds. */\n scopes: readonly string[];\n}\n\n/**\n * The declared access model: the app's own scopes and roles beside the\n * built-in ones. What `scopesForRoles` and `validateScopes` read.\n *\n * @group Auth\n */\nexport interface AccessModel {\n roles: Readonly<Record<string, RoleDefinition>>;\n scopes: Readonly<Record<string, ScopeDefinition>>;\n}\n\n/** The access model of an app that declares nothing: built-ins only. @group Auth */\nexport const EMPTY_ACCESS_MODEL: AccessModel = { roles: {}, scopes: {} };\n\n/** A scope string split into its scope and optional target. @group Auth */\nexport interface ParsedScope {\n /** `resource:action`. */\n scope: string;\n /** The one collection, bucket, function or app resource it is narrowed to. */\n target?: string;\n}\n\nconst SCOPE_PART = /^[a-z][a-z0-9-]*$/;\n\n/**\n * Split `resource:action[:target]`. Returns null for anything else.\n *\n * The target is everything after the second colon, so a target may itself\n * contain colons. Resource and action are lower-case words.\n *\n * @group Auth\n */\nexport function parseScope(value: string): ParsedScope | null {\n if (typeof value !== \"string\") return null;\n const first = value.indexOf(\":\");\n if (first < 0) return null;\n const second = value.indexOf(\":\", first + 1);\n const resource = value.slice(0, first);\n const action = second < 0 ? value.slice(first + 1) : value.slice(first + 1, second);\n if (!SCOPE_PART.test(resource) || !SCOPE_PART.test(action)) return null;\n if (second < 0) return { scope: `${resource}:${action}` };\n const target = value.slice(second + 1);\n if (target.length === 0 || /\\s/.test(target)) return null;\n return { scope: `${resource}:${action}`, target };\n}\n\n/** @group Auth */\nexport function isBuiltInScope(scope: string): scope is BuiltInScope {\n return (BUILT_IN_SCOPES as readonly string[]).includes(scope);\n}\n\n/** @group Auth */\nexport function isDataPlaneScope(scope: string): scope is DataPlaneScope {\n return (DATA_PLANE_SCOPES as readonly string[]).includes(scope);\n}\n\n/** @group Auth */\nexport function isAdminScope(scope: string): scope is AdminScope {\n return (ADMIN_SCOPES as readonly string[]).includes(scope);\n}\n\n/** Does this list of roles include the built-in `admin` role? @group Auth */\nexport function hasAdminRole(roles: readonly string[] | null | undefined): boolean {\n return !!roles?.includes(ADMIN_ROLE);\n}\n\n/**\n * Why `name` cannot be written as a role, or `undefined` when it can.\n *\n * No naming pattern is imposed — an app may call its roles anything. What is\n * refused is a name that would be read back as *other* roles: a role travels as\n * one element of a Postgres `text[]` and as one entry of the comma-joined\n * `app.user_roles` setting that RLS policies split with\n * `string_to_array(…, ',')`. Written as `\"support,admin\"`, a role comes back as\n * `admin`; braces, quotes and backslashes are array-literal syntax, so they are\n * refused too, as are empty names and control characters.\n *\n * @group Auth\n */\nexport function roleNameProblem(name: unknown): string | undefined {\n if (typeof name !== \"string\") return \"is not a string\";\n if (name.trim() === \"\") return \"is empty\";\n if (/[,{}\"\\\\]/.test(name)) return \"contains , { } \\\" or \\\\\";\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(name)) return \"contains a control character\";\n return undefined;\n}\n\n/**\n * Does a set of held scopes grant `scope`, optionally on one `target`?\n *\n * The unqualified grant covers every target. A qualified grant covers its own\n * target only, and never answers an unqualified question: a key holding\n * `data:read:posts` is not asked \"may you read data?\" and told yes.\n *\n * @group Auth\n */\nexport function scopeGrants(held: readonly string[], scope: string, target?: string): boolean {\n for (const entry of held) {\n if (entry === scope) return true;\n if (target !== undefined && entry === `${scope}:${target}`) return true;\n }\n return false;\n}\n\n/**\n * Does a set of held scopes grant `scope` on at least one target?\n *\n * For a surface that lists what is reachable — the collections an MCP client\n * may query — and filters per item afterwards.\n *\n * @group Auth\n */\nexport function scopeGrantsAny(held: readonly string[], scope: string): boolean {\n const prefix = `${scope}:`;\n return held.some(entry => entry === scope || entry.startsWith(prefix));\n}\n\n/**\n * The targets a held set narrows `scope` to: `\"all\"` when it holds the\n * unqualified scope, otherwise the listed targets (possibly none).\n *\n * @group Auth\n */\nexport function scopeTargets(held: readonly string[], scope: string): \"all\" | string[] {\n const prefix = `${scope}:`;\n const targets: string[] = [];\n for (const entry of held) {\n if (entry === scope) return \"all\";\n if (entry.startsWith(prefix)) targets.push(entry.slice(prefix.length));\n }\n return targets;\n}\n\n/**\n * Every scope a person holding `roles` has.\n *\n * The data plane and every app scope always; the whole admin plane with the\n * `admin` role; otherwise each declared role's scopes. A role nobody declared\n * adds nothing — it may still mean something to an RLS policy.\n *\n * @group Auth\n */\nexport function scopesForRoles(roles: readonly string[] | null | undefined, model: AccessModel = EMPTY_ACCESS_MODEL): string[] {\n const held = new Set<string>([...DATA_PLANE_SCOPES, ...Object.keys(model.scopes)]);\n if (hasAdminRole(roles)) {\n for (const scope of ADMIN_SCOPES) held.add(scope);\n return [...held];\n }\n for (const role of roles ?? []) {\n const definition = Object.prototype.hasOwnProperty.call(model.roles, role) ? model.roles[role] : undefined;\n for (const scope of definition?.scopes ?? []) held.add(scope);\n }\n return [...held];\n}\n\n/**\n * Every scope this access model knows, unqualified: the built-ins, then the\n * app's own.\n *\n * @group Auth\n */\nexport function knownScopes(model: AccessModel = EMPTY_ACCESS_MODEL): string[] {\n return [...BUILT_IN_SCOPES, ...Object.keys(model.scopes)];\n}\n\n/** Does this scope accept a target? @group Auth */\nexport function scopeAcceptsTarget(scope: string, model: AccessModel = EMPTY_ACCESS_MODEL): boolean {\n if (isBuiltInScope(scope)) return SCOPE_TARGETS[scope] !== undefined;\n const definition = Object.prototype.hasOwnProperty.call(model.scopes, scope) ? model.scopes[scope] : undefined;\n return definition?.target !== undefined;\n}\n\n/** How a scope string failed to validate. @group Auth */\nexport interface ScopeProblem {\n scope: string;\n reason: \"malformed\" | \"unknown\" | \"target-not-accepted\";\n}\n\n/**\n * Check a list of scope strings against an access model. Returns the\n * problems, empty when every entry is a known scope with an acceptable target.\n *\n * @group Auth\n */\nexport function validateScopes(values: readonly unknown[], model: AccessModel = EMPTY_ACCESS_MODEL): ScopeProblem[] {\n const known = new Set(knownScopes(model));\n const problems: ScopeProblem[] = [];\n for (const value of values) {\n const text = typeof value === \"string\" ? value : String(value);\n const parsed = typeof value === \"string\" ? parseScope(value) : null;\n if (!parsed) {\n problems.push({ scope: text, reason: \"malformed\" });\n } else if (!known.has(parsed.scope)) {\n problems.push({ scope: text, reason: \"unknown\" });\n } else if (parsed.target !== undefined && !scopeAcceptsTarget(parsed.scope, model)) {\n problems.push({ scope: text, reason: \"target-not-accepted\" });\n }\n }\n return problems;\n}\n\n/**\n * The entries of `requested` that `held` does not cover — what a credential\n * would hold beyond its minter. Empty means the request is within reach.\n *\n * `data:read:posts` is covered by `data:read`; `data:read` is not covered by\n * `data:read:posts`.\n *\n * @group Auth\n */\nexport function scopesBeyond(requested: readonly string[], held: readonly string[]): string[] {\n return requested.filter(entry => {\n const parsed = parseScope(entry);\n if (!parsed) return true;\n return !scopeGrants(held, parsed.scope, parsed.target);\n });\n}\n\n/**\n * Narrow `requested` to what `held` covers, entry by entry. What a personal\n * key holds today when its owner has lost a role since it was minted.\n *\n * @group Auth\n */\nexport function intersectScopes(requested: readonly string[], held: readonly string[]): string[] {\n const beyond = new Set(scopesBeyond(requested, held));\n return requested.filter(entry => !beyond.has(entry));\n}\n\n/**\n * How a scope is worded for a person: the built-in description, the app's\n * declared label, or the raw string when nothing describes it. A target is\n * named after the label.\n *\n * @group Auth\n */\nexport function describeScope(value: string, model: AccessModel = EMPTY_ACCESS_MODEL): ScopeDescription {\n const parsed = parseScope(value);\n if (!parsed) return { label: value, description: \"\" };\n let base: ScopeDescription | undefined;\n if (isBuiltInScope(parsed.scope)) {\n base = BUILT_IN_SCOPE_DESCRIPTIONS[parsed.scope];\n } else if (Object.prototype.hasOwnProperty.call(model.scopes, parsed.scope)) {\n const definition = model.scopes[parsed.scope];\n base = { label: definition.label, description: definition.description ?? \"\" };\n }\n const label = base?.label ?? parsed.scope;\n return {\n label: parsed.target !== undefined ? `${label}: ${parsed.target}` : label,\n description: base?.description ?? \"\"\n };\n}\n\n/** A role as a person managing access sees it. @group Auth */\nexport interface RoleSummary {\n id: string;\n name: string;\n description?: string;\n /** Admin-plane and app scopes. The `admin` role lists every admin-plane scope. */\n scopes: string[];\n /** True for `admin`, which the app does not declare. */\n builtIn: boolean;\n}\n\n/** A scope as a screen that grants it lists it. @group Auth */\nexport interface ScopeSummary {\n scope: string;\n label: string;\n description: string;\n /** What a target names, when the scope takes one. */\n target?: string;\n /** `data`, `admin` or `app`: which plane the scope belongs to. */\n plane: \"data\" | \"admin\" | \"app\";\n}\n\n/** The roles of an access model, `admin` first. @group Auth */\nexport function summarizeRoles(model: AccessModel = EMPTY_ACCESS_MODEL): RoleSummary[] {\n return [\n { id: ADMIN_ROLE, name: \"Admin\", description: \"Holds every scope. Row-level security does not limit it: it reads, changes and deletes every row.\", scopes: [...ADMIN_SCOPES], builtIn: true },\n ...Object.entries(model.roles).map(([id, definition]) => ({\n id,\n name: definition.name ?? id,\n ...(definition.description ? { description: definition.description } : {}),\n scopes: [...definition.scopes],\n builtIn: false\n }))\n ];\n}\n\n/** Every scope of an access model, described, in display order. @group Auth */\nexport function summarizeScopes(model: AccessModel = EMPTY_ACCESS_MODEL): ScopeSummary[] {\n const builtIn: ScopeSummary[] = BUILT_IN_SCOPES.map(scope => ({\n scope,\n ...BUILT_IN_SCOPE_DESCRIPTIONS[scope],\n ...(SCOPE_TARGETS[scope] ? { target: SCOPE_TARGETS[scope] } : {}),\n plane: isDataPlaneScope(scope) ? \"data\" : \"admin\"\n }));\n const app: ScopeSummary[] = Object.entries(model.scopes).map(([scope, definition]) => ({\n scope,\n label: definition.label,\n description: definition.description ?? \"\",\n ...(definition.target ? { target: definition.target } : {}),\n plane: \"app\"\n }));\n return [...builtIn, ...app];\n}\n","import { resourceKeyOf } from \"../types/resources\";\nimport type { ResourceRef } from \"../types/resources\";\n\n/**\n * Who may read and who may write one column, by role.\n *\n * A list that is absent leaves that direction to the table's `rls`. An empty\n * list closes it to every caller, the server's own code aside. Enforced on\n * every door — REST, realtime, MCP, caller SQL, includes, filters and sorts —\n * never only in the panel.\n *\n * @group Schema\n */\nexport interface ColumnAccess {\n /** Roles that receive the column on a read. */\n read?: readonly string[];\n /** Roles that may write the column. */\n write?: readonly string[];\n}\n\n/**\n * Per-role access in its stored form, checked: `read` and `write` must each be\n * a list of non-empty role names, and nothing else may be given.\n *\n * Checked at runtime because a JavaScript caller writing\n * `.access({ read: \"admin\" })` would otherwise have the string spread into\n * one role per character, silently.\n *\n * @param where What is being configured, for the error: `column \"title\"`.\n *\n * @group Schema\n */\nexport function normalizeColumnAccess(access: unknown, where: string): ColumnAccess {\n const expected = \"Write `{ read?: [\\\"role\\\", …], write?: [\\\"role\\\", …] }`.\";\n if (typeof access !== \"object\" || access === null || Array.isArray(access)) {\n throw new Error(`The access of ${where} must be an object of role lists, got ${JSON.stringify(access)}. ${expected}`);\n }\n const stored: ColumnAccess = {};\n for (const [key, value] of Object.entries(access)) {\n if (key !== \"read\" && key !== \"write\") {\n throw new Error(`The access of ${where} has an unknown key \"${key}\". ${expected}`);\n }\n if (value === undefined) continue;\n if (!Array.isArray(value) || value.some(role => typeof role !== \"string\" || role.length === 0)) {\n throw new Error(`\\`access.${key}\\` of ${where} must be a list of role names, got ${JSON.stringify(value)}. ${expected}`);\n }\n const roles: string[] = value.filter((role): role is string => typeof role === \"string\");\n stored[key] = roles;\n }\n return stored;\n}\n\n/**\n * A value the server writes into a column on its own: the time, or the caller.\n *\n * @group Schema\n */\nexport interface ColumnStamp {\n /** `create` stamps on insert only; `update` stamps on every write. */\n on: \"create\" | \"update\";\n /** `now` is the current instant; `user` is the id of the caller. */\n value: \"now\" | \"user\";\n}\n\n/**\n * The DEFAULT of a column.\n *\n * - `literal` — a value, written as a DDL default and applied by the driver on\n * create, so every writer gets the same row.\n * - `sql` — an expression Postgres evaluates.\n * - `random-uuid` — `gen_random_uuid()`.\n * - `identity` — `GENERATED BY DEFAULT AS IDENTITY`.\n * - `database` — the database holds a default Rebase does not state and must\n * not drop; a create may omit the column.\n *\n * @group Schema\n */\nexport type ColumnDefault =\n | { kind: \"literal\"; value: unknown }\n | { kind: \"sql\"; expression: string }\n | { kind: \"random-uuid\" }\n | { kind: \"identity\" }\n | { kind: \"database\" };\n\n/** What every `.validate()` accepts. */\nexport interface BaseValidation {\n /** The API error when a `.notNull()` column is missing from a create. */\n requiredMessage?: string;\n}\n\n/**\n * Validation of a text column, checked by the API before a write.\n *\n * @group Schema\n */\nexport interface StringValidation extends BaseValidation {\n /** Minimum length. */\n min?: number;\n /** Maximum length. */\n max?: number;\n /** Exact length. */\n length?: number;\n /** A pattern the value must match. A `RegExp` is kept as its source and flags. */\n matches?: string | RegExp;\n /** Flags of `matches`, when it was given as a string. */\n matchesFlags?: string;\n /** The API error when `matches` fails. */\n matchesMessage?: string;\n /** The value must be an e-mail address. */\n email?: boolean;\n /** The value must be a URL. */\n url?: boolean;\n /** Lower-case the value before it is stored. */\n lowercase?: boolean;\n /** Upper-case the value before it is stored. */\n uppercase?: boolean;\n /** Trim surrounding whitespace before the value is stored. */\n trim?: boolean;\n}\n\n/**\n * Validation of a numeric column, checked by the API before a write.\n *\n * @group Schema\n */\nexport interface NumberValidation extends BaseValidation {\n /** Inclusive lower bound. */\n min?: number;\n /** Inclusive upper bound. */\n max?: number;\n /** Exclusive upper bound. */\n lessThan?: number;\n /** Exclusive lower bound. */\n moreThan?: number;\n /** The value must be greater than zero. */\n positive?: boolean;\n /** The value must be less than zero. */\n negative?: boolean;\n /** The value must be a whole number. */\n integer?: boolean;\n}\n\n/**\n * Validation of a temporal column. Bounds are ISO strings.\n *\n * @group Schema\n */\nexport interface DateValidation extends BaseValidation {\n /** Earliest accepted value. */\n min?: string | Date;\n /** Latest accepted value. */\n max?: string | Date;\n}\n\n/**\n * Validation of an array column.\n *\n * @group Schema\n */\nexport interface ArrayValidation extends BaseValidation {\n /** Fewest items accepted. */\n minItems?: number;\n /** Most items accepted. */\n maxItems?: number;\n /** Refuse an array holding the same value twice. */\n uniqueItems?: boolean;\n /**\n * For a JSON array of objects (`json.array(json.object({...}))`): refuse\n * two items with the same value in any one of these fields — each field\n * is unique across the items on its own (`[\"sku\"]`: no SKU twice). The\n * fields are keys of the item object; anything else is refused when the\n * schema compiles.\n */\n uniqueBy?: string[];\n}\n\n/**\n * Every validation rule a column can carry, as stored on its definition and\n * served on the wire: patterns are strings, date bounds are ISO strings.\n *\n * @group Schema\n */\nexport interface ColumnValidation {\n /** The API error when a `.notNull()` column is missing from a create. */\n requiredMessage?: string;\n /**\n * Lower bound: minimum length of text, inclusive minimum of a number, earliest\n * accepted value of a temporal column (an ISO string).\n */\n min?: number | string;\n /**\n * Upper bound: maximum length of text, inclusive maximum of a number, latest\n * accepted value of a temporal column (an ISO string).\n */\n max?: number | string;\n /** Exact length of a text value. */\n length?: number;\n /** A pattern a text value must match: a `RegExp`'s source, its flags in `matchesFlags`. */\n matches?: string;\n /** Flags of `matches` (`\"i\"`, `\"u\"`, …). No flags when omitted. */\n matchesFlags?: string;\n /** The API error when `matches` fails. */\n matchesMessage?: string;\n /** A text value must be an e-mail address. */\n email?: boolean;\n /** A text value must be a URL. */\n url?: boolean;\n /** Lower-case a text value before it is stored. */\n lowercase?: boolean;\n /** Upper-case a text value before it is stored. */\n uppercase?: boolean;\n /** Trim surrounding whitespace from a text value before it is stored. */\n trim?: boolean;\n /** Exclusive upper bound of a number. */\n lessThan?: number;\n /** Exclusive lower bound of a number. */\n moreThan?: number;\n /** A number must be greater than zero. */\n positive?: boolean;\n /** A number must be less than zero. */\n negative?: boolean;\n /** A number must be a whole number. */\n integer?: boolean;\n /** Fewest items an array accepts. */\n minItems?: number;\n /** Most items an array accepts. */\n maxItems?: number;\n /** Refuse an array holding the same value twice. */\n uniqueItems?: boolean;\n /** Fields of a JSON array's object items, each unique across the items. See {@link ArrayValidation.uniqueBy}. */\n uniqueBy?: string[];\n}\n\n/** The rules a builder method accepts, before they are normalized. */\nexport type ValidationInput = StringValidation | NumberValidation | DateValidation | ArrayValidation | BaseValidation;\n\nconst isoOf = (value: string | Date): string => (value instanceof Date ? value.toISOString() : value);\n\n/**\n * Validation rules in their stored form: a `RegExp` becomes its source and\n * flags, a `Date` bound becomes an ISO string. What a builder keeps is then\n * exactly what the wire carries.\n *\n * @group Schema\n */\nexport function normalizeValidation(rules: ValidationInput): ColumnValidation {\n const out: ColumnValidation = {};\n for (const [key, value] of Object.entries(rules)) {\n if (value === undefined) continue;\n if (key === \"matches\" && value instanceof RegExp) {\n out.matches = value.source;\n if (value.flags) out.matchesFlags = value.flags;\n continue;\n }\n if ((key === \"min\" || key === \"max\") && (value instanceof Date)) {\n out[key] = isoOf(value);\n continue;\n }\n // A list is copied, so the stored rules do not alias the caller's array.\n Object.assign(out, { [key]: Array.isArray(value) ? [...value] : value });\n }\n return out;\n}\n\n/**\n * How an image is resized before it is stored.\n *\n * @group Schema\n */\nexport interface StorageImageResize {\n /**\n * Largest width in pixels; a wider image is scaled down proportionally. No\n * width limit when omitted.\n */\n maxWidth?: number;\n /**\n * Largest height in pixels; a taller image is scaled down proportionally. No\n * height limit when omitted.\n */\n maxHeight?: number;\n /**\n * How the image fits `maxWidth` × `maxHeight`: `contain` (the default) scales\n * it to fit inside, keeping its aspect ratio; `cover` scales it to fill the box,\n * keeping its aspect ratio, and may crop.\n */\n mode?: \"contain\" | \"cover\";\n /** The stored image's format. `original` (the default) keeps the uploaded one. */\n format?: \"original\" | \"jpeg\" | \"png\" | \"webp\";\n /**\n * Quality of a lossy output (JPEG, WebP), 0–100: higher is sharper and larger.\n * 80 when omitted.\n */\n quality?: number;\n}\n\n/**\n * What `col.storage()` and `json.storage()` take.\n *\n * @group Schema\n */\nexport interface StorageOptions {\n /** The bucket, declared in `backend/resources.ts`. The default bucket when omitted. */\n source?: ResourceRef;\n /** Where files go, as a path template: `\"posts/heroes/\"`, `\"users/{id}/\"`. */\n path: string;\n /** MIME types accepted, with wildcards: `[\"image/*\", \"application/pdf\"]`. */\n accept?: readonly string[];\n /** Largest file accepted, in bytes or as `\"10MB\"`. */\n maxBytes?: number | string;\n /** Resize images before storing them. */\n imageResize?: StorageImageResize;\n /** Files are readable without a signed URL. */\n public?: boolean;\n /** The stored file name, as a template. The uploaded name when omitted. */\n fileName?: string;\n /** Metadata stored with every file. */\n metadata?: Record<string, unknown>;\n /** Store the bucket URL in front of the path. */\n includeBucketUrl?: boolean;\n /** Store the download URL instead of the path. */\n storeUrl?: boolean;\n}\n\n/**\n * The storage rules of a column, as stored and served: the bucket by its key,\n * the size limit in bytes.\n *\n * @group Schema\n */\nexport interface ColumnStorage {\n source?: string;\n path: string;\n accept?: readonly string[];\n maxBytes?: number;\n imageResize?: StorageImageResize;\n public?: boolean;\n fileName?: string;\n metadata?: Record<string, unknown>;\n includeBucketUrl?: boolean;\n storeUrl?: boolean;\n}\n\nconst BYTE_UNITS: Record<string, number> = {\n b: 1,\n kb: 1024,\n mb: 1024 ** 2,\n gb: 1024 ** 3,\n tb: 1024 ** 4\n};\n\n/**\n * A size in bytes, from a number or from `\"10MB\"` / `\"512 kb\"` / `\"1.5GB\"`.\n *\n * Binary multiples (1 MB = 1,048,576 bytes), the unit a storage limit is\n * enforced in. Throws on anything else: a limit that silently parsed to `NaN`\n * is a limit that is never applied.\n *\n * @group Schema\n */\nexport function parseByteSize(size: number | string): number {\n if (typeof size === \"number\") {\n if (!Number.isFinite(size) || size < 0) throw new Error(`A byte size must be a non-negative number, got ${size}.`);\n return size;\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|tb)?\\s*$/i.exec(size);\n if (!match) {\n throw new Error(`Cannot read \"${size}\" as a byte size. Write a number of bytes, or a size such as \"10MB\".`);\n }\n const unit = (match[2] ?? \"b\").toLowerCase();\n return Math.round(Number(match[1]) * BYTE_UNITS[unit]);\n}\n\n/**\n * Storage options in their stored form.\n *\n * @group Schema\n */\nexport function normalizeStorage(options: StorageOptions): ColumnStorage {\n if (typeof options.path !== \"string\" || options.path.length === 0) {\n throw new Error(\"A storage column needs a `path`: where its files go, e.g. `col.storage({ path: \\\"posts/heroes/\\\" })`.\");\n }\n const out: ColumnStorage = { path: options.path };\n if (options.source !== undefined) out.source = resourceKeyOf(options.source);\n if (options.accept !== undefined) out.accept = [...options.accept];\n if (options.maxBytes !== undefined) out.maxBytes = parseByteSize(options.maxBytes);\n if (options.imageResize !== undefined) out.imageResize = { ...options.imageResize };\n if (options.public !== undefined) out.public = options.public;\n if (options.fileName !== undefined) out.fileName = options.fileName;\n if (options.metadata !== undefined) out.metadata = { ...options.metadata };\n if (options.includeBucketUrl !== undefined) out.includeBucketUrl = options.includeBucketUrl;\n if (options.storeUrl !== undefined) out.storeUrl = options.storeUrl;\n return out;\n}\n\n/**\n * The distance a vector index is built for.\n *\n * `ip` is the inner product (pgvector's `vector_ip_ops`).\n *\n * @group Schema\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"ip\";\n\n/**\n * The approximate-nearest-neighbour index of a `col.vector()` column.\n *\n * @group Schema\n */\nexport interface VectorIndexOptions {\n /** `hnsw` (the default) or `ivfflat`. */\n method?: \"hnsw\" | \"ivfflat\";\n /** The distance, or several: one index is built per metric. `cosine` by default. */\n metric?: VectorMetric | readonly VectorMetric[];\n /** HNSW: connections per layer. */\n m?: number;\n /** HNSW: size of the candidate list while building. */\n efConstruction?: number;\n /** IVFFlat: number of lists. */\n lists?: number;\n}\n","import type {\n ArrayValidation,\n BaseValidation,\n ColumnStorage,\n ColumnValidation,\n DateValidation,\n NumberValidation,\n StorageOptions,\n StringValidation,\n ValidationInput\n} from \"./column_options\";\nimport { normalizeStorage, normalizeValidation } from \"./column_options\";\nimport type { ColumnTransform } from \"./hooks\";\n\n/** What every node of a JSON shape may carry. */\ninterface JsonNodeBase {\n /** The key must be present in the document. */\n required?: boolean;\n /** The value written when the key is absent on create. */\n default?: unknown;\n /** What the value is, for OpenAPI and MCP. */\n description?: string;\n}\n\ntype JsonNode<Extra> = Extra & JsonNodeBase & (\n | {\n kind: \"string\";\n validate?: ColumnValidation;\n oneOf?: readonly string[];\n storage?: ColumnStorage;\n /**\n * The server writes the caller's user id into the field: on create\n * only (`\"createUser\"`, `.onCreateUser()`) or on every write\n * (`\"updateUser\"`, `.onUpdateUser()`).\n */\n stamp?: \"createUser\" | \"updateUser\";\n /** `\"user\"`: the field holds a user's id (`.userId()`). */\n semantic?: \"user\";\n }\n | { kind: \"number\"; validate?: ColumnValidation; oneOf?: readonly number[] }\n | { kind: \"boolean\" }\n | {\n kind: \"date\";\n validate?: ColumnValidation;\n /**\n * The server writes the current time into the field: on create only\n * (`\"create\"`, `.onCreateNow()`) or on every write (`\"update\"`,\n * `.onUpdateNow()`).\n */\n stamp?: \"create\" | \"update\";\n }\n | { kind: \"geopoint\" }\n | { kind: \"object\"; fields: Record<string, JsonNode<Extra>>; additional?: boolean }\n | { kind: \"array\"; of: JsonNode<Extra>; validate?: ColumnValidation }\n | { kind: \"oneOf\"; typeField: string; valueField: string; variants: Record<string, JsonNode<Extra>> }\n | { kind: \"unknown\" }\n);\n\n/**\n * The shape of a `json`/`jsonb` document, as served on the wire.\n *\n * It is what lets the server validate a nested field, stamp a nested date,\n * find the files a document references, and search a JSON path — and what lets\n * the panel build a form for the document without being told how.\n *\n * @group Schema\n */\nexport type JsonShape = JsonNode<unknown>;\n\n/**\n * A {@link JsonShape} as authored: the same tree, with field-level hooks on\n * its nodes. Hooks stay on the server.\n *\n * @group Schema\n */\nexport type JsonShapeDef = JsonNode<{ transform?: ColumnTransform }>;\n\n/**\n * The kind of one node of a JSON shape.\n *\n * @group Schema\n */\nexport type JsonKind = JsonShape[\"kind\"];\n\n/** A point on Earth, as a JSON document stores it. */\nexport interface JsonGeoPoint {\n /** Degrees north of the equator, −90 to 90 (south is negative). */\n latitude: number;\n /** Degrees east of Greenwich, −180 to 180 (west is negative). */\n longitude: number;\n}\n\ntype JsonValidationFor<K extends JsonKind> =\n K extends \"string\" ? StringValidation :\n K extends \"number\" ? NumberValidation :\n K extends \"date\" ? DateValidation :\n K extends \"array\" ? ArrayValidation :\n BaseValidation;\n\n/**\n * The value a JSON field's `.transform()` hooks receive and return: the\n * field's type, plus `undefined` while the field is not `.required()`.\n *\n * Read when `.transform()` is called: `.required().transform(…)` receives\n * `TData`, `.transform(…).required()` keeps `TData | undefined`.\n *\n * @group Schema\n */\nexport type JsonTransformValue<TData, TRequired extends boolean> = TRequired extends true ? TData : TData | undefined;\n\n/** The brand every JSON field builder carries, so one built by another copy of this package is still recognised. */\nexport const JSON_FIELD_BRAND = \"rebase.json-field\";\n\n/**\n * One field of a JSON document: `json.string()`, `json.object({...})`, ….\n *\n * Immutable: every modifier returns a new field.\n *\n * @group Schema\n */\nexport class JsonField<TData, TKind extends JsonKind = JsonKind, TRequired extends boolean = false> {\n\n /** Type-level only: the TypeScript type of the value. */\n declare readonly $data: TData;\n /** Type-level only: the node kind. */\n declare readonly $kind: TKind;\n /** Type-level only: whether the key must be present. */\n declare readonly $required: TRequired;\n\n readonly brand = JSON_FIELD_BRAND;\n\n constructor(\n /** The shape this field describes. */\n readonly shape: JsonShapeDef\n ) {}\n\n private with<D, K extends JsonKind, R extends boolean>(patch: Partial<JsonNodeBase> & Record<string, unknown>): JsonField<D, K, R> {\n return new JsonField<D, K, R>(Object.assign({}, this.shape, patch));\n }\n\n /** The key must be present in the document. */\n required(): JsonField<TData, TKind, true> {\n return this.with<TData, TKind, true>({ required: true });\n }\n\n /** The value written when the key is absent on create. */\n default(value: TData): JsonField<TData, TKind, TRequired> {\n return this.with<TData, TKind, TRequired>({ default: value });\n }\n\n /** What the value is, for OpenAPI and MCP. */\n describe(description: string): JsonField<TData, TKind, TRequired> {\n return this.with<TData, TKind, TRequired>({ description });\n }\n\n /** Rules the API checks before a write. */\n validate(rules: JsonValidationFor<TKind>): JsonField<TData, TKind, TRequired> {\n const input: ValidationInput = rules;\n return this.with<TData, TKind, TRequired>({ validate: normalizeValidation(input) });\n }\n\n /** A closed set of accepted values. */\n oneOf<const V extends readonly TData[], K extends \"string\" | \"number\">(\n this: JsonField<TData, K, TRequired>,\n values: V\n ): JsonField<V[number], K, TRequired> {\n return this.with<V[number], K, TRequired>({ oneOf: [...values] });\n }\n\n /** The server writes the current time into the field when the row is created. */\n onCreateNow(this: JsonField<string, \"date\", TRequired>): JsonField<string, \"date\", TRequired> {\n return this.with<string, \"date\", TRequired>({ stamp: \"create\" });\n }\n\n /** The server writes the current time into the field on every write. */\n onUpdateNow(this: JsonField<string, \"date\", TRequired>): JsonField<string, \"date\", TRequired> {\n return this.with<string, \"date\", TRequired>({ stamp: \"update\" });\n }\n\n /** The server writes the caller's user id into the field when the row is created. */\n onCreateUser(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n return this.with<string, \"string\", TRequired>({ stamp: \"createUser\" });\n }\n\n /** The server writes the caller's user id into the field on every write. */\n onUpdateUser(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n return this.with<string, \"string\", TRequired>({ stamp: \"updateUser\" });\n }\n\n /**\n * The field holds the id of a user. The panel offers a user picker for it,\n * and callers who may write the table may look users up to fill it.\n * Only on `json.string()`; anything else throws.\n */\n userId(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n if (this.shape.kind !== \"string\" || this.shape.storage !== undefined) {\n const what = this.shape.kind === \"string\" ? \"`json.storage()`\" : `a \\`json.${this.shape.kind}()\\` field`;\n throw new Error(`\\`.userId()\\` on ${what}: a user's id is held by \\`json.string()\\`.`);\n }\n return this.with<string, \"string\", TRequired>({ semantic: \"user\" });\n }\n\n /**\n * Field-level hooks. They run on the server only.\n *\n * The value is `TData | undefined` on a field not (yet) marked\n * `.required()` — the key can be absent from the document — and `TData` on\n * one that is; see {@link JsonTransformValue}. Chain `.required()` before\n * `.transform()` to get the narrower type.\n */\n transform(transform: ColumnTransform<JsonTransformValue<TData, TRequired>>): JsonField<TData, TKind, TRequired> {\n const erased: ColumnTransform = transform;\n return this.with<TData, TKind, TRequired>({ transform: erased });\n }\n}\n\n/** Any JSON field, whatever it holds. */\nexport type AnyJsonField = JsonField<unknown, JsonKind, boolean>;\n\n/** The TypeScript type a JSON field holds. */\nexport type JsonDataOf<F> = F extends JsonField<infer T, JsonKind, boolean> ? T : never;\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The TypeScript type of a `json.object({...})`: required keys required, the rest optional. */\nexport type JsonObjectOf<S extends Record<string, AnyJsonField>> = Simplify<\n { [K in keyof S as S[K] extends JsonField<unknown, JsonKind, true> ? K : never]: JsonDataOf<S[K]> } &\n { [K in keyof S as S[K] extends JsonField<unknown, JsonKind, true> ? never : K]?: JsonDataOf<S[K]> }\n>;\n\n/** One block of a `json.oneOf(...)`: its discriminator and its value. */\nexport type JsonOneOfOf<\n S extends Record<string, AnyJsonField>,\n TypeField extends string,\n ValueField extends string\n> = { [K in keyof S]: Simplify<Record<TypeField, K> & Record<ValueField, JsonDataOf<S[K]>>> }[keyof S];\n\nconst shapesOf = (fields: Record<string, AnyJsonField>): Record<string, JsonShapeDef> => {\n const out: Record<string, JsonShapeDef> = {};\n for (const [key, field] of Object.entries(fields)) out[key] = field.shape;\n return out;\n};\n\n/**\n * Builders for the shape of a `json`/`jsonb` document.\n *\n * ```ts\n * metadata: col.jsonb(json.object({\n * seoTitle: json.string().validate({ max: 60 }),\n * canonicalUrl: json.string().validate({ url: true }),\n * })),\n * content: col.jsonb(json.array(json.oneOf({\n * text: json.string(),\n * image: json.storage({ path: \"posts/content/\" }),\n * }))),\n * ```\n *\n * `col.jsonb().$type<T>()` on its own types the document statically; a shape also\n * tells the server what is inside it.\n *\n * @group Schema\n */\nexport const json = {\n /** A string. */\n string(): JsonField<string, \"string\"> {\n return new JsonField<string, \"string\">({ kind: \"string\" });\n },\n /** A number. */\n number(): JsonField<number, \"number\"> {\n return new JsonField<number, \"number\">({ kind: \"number\" });\n },\n /** A boolean. */\n boolean(): JsonField<boolean, \"boolean\"> {\n return new JsonField<boolean, \"boolean\">({ kind: \"boolean\" });\n },\n /** An instant, stored as an ISO string. */\n date(): JsonField<string, \"date\"> {\n return new JsonField<string, \"date\">({ kind: \"date\" });\n },\n /** A point on Earth: `{ latitude, longitude }`. */\n geopoint(): JsonField<JsonGeoPoint, \"geopoint\"> {\n return new JsonField<JsonGeoPoint, \"geopoint\">({ kind: \"geopoint\" });\n },\n /** The path of a stored file. Counted by the orphan sweep like a `col.storage()` column. */\n storage(options: StorageOptions): JsonField<string, \"string\"> {\n return new JsonField<string, \"string\">({ kind: \"string\", storage: normalizeStorage(options) });\n },\n /** An object with known keys. `additional: true` also accepts keys it does not name. */\n object<S extends Record<string, AnyJsonField>>(\n fields: S,\n options: { additional?: boolean } = {}\n ): JsonField<JsonObjectOf<S>, \"object\"> {\n const shape: JsonShapeDef = { kind: \"object\", fields: shapesOf(fields) };\n if (options.additional) shape.additional = true;\n return new JsonField<JsonObjectOf<S>, \"object\">(shape);\n },\n /** An array of one shape. */\n array<F extends AnyJsonField>(of: F): JsonField<JsonDataOf<F>[], \"array\"> {\n return new JsonField<JsonDataOf<F>[], \"array\">({ kind: \"array\", of: of.shape });\n },\n /**\n * A typed block: `{ type: \"<variant>\", value: <its shape> }`. The keys are\n * `type` and `value` unless `typeField` / `valueField` say otherwise.\n */\n oneOf<\n S extends Record<string, AnyJsonField>,\n const TypeField extends string = \"type\",\n const ValueField extends string = \"value\"\n >(\n variants: S,\n options: { typeField?: TypeField; valueField?: ValueField } = {}\n ): JsonField<JsonOneOfOf<S, TypeField, ValueField>, \"oneOf\"> {\n return new JsonField<JsonOneOfOf<S, TypeField, ValueField>, \"oneOf\">({\n kind: \"oneOf\",\n typeField: options.typeField ?? \"type\",\n valueField: options.valueField ?? \"value\",\n variants: shapesOf(variants)\n });\n },\n /** Anything. */\n unknown(): JsonField<unknown, \"unknown\"> {\n return new JsonField<unknown, \"unknown\">({ kind: \"unknown\" });\n }\n};\n\n/**\n * Whether a value is a JSON field builder, from this copy of the package or\n * another.\n *\n * @group Schema\n */\nexport function isJsonField(value: unknown): value is AnyJsonField {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === JSON_FIELD_BRAND;\n}\n\n/**\n * A JSON shape without its hooks: what the wire carries.\n *\n * @group Schema\n */\nexport function describeJsonShape(shape: JsonShapeDef): JsonShape {\n const { transform: _transform, ...rest } = shape;\n void _transform;\n switch (rest.kind) {\n case \"object\": {\n const fields: Record<string, JsonShape> = {};\n for (const [key, field] of Object.entries(rest.fields)) fields[key] = describeJsonShape(field);\n return { ...rest, fields };\n }\n case \"array\":\n return { ...rest, of: describeJsonShape(rest.of) };\n case \"oneOf\": {\n const variants: Record<string, JsonShape> = {};\n for (const [key, variant] of Object.entries(rest.variants)) variants[key] = describeJsonShape(variant);\n return { ...rest, variants };\n }\n default:\n return rest;\n }\n}\n","import type { ColumnKind, ColumnType, NumericColumnKind, TemporalColumnKind, TextColumnKind } from \"./column_type\";\nimport type {\n ArrayValidation,\n BaseValidation,\n ColumnAccess,\n ColumnDefault,\n ColumnStamp,\n ColumnStorage,\n ColumnValidation,\n DateValidation,\n NumberValidation,\n StorageOptions,\n StringValidation,\n ValidationInput,\n VectorIndexOptions\n} from \"./column_options\";\nimport { normalizeColumnAccess, normalizeStorage, normalizeValidation } from \"./column_options\";\nimport type { ColumnTransform } from \"./hooks\";\nimport type { JsonField, JsonGeoPoint, JsonKind, JsonShapeDef } from \"./json\";\n\n/**\n * Every Drizzle spelling Rebase refuses, with the instruction it shows.\n *\n * Each text is used twice: as a string-literal *type* placed where the\n * developer wrote the refused thing (a `this` parameter, a config key, an\n * argument), so TypeScript prints the instruction verbatim; and as the message\n * thrown at run time, for a JavaScript caller the types do not reach. See\n * `drizzle-alignment.md` for the table of Drizzle spellings.\n *\n * @group Schema\n */\nexport const DRIZZLE_REFUSALS = {\n /** `col.timestamp()` without `withTimezone: true`: Drizzle's timestamp WITHOUT time zone. */\n timestamp: \"Rebase stores instants as timestamptz: write `col.timestamp({ withTimezone: true })`. For a timestamp without time zone write `col.custom({ dataType: \\\"timestamp\\\" })`.\",\n /** `col.timestamp({ mode: \"date\" })`: Drizzle's Date-typed mode. */\n timestampMode: \"Rebase serves a timestamp as an ISO string: leave `mode` out or write `mode: \\\"string\\\"`.\",\n /** `col.timestamp({ precision })`. */\n timestampPrecision: \"Rebase does not state a timestamp's precision: leave `precision` out, or write `col.custom({ dataType: \\\"timestamp(3) with time zone\\\" })`.\",\n /** `col.date({ mode: \"date\" })`: Drizzle's Date-typed mode. */\n dateMode: \"Rebase serves a date as a `YYYY-MM-DD` string: leave `mode` out or write `mode: \\\"string\\\"`.\",\n /** `col.time({ withTimezone: true })`: a `timetz`. */\n timeZone: \"`col.time()` is a time without time zone: leave `withTimezone` out, or write `col.custom({ dataType: \\\"timetz\\\" })`.\",\n /** `col.time({ precision })`. */\n timePrecision: \"Rebase does not state a time's precision: leave `precision` out, or write `col.custom({ dataType: \\\"time(3)\\\" })`.\",\n /** `col.numeric({ mode: \"string\" | \"bigint\" })`: our value is a JSON number. */\n numericMode: \"Rebase reads and writes numeric as a JSON number: leave `mode` out or write `mode: \\\"number\\\"`. For exact decimals kept as text write `col.text()`.\",\n /** `col.bigint({ mode: \"bigint\" })`: our value is a JSON number. */\n bigintMode: \"Rebase serves bigint as a JSON number: write `{ mode: \\\"number\\\" }`. For exact 64-bit values write `col.numeric()` or `col.text()`.\",\n /** `col.varchar(\"name\")` / `col.varchar({ enum })` without a length. */\n varcharLength: \"`col.varchar()` needs a length (a bare varchar is unbounded in Postgres and Drizzle): write `col.varchar({ length: 255 })`, or `col.text()` for text of any length.\",\n /** `col.char(\"name\")` / `col.char({ enum })` without a length. */\n charLength: \"`col.char()` needs a length (a bare char is char(1) in Postgres and Drizzle): write `col.char({ length: 2 })`.\",\n /** `.generatedAlwaysAsIdentity()`: the planner creates BY DEFAULT identities only. */\n identityAlways: \"Rebase creates identity columns GENERATED BY DEFAULT: write `.generatedByDefaultAsIdentity()`.\",\n /** `.generatedByDefaultAsIdentity({ … })`: sequence options. */\n identityOptions: \"Rebase does not take sequence options: write `.generatedByDefaultAsIdentity()` with no argument.\",\n /** `.references(() => …)`: a foreign key is a `rel.belongsTo`. */\n references: \"A foreign key is a relation in Rebase: write `relations: { author: rel.belongsTo(() => users, { localKey: \\\"author_id\\\", onDelete: \\\"cascade\\\" }) }`. The relation's key is what `include` names.\",\n /** `.$defaultFn()` / `.$default()`: a run-time default function. */\n defaultFn: \"Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`…`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`.\",\n /** `.$onUpdate()` / `.$onUpdateFn()`: a run-time update function. */\n onUpdateFn: \"Rebase's schema is data, not code: write `.onUpdateNow()` for the time, `.onUpdateUser()` for the caller; anything else belongs in `hooks.beforeSave`.\",\n /** `.unique(name, { nulls })`: a named or NULLS NOT DISTINCT constraint. */\n uniqueName: \"Rebase derives constraint names and keeps NULLs distinct: write `.unique()`, or a unique index under `indexes`.\",\n /** `.generatedAlwaysAs(value)` with something other than a `sql` expression. */\n generatedValue: \"`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`…`)`.\",\n /** `.array(size)`. */\n arraySize: \"Postgres ignores array sizes: write `.array()`.\",\n /** `.notNull()` & co. before `.array()`. */\n arrayOrder: \"`.notNull()`, a default, `.primaryKey()`, `.readOnly()` and `.private()` before `.array()` would describe each item: write them after it, as in `col.text().array().notNull()`.\",\n /** `.array().array()`. */\n arrayOfArray: \"An array of arrays is not supported: use `col.jsonb()` for nested lists.\",\n /** `sql` with an interpolation. */\n sqlInterpolation: \"`sql` writes its text into the DDL verbatim: write the expression inline, without `${…}`.\",\n /** `col.bigint()` / `col.bigserial()` without `{ mode }`. */\n bigintModeMissing: \"`col.bigint()` and `col.bigserial()` take Drizzle's `{ mode: \\\"number\\\" }`: write `col.bigint({ mode: \\\"number\\\" })`.\",\n /** `col.numeric(10, 2)`: positional precision and scale. */\n numericPositional: \"`col.numeric()` takes a config object: write `col.numeric({ precision: 10, scale: 2 })`.\",\n /** `col.vector(1536)`: positional dimensions. */\n vectorPositional: \"`col.vector()` takes a config object: write `col.vector({ dimensions: 1536 })`.\",\n /** `col.enum(values, { name })`: a named enum type. */\n enumName: \"A named Postgres enum type is declared once with `pgEnum`: write `const postStatus = pgEnum(\\\"post_status\\\", [...])`, then `postStatus()` in the column.\",\n /** `col.custom(\"inet\")`: a lone string is the SQL column name. */\n customDataType: \"`col.custom()` names its Postgres type in a config object: write `col.custom({ dataType: \\\"inet\\\" })`, or `col.custom(\\\"ip\\\", { dataType: \\\"inet\\\" })` with a SQL column name.\",\n /** `pgEnum(name, { A: \"a\" })`: Drizzle's object form. */\n pgEnumObject: \"`pgEnum(name, values)` takes the list of labels: write `pgEnum(\\\"post_status\\\", [\\\"draft\\\", \\\"published\\\"])`.\"\n} as const;\n\ntype Refusal = typeof DRIZZLE_REFUSALS;\n\n/** The message of a Drizzle column type Rebase names only through `col.custom()`. */\ntype UnsupportedType<T extends string> =\n `Rebase has no \\`col.${T}()\\`: write \\`col.custom({ dataType: \"${T}\" })\\`. The value passes through as the driver returns it (a string).`;\n\nfunction unsupportedMessage<T extends string>(type: T): UnsupportedType<T> {\n return `Rebase has no \\`col.${type}()\\`: write \\`col.custom({ dataType: \"${type}\" })\\`. The value passes through as the driver returns it (a string).`;\n}\n\n/** The brand of a {@link sql} expression. */\nexport const SQL_BRAND = \"rebase.sql\";\n\n/**\n * A SQL expression written with the {@link sql} tag: `sql\\`now()\\``.\n *\n * @group Schema\n */\nexport interface SqlTemplate {\n /** Marks a value as written with the {@link sql} tag. */\n readonly brand: typeof SQL_BRAND;\n /** The expression, exactly as written between the backticks. */\n readonly text: string;\n}\n\n/**\n * A SQL expression for a default or a generated column, as Drizzle writes it:\n * `.default(sql\\`gen_short_id()\\`)`, `.generatedAlwaysAs(sql\\`lower(email)\\`)`.\n *\n * The text goes into the DDL verbatim, so it takes no interpolation: write the\n * expression inline.\n *\n * @group Schema\n */\nexport function sql(strings: TemplateStringsArray, ...values: Refusal[\"sqlInterpolation\"][]): SqlTemplate {\n if (values.length > 0 || strings.length !== 1) throw new Error(DRIZZLE_REFUSALS.sqlInterpolation);\n const text = strings[0] ?? strings.raw[0];\n if (text.trim().length === 0) throw new Error(\"`sql``` is empty: write the expression, e.g. sql`now()`.\");\n return { brand: SQL_BRAND, text };\n}\n\n/**\n * Whether a value is a {@link sql} expression, from this copy of the package or another.\n *\n * @group Schema\n */\nexport function isSqlTemplate(value: unknown): value is SqlTemplate {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === SQL_BRAND &&\n \"text\" in value && typeof value.text === \"string\";\n}\n\n/**\n * Everything a column builder has been told, as data.\n *\n * Wire-safe except for `transform` and the hooks inside `json`, which stay on\n * the server.\n *\n * @group Schema\n */\nexport interface ColumnDef {\n /** The Postgres type. */\n type: ColumnType;\n /** The SQL column name, when it is not the snake_case of the key. */\n column?: string;\n notNull: boolean;\n primaryKey: boolean;\n unique: boolean;\n default?: ColumnDefault;\n /** `GENERATED ALWAYS AS (<expression>) STORED`. */\n generatedAs?: string;\n readOnly: boolean;\n private: boolean;\n access?: ColumnAccess;\n stamp?: ColumnStamp;\n validate?: ColumnValidation;\n oneOf?: readonly (string | number)[];\n description?: string;\n storage?: ColumnStorage;\n /**\n * A meaning the Postgres type does not state: `\"geopoint\"` (`col.geopoint()`,\n * a `jsonb` point) or `\"user\"` (`.userId()`, a text or uuid column holding a\n * user's id).\n */\n semantic?: \"geopoint\" | \"user\";\n vectorIndex?: VectorIndexOptions | false;\n /** The shape of a `json`/`jsonb` document. */\n json?: JsonShapeDef;\n /** For an array column: the definition of each item. */\n element?: ColumnDef;\n /** Field-level hooks. Server only. */\n transform?: ColumnTransform;\n}\n\n/**\n * The type-level tag of a builder. A {@link ColumnKind}, or one of the two\n * builders whose meaning the Postgres type alone does not state.\n */\nexport type BuilderKind = ColumnKind | \"storage\" | \"geopoint\";\n\n/**\n * What the type system tracks about a column besides its data type.\n *\n * @group Schema\n */\nexport interface ColumnFlags {\n /** `NOT NULL`: never `null` on a row, required on create unless it has a default. */\n notNull: boolean;\n /** A create may omit it. */\n hasDefault: boolean;\n /** Clients may write it. */\n writable: boolean;\n /** It is served on the wire. */\n exposed: boolean;\n /** Part of the primary key. */\n primaryKey: boolean;\n}\n\n/** The flags of a column no modifier has touched: nullable, required-by-nobody, writable, served. */\nexport interface InitialColumnFlags extends ColumnFlags {\n notNull: false;\n hasDefault: false;\n writable: true;\n exposed: true;\n primaryKey: false;\n}\n\n/**\n * The value a column's `.transform()` hooks receive and return: the column's\n * type, plus `null` while the column is nullable.\n *\n * Read from the flags at the point `.transform()` is called, so the order of\n * the chain matters: `.notNull().transform(…)` (or `.primaryKey()` first)\n * receives `TData`; `.transform(…).notNull()` was typed before the column\n * became `NOT NULL` and keeps receiving `TData | null`. Write `.notNull()`\n * first.\n *\n * @group Schema\n */\nexport type ColumnTransformValue<TData, F extends ColumnFlags> = F[\"notNull\"] extends true ? TData : TData | null;\n\ntype SetFlag<F extends ColumnFlags, K extends keyof ColumnFlags, V extends boolean> = {\n [P in keyof ColumnFlags]: P extends K ? V : F[P]\n};\n\ntype WithDefault<F extends ColumnFlags> = SetFlag<F, \"hasDefault\", true>;\n\n/** The rules `.validate()` accepts for a kind of column. */\nexport type ValidationFor<K extends BuilderKind> =\n K extends TextColumnKind | \"storage\" ? StringValidation :\n K extends NumericColumnKind ? NumberValidation :\n K extends TemporalColumnKind ? DateValidation :\n K extends \"array\" ? ArrayValidation :\n BaseValidation;\n\n/** The value `.default()` accepts: what the column holds; a `Date` too, for a temporal column. */\nexport type DefaultValueFor<TData, K extends BuilderKind> = K extends TemporalColumnKind ? TData | Date : TData;\n\nconst STAMP_METHODS: Record<string, string> = {\n \"create:now\": \".onCreateNow\",\n \"update:now\": \".onUpdateNow\",\n \"create:user\": \".onCreateUser\",\n \"update:user\": \".onUpdateUser\"\n};\n\n/** The brand every column builder carries, so one built by another copy of this package is still recognised. */\nexport const COLUMN_BRAND = \"rebase.column\";\n\nconst baseDef = (type: ColumnType): ColumnDef => ({\n type,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n});\n\n/**\n * One column of a table: `col.text()`, `col.uuid().primaryKey()`, ….\n *\n * Immutable — every modifier returns a new builder — so a column can be shared\n * between tables. Columns are nullable until `.notNull()` or `.primaryKey()`\n * says otherwise, as in SQL.\n *\n * @typeParam TData The TypeScript type of a value on the wire.\n * @typeParam TKind Which builder made it; decides which modifiers apply.\n * @typeParam F What has been said about it so far.\n *\n * @group Schema\n */\nexport class ColumnBuilder<TData, TKind extends BuilderKind = BuilderKind, F extends ColumnFlags = InitialColumnFlags> {\n\n /** Type-level only: the TypeScript type of a value. */\n declare readonly $data: TData;\n /** Type-level only: the builder kind. */\n declare readonly $kind: TKind;\n /** Type-level only: the flags. */\n declare readonly $flags: F;\n\n readonly brand = COLUMN_BRAND;\n\n constructor(\n /** Everything this column has been told. */\n readonly def: ColumnDef\n ) {}\n\n private with<D, K extends BuilderKind, G extends ColumnFlags>(patch: Partial<ColumnDef>): ColumnBuilder<D, K, G> {\n return new ColumnBuilder<D, K, G>({ ...this.def, ...patch });\n }\n\n /**\n * The patch that sets a stamp, refusing a second, different one: a column\n * holds one stamp, so `.onCreateNow().onUpdateNow()` would otherwise keep\n * whichever came last without a word.\n */\n private stamped(stamp: ColumnStamp, method: string): Partial<ColumnDef> {\n const current = this.def.stamp;\n if (current && (current.on !== stamp.on || current.value !== stamp.value)) {\n throw new Error(\n `\\`.${method}()\\` on a column that already has \\`${STAMP_METHODS[`${current.on}:${current.value}`]}()\\`: a column ` +\n \"holds one stamp. `.onUpdateNow()` alone also stamps the row when it is created.\"\n );\n }\n return { stamp };\n }\n\n // ── Every column ─────────────────────────────────────────────────────\n\n /**\n * Types the value without changing the column, as Drizzle's `$type`:\n * `col.jsonb().$type<{ seoTitle?: string }>()`, `col.integer().$type<UserId>()`.\n * Nothing is checked at run time; use `col.jsonb(json.object({...}))` for\n * a shape the server enforces.\n */\n $type<T>(): ColumnBuilder<T, TKind, F> {\n return this.with<T, TKind, F>({});\n }\n\n /** `NOT NULL`. The API requires the column on create unless it has a default. */\n notNull(): ColumnBuilder<TData, TKind, SetFlag<F, \"notNull\", true>> {\n return this.with<TData, TKind, SetFlag<F, \"notNull\", true>>({ notNull: true });\n }\n\n /**\n * Part of the primary key. Several columns marked this way form a composite\n * key, in declaration order.\n */\n primaryKey(): ColumnBuilder<TData, TKind, SetFlag<SetFlag<F, \"notNull\", true>, \"primaryKey\", true>> {\n return this.with<TData, TKind, SetFlag<SetFlag<F, \"notNull\", true>, \"primaryKey\", true>>({\n primaryKey: true,\n notNull: true\n });\n }\n\n /**\n * A single-column `UNIQUE` constraint. Its name is derived; Drizzle's\n * `.unique(name, { nulls })` arguments are refused.\n */\n unique(name?: Refusal[\"uniqueName\"], config?: Refusal[\"uniqueName\"]): ColumnBuilder<TData, TKind, F> {\n if (name !== undefined || config !== undefined) throw new Error(DRIZZLE_REFUSALS.uniqueName);\n return this.with<TData, TKind, F>({ unique: true });\n }\n\n /**\n * A default: a value, written as the column's DDL default and applied by\n * the driver on create, so a row comes out the same whoever inserts it — or\n * an expression Postgres evaluates, `.default(sql\\`gen_short_id()\\`)`.\n */\n default(value: DefaultValueFor<TData, TKind> | SqlTemplate): ColumnBuilder<TData, TKind, WithDefault<F>> {\n if (isSqlTemplate(value)) {\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"sql\", expression: value.text } });\n }\n const stored = value instanceof Date ? value.toISOString() : value;\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"literal\", value: stored } });\n }\n\n /** Refused: Drizzle's run-time default function. See {@link DRIZZLE_REFUSALS}. */\n $defaultFn(this: Refusal[\"defaultFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.defaultFn);\n }\n\n /** Refused: Drizzle's alias of `$defaultFn`. See {@link DRIZZLE_REFUSALS}. */\n $default(this: Refusal[\"defaultFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.defaultFn);\n }\n\n /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */\n $onUpdate(this: Refusal[\"onUpdateFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.onUpdateFn);\n }\n\n /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */\n $onUpdateFn(this: Refusal[\"onUpdateFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.onUpdateFn);\n }\n\n /**\n * Refused: a foreign key is a relation, `rel.belongsTo(() => users, {...})`\n * under `relations`, whose key is what `include` names.\n */\n references(this: Refusal[\"references\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.references);\n }\n\n /**\n * The database already holds a default for this column that Rebase does not\n * state. A create may omit the column, and a schema push leaves the default\n * alone.\n */\n dbDefault(): ColumnBuilder<TData, TKind, WithDefault<F>> {\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"database\" } });\n }\n\n /**\n * `GENERATED ALWAYS AS (<expression>) STORED`, as Drizzle writes it:\n * `.generatedAlwaysAs(sql\\`lower(email)\\`)`. Nobody writes the column.\n */\n generatedAlwaysAs(as: SqlTemplate | (() => SqlTemplate)): ColumnBuilder<TData, TKind, SetFlag<WithDefault<F>, \"writable\", false>> {\n const expression: unknown = typeof as === \"function\" ? as() : as;\n if (!isSqlTemplate(expression)) throw new Error(DRIZZLE_REFUSALS.generatedValue);\n return this.with<TData, TKind, SetFlag<WithDefault<F>, \"writable\", false>>({\n generatedAs: expression.text,\n readOnly: true\n });\n }\n\n /**\n * Client writes are refused on create and update. The database (a default,\n * a trigger) and the server's own code still fill it.\n */\n readOnly(): ColumnBuilder<TData, TKind, SetFlag<F, \"writable\", false>> {\n return this.with<TData, TKind, SetFlag<F, \"writable\", false>>({ readOnly: true });\n }\n\n /**\n * Never leaves the server: absent from every row on the wire, from the SDK\n * and from OpenAPI, and refused in filters and sorts. Hooks and server code\n * still see it.\n */\n private(): ColumnBuilder<TData, TKind, SetFlag<SetFlag<F, \"exposed\", false>, \"writable\", false>> {\n return this.with<TData, TKind, SetFlag<SetFlag<F, \"exposed\", false>, \"writable\", false>>({ private: true });\n }\n\n /**\n * Who may read and who may write the column, by role. Enforced on every\n * door into the table, not only in the panel. `read` and `write` are lists\n * of role names; anything else throws.\n */\n access(access: ColumnAccess): ColumnBuilder<TData, TKind, F> {\n return this.with<TData, TKind, F>({ access: normalizeColumnAccess(access, \"a column (`.access()`)\") });\n }\n\n /** What the column holds, for OpenAPI and MCP tool descriptions. */\n describe(description: string): ColumnBuilder<TData, TKind, F> {\n return this.with<TData, TKind, F>({ description });\n }\n\n /** Rules the API checks before a write. */\n validate(rules: ValidationFor<TKind>): ColumnBuilder<TData, TKind, F> {\n const input: ValidationInput = rules;\n return this.with<TData, TKind, F>({ validate: { ...this.def.validate, ...normalizeValidation(input) } });\n }\n\n /**\n * Field-level hooks: `beforeSave` returns the value to store, `afterRead`\n * the value to serve. They run on the server, for every caller.\n *\n * The value is `TData | null` on a column not (yet) marked `.notNull()` /\n * `.primaryKey()` — a nullable column hands the hook `null` — and `TData`\n * on one that is; see {@link ColumnTransformValue}. Chain `.notNull()`\n * before `.transform()` to get the narrower type.\n */\n transform(transform: ColumnTransform<ColumnTransformValue<TData, F>>): ColumnBuilder<TData, TKind, F> {\n const erased: ColumnTransform = transform;\n return this.with<TData, TKind, F>({ transform: erased });\n }\n\n // ── Text and numbers ─────────────────────────────────────────────────\n\n /**\n * A closed set of accepted values that is *not* a Postgres enum type: the\n * API refuses anything else and the SDK types the column as their union.\n * Use `col.enum()` when the database should enforce it too.\n *\n * On a number column. On a text column write Drizzle's spelling,\n * `col.text({ enum: [...] })`.\n */\n oneOf<const V extends readonly TData[], K extends TextColumnKind | NumericColumnKind>(\n this: ColumnBuilder<TData, K, F>,\n values: V\n ): ColumnBuilder<V[number], K, F> {\n const stored: (string | number)[] = [];\n for (const value of values) {\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n throw new Error(\"`.oneOf()` takes strings or numbers.\");\n }\n stored.push(value);\n }\n return this.with<V[number], K, F>({ oneOf: stored });\n }\n\n // ── uuid ─────────────────────────────────────────────────────────────\n\n /** `DEFAULT gen_random_uuid()`. */\n defaultRandom(this: ColumnBuilder<string, \"uuid\", F>): ColumnBuilder<string, \"uuid\", WithDefault<F>> {\n return this.with<string, \"uuid\", WithDefault<F>>({ default: { kind: \"random-uuid\" } });\n }\n\n // ── Integers ─────────────────────────────────────────────────────────\n\n /** `GENERATED BY DEFAULT AS IDENTITY`. Sequence options are refused. */\n generatedByDefaultAsIdentity<K extends \"smallint\" | \"integer\" | \"bigint\">(\n this: ColumnBuilder<number, K, F>,\n sequence?: Refusal[\"identityOptions\"]\n ): ColumnBuilder<number, K, WithDefault<F>> {\n if (sequence !== undefined) throw new Error(DRIZZLE_REFUSALS.identityOptions);\n return this.with<number, K, WithDefault<F>>({ default: { kind: \"identity\" } });\n }\n\n /** Refused: Rebase creates identity columns `GENERATED BY DEFAULT`. See {@link DRIZZLE_REFUSALS}. */\n generatedAlwaysAsIdentity(this: Refusal[\"identityAlways\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.identityAlways);\n }\n\n // ── Arrays ───────────────────────────────────────────────────────────\n\n /**\n * A Postgres array of this column's type, as Drizzle writes it:\n * `col.text().array()` is `TEXT[]`. What is chained before `.array()`\n * describes each item (`col.text({ enum: [...] }).array()`,\n * `col.integer().validate({ min: 0 }).array()`); column modifiers come\n * after it (`.array().notNull().default([])`). A leading SQL name\n * (`col.text(\"tag_list\").array()`) names the array column.\n */\n array(\n this: F extends InitialColumnFlags\n ? TKind extends \"array\" ? Refusal[\"arrayOfArray\"] : ColumnBuilder<TData, TKind, F>\n : Refusal[\"arrayOrder\"],\n size?: Refusal[\"arraySize\"]\n ): ColumnBuilder<TData[], \"array\"> {\n if (size !== undefined) throw new Error(DRIZZLE_REFUSALS.arraySize);\n if (!isColumnBuilder(this)) throw new Error(\"`.array()` is called on a column builder.\");\n const { column, ...item } = this.def;\n if (item.notNull || item.primaryKey || item.default !== undefined || item.readOnly || item.private) {\n throw new Error(DRIZZLE_REFUSALS.arrayOrder);\n }\n const def = arrayDef(item);\n if (column !== undefined) def.column = column;\n return new ColumnBuilder<TData[], \"array\">(def);\n }\n\n // ── Temporal ─────────────────────────────────────────────────────────\n\n /**\n * `DEFAULT now()`, as Drizzle's `defaultNow()`: a DDL default a client may\n * still override. `.onCreateNow()` is the server stamp the client cannot.\n */\n defaultNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>({ default: { kind: \"sql\", expression: \"now()\" } });\n }\n\n /** The server stamps the current time when the row is created (`DEFAULT now()`). */\n onCreateNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"create\", value: \"now\" }, \"onCreateNow\"));\n }\n\n /**\n * The server stamps the current time on every write: `DEFAULT now()`, a\n * `BEFORE UPDATE` trigger, and the driver's own stamp.\n */\n onUpdateNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"update\", value: \"now\" }, \"onUpdateNow\"));\n }\n\n // ── Acting user ──────────────────────────────────────────────────────\n\n /** The server writes the caller's id when the row is created. */\n onCreateUser<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"create\", value: \"user\" }, \"onCreateUser\"));\n }\n\n /** The server writes the caller's id on every write. */\n onUpdateUser<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"update\", value: \"user\" }, \"onUpdateUser\"));\n }\n\n /**\n * The column holds the id of a user. The panel offers a user picker for it,\n * and callers who may write the table may look users up to fill it (the\n * user picker's read answers them even though row-level security hides\n * other users' rows).\n *\n * Only on `col.text()`, `col.varchar()`, `col.char()` and `col.uuid()`;\n * anything else throws. It declares no foreign key: use\n * `rel.belongsTo(() => users)` when the database should enforce one.\n */\n userId<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, F> {\n const kind = this.def.type.kind;\n if ((kind !== \"text\" && kind !== \"varchar\" && kind !== \"char\" && kind !== \"uuid\") || this.def.storage !== undefined) {\n const what = this.def.storage !== undefined ? \"`col.storage()`\" : `a \\`${kind}\\` column`;\n throw new Error(\n `\\`.userId()\\` on ${what}: a user's id is held by \\`col.text()\\`, \\`col.varchar()\\`, \\`col.char()\\` or \\`col.uuid()\\`.`\n );\n }\n return this.with<string, K, F>({ semantic: \"user\" });\n }\n\n // ── Storage ──────────────────────────────────────────────────────────\n\n /** The column holds several files: `TEXT[]` of paths. */\n multiple(this: ColumnBuilder<string, \"storage\", F>): ColumnBuilder<string[], \"array\", F> {\n const { storage, validate, ...rest } = this.def;\n return new ColumnBuilder<string[], \"array\", F>({\n ...rest,\n type: { kind: \"array\", of: { kind: \"text\" } },\n storage,\n element: { ...baseDef({ kind: \"text\" }), storage, validate }\n });\n }\n}\n\n/** Any column, whatever it holds. */\nexport type AnyColumn = ColumnBuilder<unknown, BuilderKind, ColumnFlags>;\n\n/**\n * The `columns` of a table: builders by key, in physical order.\n *\n * @group Schema\n */\nexport type ColumnsShape = Record<string, AnyColumn>;\n\n/** The SQL column name a builder's leading argument gives, checked. */\nfunction sqlName(name: string | undefined, builder: string): string | undefined {\n if (name === undefined) return undefined;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(`\\`col.${builder}(name, …)\\`: the leading argument is the SQL column name, a non-empty string.`);\n }\n return name;\n}\n\n/** A fresh definition, named by the builder's leading argument when it has one. */\nfunction namedDef(type: ColumnType, name: string | undefined, builder: string): ColumnDef {\n const def = baseDef(type);\n const column = sqlName(name, builder);\n if (column !== undefined) def.column = column;\n return def;\n}\n\n/** Drizzle's `(name?, config?)` arguments, either of which may be left out. */\nfunction nameAndConfig<C>(first: string | C | undefined, second: C | undefined): [string | undefined, C | undefined] {\n return typeof first === \"string\" ? [first, second] : [undefined, first];\n}\n\n/** A config object, checked at run time: JavaScript callers bypass the types. */\nfunction configOf(value: unknown, builder: string): Record<string, unknown> {\n if (value === undefined) return {};\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`\\`col.${builder}()\\` takes an optional SQL column name and a config object, got ${JSON.stringify(value)}.`);\n }\n return { ...value };\n}\n\n/** The definition of an array of `item`: what `col.text().array()` builds. */\nfunction arrayDef(item: ColumnDef): ColumnDef {\n if (item.type.kind === \"array\") throw new Error(DRIZZLE_REFUSALS.arrayOfArray);\n const def = baseDef({ kind: \"array\", of: item.type });\n def.element = item;\n if (item.storage) def.storage = item.storage;\n return def;\n}\n\n/** A list of string labels: an enum's values, Drizzle's `{ enum: [...] }`. */\nfunction labelsOf(values: unknown, where: string): string[] {\n if (!Array.isArray(values) || values.length === 0 || values.some(value => typeof value !== \"string\")) {\n throw new Error(`${where} takes a non-empty list of strings, got ${JSON.stringify(values)}.`);\n }\n return values.filter((value): value is string => typeof value === \"string\");\n}\n\n/** A non-empty list of string labels, as a type. */\ntype Labels = readonly [string, ...string[]];\n\n/** What `col.text()` takes besides the name: Drizzle's `{ enum }`, a closed set of values. */\nexport interface TextConfig<E extends Labels = Labels> {\n /** The values the API accepts; the SDK types the column as their union. A Postgres enum type is `pgEnum`. */\n enum: E;\n}\n\n/** What `col.varchar()` / `col.char()` take besides the name. */\nexport interface StringConfig<E extends Labels = Labels> {\n /** The length in characters. Required: a bare varchar is unbounded and a bare char is char(1). */\n length: number;\n /** The values the API accepts, as `col.text({ enum })`. */\n enum?: E;\n}\n\n/** What `col.numeric()` takes besides the name. */\nexport interface NumericConfig {\n /** Total number of digits. */\n precision?: number;\n /** Digits after the decimal point. Needs a precision. */\n scale?: number;\n /** The value is a JSON number. Drizzle's `\"string\"` and `\"bigint\"` modes are refused. */\n mode?: \"number\" | Refusal[\"numericMode\"];\n}\n\n/** What `col.bigint()` / `col.bigserial()` take besides the name. */\nexport interface BigintConfig {\n /** `\"number\"`: the value is a JSON number. Drizzle's `\"bigint\"` mode is refused. */\n mode: \"number\" | Refusal[\"bigintMode\"];\n}\n\n/** What `col.timestamp()` takes besides the name. */\nexport interface TimestampConfig {\n /** `true`: the column is `TIMESTAMPTZ`, the only timestamp Rebase creates. */\n withTimezone: true;\n /** `\"string\"`: an ISO string on the wire, which it always is. */\n mode?: \"string\" | Refusal[\"timestampMode\"];\n /** Refused: Rebase does not state a timestamp's precision. */\n precision?: Refusal[\"timestampPrecision\"];\n}\n\n/** What `col.date()` takes besides the name. */\nexport interface DateConfig {\n /** `\"string\"`: `YYYY-MM-DD` on the wire, which it always is. */\n mode?: \"string\" | Refusal[\"dateMode\"];\n}\n\n/** What `col.time()` takes besides the name. */\nexport interface TimeConfig {\n /** `false` or omitted: `col.time()` is a time without time zone. */\n withTimezone?: false | Refusal[\"timeZone\"];\n /** Refused: Rebase does not state a time's precision. */\n precision?: Refusal[\"timePrecision\"];\n}\n\n/** What `col.vector()` takes besides the name. */\nexport interface VectorConfig {\n /** The number of dimensions. */\n dimensions: number;\n /** The approximate-nearest-neighbour index: HNSW cosine when omitted, none with `false`. */\n index?: VectorIndexOptions | false;\n}\n\n/** What `col.custom()` takes besides the name. */\nexport interface CustomConfig {\n /** The Postgres type, verbatim: `\"inet\"`, `\"citext\"`, `\"geometry(Point, 4326)\"`. */\n dataType: string;\n}\n\nconst checkMode = (value: unknown, allowed: string, message: string): void => {\n if (value !== undefined && value !== allowed) throw new Error(message);\n};\n\nfunction jsonColumn<T, K extends \"json\" | \"jsonb\">(kind: K, first: string | JsonField<T, JsonKind, boolean> | undefined, second: JsonField<T, JsonKind, boolean> | undefined): ColumnBuilder<T, K> {\n const [name, shape] = nameAndConfig(first, second);\n const def = namedDef({ kind }, name, kind);\n if (shape) def.json = shape.shape;\n return new ColumnBuilder<T, K>(def);\n}\n\nfunction jsonb(name?: string): ColumnBuilder<unknown, \"jsonb\">;\nfunction jsonb<T>(shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\">;\nfunction jsonb<T>(name: string, shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\">;\nfunction jsonb<T>(first?: string | JsonField<T, JsonKind, boolean>, second?: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\"> {\n return jsonColumn<T, \"jsonb\">(\"jsonb\", first, second);\n}\n\nfunction json(name?: string): ColumnBuilder<unknown, \"json\">;\nfunction json<T>(shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\">;\nfunction json<T>(name: string, shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\">;\nfunction json<T>(first?: string | JsonField<T, JsonKind, boolean>, second?: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\"> {\n return jsonColumn<T, \"json\">(\"json\", first, second);\n}\n\nconst lengthOf = (length: unknown, builder: string): number => {\n if (typeof length !== \"number\" || !Number.isInteger(length) || length <= 0) {\n throw new Error(`\\`col.${builder}({ length })\\` takes a positive whole number of characters, got ${String(length)}.`);\n }\n return length;\n};\n\nfunction text(name?: string): ColumnBuilder<string, \"text\">;\nfunction text<const E extends Labels>(config: TextConfig<E>): ColumnBuilder<E[number], \"text\">;\nfunction text<const E extends Labels>(name: string, config: TextConfig<E>): ColumnBuilder<E[number], \"text\">;\nfunction text(first?: string | TextConfig, second?: TextConfig): ColumnBuilder<string, \"text\"> {\n const [name, rawConfig] = nameAndConfig(first, second);\n const config = configOf(rawConfig, \"text\");\n const def = namedDef({ kind: \"text\" }, name, \"text\");\n if (config.enum !== undefined) def.oneOf = labelsOf(config.enum, \"`col.text({ enum })`\");\n return new ColumnBuilder<string, \"text\">(def);\n}\n\n/** `varchar` / `char`: Drizzle's `(name?, { length, enum? })`. A length is required. */\nfunction stringColumn<K extends \"varchar\" | \"char\">(kind: K, first: unknown, second: unknown): ColumnBuilder<string, K> {\n const name = typeof first === \"string\" ? first : undefined;\n const raw = typeof first === \"string\" ? second : first;\n if (raw === undefined || typeof raw === \"number\") throw new Error(kind === \"varchar\" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);\n const config = configOf(raw, kind);\n if (config.length === undefined) throw new Error(kind === \"varchar\" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);\n const length = lengthOf(config.length, kind);\n const def = namedDef(kind === \"varchar\" ? { kind: \"varchar\", length } : { kind: \"char\", length }, name, kind);\n if (config.enum !== undefined) def.oneOf = labelsOf(config.enum, `\\`col.${kind}({ enum })\\``);\n return new ColumnBuilder<string, K>(def);\n}\n\nfunction varchar(config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"varchar\">;\nfunction varchar<const E extends Labels>(config: StringConfig<E> & object): ColumnBuilder<E[number], \"varchar\">;\nfunction varchar(name: string, config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"varchar\">;\nfunction varchar<const E extends Labels>(name: string, config: StringConfig<E> & object): ColumnBuilder<E[number], \"varchar\">;\nfunction varchar(this: Refusal[\"varcharLength\"], ...rest: unknown[]): never;\nfunction varchar(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"varchar\"> {\n return stringColumn(\"varchar\", first, second);\n}\n\nfunction char(config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"char\">;\nfunction char<const E extends Labels>(config: StringConfig<E> & object): ColumnBuilder<E[number], \"char\">;\nfunction char(name: string, config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"char\">;\nfunction char<const E extends Labels>(name: string, config: StringConfig<E> & object): ColumnBuilder<E[number], \"char\">;\nfunction char(this: Refusal[\"charLength\"], ...rest: unknown[]): never;\nfunction char(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"char\"> {\n return stringColumn(\"char\", first, second);\n}\n\nfunction enumColumn<const V extends Labels>(values: V): ColumnBuilder<V[number], \"enum\">;\nfunction enumColumn<const V extends Labels>(name: string, values: V): ColumnBuilder<V[number], \"enum\">;\nfunction enumColumn(this: Refusal[\"enumName\"], values: Labels, options: Readonly<Record<string, unknown>>): never;\nfunction enumColumn(this: unknown, first: string | Labels, second?: unknown): ColumnBuilder<string, \"enum\"> {\n if (typeof first === \"string\") {\n const values = labelsOf(second, \"`col.enum(name, values)`\");\n return new ColumnBuilder<string, \"enum\">(namedDef({ kind: \"enum\", values }, first, \"enum\"));\n }\n if (second !== undefined) throw new Error(DRIZZLE_REFUSALS.enumName);\n if (first.length === 0) throw new Error(\"`col.enum([...])` needs at least one value.\");\n return new ColumnBuilder<string, \"enum\">(baseDef({ kind: \"enum\", values: [...first] }));\n}\n\n/** `numeric`, Drizzle's `(name?, { precision, scale, mode })`. */\nfunction numericColumn(builder: string, first: unknown, second: unknown): ColumnBuilder<number, \"numeric\"> {\n if (typeof first === \"number\" || typeof second === \"number\") throw new Error(DRIZZLE_REFUSALS.numericPositional);\n const name = typeof first === \"string\" ? first : undefined;\n const config = configOf(typeof first === \"string\" ? second : first, builder);\n checkMode(config.mode, \"number\", DRIZZLE_REFUSALS.numericMode);\n const precision: unknown = config.precision;\n const scale: unknown = config.scale;\n if (scale !== undefined && precision === undefined) {\n throw new Error(`\\`col.${builder}({ precision, scale })\\`: a scale needs a precision.`);\n }\n for (const [what, value] of [[\"precision\", precision], [\"scale\", scale]] as const) {\n if (value !== undefined && (typeof value !== \"number\" || !Number.isInteger(value) || value < 0)) {\n throw new Error(`\\`col.${builder}()\\`: \\`${what}\\` is a whole number, got ${String(value)}.`);\n }\n }\n const type: ColumnType = typeof precision !== \"number\"\n ? { kind: \"numeric\" }\n : typeof scale !== \"number\" ? { kind: \"numeric\", precision } : { kind: \"numeric\", precision, scale };\n return new ColumnBuilder<number, \"numeric\">(namedDef(type, name, builder));\n}\n\nfunction numeric(name?: string, config?: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction numeric(config: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction numeric(this: Refusal[\"numericPositional\"], precision: number, scale?: number): never;\nfunction numeric(this: unknown, first?: string | number | NumericConfig, second?: number | NumericConfig): ColumnBuilder<number, \"numeric\"> {\n return numericColumn(\"numeric\", first, second);\n}\n\nfunction decimal(name?: string, config?: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction decimal(config: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction decimal(first?: string | NumericConfig, second?: NumericConfig): ColumnBuilder<number, \"numeric\"> {\n return numericColumn(\"decimal\", first, second);\n}\n\n/** `bigint` / `bigserial`, Drizzle's `(name?, { mode })`. */\nfunction bigColumn<K extends \"bigint\" | \"bigserial\">(kind: K, first: unknown, second: unknown): ColumnBuilder<number, K> {\n const name = typeof first === \"string\" ? first : undefined;\n const raw = typeof first === \"string\" ? second : first;\n if (raw === undefined) throw new Error(DRIZZLE_REFUSALS.bigintModeMissing);\n checkMode(configOf(raw, kind).mode, \"number\", DRIZZLE_REFUSALS.bigintMode);\n return new ColumnBuilder<number, K>(namedDef(kind === \"bigint\" ? { kind: \"bigint\" } : { kind: \"bigserial\" }, name, kind));\n}\n\nfunction bigint(config: BigintConfig): ColumnBuilder<number, \"bigint\">;\nfunction bigint(name: string, config: BigintConfig): ColumnBuilder<number, \"bigint\">;\nfunction bigint(this: Refusal[\"bigintModeMissing\"], ...rest: unknown[]): never;\nfunction bigint(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<number, \"bigint\"> {\n return bigColumn(\"bigint\", first, second);\n}\n\nfunction bigserial(config: BigintConfig): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>;\nfunction bigserial(name: string, config: BigintConfig): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>;\nfunction bigserial(this: Refusal[\"bigintModeMissing\"], ...rest: unknown[]): never;\nfunction bigserial(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>(bigColumn(\"bigserial\", first, second).def);\n}\n\nfunction timestamp(config: TimestampConfig): ColumnBuilder<string, \"timestamptz\">;\nfunction timestamp(name: string, config: TimestampConfig): ColumnBuilder<string, \"timestamptz\">;\nfunction timestamp(this: Refusal[\"timestamp\"], ...rest: unknown[]): never;\nfunction timestamp(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"timestamptz\"> {\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"timestamp\");\n if (config.withTimezone !== true) throw new Error(DRIZZLE_REFUSALS.timestamp);\n checkMode(config.mode, \"string\", DRIZZLE_REFUSALS.timestampMode);\n if (config.precision !== undefined) throw new Error(DRIZZLE_REFUSALS.timestampPrecision);\n return new ColumnBuilder<string, \"timestamptz\">(namedDef({ kind: \"timestamptz\" }, name, \"timestamp\"));\n}\n\nfunction date(name?: string, config?: DateConfig): ColumnBuilder<string, \"date\">;\nfunction date(config: DateConfig): ColumnBuilder<string, \"date\">;\nfunction date(first?: string | DateConfig, second?: DateConfig): ColumnBuilder<string, \"date\"> {\n const [name, raw] = nameAndConfig(first, second);\n checkMode(configOf(raw, \"date\").mode, \"string\", DRIZZLE_REFUSALS.dateMode);\n return new ColumnBuilder<string, \"date\">(namedDef({ kind: \"date\" }, name, \"date\"));\n}\n\nfunction time(name?: string, config?: TimeConfig): ColumnBuilder<string, \"time\">;\nfunction time(config: TimeConfig): ColumnBuilder<string, \"time\">;\nfunction time(first?: string | TimeConfig, second?: TimeConfig): ColumnBuilder<string, \"time\"> {\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"time\");\n if (config.withTimezone !== undefined && config.withTimezone !== false) throw new Error(DRIZZLE_REFUSALS.timeZone);\n if (config.precision !== undefined) throw new Error(DRIZZLE_REFUSALS.timePrecision);\n return new ColumnBuilder<string, \"time\">(namedDef({ kind: \"time\" }, name, \"time\"));\n}\n\nfunction vector(config: VectorConfig): ColumnBuilder<number[], \"vector\">;\nfunction vector(name: string, config: VectorConfig): ColumnBuilder<number[], \"vector\">;\nfunction vector(this: Refusal[\"vectorPositional\"], dimensions: number, ...rest: unknown[]): never;\nfunction vector(this: unknown, first: unknown, second?: unknown): ColumnBuilder<number[], \"vector\"> {\n if (typeof first === \"number\") throw new Error(DRIZZLE_REFUSALS.vectorPositional);\n const name = typeof first === \"string\" ? first : undefined;\n const config = configOf(typeof first === \"string\" ? second : first, \"vector\");\n const dimensions: unknown = config.dimensions;\n const index: unknown = config.index;\n if (typeof dimensions !== \"number\" || !Number.isInteger(dimensions) || dimensions <= 0) {\n throw new Error(`\\`col.vector({ dimensions })\\` takes a positive whole number, got ${String(dimensions)}.`);\n }\n const def = namedDef({ kind: \"vector\", dimensions }, name, \"vector\");\n if (index === false) def.vectorIndex = false;\n else if (typeof index === \"object\" && index !== null) def.vectorIndex = { ...index };\n else if (index !== undefined) throw new Error(\"`col.vector({ index })` takes index options or `false`.\");\n return new ColumnBuilder<number[], \"vector\">(def);\n}\n\nfunction storage(options: StorageOptions): ColumnBuilder<string, \"storage\">;\nfunction storage(name: string, options: StorageOptions): ColumnBuilder<string, \"storage\">;\nfunction storage(first: string | StorageOptions, second?: StorageOptions): ColumnBuilder<string, \"storage\"> {\n const [name, options] = nameAndConfig(first, second);\n if (options === undefined) throw new Error(\"`col.storage()` takes its options: `col.storage({ path: \\\"posts/heroes/\\\" })`.\");\n const def = namedDef({ kind: \"text\" }, name, \"storage\");\n def.storage = normalizeStorage(options);\n return new ColumnBuilder<string, \"storage\">(def);\n}\n\nfunction custom<T = string>(config: CustomConfig): ColumnBuilder<T, \"other\">;\nfunction custom<T = string>(name: string, config: CustomConfig): ColumnBuilder<T, \"other\">;\nfunction custom(this: Refusal[\"customDataType\"], name: string): never;\nfunction custom<T = string>(this: unknown, first: string | CustomConfig, second?: CustomConfig): ColumnBuilder<T, \"other\"> {\n if (typeof first === \"string\" && second === undefined) throw new Error(DRIZZLE_REFUSALS.customDataType);\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"custom\");\n if (typeof config.dataType !== \"string\") {\n throw new Error(\"`col.custom()` names its Postgres type: `col.custom({ dataType: \\\"inet\\\" })`.\");\n }\n return new ColumnBuilder<T, \"other\">(namedDef({ kind: \"other\", sqlType: customSqlType(config.dataType) }, name, \"custom\"));\n}\n\n/** A builder for a Drizzle column type Rebase serves only through `col.custom()`: refused with the spelling. */\nfunction unsupported<T extends string>(type: T): (this: UnsupportedType<T>, ..._args: unknown[]) => never {\n return () => {\n throw new Error(unsupportedMessage(type));\n };\n}\n\n/** A builder that takes only the optional SQL column name. */\nfunction simple<D, K extends ColumnKind>(kind: K & BuilderKind, type: ColumnType): (name?: string) => ColumnBuilder<D, K> {\n return (name?: string) => new ColumnBuilder<D, K>(namedDef(type, name, kind));\n}\n\n/**\n * The column builders, spelled as Drizzle's `pg-core` spells them: the\n * optional SQL column name first, then Drizzle's config object, then the\n * chain.\n *\n * ```ts\n * columns: {\n * id: col.uuid().primaryKey().defaultRandom(),\n * title: col.text().notNull().validate({ min: 3, max: 200 }),\n * slug: col.varchar({ length: 160 }).notNull().unique(),\n * status: postStatus().notNull().default(\"draft\"), // const postStatus = pgEnum(\"post_status\", [...])\n * tags: col.text().array().notNull().default([]),\n * heroImage: col.storage({ path: \"posts/heroes/\", accept: [\"image/*\"], maxBytes: \"10MB\" }),\n * createdAt: col.timestamp({ withTimezone: true }).notNull().defaultNow(),\n * }\n * ```\n *\n * @group Schema\n */\nexport const col = {\n /** `UUID`. */\n uuid: simple<string, \"uuid\">(\"uuid\", { kind: \"uuid\" }),\n /** `TEXT`. `col.text({ enum: [...] })` accepts only those values. */\n text,\n /** `VARCHAR(n)`: `col.varchar({ length: n })`. */\n varchar,\n /** `CHAR(n)`: `col.char({ length: n })`. */\n char,\n /**\n * A Postgres enum type of its own, created as `<table>_<column>`. A type\n * with a stated name, shared by several columns, is `pgEnum(name, values)`.\n */\n enum: enumColumn,\n /** `SMALLINT`. */\n smallint: simple<number, \"smallint\">(\"smallint\", { kind: \"smallint\" }),\n /** `INTEGER`. */\n integer: simple<number, \"integer\">(\"integer\", { kind: \"integer\" }),\n /** `BIGINT`, read and written as a JavaScript number: `col.bigint({ mode: \"number\" })`. */\n bigint,\n /** `SMALLSERIAL`. Prefer `col.smallint().generatedByDefaultAsIdentity()` in a new schema. */\n smallserial(name?: string): ColumnBuilder<number, \"smallserial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"smallserial\", WithDefault<InitialColumnFlags>>(namedDef({ kind: \"smallserial\" }, name, \"smallserial\"));\n },\n /** `SERIAL`. Prefer `col.integer().generatedByDefaultAsIdentity()` in a new schema. */\n serial(name?: string): ColumnBuilder<number, \"serial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"serial\", WithDefault<InitialColumnFlags>>(namedDef({ kind: \"serial\" }, name, \"serial\"));\n },\n /** `BIGSERIAL`: `col.bigserial({ mode: \"number\" })`. Prefer an identity column in a new schema. */\n bigserial,\n /** `REAL`. */\n real: simple<number, \"real\">(\"real\", { kind: \"real\" }),\n /** `DOUBLE PRECISION`. */\n doublePrecision: simple<number, \"doublePrecision\">(\"doublePrecision\", { kind: \"doublePrecision\" }),\n /** `NUMERIC`, `NUMERIC(p)` or `NUMERIC(p, s)`: `col.numeric({ precision, scale })`. A JSON number. */\n numeric,\n /** Drizzle's alias of `col.numeric()`. */\n decimal,\n /** `BOOLEAN`. */\n boolean: simple<boolean, \"boolean\">(\"boolean\", { kind: \"boolean\" }),\n /** `TIMESTAMPTZ`: `col.timestamp({ withTimezone: true })`. An ISO string on the wire. */\n timestamp,\n /** `DATE`. `YYYY-MM-DD` on the wire. */\n date,\n /** `TIME`. `HH:MM:SS` on the wire. */\n time,\n /**\n * `JSONB`. `col.jsonb().$type<T>()` types the document;\n * `col.jsonb(json.object({...}))` also tells the server its shape, so\n * nested fields are validated, stamped and searchable.\n */\n jsonb,\n /** `JSON`. As `col.jsonb`, for a column that must keep the text it was given. */\n json,\n /**\n * `vector(dimensions)` (pgvector): `col.vector({ dimensions: 1536 })`. An\n * HNSW cosine index is created unless `index` says otherwise; `index: false`\n * creates none.\n */\n vector,\n /** `BYTEA`. Base64 on the wire. */\n bytea: simple<string, \"bytea\">(\"bytea\", { kind: \"bytea\" }),\n /** A point on Earth, stored as `JSONB` `{ latitude, longitude }`. */\n geopoint(name?: string): ColumnBuilder<JsonGeoPoint, \"geopoint\"> {\n const def = namedDef({ kind: \"jsonb\" }, name, \"geopoint\");\n def.semantic = \"geopoint\";\n return new ColumnBuilder<JsonGeoPoint, \"geopoint\">(def);\n },\n /**\n * The path of a stored file, as `TEXT` — or several with `.multiple()`. The\n * upload route enforces `accept` and `maxBytes`, and the orphan sweep counts\n * the file as referenced.\n */\n storage,\n /**\n * A column of a Postgres type no other builder names —\n * `col.custom({ dataType: \"inet\" })`, `col.custom({ dataType: \"citext\" })`,\n * `col.custom({ dataType: \"geometry(Point, 4326)\" })`. What\n * `rebase schema introspect` writes for a column of such a type, so a\n * project generated from an existing database keeps it.\n *\n * Rebase names the type in DDL, verbatim, and does nothing else with it: it\n * does not create, alter or drop the type's definition (an extension or a\n * `CREATE TYPE` the database already holds provides it), it does not\n * validate values, and it passes every value through exactly as the\n * driver returns it — a string for most types. `.$type<T>()` types it for\n * the SDK when the driver returns something else.\n */\n custom,\n /** Refused: write `col.custom({ dataType: \"interval\" })`. */\n interval: unsupported(\"interval\"),\n /** Refused: write `col.custom({ dataType: \"inet\" })`. */\n inet: unsupported(\"inet\"),\n /** Refused: write `col.custom({ dataType: \"cidr\" })`. */\n cidr: unsupported(\"cidr\"),\n /** Refused: write `col.custom({ dataType: \"macaddr\" })`. */\n macaddr: unsupported(\"macaddr\"),\n /** Refused: write `col.custom({ dataType: \"macaddr8\" })`. */\n macaddr8: unsupported(\"macaddr8\"),\n /** Refused: write `col.custom({ dataType: \"point\" })`. */\n point: unsupported(\"point\"),\n /** Refused: write `col.custom({ dataType: \"line\" })`. */\n line: unsupported(\"line\"),\n /** Refused: write `col.custom({ dataType: \"halfvec\" })`. */\n halfvec: unsupported(\"halfvec\"),\n /** Refused: write `col.custom({ dataType: \"sparsevec\" })`. */\n sparsevec: unsupported(\"sparsevec\"),\n /** Refused: write `col.custom({ dataType: \"bit\" })`. */\n bit: unsupported(\"bit\")\n};\n\n/**\n * A Postgres enum type with a stated name, as Drizzle declares one: call it in\n * a column, `status: postStatus().notNull()`, or with the SQL column name,\n * `postStatus(\"state\")`.\n *\n * @group Schema\n */\nexport interface PgEnum<V extends Labels> {\n /** A column of this enum type; the optional argument is the SQL column name. */\n (name?: string): ColumnBuilder<V[number], \"enum\">;\n /** The type's name in Postgres. */\n readonly enumName: string;\n /** Its labels, in order. */\n readonly enumValues: V;\n}\n\n/**\n * Declare a Postgres enum type by name, as Drizzle does:\n *\n * ```ts\n * export const postStatus = pgEnum(\"post_status\", [\"draft\", \"published\"]);\n * // columns: { status: postStatus().notNull().default(\"draft\") }\n * ```\n *\n * Every column of it shares the one type. Two declarations of the same name\n * must list the same labels.\n *\n * @group Schema\n */\nexport function pgEnum<const V extends Labels>(enumName: string, values: V): PgEnum<V>;\nexport function pgEnum(this: Refusal[\"pgEnumObject\"], enumName: string, values: Readonly<Record<string, string>>): never;\nexport function pgEnum<const V extends Labels>(this: unknown, enumName: string, values: V | Readonly<Record<string, string>>): PgEnum<V> {\n if (typeof enumName !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(enumName)) {\n throw new Error(`\\`pgEnum(name, values)\\`: the name is a plain SQL identifier, got ${JSON.stringify(enumName)}.`);\n }\n if (!isLabelTuple<V>(values)) throw new Error(DRIZZLE_REFUSALS.pgEnumObject);\n const labels = [...values];\n const factory = (name?: string): ColumnBuilder<V[number], \"enum\"> =>\n new ColumnBuilder<V[number], \"enum\">(namedDef({ kind: \"enum\", values: labels, name: enumName }, name, \"enum\"));\n return Object.assign(factory, { enumName, enumValues: values });\n}\n\nfunction isLabelTuple<V extends Labels>(values: V | Readonly<Record<string, string>>): values is V {\n return Array.isArray(values) && values.length > 0 && values.every(value => typeof value === \"string\");\n}\n\n/**\n * The type name `col.custom()` puts into DDL: trimmed, and refused when it is\n * empty or could end the statement it is written into.\n */\nfunction customSqlType(sqlType: string): string {\n const trimmed = typeof sqlType === \"string\" ? sqlType.trim() : \"\";\n if (trimmed.length === 0) throw new Error(\"`col.custom()` takes the Postgres type, e.g. `col.custom({ dataType: \\\"inet\\\" })`.\");\n if (/;|--|\\/\\*/.test(trimmed)) {\n throw new Error(`\\`col.custom({ dataType: ${JSON.stringify(sqlType)} })\\`: a type name holds no \\`;\\` and no comment.`);\n }\n return trimmed;\n}\n\n/**\n * Whether a value is a column builder, from this copy of the package or\n * another.\n *\n * @group Schema\n */\nexport function isColumnBuilder(value: unknown): value is AnyColumn {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === COLUMN_BRAND;\n}\n","import type { JoinStep, OnAction } from \"../types/relations\";\nimport type { OrderByTuple } from \"../types/filter-operators\";\nimport type { ColumnAccess } from \"./column_options\";\nimport { normalizeColumnAccess } from \"./column_options\";\nimport type { ColumnsShape } from \"./columns\";\n\n/**\n * A relation's target, as written: `() => users`.\n *\n * Typed `() => void` on purpose. A thunk typed by what it returns (generic\n * over the returned table, a structural table type, or `() => unknown`) makes\n * TypeScript resolve the returned table's type while it is still inferring the\n * table being defined, so two tables that point at each other — `posts.author`\n * → `users`, `users.posts` → `posts` — failed with TS7022/TS7024 unless one\n * thunk was annotated. A `void` return is the one form TypeScript never\n * resolves, so mutual and self relations need no annotation, in one file or\n * across files.\n *\n * What the thunk returns is checked when the schema is compiled instead: a\n * thunk that does not return a `defineTable` / `defineView` result is refused\n * by `compileTables`, naming the table and the relation.\n *\n * @group Schema\n */\nexport type TableThunk = () => void;\n\n/** The brand every relation builder result carries. */\nexport const RELATION_BRAND = \"rebase.relation\";\n\ninterface RelationDefBase {\n readonly brand: typeof RELATION_BRAND;\n /**\n * The table it points at, behind a thunk so two tables can point at each\n * other. Typed `() => unknown`: read it through `isTableDef` / `isViewDef`.\n */\n readonly target: () => unknown;\n}\n\n/**\n * Field-level access on a relation, accepted by every `rel.*`: who may read\n * the relation (`include` it, see its key) and who may write a link through it.\n * The same rules a column states with `.access()` / `.private()`, enforced by\n * the server on every door — an `include` the caller may not read is refused,\n * a nested write the caller may not make is refused.\n *\n * @group Schema\n */\nexport interface RelationAccessOptions {\n /**\n * Per-role read and write access to the relation. `read` lists the roles\n * that may include it; `write` the roles that may link or unlink through\n * it. Omitted: whoever the table's `rls` lets read or write the row.\n */\n access?: ColumnAccess;\n /**\n * `true` keeps the relation off the wire entirely: not includable, not in\n * the SDK or OpenAPI. Only server code traverses it. Not combined with\n * `access`.\n */\n private?: boolean;\n}\n\n/**\n * Options of `rel.belongsTo`.\n *\n * @group Schema\n */\nexport interface BelongsToOptions extends RelationAccessOptions {\n /**\n * The SQL column on this table holding the foreign key. `<relation>_id`\n * when omitted. A column in `columns` with this SQL name is bound to;\n * otherwise the column is derived from the target's key.\n */\n localKey?: string;\n /** The derived column is `NOT NULL`. A bound column says so itself. */\n notNull?: boolean;\n /** The derived column is `UNIQUE`, making this side one-to-one. */\n unique?: boolean;\n /** `RESTRICT` when the column is `NOT NULL`, `SET NULL` otherwise. */\n onDelete?: OnAction;\n /**\n * What the foreign key does when the referenced key changes. No `ON UPDATE`\n * clause when omitted, so Postgres's default applies: `NO ACTION`.\n */\n onUpdate?: OnAction;\n /** `false` skips the index on the foreign key that is otherwise created. */\n index?: boolean;\n /** `false` stores the key without a `FOREIGN KEY` constraint. */\n constraint?: boolean;\n}\n\n/**\n * Options of `rel.hasOne` and `rel.hasMany`.\n *\n * @group Schema\n */\nexport interface HasOptions extends RelationAccessOptions {\n /** The SQL column on the target that points back here. Derived from this table's slug when omitted. */\n foreignKey?: string;\n /** The SQL column on this table it points at, when that is not the primary key. */\n sourceKey?: string;\n}\n\n/**\n * Options of `rel.hasMany`.\n *\n * @group Schema\n */\nexport interface HasManyOptions extends HasOptions {\n /** The order related rows come back in when the caller names none. */\n orderBy?: OrderByTuple | readonly OrderByTuple[];\n}\n\n/**\n * Options of `rel.manyToMany`.\n *\n * @group Schema\n */\nexport interface ManyToManyOptions<P extends ColumnsShape = ColumnsShape> extends RelationAccessOptions {\n /** The junction table. The two table names, sorted and joined by `_`, when omitted. */\n through?: string;\n /** The junction column pointing at this table. */\n sourceKey?: string;\n /** The junction column pointing at the target. */\n targetKey?: string;\n /** Extra columns on the junction, read and written as `_pivot`. */\n pivot?: P;\n /** What happens to a link when either row is deleted. `CASCADE` when omitted. */\n onDelete?: OnAction;\n}\n\n/**\n * Options of `rel.via`.\n *\n * @group Schema\n */\nexport interface ViaOptions extends RelationAccessOptions {\n /** The joins from this table to the target, in order. */\n steps: readonly JoinStep[];\n /** `many` when omitted. */\n cardinality?: \"one\" | \"many\";\n}\n\n/** `rel.belongsTo(...)`. */\nexport interface BelongsToDef extends RelationDefBase, BelongsToOptions {\n readonly kind: \"belongsTo\";\n}\n\n/** `rel.hasOne(...)`. */\nexport interface HasOneDef extends RelationDefBase, HasOptions {\n readonly kind: \"hasOne\";\n}\n\n/** `rel.hasMany(...)`. */\nexport interface HasManyDef extends RelationDefBase, HasManyOptions {\n readonly kind: \"hasMany\";\n}\n\n/** `rel.manyToMany(...)`. */\nexport interface ManyToManyDef<P extends ColumnsShape = ColumnsShape> extends RelationDefBase, ManyToManyOptions<P> {\n readonly kind: \"manyToMany\";\n}\n\n/** `rel.via(...)`. */\nexport interface ViaDef extends RelationDefBase, ViaOptions {\n readonly kind: \"via\";\n}\n\n/**\n * A relation as authored: the result of one `rel.*` call.\n *\n * @group Schema\n */\nexport type RelationDef =\n | BelongsToDef\n | HasOneDef\n | HasManyDef\n | ManyToManyDef\n | ViaDef;\n\n/**\n * The `relations` of a table: `rel.*` results by relation name.\n *\n * @group Schema\n */\nexport type RelationsShape = Record<string, RelationDef>;\n\n/** The options with `access` checked and copied: a role list, never a string spread into characters. */\nfunction withCheckedAccess<O extends RelationAccessOptions>(kind: string, options: O): O {\n if (options.access === undefined) return options;\n return { ...options, access: normalizeColumnAccess(options.access, `a relation (\\`rel.${kind}(…, { access })\\`)`) };\n}\n\nfunction belongsTo(target: TableThunk): BelongsToDef;\nfunction belongsTo<const O extends BelongsToOptions>(target: TableThunk, options: O): BelongsToDef & O;\nfunction belongsTo(target: TableThunk, options: BelongsToOptions = {}): BelongsToDef {\n return { ...withCheckedAccess(\"belongsTo\", options), brand: RELATION_BRAND, kind: \"belongsTo\", target };\n}\n\n/**\n * The relation builders. All five kinds; the target is a thunk, so two tables\n * can point at each other whatever order their modules load in — and, being a\n * {@link TableThunk}, without a type annotation on either side.\n *\n * ```ts\n * relations: {\n * author: rel.belongsTo(() => users, { localKey: \"author_id\", notNull: true, onDelete: \"restrict\" }),\n * tags: rel.manyToMany(() => tags, { through: \"posts_tags\", pivot: { sortOrder: col.integer().default(0) } }),\n * }\n * ```\n *\n * @group Schema\n */\nexport const rel = {\n /**\n * This table holds the foreign key. Binds to the column in `columns` whose\n * SQL name is `localKey`, or derives that column and indexes it.\n */\n belongsTo,\n /** The target holds a unique foreign key pointing here. */\n hasOne(target: TableThunk, options: HasOptions = {}): HasOneDef {\n return { ...withCheckedAccess(\"hasOne\", options), brand: RELATION_BRAND, kind: \"hasOne\", target };\n },\n /** The target holds a foreign key pointing here. */\n hasMany(target: TableThunk, options: HasManyOptions = {}): HasManyDef {\n return { ...withCheckedAccess(\"hasMany\", options), brand: RELATION_BRAND, kind: \"hasMany\", target };\n },\n /**\n * Linked through a junction table, which is created with its own row-level\n * security. `pivot` columns are read and written as `_pivot`.\n */\n manyToMany<P extends ColumnsShape = Record<never, never>>(\n target: TableThunk,\n options: ManyToManyOptions<P> = {}\n ): ManyToManyDef<P> {\n return { ...withCheckedAccess(\"manyToMany\", options), brand: RELATION_BRAND, kind: \"manyToMany\", target };\n },\n /** A read-only traversal across several joins. */\n via(target: TableThunk, options: ViaOptions): ViaDef {\n if (!options.steps || options.steps.length === 0) {\n throw new Error(\"`rel.via(target, { steps })` needs at least one join step.\");\n }\n return { ...withCheckedAccess(\"via\", options), brand: RELATION_BRAND, kind: \"via\", target };\n }\n};\n\n/**\n * Whether a value is the result of a `rel.*` call.\n *\n * @group Schema\n */\nexport function isRelationDef(value: unknown): value is RelationDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === RELATION_BRAND;\n}\n","import type { User } from \"../users\";\nimport type { ResourceRef } from \"../types/resources\";\nimport type { SearchConfig } from \"../types/search\";\nimport type { RoleDefinition, ScopeDefinition } from \"../types/scopes\";\nimport type {\n AuthCollectionContext,\n AuthCollectionCreateResult,\n AuthCollectionResetResult\n} from \"../types/auth_hooks\";\nimport type { ColumnsShape } from \"./columns\";\nimport { isColumnBuilder } from \"./columns\";\nimport type { BelongsToDef, RelationsShape } from \"./relations\";\nimport { isRelationDef } from \"./relations\";\nimport type { TableHooks } from \"./hooks\";\nimport type { RlsPosture, TableIndex, TableTenant } from \"./table_options\";\nimport type { InsertOfColumns, RowOfColumns } from \"./infer\";\n\n/** The brand of a `defineTable` / `defineAuthTable` result. */\nexport const TABLE_BRAND = \"rebase.table\";\n/** The brand of a `defineView` result. */\nexport const VIEW_BRAND = \"rebase.view\";\n\n/**\n * What `defineTable` takes besides the name.\n *\n * @group Schema\n */\nexport interface TableConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> {\n /**\n * The name in the API, the SDK and in scopes. The table's name when\n * omitted. Captured as a literal type, so `TableSlugOf<typeof table>` reads it.\n */\n slug?: S;\n /** The SQL table name, when it is not the name the table is defined under. */\n table?: string;\n /** The Postgres schema. `public` when omitted. */\n schema?: string;\n /** A non-default Postgres database, declared in `backend/resources.ts`. */\n database?: ResourceRef;\n /** What the table holds, for OpenAPI and MCP tool descriptions. */\n description?: string;\n /**\n * The columns, in physical order. At least one must be `.primaryKey()`;\n * several form a composite key in declaration order.\n */\n columns: C;\n /** The relations, by name. */\n relations?: R;\n /**\n * The row-level security posture. Required: `\"admin-only\"`, `\"inherit\"`\n * (the project's `defaultRls`), or the rules to generate policies from.\n */\n rls: RlsPosture;\n /**\n * `false` generates only the declared rules, without the injected admin\n * baseline. Refused together with `rls: \"admin-only\"`. `true` keeps the\n * baseline even when the table's database switches it off for every\n * table (`database({ rls: { defaultPolicies: false } })`). Absent, the\n * database's declaration decides.\n */\n defaultPolicies?: boolean;\n /**\n * `false` serves the table even when the database does not enforce its\n * `rls`: row-level security off, or its declared policies missing. For a\n * table whose schema something else owns (Alembic, Prisma, a DBA) and\n * whose access the app enforces itself. The boot names every table it\n * serves this way. A boot that provisions still writes the declared\n * policies; this only stops a boot that provisions nothing from refusing\n * the table. `true` requires it even when the table's database says\n * `database({ rls: { required: false } })`. Absent, the database's\n * declaration decides (required by default).\n */\n rlsRequired?: boolean;\n /**\n * Scope every row to a tenant: a column key, or a `belongsTo` relation's\n * name, which stands for its foreign-key column (as the compiler reads it).\n */\n tenant?: TableTenant<NoInfer<Extract<keyof C, string> | BelongsToKeys<R>>>;\n /** Deleting stamps a timestamp column instead of removing the row. */\n softDelete?: boolean | { field?: NoInfer<Extract<keyof C, string>> };\n /** Record every write in the history table. */\n history?: boolean;\n /** Full-text search over these columns. */\n search?: SearchConfig;\n /**\n * Indexes, each with the query it serves. The keys are not inferred from:\n * without `NoInfer`, a key naming nothing made TypeScript infer a relation\n * of that name instead of refusing it.\n */\n indexes?: readonly TableIndex<NoInfer<Extract<keyof C, string> | Extract<keyof R, string>>>[];\n /** Server-side lifecycle hooks. */\n hooks?: TableHooks<RowOfColumns<C>, InsertOfColumns<C>, USER>;\n /** `false` accepts writes naming columns the table does not declare. */\n strictWrites?: false;\n /** Opaque data, served with the table's descriptor. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * The names of the `belongsTo` relations in `R`: the relations that own a\n * foreign-key column on this table, and so can stand for it.\n *\n * @group Schema\n */\nexport type BelongsToKeys<R extends RelationsShape> = {\n [K in Extract<keyof R, string>]: R[K] extends BelongsToDef ? K : never\n}[Extract<keyof R, string>];\n\n/**\n * A table as authored: the result of `defineTable`.\n *\n * `N` is the name it was defined under and `S` its slug — the `slug` it was\n * given, or the name when it was given none — both as literal types, so a\n * frontend holding only `typeof posts` knows the slug (`TableSlugOf`).\n *\n * @group Schema\n */\nexport interface TableDef<\n N extends string = string,\n C extends ColumnsShape = ColumnsShape,\n R extends RelationsShape = RelationsShape,\n S extends string = N\n> {\n readonly brand: typeof TABLE_BRAND;\n /** The name it was defined under. */\n readonly name: N;\n /** What it was defined with, as written. */\n readonly config: TableConfig<C, R, User, S>;\n /** Present when defined with `defineAuthTable`. */\n readonly auth?: AuthTableOptions;\n}\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertTableShape(builder: string, name: unknown, config: unknown): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(`\\`${builder}(name, config)\\` needs the table's name as its first argument.`);\n }\n if (typeof config !== \"object\" || config === null) {\n throw new Error(`\\`${builder}(\"${name}\", config)\\` needs a config object.`);\n }\n const columns = \"columns\" in config ? config.columns : undefined;\n if (typeof columns !== \"object\" || columns === null || Object.keys(columns).length === 0) {\n throw new Error(`Table \"${name}\" declares no columns. Add \\`columns: { id: col.uuid().primaryKey().defaultRandom(), … }\\`.`);\n }\n for (const [key, column] of Object.entries(columns)) {\n if (!isColumnBuilder(column)) {\n throw new Error(`Column \"${key}\" of table \"${name}\" is not a \\`col.*\\` builder.`);\n }\n }\n const relations = \"relations\" in config ? config.relations : undefined;\n if (relations !== undefined) {\n if (typeof relations !== \"object\" || relations === null) {\n throw new Error(`\\`relations\\` of table \"${name}\" must be an object of \\`rel.*\\` results.`);\n }\n for (const [key, relation] of Object.entries(relations)) {\n if (!isRelationDef(relation)) {\n throw new Error(`Relation \"${key}\" of table \"${name}\" is not a \\`rel.*\\` result.`);\n }\n if (key in columns) {\n throw new Error(\n `Table \"${name}\" has both a column and a relation named \"${key}\". ` +\n \"A relation's key is what `include` names; give the foreign-key column its own key.\"\n );\n }\n }\n }\n for (const key of [\"schema\", \"table\"] as const) {\n const value: unknown = key in config ? Reflect.get(config, key) : undefined;\n if (value !== undefined && (typeof value !== \"string\" || !IDENTIFIER.test(value))) {\n throw new Error(`\\`${key}\\` of table \"${name}\" must be a plain SQL identifier, got ${JSON.stringify(value)}.`);\n }\n }\n}\n\nfunction assertRlsDeclared(builder: string, name: string, config: object): void {\n const rls = \"rls\" in config ? config.rls : undefined;\n const ok = rls === \"admin-only\" || rls === \"inherit\" || (Array.isArray(rls) && rls.length > 0);\n if (ok) return;\n const detail = Array.isArray(rls)\n ? \"`rls: []` grants nothing and says nothing. Write `rls: \\\"admin-only\\\"` to lock the table to admins.\"\n : \"Every table needs an explicit row-level security posture.\";\n throw new Error(\n `\\`${builder}(\"${name}\", …)\\` has no usable \\`rls\\`. ${detail} ` +\n \"Accepted: `\\\"admin-only\\\"`, `\\\"inherit\\\"` (the `defaultRls` exported from backend/schema/index.ts), \" +\n \"or a non-empty list of rules.\"\n );\n}\n\n/**\n * Define a Postgres table.\n *\n * The name is the SQL table and the API slug; `rls` is mandatory. The result\n * is what the backend reads from `backend/schema/index.ts` — it generates the\n * DDL and the policies, serves the REST, realtime and MCP surfaces, and types\n * the SDK.\n *\n * ```ts\n * export const posts = defineTable(\"posts\", {\n * columns: {\n * id: col.uuid().primaryKey().defaultRandom(),\n * title: col.text().notNull(),\n * },\n * rls: [\n * { operation: \"select\", access: \"public\" },\n * { operations: [\"insert\", \"update\", \"delete\"], roles: [\"editor\"] },\n * ],\n * });\n * ```\n *\n * @group Schema\n */\nexport function defineTable<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: TableConfig<C, R, User, S>): TableDef<N, C, R, S> {\n assertTableShape(\"defineTable\", name, config);\n assertRlsDeclared(\"defineTable\", name, config);\n return { brand: TABLE_BRAND, name, config };\n}\n\n/**\n * The auth half of `defineAuthTable`.\n *\n * @group Schema\n */\nexport interface AuthTableOptions {\n /** The roles a user can hold, each with the scopes it grants. */\n roles?: Record<string, RoleDefinition>;\n /** The scopes an API key or token can be granted. */\n scopes?: Record<string, ScopeDefinition>;\n /** Let users create personal API keys. */\n personalKeys?: boolean;\n /** Runs when an admin creates a user: hash the password, send the invitation. */\n onCreateUser?: (values: Record<string, unknown>, ctx: AuthCollectionContext) => Promise<AuthCollectionCreateResult>;\n /** Runs when an admin resets a user's password. */\n onResetPassword?: (uid: string, ctx: AuthCollectionContext) => Promise<AuthCollectionResetResult>;\n}\n\n/**\n * What `defineAuthTable` takes besides the name.\n *\n * @group Schema\n */\nexport interface AuthTableConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> extends TableConfig<C, R, USER, S> {\n /** Roles, scopes, personal keys and the user-lifecycle hooks. */\n auth?: AuthTableOptions;\n}\n\n/**\n * Define the table users are stored in.\n *\n * A `defineTable` that auth reads and writes: the columns auth needs are added\n * when the table does not declare them, a signed-in user can read their own\n * row, and the privilege columns (`roles`) can only be written by an admin —\n * whatever `rls` says. A project has at most one.\n *\n * @group Schema\n */\nexport function defineAuthTable<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: AuthTableConfig<C, R, User, S>): TableDef<N, C, R, S> {\n assertTableShape(\"defineAuthTable\", name, config);\n assertRlsDeclared(\"defineAuthTable\", name, config);\n const { auth, ...table } = config;\n return { brand: TABLE_BRAND, name, config: table, auth: auth ?? {} };\n}\n\n/**\n * What `defineView` takes besides the name.\n *\n * @group Schema\n */\nexport interface ViewConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> {\n /** The defining `SELECT`. */\n query: string;\n /**\n * `true` stores the rows. Postgres cannot attach row policies to a\n * materialized view, so it is read through a gate that admits `roles`.\n */\n materialized?: boolean;\n /** Who may read a materialized view. `[\"admin\"]` when omitted. Not accepted on a plain view. */\n roles?: readonly string[];\n /** The columns the query returns. `.primaryKey()` marks the ones that identify a row. */\n columns: C;\n /** The name in the API. The view's name when omitted. Captured as a literal type, like a table's. */\n slug?: S;\n /** The SQL view name, when it is not the name the view is defined under. A plain SQL identifier. */\n table?: string;\n /** The Postgres schema. `public` when omitted. */\n schema?: string;\n /** A non-default Postgres database. */\n database?: ResourceRef;\n /** What the view holds, for OpenAPI and MCP. */\n description?: string;\n /** Relations to read through. No constraint is created for a view. */\n relations?: R;\n /** Indexes on a materialized view's stored rows. */\n indexes?: readonly TableIndex<NoInfer<Extract<keyof C, string>>>[];\n /** Read hooks. A view is never written. */\n hooks?: Pick<TableHooks<RowOfColumns<C>, RowOfColumns<C>, USER>, \"beforeQuery\" | \"afterRead\">;\n /** Opaque data, served with the view's descriptor. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * A view as authored: the result of `defineView`.\n *\n * @group Schema\n */\nexport interface ViewDef<\n N extends string = string,\n C extends ColumnsShape = ColumnsShape,\n R extends RelationsShape = RelationsShape,\n S extends string = N\n> {\n readonly brand: typeof VIEW_BRAND;\n /** The name it was defined under. */\n readonly name: N;\n /** What it was defined with, as written. */\n readonly config: ViewConfig<C, R, User, S>;\n}\n\n/**\n * Define a SQL view, served read-only.\n *\n * A plain view is created `WITH (security_invoker = true)`: the row-level\n * security of the tables it reads decides what each caller sees. A\n * materialized view stores its rows, so it is gated by `roles` instead.\n *\n * @group Schema\n */\nexport function defineView<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: ViewConfig<C, R, User, S>): ViewDef<N, C, R, S> {\n assertTableShape(\"defineView\", name, config);\n if (typeof config.query !== \"string\" || config.query.trim().length === 0) {\n throw new Error(`View \"${name}\" needs a \\`query\\`: the SELECT that defines it.`);\n }\n if (config.roles !== undefined && !config.materialized) {\n throw new Error(\n `View \"${name}\" lists \\`roles\\` but is not materialized. A plain view is governed by the row-level ` +\n \"security of the tables it reads; `roles` gates a materialized view only.\"\n );\n }\n return { brand: VIEW_BRAND, name, config };\n}\n\n/**\n * The slug of a table or view, from its type: `TableSlugOf<typeof posts>`.\n *\n * The `slug` it was defined with, or the name it was defined under when it was\n * given none — the table's API path, SDK accessor and what scopes name. Reads\n * any `{ name, config: { slug? } }` structurally, so `import type { posts }`\n * is enough; `string` for a table whose type is not literal.\n *\n * ```ts\n * const posts = defineTable(\"blog_posts\", { slug: \"posts\", … });\n * type S = TableSlugOf<typeof posts>; // \"posts\"\n * ```\n *\n * @group Schema\n */\nexport type TableSlugOf<T extends { readonly name: string }> =\n T extends { readonly config: { readonly slug?: infer S } }\n ? [Exclude<S, undefined>] extends [never]\n ? T[\"name\"]\n : Exclude<S, undefined> extends string ? Exclude<S, undefined> : T[\"name\"]\n : T[\"name\"];\n\n/**\n * A type compared member by member rather than through its type parameters.\n *\n * `TableConfig<C>` names `keyof C` (in `tenant`, `softDelete`, `indexes`), and\n * TypeScript measures a type parameter read through `keyof` as contravariant —\n * so `TableConfig<{ id: … }>` was refused where `TableConfig<ColumnsShape>`\n * was expected, although every member is assignable. Spelling the \"any\" types\n * out structurally makes the compiler compare the members, which is the\n * question actually being asked.\n */\ntype Structural<T> = { [K in keyof T]: T[K] };\n\n/**\n * Any table, whatever its columns: what a list of `defineTable` results is\n * typed as (`compileTables(defs)`, `backend/schema/index.ts`).\n *\n * @group Schema\n */\nexport interface AnyTableDef {\n readonly brand: typeof TABLE_BRAND;\n readonly name: string;\n readonly config: Structural<TableConfig<ColumnsShape, RelationsShape>>;\n readonly auth?: AuthTableOptions;\n}\n\n/**\n * Any view, whatever its columns.\n *\n * @group Schema\n */\nexport interface AnyViewDef {\n readonly brand: typeof VIEW_BRAND;\n readonly name: string;\n readonly config: Structural<ViewConfig<ColumnsShape, RelationsShape>>;\n}\n\n/**\n * Whether a value is the result of `defineTable` or `defineAuthTable`, from\n * this copy of the package or another.\n *\n * @group Schema\n */\nexport function isTableDef(value: unknown): value is AnyTableDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === TABLE_BRAND;\n}\n\n/**\n * Whether a value is the result of `defineAuthTable`.\n *\n * @group Schema\n */\nexport function isAuthTableDef(value: unknown): value is AnyTableDef & { auth: AuthTableOptions } {\n return isTableDef(value) && value.auth !== undefined;\n}\n\n/**\n * Whether a value is the result of `defineView`.\n *\n * @group Schema\n */\nexport function isViewDef(value: unknown): value is AnyViewDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === VIEW_BRAND;\n}\n"],"mappings":";;AAoaA,IAAa,oBAAmE;CAC5E,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,MAAM;CACN,OAAO;CACP,SAAS;CACT,MAAM;CACN,QAAQ;CACR,SAAS;CACT,SAAS;CACT,UAAU;CACV,UAAU;CACV,WAAW;AACf;;;;;;;AA8BA,IAAa,uBAAiD;CAC1D;CAAK;CAAM;CAAM;CAAM;CAAM;CAC7B;CAAM;CACN;CAAkB;CAAsB;CAAsB;CAC9D;CAAQ;CAAS;CAAY;CAC7B;CAAW;AACf;AAG2C,IAAI,IAAmB,oBAAoB;AAc3B,IAAI,IAC3D,OAAO,QAAQ,iBAAiB,CACpC;;;;ACtCA,IAAa,SAAS;CAClB,aAAmC,EAAE,MAAM,OAAO;CAClD,cAAqC,EAAE,MAAM,QAA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