@rebasepro/server 0.31.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
- package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
- package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
- package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
- package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
- package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
- package/dist/api/errors.d.ts +4 -0
- package/dist/api/rest/api-generator.d.ts +8 -0
- package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
- package/dist/auth-Bfwjg4Bg.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +10 -0
- package/dist/backend/services.d.ts +9 -0
- package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
- package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
- package/dist/boot/bundle.d.ts +11 -1
- package/dist/boot/env.d.ts +5 -0
- package/dist/boot/security-headers.d.ts +15 -5
- package/dist/boot/static-routing.d.ts +58 -0
- package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
- package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
- package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
- package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
- package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
- package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
- package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
- package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
- package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
- package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
- package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
- package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
- package/dist/dist-C1vNURUy.js +19354 -0
- package/dist/dist-C1vNURUy.js.map +1 -0
- package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
- package/dist/errors-NVbAQU25.js.map +1 -0
- package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
- package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
- package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
- package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
- package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
- package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
- package/dist/functions/index.d.ts +2 -0
- package/dist/functions/index.js +162 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/rate-limit.d.ts +71 -0
- package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
- package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
- package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
- package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.es.js +1241 -213
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
- package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
- package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
- package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
- package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
- package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
- package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
- package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
- package/dist/{load-schema-Cv5XLVjW.js → load-schema-B4Nv1mwq.js} +32 -4
- package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-B4Nv1mwq.js.map} +1 -1
- package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
- package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
- package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
- package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
- package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
- package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
- package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
- package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
- package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
- package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
- package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
- package/dist/push/push-options.d.ts +26 -0
- package/dist/push/push-routes.d.ts +30 -0
- package/dist/push/push-service.d.ts +13 -0
- package/dist/push/push-store.d.ts +45 -0
- package/dist/push/set-up.d.ts +25 -0
- package/dist/push/subscription-input.d.ts +26 -0
- package/dist/push/vapid-config.d.ts +35 -0
- package/dist/push/web-push-crypto.d.ts +44 -0
- package/dist/push/web-push-sender.d.ts +10 -0
- package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
- package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
- package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
- package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
- package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
- package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
- package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-DEGwyQmx.js} +5 -5
- package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
- package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
- package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
- package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
- package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
- package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
- package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
- package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
- package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
- package/dist/serve-spa.d.ts +12 -0
- package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
- package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
- package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
- package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
- package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
- package/dist/src-CNZB3fuE.js.map +1 -0
- package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-D_zNDhEU.js} +3 -3
- package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
- package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
- package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-BOz84vIr.js.map +0 -1
- package/dist/dist-fBcYxf4h.js +0 -19354
- package/dist/dist-fBcYxf4h.js.map +0 -1
- package/dist/errors-DpTMfX77.js.map +0 -1
- package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
- package/dist/src-DLIb1O9l.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-source-editor-qmyi5vxX.js","names":[],"sources":["../../common/src/util/relations.ts","../../common/src/schema/descriptor-to-def.ts","../../common/src/schema/print-doc.ts","../../common/src/schema/print-value.ts","../../common/src/schema/print-column.ts","../../common/src/schema/print-table.ts","../src/schema-edit/source-importer.ts","../src/schema-edit/source-text.ts","../src/api/table-source-editor.ts"],"sourcesContent":["/**\n * The names the schema generator gives a table's Drizzle variable and its enum\n * types. (The panel's relation helpers live in `@rebasepro/cms-types`.)\n *\n * @module\n */\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * A JavaScript identifier: what a generated `export const <name> =` needs.\n *\n * Deliberately the same shape the two schema generators already define\n * privately — this is the third place that needed it, and the first two guard\n * property keys and member accesses while nothing guarded the variable name\n * itself.\n */\nconst JS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * The variable name a generated table is bound to.\n *\n * Camel-cases underscores, and then guarantees the result is a legal\n * identifier. It did only the first, so a table name that is legal in Postgres\n * and not in JavaScript produced a `schema.generated.ts` that does not parse:\n *\n * `2024_archive` → `export const 2024Archive = pgTable(…)`\n * \"An identifier or keyword cannot immediately follow\n * a numeric literal\"\n * `reporting.events` → `export const reporting.events = pgTable(…)`\n * \"',' expected\"\n *\n * That file is imported by the server, so the failure is not one broken\n * collection — `rebase build` and `db push` fail at tsc for the whole\n * directory. And it is reachable from a documented flow: `rebase init` against\n * a database holding a table called `2024_archive` writes a collection file\n * that parses and a schema file that does not.\n *\n * **A no-op for every name that already worked**, which is what makes changing\n * a derived name safe here: the only inputs whose output changes are the ones\n * that produced a syntax error, and nothing can be running against those.\n * Separators become camel case rather than disappearing, so `reporting.events`\n * and `reporting_events` do not collide into one variable.\n */\nexport function getTableVarName(tableName: string): string {\n const camel = tableName.replace(/_([a-z])/g, (_, char: string) => char.toUpperCase());\n if (JS_IDENTIFIER.test(camel)) return camel;\n\n const sanitised = camel\n // Any other separator gets the same treatment `_` did, so two tables\n // differing only by separator keep differing.\n .replace(/[^A-Za-z0-9_$]+([A-Za-z0-9])?/g, (_, char?: string) =>\n (char ? char.toUpperCase() : \"\"))\n // A leading digit is legal in Postgres and not in JavaScript. Prefixed\n // rather than stripped, so `2024_archive` and `archive` stay distinct.\n .replace(/^([0-9])/, \"t$1\");\n\n return JS_IDENTIFIER.test(sanitised) ? sanitised : `t${sanitised}`;\n}\n\nexport function getEnumVarName(tableName: string, propName: string): string {\n const tableVar = getTableVarName(tableName);\n const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);\n return `${tableVar}${propVar}`;\n}\n","/**\n * From a {@link TableDescriptor} back to the definition that compiles to it.\n *\n * The printer reads descriptors and the lowering reads definitions; a\n * descriptor nobody authored — what `introspectTables` reports for a database\n * no project declared — reaches the lowering through here, at the same\n * boundary a declared table crosses at boot.\n *\n * The definition states every derived name explicitly (`localKey`,\n * `foreignKey`, `through`, …) rather than leaving it to be re-derived, so it\n * means exactly what the descriptor says. A foreign-key column the descriptor\n * marks `derived` is left to its relation, as the printer leaves it, with its\n * nullability and uniqueness on the relation.\n *\n * @module\n */\nimport {\n ColumnBuilder,\n defineTable,\n defineView,\n rel,\n type AnyColumn,\n type AnyTableDef,\n type AnyViewDef,\n type ColumnDef,\n type ColumnDescriptor,\n type RelationDef,\n type RelationDescriptor,\n type RlsDescriptor,\n type RlsPosture,\n type TableDescriptor\n} from \"@rebasepro/types\";\n\nimport { SchemaDefinitionError, type SchemaDefinitionProblem } from \"./errors\";\n\n/**\n * A descriptor column, as the definition that compiles to it.\n *\n * @group Schema\n */\nexport function columnDefOfDescriptor(column: ColumnDescriptor): ColumnDef {\n const def: ColumnDef = {\n type: column.type,\n column: column.column,\n notNull: !column.nullable,\n primaryKey: column.primaryKey === true,\n unique: column.unique === true,\n readOnly: column.readOnly === true,\n private: column.private === true\n };\n if (column.default !== undefined) def.default = column.default;\n if (column.generated !== undefined) def.generatedAs = column.generated.expression;\n if (column.access !== undefined) def.access = column.access;\n if (column.stamp !== undefined) def.stamp = column.stamp;\n if (column.validate !== undefined) def.validate = column.validate;\n if (column.oneOf !== undefined) def.oneOf = column.oneOf;\n if (column.description !== undefined) def.description = column.description;\n if (column.storage !== undefined) def.storage = column.storage;\n if (column.semantic !== undefined) def.semantic = column.semantic;\n if (column.vectorIndex !== undefined) def.vectorIndex = column.vectorIndex;\n if (column.json !== undefined) def.json = column.json;\n if (column.type.kind === \"array\") {\n const element: ColumnDef = {\n type: column.type.of,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n };\n if (column.element?.validate !== undefined) element.validate = column.element.validate;\n if (column.element?.oneOf !== undefined) element.oneOf = column.element.oneOf;\n if (column.element?.storage !== undefined) element.storage = column.element.storage;\n if (column.element?.semantic !== undefined) element.semantic = column.element.semantic;\n def.element = element;\n }\n return def;\n}\n\n/**\n * Options of {@link tableDefsFromDescriptors}.\n *\n * @group Schema\n */\nexport interface TableDefsFromDescriptorsOptions {\n /**\n * The `rls` each definition is given in place of the one its descriptor\n * states. For a caller whose tables' access the database decides and that\n * lowers them only to serve them — introspection, where Rebase generates no\n * policy, so the request-time collection carries no rule (`\"admin-only\"`\n * lowers to none) while the descriptor keeps stating the catalogue's.\n */\n rls?: (descriptor: TableDescriptor) => RlsPosture;\n}\n\n/** A descriptor column as a builder, so `defineTable` accepts it. */\nconst builderOf = (column: ColumnDescriptor): AnyColumn => new ColumnBuilder(columnDefOfDescriptor(column));\n\n/** Where a problem is, for the error. */\nclass ConversionProblem extends Error {\n constructor(readonly problem: SchemaDefinitionProblem) {\n super(problem.message);\n }\n}\n\n/**\n * A descriptor's row-level security as a definition's `rls` (and\n * `defaultPolicies`), or a problem when no definition can say it.\n */\nfunction rlsOf(descriptor: TableDescriptor, rls: RlsDescriptor): { rls: RlsPosture; defaultPolicies?: boolean } {\n const rules = rls.rules;\n const declared = rls.declaredDefaultPolicies ? { defaultPolicies: true } : {};\n if (rls.posture === \"admin-only\") return { rls: \"admin-only\", ...declared };\n if (rules.length > 0) {\n const posture: RlsPosture = [rules[0], ...rules.slice(1)];\n return rls.defaultPolicies ? { rls: posture, ...declared } : { rls: posture, defaultPolicies: false };\n }\n if (rls.defaultPolicies) return { rls: \"admin-only\", ...declared };\n throw new ConversionProblem({\n table: descriptor.name,\n message: \"has row-level security with no rule and no admin baseline, so nobody may read a row. \" +\n \"`defineTable` does not write a table nobody may read: list the rules that grant access, or say \\\"admin-only\\\".\"\n });\n}\n\n/** A descriptor relation as the `rel.*` definition that resolves to it. */\nfunction relationOf(\n relation: RelationDescriptor,\n owner: TableDescriptor,\n target: () => AnyTableDef | AnyViewDef\n): RelationDef {\n const access = {\n ...(relation.access !== undefined ? { access: relation.access } : {}),\n ...(relation.private === true ? { private: true } : {})\n };\n switch (relation.kind) {\n case \"belongsTo\": {\n const derived = owner.columns.find(column => column.key === relation.localField && column.derived === true);\n return rel.belongsTo(target, {\n localKey: relation.localKey,\n ...(derived && !derived.nullable ? { notNull: true } : {}),\n ...(derived?.unique ? { unique: true } : {}),\n ...(relation.onDelete !== undefined ? { onDelete: relation.onDelete } : {}),\n ...(relation.onUpdate !== undefined ? { onUpdate: relation.onUpdate } : {}),\n ...(relation.index ? {} : { index: false }),\n ...(relation.constraint ? {} : { constraint: false }),\n ...access\n });\n }\n case \"hasOne\":\n return rel.hasOne(target, {\n foreignKey: relation.foreignKey,\n ...(relation.sourceKey !== undefined ? { sourceKey: relation.sourceKey } : {}),\n ...access\n });\n case \"hasMany\":\n return rel.hasMany(target, {\n foreignKey: relation.foreignKey,\n ...(relation.sourceKey !== undefined ? { sourceKey: relation.sourceKey } : {}),\n ...(relation.orderBy !== undefined ? { orderBy: relation.orderBy } : {}),\n ...access\n });\n case \"manyToMany\": {\n const pivot: Record<string, AnyColumn> = {};\n for (const column of relation.through.pivot) pivot[column.key] = builderOf(column);\n return rel.manyToMany(target, {\n through: relation.through.table,\n sourceKey: relation.through.sourceKey,\n targetKey: relation.through.targetKey,\n ...(relation.through.pivot.length > 0 ? { pivot } : {}),\n ...(relation.onDelete !== undefined ? { onDelete: relation.onDelete } : {}),\n ...access\n });\n }\n case \"via\":\n return rel.via(target, { steps: relation.steps, cardinality: relation.cardinality, ...access });\n }\n}\n\n/** One descriptor as a definition, its relations' targets resolved through `resolve`. */\nfunction defOf(descriptor: TableDescriptor, resolve: (slug: string) => AnyTableDef | AnyViewDef, options: TableDefsFromDescriptorsOptions): AnyTableDef | AnyViewDef {\n if (descriptor.auth !== undefined) {\n throw new ConversionProblem({\n table: descriptor.name,\n message: \"is an auth table. `defineAuthTable` adds the auth columns and policies itself; print the descriptor instead of converting it.\"\n });\n }\n const declared = Object.keys(descriptor.hooks ?? {});\n if (declared.length > 0) {\n throw new ConversionProblem({\n table: descriptor.name,\n message: `declares hooks (${declared.join(\", \")}), whose code never leaves the server; a descriptor cannot be turned back into them.`\n });\n }\n const columns: Record<string, AnyColumn> = {};\n for (const column of descriptor.columns) {\n if (column.derived === true) continue;\n columns[column.key] = builderOf(column);\n }\n const relations: Record<string, RelationDef> = {};\n for (const relation of descriptor.relations) {\n relations[relation.name] = relationOf(relation, descriptor, () => resolve(relation.target));\n }\n const common = {\n ...(descriptor.slug !== descriptor.name ? { slug: descriptor.slug } : {}),\n ...(descriptor.table !== descriptor.name ? { table: descriptor.table } : {}),\n ...(descriptor.schema !== \"public\" ? { schema: descriptor.schema } : {}),\n ...(descriptor.database !== undefined ? { database: descriptor.database } : {}),\n ...(descriptor.description !== undefined ? { description: descriptor.description } : {}),\n columns,\n ...(descriptor.relations.length > 0 ? { relations } : {}),\n ...(descriptor.indexes !== undefined ? { indexes: descriptor.indexes } : {}),\n ...(descriptor.metadata !== undefined ? { metadata: descriptor.metadata } : {})\n };\n if (descriptor.kind === \"view\") {\n const view = descriptor.view;\n if (view?.query === undefined) {\n throw new ConversionProblem({\n table: descriptor.name,\n message: \"is a view whose descriptor carries no query (it is served to admins only). Convert a descriptor that includes it.\"\n });\n }\n return defineView(descriptor.name, {\n ...common,\n query: view.query,\n ...(view.materialized ? { materialized: true } : {}),\n ...(view.materialized && view.roles !== undefined ? { roles: view.roles } : {})\n });\n }\n const rls = options.rls ? { rls: options.rls(descriptor) } : rlsOf(descriptor, descriptor.rls);\n return defineTable(descriptor.name, {\n ...common,\n ...rls,\n ...(descriptor.tenant !== undefined ? { tenant: descriptor.tenant } : {}),\n ...(descriptor.softDelete !== undefined ? { softDelete: descriptor.softDelete } : {}),\n ...(descriptor.history !== undefined ? { history: descriptor.history } : {}),\n ...(descriptor.search !== undefined ? { search: descriptor.search } : {}),\n ...(descriptor.strictWrites === false ? { strictWrites: false } : {})\n });\n}\n\n/**\n * Definitions for a set of descriptors, in the order given: what\n * `compileTables` compiles back to the same descriptors (derived names and\n * defaults stated explicitly), and what the planner plans from.\n *\n * A relation's target is resolved by slug among `descriptors`, lazily, so two\n * tables may point at each other. Throws a {@link SchemaDefinitionError}\n * listing every descriptor no definition can state: an auth table, a table\n * with hooks, a view without its query, row-level security that grants nobody\n * anything (unless `options.rls` replaces it), and whatever `defineTable`\n * itself refuses. A target outside the set is a problem when the thunk is\n * called.\n *\n * @group Schema\n */\nexport function tableDefsFromDescriptors(\n descriptors: readonly TableDescriptor[],\n options: TableDefsFromDescriptorsOptions = {}\n): (AnyTableDef | AnyViewDef)[] {\n const bySlug = new Map<string, AnyTableDef | AnyViewDef>();\n const resolve = (slug: string): AnyTableDef | AnyViewDef => {\n const def = bySlug.get(slug);\n if (!def) {\n throw new SchemaDefinitionError([{ table: slug, message: \"is the target of a relation, and no descriptor in the set has that slug.\" }]);\n }\n return def;\n };\n const problems: SchemaDefinitionProblem[] = [];\n const out: (AnyTableDef | AnyViewDef)[] = [];\n for (const descriptor of descriptors) {\n try {\n const def = defOf(descriptor, resolve, options);\n bySlug.set(descriptor.slug, def);\n out.push(def);\n } catch (error) {\n if (error instanceof ConversionProblem) problems.push(error.problem);\n else problems.push({ table: descriptor.name, message: error instanceof Error ? error.message : String(error) });\n }\n }\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n return out;\n}\n","/**\n * The layout half of the schema printer: a tiny document model and the one\n * renderer that turns it into source text.\n *\n * Printing is split in two so that every printer (columns, JSON shapes,\n * relations, rules, whole modules) only says *what* it prints, and the line\n * breaking is decided in one place, the same way for all of them:\n *\n * - an object, array or call is printed on one line when it fits in\n * {@link PRINT_WIDTH} columns and none of its children must break;\n * - otherwise an object or array puts one entry per line, indented four\n * spaces; a call keeps its last argument hugged against the parenthesis\n * when that argument is an object, array or call (`col.jsonb(json.object({`),\n * and breaks one argument per line when it is not.\n *\n * No trailing commas (the repository's `comma-dangle` rule), double quotes,\n * four-space indentation. Pure: the same document always renders to the same\n * bytes.\n */\n\n/** The width a line may reach before an object, array or call is broken over several. */\nexport const PRINT_WIDTH = 120;\n\nconst INDENT = 4;\n\n/**\n * A piece of source, before layout.\n *\n * - `text` — printed as is. Text holding a newline (a hook's source) cannot\n * share a line with its siblings, so it forces its parents to break.\n * - `object` / `array` — a literal; `breaks` forces one entry per line.\n * - `call` — `callee(args)`.\n * - `concat` — pieces printed one after another (a builder chain).\n */\nexport type Doc =\n | { kind: \"text\"; text: string }\n | { kind: \"object\"; entries: ObjectEntry[]; breaks?: boolean }\n | { kind: \"array\"; items: Doc[]; breaks?: boolean }\n | { kind: \"call\"; callee: string; args: Doc[] }\n | { kind: \"concat\"; parts: Doc[] };\n\n/** One `key: value` of an object literal. `key` is already printed (quoted when it must be). */\nexport interface ObjectEntry {\n /** The printed key: a bare identifier, or a double-quoted string. */\n key: string;\n /** The printed value. */\n value: Doc;\n}\n\n/** A piece of literal source text. */\nexport const text = (value: string): Doc => ({ kind: \"text\", text: value });\n\n/** `callee(args)`. */\nexport const call = (callee: string, args: Doc[] = []): Doc => ({ kind: \"call\", callee, args });\n\n/** Pieces printed one after another. */\nexport const concat = (parts: Doc[]): Doc => ({ kind: \"concat\", parts });\n\n/** An array literal. */\nexport const array = (items: Doc[], breaks = false): Doc => ({ kind: \"array\", items, breaks });\n\n/** An object literal from `[key, value]` pairs, keys printed bare when they can be. */\nexport const object = (entries: readonly (readonly [string, Doc])[], breaks = false): Doc => ({\n kind: \"object\",\n entries: entries.map(([key, value]) => ({ key: printKey(key), value })),\n breaks\n});\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * An object key as written in source: bare when it is an identifier name\n * (reserved words included — they are legal property names), double-quoted\n * otherwise.\n */\nexport function printKey(key: string): string {\n return IDENTIFIER.test(key) ? key : printString(key);\n}\n\n/** A string literal, double-quoted. */\nexport function printString(value: string): string {\n return JSON.stringify(value);\n}\n\n/**\n * A string literal for text that may span lines (a view's query): a template\n * literal when it holds a newline, so the SQL reads as SQL, and a\n * double-quoted string otherwise.\n */\nexport function printMultilineString(value: string): string {\n if (!value.includes(\"\\n\")) return printString(value);\n return \"`\" + value.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$\\{/g, \"\\\\${\") + \"`\";\n}\n\n/** The text of a doc on one line, or `undefined` when it cannot be put on one. */\nfunction flat(doc: Doc): string | undefined {\n switch (doc.kind) {\n case \"text\":\n return doc.text.includes(\"\\n\") ? undefined : doc.text;\n case \"object\": {\n if (doc.entries.length === 0) return \"{}\";\n if (doc.breaks) return undefined;\n const parts: string[] = [];\n for (const entry of doc.entries) {\n const value = flat(entry.value);\n if (value === undefined) return undefined;\n parts.push(`${entry.key}: ${value}`);\n }\n return `{ ${parts.join(\", \")} }`;\n }\n case \"array\": {\n if (doc.items.length === 0) return \"[]\";\n if (doc.breaks) return undefined;\n const parts: string[] = [];\n for (const item of doc.items) {\n const value = flat(item);\n if (value === undefined) return undefined;\n parts.push(value);\n }\n return `[${parts.join(\", \")}]`;\n }\n case \"call\": {\n const parts: string[] = [];\n for (const arg of doc.args) {\n const value = flat(arg);\n if (value === undefined) return undefined;\n parts.push(value);\n }\n return `${doc.callee}(${parts.join(\", \")})`;\n }\n case \"concat\": {\n let out = \"\";\n for (const part of doc.parts) {\n const value = flat(part);\n if (value === undefined) return undefined;\n out += value;\n }\n return out;\n }\n }\n}\n\nconst pad = (width: number): string => \" \".repeat(width);\n\n/** The column the cursor stands at after printing `printed` from `column`. */\nfunction columnAfter(printed: string, column: number): number {\n const newline = printed.lastIndexOf(\"\\n\");\n return newline < 0 ? column + printed.length : printed.length - newline - 1;\n}\n\nconst huggable = (doc: Doc): boolean =>\n (doc.kind === \"object\" && doc.entries.length > 0) ||\n (doc.kind === \"array\" && doc.items.length > 0) ||\n (doc.kind === \"call\" && doc.args.length > 0);\n\n/**\n * Lay a doc out.\n *\n * @param indent The indentation of the line the doc starts on.\n * @param column The column the doc starts at on that line.\n */\nexport function render(doc: Doc, indent = 0, column = indent): string {\n const oneLine = flat(doc);\n if (oneLine !== undefined && (doc.kind === \"text\" || column + oneLine.length <= PRINT_WIDTH)) return oneLine;\n switch (doc.kind) {\n case \"text\":\n return doc.text;\n case \"object\": {\n const inner = indent + INDENT;\n const lines = doc.entries.map(entry =>\n `${pad(inner)}${entry.key}: ${render(entry.value, inner, inner + entry.key.length + 2)}`);\n return `{\\n${lines.join(\",\\n\")}\\n${pad(indent)}}`;\n }\n case \"array\": {\n const inner = indent + INDENT;\n const lines = doc.items.map(item => `${pad(inner)}${render(item, inner, inner)}`);\n return `[\\n${lines.join(\",\\n\")}\\n${pad(indent)}]`;\n }\n case \"call\":\n return renderCall(doc.callee, doc.args, indent, column);\n case \"concat\": {\n // A chain never breaks inside a link whose arguments fit on one\n // line (`.validate({ max: 60 })` at the end of a long chain stays\n // whole): only the type builder at its head is laid out by width.\n let out = \"\";\n let at = column;\n for (const [index, part] of doc.parts.entries()) {\n const partFlat = index > 0 ? flat(part) : undefined;\n const printed = partFlat ?? render(part, indent, at);\n out += printed;\n at = columnAfter(printed, at);\n }\n return out;\n }\n }\n}\n\nfunction renderCall(callee: string, args: Doc[], indent: number, column: number): string {\n const head = `${callee}(`;\n if (args.length === 0) return `${head})`;\n const flats = args.map(flat);\n const last = args[args.length - 1];\n // One argument that cannot break (a long string, a hook's source) gains\n // nothing from a line of its own.\n if (args.length === 1 && !huggable(last)) return `${head}${render(last, indent, column + head.length)})`;\n // Hug the last argument: `rel.belongsTo(() => users, {` … `})`.\n if (huggable(last) && flats.slice(0, -1).every(value => value !== undefined)) {\n const prefix = head + flats.slice(0, -1).map(value => `${value}, `).join(\"\");\n if (args.length === 1 || column + prefix.length <= PRINT_WIDTH) {\n return `${prefix}${render(last, indent, column + prefix.length)})`;\n }\n }\n // Hug the first: `json.object({` … `}, { additional: true })`.\n const first = args[0];\n if (args.length > 1 && huggable(first) && flats.slice(1).every(value => value !== undefined)) {\n const printed = render(first, indent, column + head.length);\n return `${head}${printed}, ${flats.slice(1).join(\", \")})`;\n }\n const inner = indent + INDENT;\n const lines = args.map(arg => `${pad(inner)}${render(arg, inner, inner)}`);\n return `${head}\\n${lines.join(\",\\n\")}\\n${pad(indent)})`;\n}\n","import { array, object, printString, text } from \"./print-doc\";\nimport type { Doc } from \"./print-doc\";\n\n/**\n * A definition the printer cannot turn into source without losing something:\n * a hook whose source was not supplied, a value that is not data, a column\n * shape no builder chain produces.\n *\n * The printer never drops what it cannot print — it refuses, naming where the\n * value sits and what to supply instead.\n *\n * @group Schema\n */\nexport class TablePrintError extends Error {\n\n readonly code = \"TABLE_PRINT_UNPRINTABLE\";\n\n constructor(\n /** Where the value sits: `posts.columns.title`, `posts.hooks.beforeSave`. */\n readonly path: string,\n message: string\n ) {\n super(`Cannot print ${path}: ${message}`);\n this.name = \"TablePrintError\";\n }\n}\n\nconst isPlainObject = (value: object): boolean => {\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/** A number literal, including the values JSON has no spelling for. */\nexport function printNumber(value: number): string {\n if (Object.is(value, -0)) return \"-0\";\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return String(value);\n}\n\n/**\n * A data value as a source literal: strings, numbers, booleans, `null`,\n * `bigint`, regular expressions, arrays and plain objects (keys in their own\n * order, `undefined` members left out as `JSON.stringify` leaves them out).\n *\n * Anything else — a function, a class instance, a `Date`, a symbol — has no\n * faithful literal and is refused with its path.\n *\n * @param path Where the value sits, for the refusal.\n */\nexport function valueDoc(value: unknown, path: string): Doc {\n switch (typeof value) {\n case \"string\":\n return text(printString(value));\n case \"number\":\n return text(printNumber(value));\n case \"boolean\":\n return text(String(value));\n case \"bigint\":\n return text(`${value.toString()}n`);\n case \"undefined\":\n return text(\"undefined\");\n case \"function\":\n throw new TablePrintError(path, \"it is a function, which is code rather than data. Supply its source text instead.\");\n case \"symbol\":\n throw new TablePrintError(path, \"it is a symbol, which has no source literal.\");\n case \"object\":\n break;\n }\n if (value === null) return text(\"null\");\n if (value instanceof RegExp) return text(String(value));\n if (Array.isArray(value)) {\n const items: Doc[] = [];\n value.forEach((item: unknown, index) => items.push(valueDoc(item, `${path}[${index}]`)));\n return array(items);\n }\n if (!isPlainObject(value)) {\n const name = value.constructor?.name ?? \"object\";\n throw new TablePrintError(path, `it is a \\`${name}\\` instance, which has no source literal. Pass plain data (strings, numbers, arrays, objects).`);\n }\n const entries: [string, Doc][] = [];\n for (const [key, member] of Object.entries(value)) {\n if (member === undefined) continue;\n entries.push([key, valueDoc(member, `${path}.${key}`)]);\n }\n return object(entries);\n}\n","import type {\n ColumnDef,\n ColumnStorage,\n ColumnTransform,\n ColumnType,\n ColumnValidation,\n JsonShapeDef\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\nimport { array, call, concat, object, printString, render, text } from \"./print-doc\";\nimport type { Doc } from \"./print-doc\";\nimport { TablePrintError, printNumber, valueDoc } from \"./print-value\";\n\n/**\n * Which builders a printed piece of source uses, so the module printer imports\n * exactly those.\n *\n * @group Schema\n */\nexport type SchemaBuilderName = \"defineTable\" | \"defineAuthTable\" | \"defineView\" | \"col\" | \"rel\" | \"json\" | \"pgEnum\" | \"sql\";\n\n/**\n * What the column and JSON-shape printers need besides the definition.\n * Internal: the public functions build it from their options.\n */\nexport interface ColumnPrintContext {\n /** Where the column sits, for refusals: `posts.columns.title`. */\n path: string;\n /**\n * The source of a field-level `transform`, by path relative to the column:\n * `\"\"` the column itself, `\"[]\"` an array column's element, `\"seo.title\"`\n * a field of its JSON shape, `\"[].image\"` a field inside a JSON array.\n */\n transforms: Readonly<Record<string, string>>;\n /** Collects the builders the printed source uses. */\n used: Set<SchemaBuilderName>;\n /** Where this context sits below the printed column (`\"\"`, `\"[]\"`), for the refusal's hint. */\n origin: string;\n /** How the caller supplies the source of the transform at a path below the printed column. */\n sourceHint: (relative: string) => string;\n /**\n * The identifier a named enum type is bound to by a `pgEnum(...)`\n * declaration the caller writes. Without it a named enum prints its\n * declaration inline: `pgEnum(\"status\", [...])()`.\n */\n enumIdentifier?: (enumName: string, values: readonly string[]) => string;\n}\n\n/** The hint of {@link printColumn}: its own options. */\nconst columnOptionHint = (relative: string): string =>\n relative === \"\" ? \"as `transform`\" : `under \\`transforms[\"${relative}\"]\\``;\n\n/**\n * Options of {@link printColumn}.\n *\n * @group Schema\n */\nexport interface PrintColumnOptions {\n /**\n * The column's key in `columns`. With it, the leading SQL name\n * (`col.text(\"legacy_title\")`) is left out when it is the snake_case of the\n * key (the builder's own default).\n */\n key?: string;\n /**\n * The identifier a named enum type is bound to (`const postStatus =\n * pgEnum(\"post_status\", [...])`), so the column prints `postStatus()`. The\n * caller writes the declaration. Without it the declaration is inlined.\n */\n enumIdentifier?: (enumName: string, values: readonly string[]) => string;\n /**\n * The source text of the column's `transform` (`\"{ beforeSave: ({ value }) => value.trim() }\"`),\n * printed verbatim. Required when the definition carries a transform: a\n * function cannot be printed from its value.\n */\n transform?: string;\n /**\n * Sources of transforms nested inside the column, by path relative to it:\n * `\"[]\"` an array column's element, `\"seo.title\"` a field of its JSON\n * shape, `\"[].image\"` a field inside a JSON array, `\"blocks.[].text\"` …\n * see {@link joinTransformPath}.\n */\n transforms?: Readonly<Record<string, string>>;\n}\n\n/**\n * The path of a nested transform: a JSON field is joined with `.`, an array\n * item is `[]`.\n *\n * @group Schema\n */\nexport function joinTransformPath(parent: string, segment: string): string {\n if (parent === \"\") return segment;\n if (segment === \"\") return parent;\n return segment === \"[]\" ? `${parent}[]` : `${parent}.${segment}`;\n}\n\nconst BYTE_UNITS: readonly [string, number][] = [\n [\"TB\", 1024 ** 4],\n [\"GB\", 1024 ** 3],\n [\"MB\", 1024 ** 2],\n [\"KB\", 1024]\n];\n\n/**\n * A byte size as it reads best: `\"10MB\"` when it is an exact multiple of a\n * binary unit (what `parseByteSize` reads back to the same number), the\n * number of bytes otherwise.\n *\n * @group Schema\n */\nexport function printByteSize(bytes: number): string {\n if (Number.isInteger(bytes) && bytes > 0) {\n for (const [unit, size] of BYTE_UNITS) {\n if (bytes % size === 0) return printString(`${bytes / size}${unit}`);\n }\n }\n return printNumber(bytes);\n}\n\nconst STORAGE_KEYS: readonly (keyof ColumnStorage)[] = [\n \"source\", \"path\", \"accept\", \"maxBytes\", \"imageResize\", \"public\", \"fileName\", \"metadata\", \"includeBucketUrl\", \"storeUrl\"\n];\n\nfunction storageDoc(storage: ColumnStorage, path: string): Doc {\n const known = new Set<string>(STORAGE_KEYS);\n for (const key of Object.keys(storage)) {\n if (!known.has(key)) throw new TablePrintError(`${path}.storage.${key}`, \"it is not a storage option `col.storage()` takes.\");\n }\n const entries: [string, Doc][] = [];\n for (const key of STORAGE_KEYS) {\n const value = storage[key];\n if (value === undefined) continue;\n entries.push([key, key === \"maxBytes\" && typeof value === \"number\" ? text(printByteSize(value)) : valueDoc(value, `${path}.storage.${key}`)]);\n }\n return object(entries);\n}\n\n/**\n * Whether a pattern prints as a RegExp literal: when it has flags (one\n * literal instead of `matches` + `matchesFlags`) or holds backslashes (which\n * a string would double), and the literal reads back to the same source.\n */\nfunction regexLiteral(matches: string, flags: string | undefined): string | undefined {\n if (flags === \"\") return undefined;\n if (flags === undefined && !matches.includes(\"\\\\\")) return undefined;\n try {\n const parsed = new RegExp(matches, flags);\n if (parsed.source !== matches) return undefined;\n return String(parsed);\n } catch {\n return undefined;\n }\n}\n\n/** `.validate({...})`'s argument: the rules in their own order, a pattern as a RegExp literal where it reads better. */\nfunction validationDoc(rules: ColumnValidation, path: string): Doc {\n const literal = typeof rules.matches === \"string\" ? regexLiteral(rules.matches, rules.matchesFlags) : undefined;\n const entries: [string, Doc][] = [];\n for (const [key, value] of Object.entries(rules)) {\n if (value === undefined) continue;\n if (literal !== undefined && key === \"matchesFlags\") continue;\n entries.push([key, literal !== undefined && key === \"matches\" ? text(literal) : valueDoc(value, `${path}.validate.${key}`)]);\n }\n return object(entries);\n}\n\n/** `.method(args)`, as a chain link. */\nconst link = (method: string, args: Doc[] = []): Doc => call(`.${method}`, args);\n\nconst hasFunction = (transform: ColumnTransform | undefined): boolean =>\n transform !== undefined && Object.values(transform).some(value => typeof value === \"function\");\n\n/**\n * The `.transform(...)` link, from the caller's source. A transform carrying a\n * function and no source is refused: dropping a hook silently would change\n * what the server does with every write.\n */\nfunction transformLink(declared: boolean, transform: ColumnTransform | undefined, relative: string, ctx: ColumnPrintContext): Doc | undefined {\n const source = ctx.transforms[relative];\n if (source !== undefined) return link(\"transform\", [text(source)]);\n if (declared || hasFunction(transform)) {\n const full = joinTransformPath(ctx.origin, relative);\n throw new TablePrintError(\n relative === \"\" ? `${ctx.path}.transform` : `${ctx.path} (transform at \"${relative}\")`,\n `the transform is a function, which cannot be printed from its value. Pass its source text ${ctx.sourceHint(full)}.`\n );\n }\n if (transform !== undefined) return link(\"transform\", [valueDoc(transform, `${ctx.path}.transform`)]);\n return undefined;\n}\n\n/** The column types `.defaultNow()` applies to. */\nconst TEMPORAL_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"timestamptz\", \"date\", \"time\"]);\n\n/** The column types `.userId()` applies to. */\nconst USER_ID_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"text\", \"varchar\", \"char\", \"uuid\"]);\n\n/** The flags and options every builder starts from: what is left out when printing. */\nconst isUntouchedElement = (element: ColumnDef): boolean =>\n element.column === undefined && !element.notNull && !element.primaryKey && !element.unique &&\n element.default === undefined && element.generatedAs === undefined && !element.readOnly && !element.private &&\n element.access === undefined && element.stamp === undefined && element.oneOf === undefined &&\n element.description === undefined && element.semantic === undefined && element.vectorIndex === undefined &&\n element.json === undefined && element.element === undefined && element.transform === undefined;\n\nconst sameData = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/** `sql\\`…\\``: the expression as a template literal whose cooked text is exactly the expression. */\nexport function printSqlTemplate(expression: string): string {\n return `sql\\`${expression.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$\\{/g, \"\\\\${\")}\\``;\n}\n\n/** The kinds whose `.oneOf()` is Drizzle's `{ enum: [...] }` config. */\nconst TEXT_ENUM_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"text\", \"varchar\", \"char\"]);\n\n/** Whether a column's `oneOf` prints inside its builder's config (`col.text({ enum })`) rather than as `.oneOf()`. */\nconst oneOfInConfig = (def: ColumnDef): boolean =>\n def.oneOf !== undefined && def.storage === undefined && def.semantic === undefined &&\n TEXT_ENUM_KINDS.has(def.type.kind) && def.oneOf.length > 0 && def.oneOf.every(value => typeof value === \"string\");\n\n/** `name` (the SQL column name, when there is one) and `config` as a builder's arguments. */\nconst builderArgs = (name: string | undefined, ...rest: (Doc | undefined)[]): Doc[] => {\n const args: Doc[] = name !== undefined ? [text(printString(name))] : [];\n for (const each of rest) if (each !== undefined) args.push(each);\n return args;\n};\n\nfunction simpleBuilder(def: ColumnDef, name: string | undefined, ctx: ColumnPrintContext): Doc {\n const { type } = def;\n switch (type.kind) {\n case \"text\":\n return call(\"col.text\", builderArgs(name, oneOfInConfig(def) ? object([[\"enum\", valueDoc(def.oneOf, `${ctx.path}.oneOf`)]]) : undefined));\n case \"uuid\":\n case \"smallint\":\n case \"integer\":\n case \"smallserial\":\n case \"serial\":\n case \"real\":\n case \"doublePrecision\":\n case \"boolean\":\n case \"date\":\n case \"time\":\n case \"bytea\":\n case \"json\":\n case \"jsonb\":\n return call(`col.${type.kind}`, builderArgs(name));\n case \"bigint\":\n case \"bigserial\":\n return call(`col.${type.kind}`, builderArgs(name, object([[\"mode\", text(printString(\"number\"))]])));\n case \"timestamptz\":\n return call(\"col.timestamp\", builderArgs(name, object([[\"withTimezone\", text(\"true\")]])));\n case \"varchar\":\n case \"char\": {\n const entries: [string, Doc][] = [[\"length\", text(printNumber(type.length))]];\n if (oneOfInConfig(def)) entries.push([\"enum\", valueDoc(def.oneOf, `${ctx.path}.oneOf`)]);\n return call(`col.${type.kind}`, builderArgs(name, object(entries)));\n }\n case \"numeric\": {\n const entries: [string, Doc][] = [];\n if (type.precision !== undefined) entries.push([\"precision\", text(printNumber(type.precision))]);\n if (type.scale !== undefined) entries.push([\"scale\", text(printNumber(type.scale))]);\n return call(\"col.numeric\", builderArgs(name, entries.length > 0 ? object(entries) : undefined));\n }\n case \"enum\": {\n const values = array(type.values.map(value => text(printString(value))));\n if (type.name === undefined) return call(\"col.enum\", builderArgs(name, values));\n const identifier = ctx.enumIdentifier?.(type.name, type.values);\n if (identifier !== undefined) return call(identifier, builderArgs(name));\n ctx.used.add(\"pgEnum\");\n return call(render(call(\"pgEnum\", [text(printString(type.name)), values])), builderArgs(name));\n }\n case \"vector\":\n return call(\"col.vector\", builderArgs(name, object([[\"dimensions\", text(printNumber(type.dimensions))]])));\n case \"array\":\n throw new TablePrintError(ctx.path, \"an array column needs its element definition to be printed.\");\n case \"other\":\n return call(\"col.custom\", builderArgs(name, object([[\"dataType\", text(printString(type.sqlType))]])));\n }\n}\n\n/**\n * The type builder of a column and the `ColumnDef` members it accounts for:\n * `col.storage(...)`, `col.geopoint()`, `col.jsonb(json…)`,\n * `col.vector({ dimensions, index })`, an array's item chain and `.array()`,\n * `col.storage(...).multiple()`, or the plain builder of the type — each with\n * the SQL column name as its leading argument when there is one.\n */\nfunction typeBuilder(def: ColumnDef, ctx: ColumnPrintContext, name: string | undefined): Doc {\n const { type } = def;\n if (def.semantic === \"geopoint\") {\n if (type.kind !== \"jsonb\" || def.json !== undefined) {\n throw new TablePrintError(ctx.path, `the meaning \"geopoint\" on a \\`${type.kind}\\` column has no builder.`);\n }\n return call(\"col.geopoint\", builderArgs(name));\n }\n if (def.semantic === \"user\" && (def.storage !== undefined || !USER_ID_KINDS.has(type.kind))) {\n throw new TablePrintError(\n ctx.path,\n `\\`.userId()\\` on ${def.storage !== undefined ? \"a storage column\" : `a \\`${type.kind}\\` column`}; it applies to text, varchar, char and uuid columns.`\n );\n }\n if (def.vectorIndex !== undefined && type.kind !== \"vector\") {\n throw new TablePrintError(ctx.path, \"a vector index on a column that is not `col.vector()`.\");\n }\n if (def.json !== undefined && type.kind !== \"json\" && type.kind !== \"jsonb\") {\n throw new TablePrintError(ctx.path, \"a JSON shape on a column that is not `col.json()` / `col.jsonb()`.\");\n }\n if (def.element !== undefined && type.kind !== \"array\") {\n throw new TablePrintError(ctx.path, \"an element definition on a column that is not an array.\");\n }\n switch (type.kind) {\n case \"text\":\n if (def.storage !== undefined) return call(\"col.storage\", builderArgs(name, storageDoc(def.storage, ctx.path)));\n break;\n case \"json\":\n case \"jsonb\":\n if (def.json !== undefined) {\n return call(`col.${type.kind}`, builderArgs(name, jsonShapeDoc(def.json, ctx, \"\")));\n }\n break;\n case \"vector\":\n if (def.vectorIndex !== undefined) {\n return call(\"col.vector\", builderArgs(name, object([\n [\"dimensions\", text(printNumber(type.dimensions))],\n [\"index\", valueDoc(def.vectorIndex, `${ctx.path}.vectorIndex`)]\n ])));\n }\n break;\n case \"array\":\n return arrayBuilder(def, type, ctx, name);\n default:\n break;\n }\n if (def.storage !== undefined) {\n throw new TablePrintError(ctx.path, `storage rules on a \\`${type.kind}\\` column; \\`col.storage()\\` is a text column.`);\n }\n return simpleBuilder(def, name, ctx);\n}\n\n/** What an array's item may not carry and still print before `.array()`: those describe a column. */\nconst ITEM_COLUMN_ONLY = (element: ColumnDef): boolean =>\n element.notNull || element.primaryKey || element.default !== undefined || element.readOnly || element.private;\n\nfunction arrayBuilder(def: ColumnDef, type: Extract<ColumnType, { kind: \"array\" }>, ctx: ColumnPrintContext, name: string | undefined): Doc {\n const element: ColumnDef = def.element ?? {\n type: type.of,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n };\n if (!sameData(element.type, type.of)) {\n throw new TablePrintError(ctx.path, \"the array's element definition is of another type than the array.\");\n }\n // `col.storage(...).multiple()`: TEXT[] of files, the element carrying the\n // storage rules and (only) the per-file validation.\n if (def.storage !== undefined && type.of.kind === \"text\" && element.storage !== undefined &&\n sameData(element.storage, def.storage) && isUntouchedElement(element) && ctx.transforms[\"[]\"] === undefined) {\n const parts: Doc[] = [call(\"col.storage\", builderArgs(name, storageDoc(def.storage, ctx.path)))];\n if (element.validate !== undefined) parts.push(link(\"validate\", [validationDoc(element.validate, `${ctx.path}[]`)]));\n parts.push(link(\"multiple\"));\n return concat(parts);\n }\n if (!sameData(def.storage, element.storage)) {\n throw new TablePrintError(\n ctx.path,\n \"the array's storage rules differ from its element's; `col.storage(...).array()` and `.multiple()` both keep them equal.\"\n );\n }\n if (ITEM_COLUMN_ONLY(element)) {\n throw new TablePrintError(\n `${ctx.path}[]`,\n \"the array's items carry `.notNull()`, a default, `.primaryKey()`, `.readOnly()` or `.private()`, which describe a column: put them on the array.\"\n );\n }\n if (element.column !== undefined) {\n throw new TablePrintError(`${ctx.path}[]`, \"the array's items carry a SQL column name; the name belongs to the array column.\");\n }\n const inner = columnChain(element, {\n ...ctx,\n path: `${ctx.path}[]`,\n transforms: nestedTransforms(ctx.transforms, \"[]\"),\n origin: joinTransformPath(ctx.origin, \"[]\")\n }, undefined, false, name);\n return concat([inner, link(\"array\")]);\n}\n\n/** The transforms under one nested path, re-rooted at it. */\nexport function nestedTransforms(transforms: Readonly<Record<string, string>>, prefix: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [path, source] of Object.entries(transforms)) {\n if (path === prefix) out[\"\"] = source;\n else if (path.startsWith(`${prefix}.`)) out[path.slice(prefix.length + 1)] = source;\n else if (path.startsWith(`${prefix}[]`)) out[path.slice(prefix.length)] = source;\n }\n return out;\n}\n\n/**\n * The canonical modifier order, after the type builder. Each step prints only\n * what differs from the builder's own default.\n *\n * The type builder spells the column as Drizzle does: the SQL column name as\n * its leading argument (left out when it is the snake_case of the key), then\n * Drizzle's config (`col.varchar({ length: 160 })`, `col.timestamp({ withTimezone: true })`,\n * `col.text({ enum: [...] })`). Then:\n *\n * 1. `.primaryKey()`\n * 2. `.notNull()` — left out when `.primaryKey()` implies it\n * 3. `.unique()`\n * 4. the default: `.default(v)` / `.default(sql\\`…\\`)` / `.defaultNow()` / `.defaultRandom()` /\n * `.generatedByDefaultAsIdentity()` / `.dbDefault()`\n * 5. `.generatedAlwaysAs(sql\\`…\\`)`\n * 6. the stamp: `.onCreateNow()` / `.onUpdateNow()` / `.onCreateUser()` / `.onUpdateUser()`\n * 7. `.userId()` — what the column holds, beside the stamp that may fill it\n * 8. `.oneOf([...])` — on a number column (a text column says `{ enum }`)\n * 9. `.validate({...})`\n * 10. `.transform(...)`\n * 11. `.readOnly()` — left out when `.generatedAlwaysAs()` implies it\n * 12. `.private()`\n * 13. `.access({...})`\n * 14. `.describe(text)`\n *\n * An array prints its item's chain, then `.array()`, then these modifiers.\n * `.multiple()` belongs to the type builder (`col.storage({...}).multiple()`):\n * every modifier after it applies to the `TEXT[]` column, and a per-file\n * `.validate()` sits before it.\n *\n * @group Schema\n */\nexport const COLUMN_MODIFIER_ORDER = [\n \"primaryKey\", \"notNull\", \"unique\", \"default\", \"generatedAlwaysAs\", \"stamp\", \"userId\",\n \"oneOf\", \"validate\", \"transform\", \"readOnly\", \"private\", \"access\", \"describe\"\n] as const;\n\nconst STAMP_LINKS: Record<string, string> = {\n \"create:now\": \"onCreateNow\",\n \"update:now\": \"onUpdateNow\",\n \"create:user\": \"onCreateUser\",\n \"update:user\": \"onUpdateUser\"\n};\n\n/**\n * The builder chain of one column, as a doc.\n *\n * @param key The column's key, to leave out a SQL name that only repeats its snake_case.\n * @param declaresTransform The column has a transform although `def.transform`\n * carries no function (a descriptor says so with a flag).\n * @param inheritedName For an array's item: the array column's SQL name, which\n * Drizzle's spelling writes on the item's builder (`col.text(\"tag_list\").array()`).\n */\nexport function columnChain(def: ColumnDef, ctx: ColumnPrintContext, key: string | undefined, declaresTransform: boolean, inheritedName?: string): Doc {\n ctx.used.add(\"col\");\n const name = inheritedName ?? (def.column !== undefined && !(key !== undefined && def.column === toSnakeCase(key)) ? def.column : undefined);\n const base = typeBuilder(def, ctx, name);\n const parts: Doc[] = [base];\n if (def.primaryKey) parts.push(link(\"primaryKey\"));\n if (def.notNull && !def.primaryKey) parts.push(link(\"notNull\"));\n if (def.unique) parts.push(link(\"unique\"));\n if (def.default !== undefined) {\n switch (def.default.kind) {\n case \"literal\":\n parts.push(link(\"default\", [valueDoc(def.default.value, `${ctx.path}.default`)]));\n break;\n case \"sql\":\n if (def.default.expression === \"now()\" && TEMPORAL_KINDS.has(def.type.kind)) {\n parts.push(link(\"defaultNow\"));\n } else {\n ctx.used.add(\"sql\");\n parts.push(link(\"default\", [text(printSqlTemplate(def.default.expression))]));\n }\n break;\n case \"random-uuid\":\n parts.push(link(\"defaultRandom\"));\n break;\n case \"identity\":\n parts.push(link(\"generatedByDefaultAsIdentity\"));\n break;\n case \"database\":\n parts.push(link(\"dbDefault\"));\n break;\n }\n }\n if (def.generatedAs !== undefined) {\n ctx.used.add(\"sql\");\n parts.push(link(\"generatedAlwaysAs\", [text(printSqlTemplate(def.generatedAs))]));\n }\n if (def.stamp !== undefined) {\n const method = STAMP_LINKS[`${def.stamp.on}:${def.stamp.value}`];\n if (method === undefined) throw new TablePrintError(`${ctx.path}.stamp`, `unknown stamp ${JSON.stringify(def.stamp)}.`);\n parts.push(link(method));\n }\n if (def.semantic === \"user\") parts.push(link(\"userId\"));\n if (def.oneOf !== undefined && !oneOfInConfig(def)) parts.push(link(\"oneOf\", [valueDoc(def.oneOf, `${ctx.path}.oneOf`)]));\n if (def.validate !== undefined) parts.push(link(\"validate\", [validationDoc(def.validate, ctx.path)]));\n const transform = transformLink(declaresTransform, def.transform, \"\", ctx);\n if (transform) parts.push(transform);\n if (def.readOnly && def.generatedAs === undefined) parts.push(link(\"readOnly\"));\n if (def.private) parts.push(link(\"private\"));\n if (def.access !== undefined) parts.push(link(\"access\", [valueDoc(def.access, `${ctx.path}.access`)]));\n if (def.description !== undefined) parts.push(link(\"describe\", [text(printString(def.description))]));\n return parts.length === 1 ? base : concat(parts);\n}\n\nconst JSON_SIMPLE: Readonly<Record<string, string>> = {\n number: \"json.number\",\n boolean: \"json.boolean\",\n date: \"json.date\",\n geopoint: \"json.geopoint\",\n unknown: \"json.unknown\"\n};\n\n/**\n * The builder of one node of a JSON shape, as a doc. Modifier order:\n * `.required()` → `.default(v)` → `.onCreateNow()` / `.onUpdateNow()` /\n * `.onCreateUser()` / `.onUpdateUser()` → `.userId()` → `.oneOf([...])` → `.validate({...})` → `.transform(...)` → `.describe(text)`.\n *\n * @param relative The node's path inside the column, for nested transforms.\n */\nexport function jsonShapeDoc(shape: JsonShapeDef, ctx: ColumnPrintContext, relative: string): Doc {\n ctx.used.add(\"json\");\n const here = relative === \"\" ? ctx.path : `${ctx.path} (at \"${relative}\")`;\n let base: Doc;\n switch (shape.kind) {\n case \"string\":\n base = shape.storage !== undefined ? call(\"json.storage\", [storageDoc(shape.storage, here)]) : call(\"json.string\");\n break;\n case \"object\": {\n const fields = Object.entries(shape.fields).map(([key, field]): [string, Doc] =>\n [key, jsonShapeDoc(field, ctx, joinTransformPath(relative, key))]);\n const args: Doc[] = [object(fields)];\n if (shape.additional === true) args.push(object([[\"additional\", text(\"true\")]]));\n base = call(\"json.object\", args);\n break;\n }\n case \"array\":\n base = call(\"json.array\", [jsonShapeDoc(shape.of, ctx, joinTransformPath(relative, \"[]\"))]);\n break;\n case \"oneOf\": {\n const variants = Object.entries(shape.variants).map(([key, variant]): [string, Doc] =>\n [key, jsonShapeDoc(variant, ctx, joinTransformPath(relative, key))]);\n const args: Doc[] = [object(variants)];\n const options: [string, Doc][] = [];\n if (shape.typeField !== \"type\") options.push([\"typeField\", text(printString(shape.typeField))]);\n if (shape.valueField !== \"value\") options.push([\"valueField\", text(printString(shape.valueField))]);\n if (options.length > 0) args.push(object(options));\n base = call(\"json.oneOf\", args);\n break;\n }\n default:\n base = call(JSON_SIMPLE[shape.kind]);\n break;\n }\n const parts: Doc[] = [base];\n if (shape.required === true) parts.push(link(\"required\"));\n if (shape.default !== undefined) parts.push(link(\"default\", [valueDoc(shape.default, `${here}.default`)]));\n if (shape.kind === \"date\" && shape.stamp !== undefined) parts.push(link(shape.stamp === \"create\" ? \"onCreateNow\" : \"onUpdateNow\"));\n if (shape.kind === \"string\" && shape.stamp !== undefined) parts.push(link(shape.stamp === \"createUser\" ? \"onCreateUser\" : \"onUpdateUser\"));\n if (shape.kind === \"string\" && shape.semantic === \"user\") {\n if (shape.storage !== undefined) throw new TablePrintError(here, \"`.userId()` on `json.storage()`; it applies to `json.string()`.\");\n parts.push(link(\"userId\"));\n }\n if ((shape.kind === \"string\" || shape.kind === \"number\") && shape.oneOf !== undefined) {\n parts.push(link(\"oneOf\", [valueDoc(shape.oneOf, `${here}.oneOf`)]));\n }\n if ((shape.kind === \"string\" || shape.kind === \"number\" || shape.kind === \"date\" || shape.kind === \"array\") && shape.validate !== undefined) {\n parts.push(link(\"validate\", [validationDoc(shape.validate, here)]));\n }\n const transform = transformLink(false, shape.transform, relative, ctx);\n if (transform) parts.push(transform);\n if (shape.description !== undefined) parts.push(link(\"describe\", [text(printString(shape.description))]));\n return parts.length === 1 ? base : concat(parts);\n}\n\n/**\n * The builder chain of one column: `col.uuid().primaryKey().defaultRandom()`.\n *\n * Deterministic, in the canonical modifier order ({@link COLUMN_MODIFIER_ORDER}),\n * printing only what differs from the builder's defaults. Throws a\n * {@link TablePrintError} for what no chain reproduces — a transform without\n * its source, a type with no builder.\n *\n * @group Schema\n */\nexport function printColumn(def: ColumnDef, options: PrintColumnOptions = {}): string {\n const transforms: Record<string, string> = { ...options.transforms };\n if (options.transform !== undefined) transforms[\"\"] = options.transform;\n const ctx: ColumnPrintContext = {\n path: options.key ?? \"column\",\n transforms,\n used: new Set(),\n origin: \"\",\n sourceHint: columnOptionHint,\n ...(options.enumIdentifier !== undefined ? { enumIdentifier: options.enumIdentifier } : {})\n };\n return render(columnChain(def, ctx, options.key, false));\n}\n\n/**\n * The builder of a JSON shape: `json.object({ title: json.string().required() })`.\n *\n * @param transforms Sources of the transforms inside the shape, by path\n * (`\"\"` the node itself, `\"title\"`, `\"[].text\"`).\n *\n * @group Schema\n */\nexport function printJsonShape(shape: JsonShapeDef, transforms: Readonly<Record<string, string>> = {}): string {\n const ctx: ColumnPrintContext = { path: \"json\", transforms, used: new Set(), origin: \"\", sourceHint: columnOptionHint };\n return render(jsonShapeDoc(shape, ctx, \"\"));\n}\n","import type {\n AnyTableDef,\n AnyViewDef,\n ColumnDef,\n ColumnDescriptor,\n DefaultRls,\n RelationDef,\n RelationDescriptor,\n RlsDescriptor,\n RlsPosture,\n TableDescriptor,\n TableIndex\n} from \"@rebasepro/types\";\nimport { isColumnBuilder, isTableDef, isViewDef, resourceKeyOf } from \"@rebasepro/types\";\n\nimport { getTableVarName } from \"../util/relations\";\nimport {\n deriveBelongsToLocalKey,\n deriveJunctionSourceKey,\n deriveJunctionTable,\n deriveJunctionTargetKey,\n deriveTargetForeignKey\n} from \"./derive-names\";\nimport { columnDefOfDescriptor } from \"./descriptor-to-def\";\nimport { columnChain, joinTransformPath, nestedTransforms } from \"./print-column\";\nimport type { ColumnPrintContext, SchemaBuilderName } from \"./print-column\";\nimport { array, call, object, printMultilineString, printString, render, text } from \"./print-doc\";\nimport type { Doc } from \"./print-doc\";\nimport { TablePrintError, valueDoc } from \"./print-value\";\n\nexport { TablePrintError } from \"./print-value\";\nexport {\n COLUMN_MODIFIER_ORDER,\n joinTransformPath,\n printByteSize,\n printColumn,\n printJsonShape,\n printSqlTemplate\n} from \"./print-column\";\nexport type { PrintColumnOptions, SchemaBuilderName } from \"./print-column\";\n\n/**\n * Turning a table back into `defineTable` source.\n *\n * One printer for every writer of `backend/schema/*.ts`: the migration codemod\n * (legacy collections → tables), database introspection (descriptors → tables)\n * and the Studio schema editor (one column or relation at a time). They bring\n * their own AST handling and call this for the text, so a column prints the\n * same whoever writes it.\n *\n * Deterministic: the same input is the same bytes — no dates, no environment.\n * Lossless or loud: a value that is code (a hook, a transform) is printed from\n * the source text the caller supplies, and refused with a\n * {@link TablePrintError} when none was supplied.\n */\n\n/** The import specifier the builders come from unless the caller names another. */\nexport const DEFAULT_SCHEMA_SPECIFIER = \"@rebasepro/server/schema\";\n\n/**\n * The table-level key order of a printed `defineTable` / `defineAuthTable`.\n * `auth` (from `defineAuthTable`) comes last.\n *\n * @group Schema\n */\nexport const TABLE_KEY_ORDER = [\n \"slug\", \"table\", \"schema\", \"database\", \"description\", \"columns\", \"relations\", \"rls\", \"defaultPolicies\",\n \"tenant\", \"softDelete\", \"history\", \"search\", \"indexes\", \"hooks\", \"strictWrites\", \"metadata\", \"auth\"\n] as const;\n\n/**\n * The key order of a printed `defineView`.\n *\n * @group Schema\n */\nexport const VIEW_KEY_ORDER = [\n \"slug\", \"table\", \"schema\", \"database\", \"description\", \"query\", \"materialized\", \"roles\", \"columns\", \"relations\",\n \"indexes\", \"hooks\", \"metadata\"\n] as const;\n\n/** The seven table hooks, in the order a descriptor's flags print. */\nconst HOOK_ORDER = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/**\n * The name of a table hook.\n *\n * @group Schema\n */\nexport type TableHookName = typeof HOOK_ORDER[number];\n\n/**\n * How a relation's target is written in the printed module.\n *\n * @group Schema\n */\nexport interface PrintTarget {\n /** The identifier the target table is bound to: what the thunk returns, `() => users`. */\n identifier: string;\n /** The module to import it from, `\"./users\"`. No import when absent (the same module). */\n importPath?: string;\n /**\n * The target's SQL table, when known. Lets a descriptor's junction table\n * be left out when it is the derived one; without it `through` is printed.\n */\n table?: string;\n /** Whether the target is a view. A view never gets a `FOREIGN KEY`, so `constraint: false` is not printed for it. */\n kind?: \"table\" | \"view\";\n}\n\n/**\n * Maps a relation's target to the identifier and module it is printed with.\n * A definition's target is known by name and slug; a descriptor's by slug.\n *\n * @group Schema\n */\nexport type PrintTargetResolver = (target: { name?: string; slug: string }) => PrintTarget;\n\n/**\n * Source text for what is code rather than data, printed verbatim.\n *\n * @group Schema\n */\nexport interface TableSources {\n /**\n * Field-level transforms by path: `\"title\"` the column, `\"tags[]\"` an array\n * column's element, `\"seo.title\"` a field of a JSON column,\n * `\"content[].image\"` inside a JSON array, `\"tags.pivot.note\"` a pivot\n * column of the relation `tags`.\n */\n transforms?: Readonly<Record<string, string>>;\n /**\n * The table hooks: the whole `hooks` expression as one string, or each\n * hook's source by name.\n */\n hooks?: string | Readonly<Partial<Record<TableHookName, string>>>;\n /** The user-lifecycle functions of `defineAuthTable`'s `auth`. */\n auth?: { onCreateUser?: string; onResetPassword?: string };\n}\n\n/**\n * Options of {@link printTableSource} and {@link printTableModule}.\n *\n * @group Schema\n */\nexport interface PrintTableOptions {\n /** The identifier of `export const <identifier>`. The camelCase of the table's name when omitted. */\n identifier?: string;\n /** Where the builders are imported from. {@link DEFAULT_SCHEMA_SPECIFIER} when omitted. */\n specifier?: string;\n /** How relation targets are written. `./<name>` exporting the camelCase of the name when omitted. */\n resolveTarget?: PrintTargetResolver;\n /** Source text of the hooks and transforms. */\n sources?: TableSources;\n /** Extra import lines, printed verbatim after the generated ones (what hook sources reference). */\n extraImports?: readonly string[];\n}\n\n/**\n * One table identifier imported for a relation thunk.\n *\n * @group Schema\n */\nexport interface PrintedTableImport {\n /** The bound name. */\n identifier: string;\n /** The module it comes from. */\n importPath: string;\n}\n\n/**\n * What a printed table needs imported.\n *\n * @group Schema\n */\nexport interface PrintedImports {\n /** The builders' module. */\n specifier: string;\n /** The builders used, in import order (`define*`, `col`, `rel`, `json`). */\n builders: SchemaBuilderName[];\n /** The related tables, in the order their relations are declared, each once. */\n tables: PrintedTableImport[];\n}\n\n/**\n * A printed table: the `export const` statement and what it needs imported.\n *\n * @group Schema\n */\nexport interface PrintedTable {\n /** The exported identifier. */\n identifier: string;\n /**\n * `export const <identifier> = defineTable(\"<name>\", { … });`, preceded by\n * a `const <name>Enum = pgEnum(\"<type>\", [...]);` for each named enum type\n * its columns use.\n */\n code: string;\n /** What the statement needs imported. */\n imports: PrintedImports;\n}\n\n/**\n * What {@link printRelation} needs besides the relation.\n *\n * @group Schema\n */\nexport interface PrintRelationContext {\n /** How the target is written. `./<name>` exporting the camelCase of the name when omitted. */\n resolveTarget?: PrintTargetResolver;\n /** For a descriptor: the table that declares the relation, to leave derived names out. */\n owner?: TableDescriptor;\n /** Transform sources of pivot columns, by `<relation>.pivot.<column>` path. */\n transforms?: Readonly<Record<string, string>>;\n}\n\n/** Anything the module printer takes. */\nexport type PrintableTable = AnyTableDef | AnyViewDef | TableDescriptor;\n\nconst BUILDER_ORDER: readonly SchemaBuilderName[] = [\"defineTable\", \"defineAuthTable\", \"defineView\", \"col\", \"rel\", \"json\", \"pgEnum\", \"sql\"];\n\nconst RESERVED = new Set([\n \"break\", \"case\", \"catch\", \"class\", \"const\", \"continue\", \"debugger\", \"default\", \"delete\", \"do\", \"else\", \"enum\",\n \"export\", \"extends\", \"false\", \"finally\", \"for\", \"function\", \"if\", \"import\", \"in\", \"instanceof\", \"new\", \"null\",\n \"return\", \"super\", \"switch\", \"this\", \"throw\", \"true\", \"try\", \"typeof\", \"var\", \"void\", \"while\", \"with\", \"yield\",\n \"let\", \"static\", \"implements\", \"interface\", \"package\", \"private\", \"protected\", \"public\", \"await\", \"arguments\",\n \"eval\", \"undefined\", \"NaN\", \"Infinity\",\n // The builders a printed module imports: a table bound to one would shadow it.\n ...BUILDER_ORDER\n]);\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * The identifier a table is exported as: the camelCase of its name, made a\n * valid identifier (a leading digit is prefixed), with `Table` appended when\n * it is a reserved word or the name of a builder the module imports.\n *\n * @group Schema\n */\nexport function tableIdentifier(name: string): string {\n const identifier = getTableVarName(name);\n return RESERVED.has(identifier) ? `${identifier}Table` : identifier;\n}\n\nfunction checkIdentifier(identifier: string, what: string): string {\n if (!IDENTIFIER.test(identifier) || RESERVED.has(identifier)) {\n throw new TablePrintError(what, `\"${identifier}\" is not a usable identifier: it must be a JavaScript identifier, not a reserved word or a builder's name.`);\n }\n return identifier;\n}\n\nconst defaultResolver: PrintTargetResolver = target => {\n const name = target.name ?? target.slug;\n return { identifier: tableIdentifier(name), importPath: `./${name}` };\n};\n\n/** Everything printing one table collects and consults. */\ninterface TableState {\n label: string;\n identifier: string;\n used: Set<SchemaBuilderName>;\n imports: PrintedTableImport[];\n transforms: Readonly<Record<string, string>>;\n resolve: PrintTargetResolver;\n /** Whether a relation target is the table being printed. */\n isSelf: (target: { def?: unknown; slug: string }) => boolean;\n /**\n * The named enum types the table's columns use, by type name: each is\n * declared once with `pgEnum` above the table. Absent when nothing is\n * printed above (a lone relation): a named enum then inlines its `pgEnum`.\n */\n enums?: Map<string, { identifier: string; values: readonly string[] }>;\n}\n\n/**\n * The identifier a named enum type is bound to in printed source: the\n * camelCase of its name with `Enum` appended (`post_status` → `postStatusEnum`,\n * `issue_status_enum` → `issueStatusEnum`), as Drizzle projects name theirs.\n *\n * @group Schema\n */\nexport function enumIdentifier(enumName: string): string {\n const camel = getTableVarName(enumName);\n const identifier = /Enum$/.test(camel) ? camel : `${camel}Enum`;\n return RESERVED.has(identifier) ? `${identifier}Type` : identifier;\n}\n\n/** Records a named enum the table uses and returns its binding; one name with two lists of values is refused. */\nfunction enumBinding(state: TableState, enums: NonNullable<TableState[\"enums\"]>, path: string): (enumName: string, values: readonly string[]) => string {\n return (enumName, values) => {\n const known = enums.get(enumName);\n if (known !== undefined) {\n if (known.values.join(\"\\u0000\") !== values.join(\"\\u0000\")) {\n throw new TablePrintError(path, `the enum type \"${enumName}\" is declared with two different lists of values in one table.`);\n }\n return known.identifier;\n }\n let identifier = enumIdentifier(enumName);\n const taken = new Set([state.identifier, ...state.imports.map(entry => entry.identifier), ...[...enums.values()].map(entry => entry.identifier)]);\n while (taken.has(identifier)) identifier = `${identifier}Type`;\n enums.set(enumName, { identifier, values });\n state.used.add(\"pgEnum\");\n return identifier;\n };\n}\n\nfunction columnContext(state: TableState, path: string, prefix: string): ColumnPrintContext {\n return {\n path,\n transforms: nestedTransforms(state.transforms, prefix),\n used: state.used,\n origin: \"\",\n sourceHint: relative => `as \\`sources.transforms[\"${relative === \"\" ? prefix : joinTransformPath(prefix, relative)}\"]\\``,\n ...(state.enums !== undefined ? { enumIdentifier: enumBinding(state, state.enums, path) } : {})\n };\n}\n\n/** A `columns` map (or a pivot) as a doc, one column per line. */\nfunction columnsDoc(columns: readonly { key: string; def: ColumnDef; declaresTransform: boolean }[], state: TableState, pathPrefix: string, transformPrefix: string): Doc {\n return object(\n columns.map(({ key, def, declaresTransform }): [string, Doc] => [\n key,\n columnChain(def, columnContext(state, `${pathPrefix}.${key}`, joinTransformPath(transformPrefix, key)), key, declaresTransform)\n ]),\n true\n );\n}\n\nfunction columnsOfDef(columns: object, path: string): { key: string; def: ColumnDef; declaresTransform: boolean }[] {\n return Object.entries(columns).map(([key, builder]: [string, unknown]) => {\n if (!isColumnBuilder(builder)) throw new TablePrintError(`${path}.${key}`, \"it is not a `col.*` builder.\");\n return { key, def: builder.def, declaresTransform: false };\n });\n}\n\nfunction columnsOfDescriptor(columns: readonly ColumnDescriptor[]): { key: string; def: ColumnDef; declaresTransform: boolean }[] {\n return columns\n .filter(column => column.derived !== true)\n .map(column => ({ key: column.key, def: columnDefOfDescriptor(column), declaresTransform: column.transforms !== undefined }));\n}\n\n// ── Relations ────────────────────────────────────────────────────────────────\n\n/** Each relation kind's options, in print order; the field rules every kind takes come last. */\nconst RELATION_KEYS: Readonly<Record<RelationDef[\"kind\"], readonly string[]>> = {\n belongsTo: [\"localKey\", \"notNull\", \"unique\", \"onDelete\", \"onUpdate\", \"index\", \"constraint\", \"access\", \"private\"],\n hasOne: [\"foreignKey\", \"sourceKey\", \"access\", \"private\"],\n hasMany: [\"foreignKey\", \"sourceKey\", \"orderBy\", \"access\", \"private\"],\n manyToMany: [\"through\", \"sourceKey\", \"targetKey\", \"pivot\", \"onDelete\", \"access\", \"private\"],\n via: [\"steps\", \"cardinality\", \"access\", \"private\"]\n};\n\n/**\n * The thunk `() => <identifier>`, recording the import it needs. Never\n * annotated: `rel.*` take a `TableThunk` (`() => void`), so tables that point\n * at each other compile as written.\n */\nfunction targetThunk(state: TableState, target: { name?: string; slug: string; def?: unknown }, path: string): { doc: Doc; printed: PrintTarget } {\n const self = state.isSelf(target);\n const printed: PrintTarget = self ? { identifier: state.identifier } : state.resolve({ name: target.name, slug: target.slug });\n if (!self) {\n checkIdentifier(printed.identifier, `${path} (target identifier)`);\n if (printed.importPath !== undefined && !state.imports.some(entry => entry.identifier === printed.identifier && entry.importPath === printed.importPath)) {\n state.imports.push({ identifier: printed.identifier, importPath: printed.importPath });\n }\n }\n return { doc: text(`() => ${printed.identifier}`), printed };\n}\n\nfunction relationOfDef(name: string, relation: RelationDef, state: TableState): Doc {\n const path = `${state.label}.relations.${name}`;\n state.used.add(\"rel\");\n let target: unknown;\n try {\n target = relation.target();\n } catch (error) {\n throw new TablePrintError(path, `its target thunk threw: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!isTableDef(target) && !isViewDef(target)) {\n throw new TablePrintError(path, \"its target thunk does not return a `defineTable` / `defineView` result.\");\n }\n const { doc: thunk } = targetThunk(state, { name: target.name, slug: target.config.slug ?? target.name, def: target }, path);\n const known = RELATION_KEYS[relation.kind];\n for (const key of Object.keys(relation)) {\n if (key === \"brand\" || key === \"kind\" || key === \"target\") continue;\n if (!known.includes(key)) throw new TablePrintError(`${path}.${key}`, `it is not an option of \\`rel.${relation.kind}\\`.`);\n }\n const entries: [string, Doc][] = [];\n for (const key of known) {\n const value: unknown = Reflect.get(relation, key);\n if (value === undefined) continue;\n if (key === \"pivot\" && typeof value === \"object\" && value !== null) {\n const pivot = columnsOfDef(value, `${path}.pivot`);\n entries.push([key, columnsDoc(pivot, state, `${path}.pivot`, `${name}.pivot`)]);\n } else {\n entries.push([key, valueDoc(value, `${path}.${key}`)]);\n }\n }\n return call(`rel.${relation.kind}`, entries.length > 0 || relation.kind === \"via\" ? [thunk, object(entries)] : [thunk]);\n}\n\nfunction relationOfDescriptor(relation: RelationDescriptor, owner: TableDescriptor, state: TableState): Doc {\n const path = `${state.label}.relations.${relation.name}`;\n state.used.add(\"rel\");\n const { doc: thunk, printed } = targetThunk(state, { slug: relation.target }, path);\n const entries: [string, Doc][] = [];\n const str = (value: string): Doc => text(printString(value));\n switch (relation.kind) {\n case \"belongsTo\": {\n if (relation.localKey !== deriveBelongsToLocalKey(relation.name, undefined)) entries.push([\"localKey\", str(relation.localKey)]);\n const derived = owner.columns.find(column => column.key === relation.localField && column.derived === true);\n if (derived && !derived.nullable && !(owner.tenant?.field === derived.key)) entries.push([\"notNull\", text(\"true\")]);\n if (derived?.unique) entries.push([\"unique\", text(\"true\")]);\n if (relation.onDelete !== undefined) entries.push([\"onDelete\", str(relation.onDelete)]);\n if (relation.onUpdate !== undefined) entries.push([\"onUpdate\", str(relation.onUpdate)]);\n if (!relation.index) entries.push([\"index\", text(\"false\")]);\n const targetIsView = printed.kind === \"view\" || (state.isSelf({ slug: relation.target }) && owner.kind === \"view\");\n if (!relation.constraint && owner.kind === \"table\" && !targetIsView) entries.push([\"constraint\", text(\"false\")]);\n break;\n }\n case \"hasOne\":\n case \"hasMany\":\n if (relation.foreignKey !== deriveTargetForeignKey(owner.slug, undefined)) entries.push([\"foreignKey\", str(relation.foreignKey)]);\n if (relation.sourceKey !== undefined) entries.push([\"sourceKey\", str(relation.sourceKey)]);\n if (relation.kind === \"hasMany\" && relation.orderBy !== undefined) entries.push([\"orderBy\", valueDoc(relation.orderBy, `${path}.orderBy`)]);\n break;\n case \"manyToMany\": {\n const targetTable = state.isSelf({ slug: relation.target }) ? owner.table : printed.table;\n if (targetTable === undefined || relation.through.table !== deriveJunctionTable(owner.table, targetTable, undefined)) {\n entries.push([\"through\", str(relation.through.table)]);\n }\n if (relation.through.sourceKey !== deriveJunctionSourceKey(owner.slug, undefined)) entries.push([\"sourceKey\", str(relation.through.sourceKey)]);\n if (relation.through.targetKey !== deriveJunctionTargetKey(relation.name, undefined)) entries.push([\"targetKey\", str(relation.through.targetKey)]);\n if (relation.through.pivot.length > 0) {\n entries.push([\"pivot\", columnsDoc(columnsOfDescriptor(relation.through.pivot), state, `${path}.pivot`, `${relation.name}.pivot`)]);\n }\n if (relation.onDelete !== undefined) entries.push([\"onDelete\", str(relation.onDelete)]);\n break;\n }\n case \"via\":\n entries.push([\"steps\", valueDoc(relation.steps, `${path}.steps`)]);\n if (relation.cardinality === \"one\") entries.push([\"cardinality\", str(\"one\")]);\n break;\n }\n if (relation.access !== undefined) entries.push([\"access\", valueDoc(relation.access, `${path}.access`)]);\n if (relation.private === true) entries.push([\"private\", text(\"true\")]);\n return call(`rel.${relation.kind}`, entries.length > 0 ? [thunk, object(entries)] : [thunk]);\n}\n\n// ── rls, hooks, indexes ──────────────────────────────────────────────────────\n\n/** `rls` as a doc: a posture string, or one rule per line, each rule's keys in the order written. */\nfunction rlsDoc(rls: RlsPosture | DefaultRls | readonly unknown[], path: string): Doc {\n if (typeof rls === \"string\") return text(printString(rls));\n return array(rls.map((rule, index) => valueDoc(rule, `${path}[${index}]`)), true);\n}\n\nfunction rlsOfDescriptor(rls: RlsDescriptor, path: string): Doc {\n if (rls.inherited) return text(printString(\"inherit\"));\n if (rls.posture === \"admin-only\") return text(printString(\"admin-only\"));\n if (rls.posture === \"view\") {\n throw new TablePrintError(path, \"a view has no `rls` of its own: a plain view is governed by the tables it reads, a materialized one by `roles`. Print the view, not its rls.\");\n }\n if (rls.rules.length === 0) throw new TablePrintError(path, \"the descriptor has rule-based rls with no rules, which `defineTable` refuses. Say `\\\"admin-only\\\"` or list the rules.\");\n return rlsDoc(rls.rules, path);\n}\n\nfunction hooksDoc(hooks: object | undefined, flags: readonly TableHookName[], state: TableState, sources: TableSources[\"hooks\"]): Doc | undefined {\n const path = `${state.label}.hooks`;\n if (typeof sources === \"string\") return text(sources);\n const names: string[] = hooks !== undefined ? Object.keys(hooks) : [...flags];\n if (hooks === undefined && names.length === 0) return undefined;\n const entries: [string, Doc][] = [];\n for (const name of names) {\n const value: unknown = hooks !== undefined ? Reflect.get(hooks, name) : undefined;\n if (value === undefined && hooks !== undefined) continue;\n if (hooks !== undefined && typeof value !== \"function\") {\n throw new TablePrintError(`${path}.${name}`, \"a hook must be a function.\");\n }\n const source = sources !== undefined ? Reflect.get(sources, name) : undefined;\n if (typeof source !== \"string\") {\n throw new TablePrintError(`${path}.${name}`, `the hook is a function, which cannot be printed from its value. Pass its source text as \\`sources.hooks.${name}\\`.`);\n }\n entries.push([name, text(source)]);\n }\n return object(entries, true);\n}\n\n/**\n * The `rls` of a table as source: `\"admin-only\"`, `\"inherit\"`, or the rules,\n * one per line, each rule's keys in the order written (a policy's name is a\n * hash of its rule as written, so a rule is never reordered).\n *\n * @group Schema\n */\nexport function printRls(rls: RlsPosture | DefaultRls | RlsDescriptor): string {\n if (typeof rls === \"object\" && \"posture\" in rls) return render(rlsOfDescriptor(rls, \"rls\"));\n return render(rlsDoc(rls, \"rls\"));\n}\n\n/**\n * The `indexes` of a table as source.\n *\n * @group Schema\n */\nexport function printIndexes(indexes: readonly TableIndex[]): string {\n return render(valueDoc(indexes, \"indexes\"));\n}\n\n/**\n * A data value as source, the way the table printer writes every data-valued\n * key: a table-level option (`tenant`, `search`, `softDelete`, `metadata`…),\n * or one rule of an `rls` list. Objects keep the key order they were given (a\n * rule is never reordered: its policy's name is a hash of the rule as\n * written). Throws a {@link TablePrintError} for a function or a value with no\n * literal form.\n *\n * @param path Where the value sits, for the error: `posts.tenant`.\n *\n * @group Schema\n */\nexport function printSchemaValue(value: unknown, path: string): string {\n return render(valueDoc(value, path));\n}\n\n/**\n * One relation as source: `rel.belongsTo(() => users, { onDelete: \"restrict\" })`.\n *\n * A definition prints with the options it was written with; a descriptor\n * prints the options that differ from what the compiler derives (give\n * `context.owner`, the declaring table's descriptor).\n *\n * @group Schema\n */\nexport function printRelation(name: string, relation: RelationDef | RelationDescriptor, context: PrintRelationContext = {}): string {\n const state: TableState = {\n label: context.owner?.name ?? \"table\",\n identifier: context.owner ? tableIdentifier(context.owner.name) : \"table\",\n used: new Set(),\n imports: [],\n transforms: context.transforms ?? {},\n resolve: context.resolveTarget ?? defaultResolver,\n isSelf: target => context.owner !== undefined && target.def === undefined && target.slug === context.owner.slug\n };\n if (\"brand\" in relation) return render(relationOfDef(name, relation, state));\n if (!context.owner) {\n throw new TablePrintError(`relations.${name}`, \"a relation descriptor prints against the table that declares it: pass `context.owner`.\");\n }\n return render(relationOfDescriptor(relation, context.owner, state));\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────────\n\nconst TABLE_CONFIG_KEYS = new Set<string>(TABLE_KEY_ORDER);\nconst VIEW_CONFIG_KEYS = new Set<string>(VIEW_KEY_ORDER);\n\nfunction checkKnownKeys(config: object, known: ReadonlySet<string>, path: string, builder: string): void {\n for (const key of Object.keys(config)) {\n if (!known.has(key) || key === \"auth\") {\n if (Reflect.get(config, key) === undefined) continue;\n throw new TablePrintError(`${path}.${key}`, `it is not an option of \\`${builder}\\`.`);\n }\n }\n}\n\nfunction authDoc(auth: object, state: TableState, sources: TableSources[\"auth\"], declaredHooks: readonly AuthHookName[] = []): Doc | undefined {\n const entries: [string, Doc][] = [];\n const hookDoc = (key: AuthHookName): Doc => {\n const source = sources?.[key];\n if (source === undefined) {\n throw new TablePrintError(`${state.label}.auth.${key}`, `it is a function, which cannot be printed from its value. Pass its source text as \\`sources.auth.${key}\\`.`);\n }\n return text(source);\n };\n for (const [key, value] of Object.entries(auth)) {\n if (value === undefined) continue;\n if (typeof value === \"function\") {\n if (key !== \"onCreateUser\" && key !== \"onResetPassword\") {\n throw new TablePrintError(`${state.label}.auth.${key}`, \"it is a function, and only `onCreateUser` and `onResetPassword` are.\");\n }\n entries.push([key, hookDoc(key)]);\n } else {\n entries.push([key, valueDoc(value, `${state.label}.auth.${key}`)]);\n }\n }\n for (const key of declaredHooks) entries.push([key, hookDoc(key)]);\n return entries.length > 0 ? object(entries) : undefined;\n}\n\n/** A user-lifecycle hook of `defineAuthTable`'s `auth`. */\ntype AuthHookName = \"onCreateUser\" | \"onResetPassword\";\n\nfunction newState(name: string, identifier: string, options: PrintTableOptions, isSelf: TableState[\"isSelf\"]): TableState {\n return {\n label: name,\n identifier,\n used: new Set(),\n imports: [],\n transforms: options.sources?.transforms ?? {},\n resolve: options.resolveTarget ?? defaultResolver,\n isSelf,\n enums: new Map()\n };\n}\n\nfunction definitionDoc(def: AnyTableDef | AnyViewDef, state: TableState, options: PrintTableOptions): Doc {\n const config = def.config;\n const entries: [string, Doc][] = [];\n const put = (key: string, value: unknown): void => {\n if (value !== undefined) entries.push([key, valueDoc(value, `${state.label}.${key}`)]);\n };\n const columns = (): Doc => columnsDoc(columnsOfDef(config.columns, `${state.label}.columns`), state, `${state.label}.columns`, \"\");\n const relations = (): void => {\n if (config.relations === undefined) return;\n entries.push([\"relations\", object(\n Object.entries(config.relations).map(([name, relation]): [string, Doc] => [name, relationOfDef(name, relation, state)]),\n true\n )]);\n };\n const hooks = (): void => {\n const doc = hooksDoc(config.hooks, [], state, options.sources?.hooks);\n if (config.hooks !== undefined && doc) entries.push([\"hooks\", doc]);\n };\n const database = config.database !== undefined ? resourceKeyOf(config.database) : undefined;\n\n if (isViewDef(def)) {\n state.used.add(\"defineView\");\n checkKnownKeys(def.config, VIEW_CONFIG_KEYS, state.label, \"defineView\");\n const view = def.config;\n put(\"slug\", view.slug);\n put(\"table\", view.table);\n put(\"schema\", view.schema);\n put(\"database\", database);\n put(\"description\", view.description);\n entries.push([\"query\", text(printMultilineString(view.query))]);\n put(\"materialized\", view.materialized);\n put(\"roles\", view.roles);\n entries.push([\"columns\", columns()]);\n relations();\n put(\"indexes\", view.indexes);\n hooks();\n put(\"metadata\", view.metadata);\n return call(\"defineView\", [text(printString(def.name)), object(entries, true)]);\n }\n\n const table = def.config;\n const auth = def.auth !== undefined;\n state.used.add(auth ? \"defineAuthTable\" : \"defineTable\");\n checkKnownKeys(table, TABLE_CONFIG_KEYS, state.label, auth ? \"defineAuthTable\" : \"defineTable\");\n put(\"slug\", table.slug);\n put(\"table\", table.table);\n put(\"schema\", table.schema);\n put(\"database\", database);\n put(\"description\", table.description);\n entries.push([\"columns\", columns()]);\n relations();\n entries.push([\"rls\", rlsDoc(table.rls, `${state.label}.rls`)]);\n put(\"defaultPolicies\", table.defaultPolicies);\n put(\"tenant\", table.tenant);\n put(\"softDelete\", table.softDelete);\n put(\"history\", table.history);\n put(\"search\", table.search);\n put(\"indexes\", table.indexes);\n hooks();\n put(\"strictWrites\", table.strictWrites);\n put(\"metadata\", table.metadata);\n if (def.auth !== undefined) {\n const doc = authDoc(def.auth, state, options.sources?.auth);\n if (doc) entries.push([\"auth\", doc]);\n }\n return call(auth ? \"defineAuthTable\" : \"defineTable\", [text(printString(def.name)), object(entries, true)]);\n}\n\nfunction descriptorDoc(descriptor: TableDescriptor, state: TableState, options: PrintTableOptions): Doc {\n const entries: [string, Doc][] = [];\n const put = (key: string, value: unknown): void => {\n if (value !== undefined) entries.push([key, valueDoc(value, `${state.label}.${key}`)]);\n };\n const view = descriptor.kind === \"view\";\n put(\"slug\", descriptor.slug !== descriptor.name ? descriptor.slug : undefined);\n put(\"table\", descriptor.table !== descriptor.name ? descriptor.table : undefined);\n put(\"schema\", descriptor.schema !== \"public\" ? descriptor.schema : undefined);\n put(\"database\", descriptor.database);\n put(\"description\", descriptor.description);\n const columns = object(\n columnsOfDescriptor(descriptor.columns).map(({ key, def, declaresTransform }): [string, Doc] =>\n [key, columnChain(def, columnContext(state, `${state.label}.columns.${key}`, key), key, declaresTransform)]),\n true\n );\n const relations = descriptor.relations.length > 0\n ? object(descriptor.relations.map((relation): [string, Doc] => [relation.name, relationOfDescriptor(relation, descriptor, state)]), true)\n : undefined;\n const hookNames = HOOK_ORDER.filter(name => descriptor.hooks?.[name] === true);\n const hooks = hookNames.length > 0 ? hooksDoc(undefined, hookNames, state, options.sources?.hooks) : undefined;\n\n if (view) {\n state.used.add(\"defineView\");\n if (descriptor.view?.query === undefined) {\n throw new TablePrintError(`${state.label}.query`, \"the view's descriptor carries no query (it is served to admins only). Print from a descriptor that includes it.\");\n }\n entries.push([\"query\", text(printMultilineString(descriptor.view.query))]);\n if (descriptor.view.materialized) {\n put(\"materialized\", true);\n const roles = descriptor.view.roles;\n if (roles !== undefined && !(roles.length === 1 && roles[0] === \"admin\")) put(\"roles\", roles);\n }\n entries.push([\"columns\", columns]);\n if (relations) entries.push([\"relations\", relations]);\n put(\"indexes\", descriptor.indexes);\n if (hooks) entries.push([\"hooks\", hooks]);\n put(\"metadata\", descriptor.metadata);\n return call(\"defineView\", [text(printString(descriptor.name)), object(entries, true)]);\n }\n\n const auth = descriptor.auth !== undefined;\n state.used.add(auth ? \"defineAuthTable\" : \"defineTable\");\n entries.push([\"columns\", columns]);\n if (relations) entries.push([\"relations\", relations]);\n entries.push([\"rls\", rlsOfDescriptor(descriptor.rls, `${state.label}.rls`)]);\n if (!descriptor.rls.defaultPolicies && descriptor.rls.posture === \"rules\") put(\"defaultPolicies\", false);\n else if (descriptor.rls.declaredDefaultPolicies) put(\"defaultPolicies\", true);\n put(\"tenant\", descriptor.tenant);\n put(\"softDelete\", descriptor.softDelete);\n put(\"history\", descriptor.history);\n put(\"search\", descriptor.search);\n put(\"indexes\", descriptor.indexes);\n if (hooks) entries.push([\"hooks\", hooks]);\n put(\"strictWrites\", descriptor.strictWrites);\n put(\"metadata\", descriptor.metadata);\n if (descriptor.auth !== undefined) {\n // The hook flags stand for code that never left the server: printed from `sources.auth`.\n const { hooks: authHooks, ...authOptions } = descriptor.auth;\n const declared = ([\"onCreateUser\", \"onResetPassword\"] as const).filter(name => authHooks?.[name] === true);\n const doc = authDoc(authOptions, state, options.sources?.auth, declared);\n if (doc) entries.push([\"auth\", doc]);\n }\n return call(auth ? \"defineAuthTable\" : \"defineTable\", [text(printString(descriptor.name)), object(entries, true)]);\n}\n\n/**\n * One table as an `export const` statement, with what it needs imported.\n *\n * Takes an authored definition (`defineTable` / `defineAuthTable` /\n * `defineView`, printed as written) or a compiled {@link TableDescriptor}\n * (introspection's output: derived names and defaults are left out, derived\n * foreign-key columns are left to their relation).\n *\n * Keys in {@link TABLE_KEY_ORDER} / {@link VIEW_KEY_ORDER}, columns in the\n * canonical modifier order, four-space indentation, double quotes, no\n * trailing commas.\n *\n * @group Schema\n */\nexport function printTableSource(input: PrintableTable, options: PrintTableOptions = {}): PrintedTable {\n const name = input.name;\n const identifier = options.identifier !== undefined\n ? checkIdentifier(options.identifier, `${name} (identifier)`)\n : tableIdentifier(name);\n let state: TableState;\n let doc: Doc;\n if (isTableDef(input) || isViewDef(input)) {\n state = newState(name, identifier, options, target => target.def === input);\n doc = definitionDoc(input, state, options);\n } else {\n state = newState(name, identifier, options, target => target.def === undefined && target.slug === input.slug);\n doc = descriptorDoc(input, state, options);\n }\n const declarations = [...(state.enums ?? [])].map(([enumName, { identifier: binding, values }]) => {\n const prefix = `const ${binding} = `;\n return `${prefix}${render(call(\"pgEnum\", [text(printString(enumName)), array(values.map(value => text(printString(value))))]), 0, prefix.length)};`;\n });\n const statement = `export const ${identifier} = ${render(doc, 0, `export const ${identifier} = `.length)};`;\n const code = declarations.length > 0 ? `${declarations.join(\"\\n\")}\\n\\n${statement}` : statement;\n return {\n identifier,\n code,\n imports: {\n specifier: options.specifier ?? DEFAULT_SCHEMA_SPECIFIER,\n builders: BUILDER_ORDER.filter(builder => state.used.has(builder)),\n tables: state.imports\n }\n };\n}\n\n/** The import lines of a printed table: builders first, then related tables grouped by module. */\nexport function printImportLines(imports: PrintedImports): string[] {\n const lines = [`import { ${imports.builders.join(\", \")} } from ${printString(imports.specifier)};`];\n const byPath = new Map<string, string[]>();\n for (const entry of imports.tables) {\n const list = byPath.get(entry.importPath) ?? [];\n if (!list.includes(entry.identifier)) list.push(entry.identifier);\n byPath.set(entry.importPath, list);\n }\n for (const [importPath, identifiers] of byPath) lines.push(`import { ${identifiers.join(\", \")} } from ${printString(importPath)};`);\n return lines;\n}\n\n/**\n * One table as a whole module — what `backend/schema/<table>.ts` holds:\n *\n * ```ts\n * import { defineTable, col, rel } from \"@rebasepro/server/schema\";\n * import { users } from \"./users\";\n *\n * export const posts = defineTable(\"posts\", { … });\n * ```\n *\n * @group Schema\n */\nexport function printTableModule(input: PrintableTable, options: PrintTableOptions = {}): string {\n const printed = printTableSource(input, options);\n const imports = [...printImportLines(printed.imports), ...(options.extraImports ?? [])];\n return `${imports.join(\"\\n\")}\\n\\n${printed.code}\\n`;\n}\n\n/**\n * Options of {@link printIndexModule}.\n *\n * @group Schema\n */\nexport interface PrintIndexModuleOptions {\n /** The project's `defaultRls`, exported for every `rls: \"inherit\"` table. */\n defaultRls?: DefaultRls;\n}\n\n/**\n * `backend/schema/index.ts`: one re-export per table, in the order given, and\n * `defaultRls` when the project has one.\n *\n * @group Schema\n */\nexport function printIndexModule(tables: readonly PrintedTableImport[], options: PrintIndexModuleOptions = {}): string {\n const lines = tables.map(table => {\n checkIdentifier(table.identifier, `index (${table.importPath})`);\n return `export { ${table.identifier} } from ${printString(table.importPath)};`;\n });\n if (options.defaultRls !== undefined) {\n const prefix = \"export const defaultRls = \";\n lines.push(\"\", `${prefix}${render(rlsDoc(options.defaultRls, \"defaultRls\"), 0, prefix.length)} as const;`);\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n","/**\n * Importing a `backend/schema` directory as it *would be* after an edit.\n *\n * The schema editor refuses an edit whose result does not compile, and the\n * result is text that has not been written anywhere the project reads. So the\n * edited modules are evaluated from that text: each is transpiled to CommonJS\n * with the TypeScript that ships with ts-morph and run in this process, with\n * a `require` that serves the edited text for every module of the schema\n * directory and the disk for everything else.\n *\n * The builders a schema module imports (`@rebasepro/server/schema`, which\n * only re-exports `@rebasepro/types`) are served from this process's own\n * copy, so a definition evaluated here is the same kind of object the server\n * runs — the definitions it yields are what the server is refreshed with after\n * an apply.\n */\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport vm from \"node:vm\";\nimport { ts } from \"ts-morph\";\nimport * as schemaBuilders from \"@rebasepro/types\";\n\nimport type { SchemaModuleImporter } from \"../schema/load-schema\";\n\n/** The module specifiers served from this process's builders. */\nconst BUILDER_SPECIFIERS = new Set([\"@rebasepro/server/schema\", \"@rebasepro/types\"]);\n\n/** What a module file may be named, in the order an extensionless import tries them. */\nconst RESOLVE_SUFFIXES = [\".ts\", \".mts\", \".tsx\", \".js\", \".mjs\", \".cjs\", \".json\", \"/index.ts\", \"/index.mts\", \"/index.js\", \"/index.mjs\"];\nconst TRANSPILED = /\\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;\n\n/**\n * Options of {@link createSourceImporter}.\n */\nexport interface SourceImporterOptions {\n /** The edited text of every module of the schema directory, by real absolute path. */\n sources: ReadonlyMap<string, string>;\n /** The schema directory the edited text belongs to. */\n realDir: string;\n /**\n * The directory the loader is pointed at — a scratch copy of `realDir`\n * holding the edited files, so it can list them. Paths under it are read\n * as the same paths under `realDir`.\n */\n scratchDir: string;\n /**\n * Where a bare specifier (`slugify`, `@acme/lib`) is resolved from: the\n * importing module's real location when absent. A schema fetched from a\n * repository into a scratch directory has no `node_modules` above it, so\n * its caller names the runtime's own directory.\n */\n resolveBareFrom?: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * A {@link SchemaModuleImporter} that sees the edited text.\n *\n * Modules are cached for the importer's lifetime, so the index and a sibling\n * that import the same table get the same object, as under Node.\n */\nexport function createSourceImporter(options: SourceImporterOptions): SchemaModuleImporter {\n const { sources, realDir, scratchDir } = options;\n const cache = new Map<string, { exports: unknown }>();\n const bareRequire = options.resolveBareFrom\n ? createRequire(path.join(options.resolveBareFrom, \"noop.js\"))\n : undefined;\n\n const realPathOf = (file: string): string => {\n const relative = path.relative(scratchDir, file);\n return relative.startsWith(\"..\") || path.isAbsolute(relative) ? file : path.join(realDir, relative);\n };\n\n const exists = (file: string): boolean =>\n sources.has(file) || (fs.existsSync(file) && fs.statSync(file).isFile());\n\n const resolveRelative = (specifier: string, from: string): string => {\n const base = path.resolve(path.dirname(from), specifier);\n const candidates = [base, ...RESOLVE_SUFFIXES.map(suffix => base + suffix)];\n // `./users.js` written for a `.ts` file, as TypeScript's own resolution allows.\n if (/\\.[mc]?js$/.test(base)) candidates.push(base.replace(/\\.([mc]?)js$/, \".$1ts\"));\n const found = candidates.find(exists);\n if (!found) throw new Error(`Cannot find module \"${specifier}\" imported from ${from}.`);\n return found;\n };\n\n const evaluate = (file: string): unknown => {\n const cached = cache.get(file);\n if (cached) return cached.exports;\n const text = sources.get(file) ?? fs.readFileSync(file, \"utf8\");\n if (file.endsWith(\".json\")) {\n const parsed: unknown = JSON.parse(text);\n cache.set(file, { exports: parsed });\n return parsed;\n }\n if (!TRANSPILED.test(file)) throw new Error(`Cannot import ${file}: not a module.`);\n const { outputText } = ts.transpileModule(text, {\n fileName: file,\n compilerOptions: {\n module: ts.ModuleKind.CommonJS,\n target: ts.ScriptTarget.ES2022,\n esModuleInterop: true,\n jsx: ts.JsxEmit.ReactJSX,\n sourceMap: false\n }\n });\n const module: { exports: unknown } = { exports: {} };\n cache.set(file, module);\n const localRequire = (specifier: string): unknown => {\n if (BUILDER_SPECIFIERS.has(specifier)) return schemaBuilders;\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) return evaluate(resolveRelative(specifier, file));\n return (bareRequire ?? createRequire(file))(specifier);\n };\n const wrapper: unknown = vm.runInThisContext(\n `(function (exports, require, module, __filename, __dirname) {${outputText}\\n})`,\n { filename: file }\n );\n if (typeof wrapper !== \"function\") throw new Error(`Could not evaluate ${file}.`);\n Reflect.apply(wrapper, undefined, [module.exports, localRequire, module, file, path.dirname(file)]);\n return module.exports;\n };\n\n return async (file: string): Promise<Record<string, unknown>> => {\n const exported = evaluate(realPathOf(file));\n return isRecord(exported) ? exported : { default: exported };\n };\n}\n","/**\n * Byte-preserving edits of a TypeScript module's text.\n *\n * The schema editor parses with ts-morph to find positions, and writes by\n * splicing text at those positions — never through ts-morph's manipulation\n * API, which reformats what it touches. Everything outside a spliced range is\n * the file as it was: comments, blank lines, trailing commas, quote style.\n *\n * The list helpers edit the members of an object literal (`columns`,\n * `relations`, a `defineTable` config) or the elements of an array literal\n * (`rls` rules) in the layout they are written in: one member per line, or\n * all on one line.\n */\nimport type { Node } from \"ts-morph\";\n\n/** One replacement of `[start, end)` by `text`. */\nexport interface TextEdit {\n start: number;\n end: number;\n text: string;\n}\n\n/** Apply non-overlapping edits to `text`. */\nexport function applyEdits(text: string, edits: readonly TextEdit[]): string {\n const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end);\n let out = text;\n let floor = Number.POSITIVE_INFINITY;\n for (const edit of sorted) {\n if (edit.end > floor) throw new Error(\"Overlapping source edits.\");\n out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);\n floor = edit.start;\n }\n return out;\n}\n\n/** The offset of the first character of the line holding `pos`. */\nexport function lineStart(text: string, pos: number): number {\n return text.lastIndexOf(\"\\n\", pos - 1) + 1;\n}\n\n/** The offset of the `\\n` ending the line holding `pos` (or the end of the text). */\nexport function lineEnd(text: string, pos: number): number {\n const end = text.indexOf(\"\\n\", pos);\n return end === -1 ? text.length : end;\n}\n\n/** The whitespace a line starts with. */\nexport function indentAt(text: string, pos: number): string {\n const start = lineStart(text, pos);\n return /^[ \\t]*/.exec(text.slice(start))?.[0] ?? \"\";\n}\n\n/** Whether only spaces and tabs stand between `from` and `to`. */\nconst blankBetween = (text: string, from: number, to: number): boolean => /^[ \\t]*$/.test(text.slice(from, to));\n\n/**\n * Text printed at indentation 0, shifted so its continuation lines sit under\n * a line indented by `indent`. The first line is placed by the caller.\n */\nexport function reindent(printed: string, indent: string): string {\n return printed.split(\"\\n\").map((line, index) => (index === 0 || line === \"\" ? line : indent + line)).join(\"\\n\");\n}\n\n/** The indentation one level deeper than `indent`, in its own unit (four spaces, or a tab). */\nexport function deeper(indent: string): string {\n return indent + (indent.includes(\"\\t\") ? \"\\t\" : \" \");\n}\n\n/**\n * Where an item's own text begins, its comments included: the leading\n * comments that sit on lines of their own above it. A comment on the line of\n * the previous token (`{ // note`) belongs to that token and is not counted.\n */\nexport function itemStart(text: string, item: Node, previousEnd: number): number {\n for (const range of item.getLeadingCommentRanges()) {\n const pos = range.getPos();\n if (text.slice(previousEnd, pos).includes(\"\\n\")) return pos;\n }\n return item.getStart();\n}\n\n/**\n * Past the separator and the same-line comment that follow an item: the comma\n * if there is one, then a `// …` or `/* … *\\/` on the same line.\n */\nfunction afterSeparator(text: string, pos: number): { end: number; comma: boolean } {\n let at = pos;\n while (at < text.length && (text[at] === \" \" || text[at] === \"\\t\")) at++;\n let comma = false;\n if (text[at] === \",\") {\n comma = true;\n at++;\n }\n let probe = at;\n while (probe < text.length && (text[probe] === \" \" || text[probe] === \"\\t\")) probe++;\n if (text.startsWith(\"//\", probe)) return { end: lineEnd(text, probe), comma };\n if (text.startsWith(\"/*\", probe)) {\n const close = text.indexOf(\"*/\", probe + 2);\n if (close !== -1 && !text.slice(probe, close).includes(\"\\n\")) return { end: close + 2, comma };\n }\n return { end: at, comma };\n}\n\n/** An object or array literal and its members, as the list helpers see it. */\nexport interface ListShape {\n /** Offset just after the opening bracket. */\n open: number;\n /** Offset of the closing bracket. */\n close: number;\n /** The members, in order. */\n items: readonly Node[];\n}\n\n/** The list shape of an object literal's properties or an array literal's elements. */\nexport function listShape(container: Node, items: readonly Node[]): ListShape {\n return { open: container.getStart() + 1, close: container.getEnd() - 1, items };\n}\n\n/** Whether the members are written one per line. */\nfunction isMultiline(text: string, list: ListShape): boolean {\n if (list.items.length === 0) return text.slice(list.open, list.close).includes(\"\\n\");\n const first = list.items[0];\n return text.slice(list.open, itemStart(text, first, list.open)).includes(\"\\n\");\n}\n\n/**\n * Insert `member` (printed at indentation 0) at `index` of the list.\n *\n * @param emptyStyle How an empty list is written to: `\"lines\"` opens it onto\n * its own lines (an object holding columns), `\"inline\"` keeps it on one.\n */\nexport function insertListItem(text: string, list: ListShape, index: number, member: string, emptyStyle: \"lines\" | \"inline\"): TextEdit[] {\n const { items } = list;\n if (items.length === 0) {\n const containerIndent = indentAt(text, list.open - 1);\n if (emptyStyle === \"lines\" || text.slice(list.open, list.close).includes(\"\\n\")) {\n const indent = deeper(containerIndent);\n return [{ start: list.open, end: list.close, text: `\\n${indent}${reindent(member, indent)}\\n${containerIndent}` }];\n }\n const brace = text[list.open - 1] === \"{\";\n return [{ start: list.open, end: list.close, text: brace ? ` ${member} ` : member }];\n }\n if (isMultiline(text, list)) {\n if (index < items.length) {\n const anchor = items[index];\n const previousEnd = index === 0 ? list.open : items[index - 1].getEnd();\n const start = lineStart(text, itemStart(text, anchor, previousEnd));\n const indent = indentAt(text, anchor.getStart());\n return [{ start, end: start, text: `${indent}${reindent(member, indent)},\\n` }];\n }\n const last = items[items.length - 1];\n const indent = indentAt(text, last.getStart());\n const after = afterSeparator(text, last.getEnd());\n if (after.comma) return [{ start: after.end, end: after.end, text: `\\n${indent}${reindent(member, indent)},` }];\n // No trailing comma: one after the last member, the new member on the\n // line after it (and after a comment that ends the last member's line).\n const placed = `\\n${indent}${reindent(member, indent)}`;\n if (after.end === last.getEnd()) return [{ start: last.getEnd(), end: last.getEnd(), text: `,${placed}` }];\n return [\n { start: last.getEnd(), end: last.getEnd(), text: \",\" },\n { start: after.end, end: after.end, text: placed }\n ];\n }\n if (index < items.length) {\n const anchor = items[index];\n return [{ start: anchor.getStart(), end: anchor.getStart(), text: `${member}, ` }];\n }\n const last = items[items.length - 1];\n return [{ start: last.getEnd(), end: last.getEnd(), text: `, ${member}` }];\n}\n\n/** Remove the member at `index` of the list, with its own comments and separator. */\nexport function removeListItem(text: string, list: ListShape, index: number): TextEdit[] {\n const { items } = list;\n const item = items[index];\n const previousEnd = index === 0 ? list.open : items[index - 1].getEnd();\n if (isMultiline(text, list)) {\n const start = lineStart(text, itemStart(text, item, previousEnd));\n const after = afterSeparator(text, item.getEnd());\n const end = blankBetween(text, after.end, lineEnd(text, after.end))\n ? Math.min(text.length, lineEnd(text, after.end) + 1)\n : after.end;\n return [{ start, end, text: \"\" }];\n }\n if (index < items.length - 1) return [{ start: item.getStart(), end: items[index + 1].getStart(), text: \"\" }];\n if (items.length > 1) {\n const after = afterSeparator(text, item.getEnd());\n return [{ start: items[index - 1].getEnd(), end: after.comma ? after.end : item.getEnd(), text: \"\" }];\n }\n const after = afterSeparator(text, item.getEnd());\n return [{ start: item.getStart(), end: after.comma ? after.end : item.getEnd(), text: \"\" }];\n}\n\n/** The member's whole text as written, its own leading comments included, for moving it. */\nexport function itemText(text: string, list: ListShape, index: number): string {\n const item = list.items[index];\n const previousEnd = index === 0 ? list.open : list.items[index - 1].getEnd();\n const start = itemStart(text, item, previousEnd);\n const indent = indentAt(text, item.getStart());\n // Dedent the continuation lines, so `insertListItem` can place them anew.\n return text.slice(start, item.getEnd()).split(\"\\n\")\n .map((line, i) => (i > 0 && line.startsWith(indent) ? line.slice(indent.length) : line))\n .join(\"\\n\");\n}\n\n/** Replace a node's text by `printed` (indentation 0), aligned under the line it sits on. */\nexport function replaceNode(text: string, node: Node, printed: string): TextEdit {\n return { start: node.getStart(), end: node.getEnd(), text: reindent(printed, indentAt(text, node.getStart())) };\n}\n\n/** Remove whole statements (with their own leading comment lines) from a module. */\nexport function removeStatement(text: string, statement: Node, previousEnd: number): TextEdit {\n const start = lineStart(text, itemStart(text, statement, previousEnd));\n const end = Math.min(text.length, lineEnd(text, statement.getEnd()) + 1);\n // Between two blank lines, take one of them too, so no gap of two is left.\n const blankBefore = start >= 2 && text[start - 2] === \"\\n\";\n const blankAfter = end < text.length && text[end] === \"\\n\";\n return { start, end: blankBefore && blankAfter ? end + 1 : end, text: \"\" };\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n type ArrayLiteralExpression,\n type ImportDeclaration,\n type ObjectLiteralExpression,\n type SourceFile,\n type VariableDeclaration,\n type VariableStatement\n} from \"ts-morph\";\nimport {\n ColumnBuilder,\n col,\n columnDefFromWire,\n defineTable,\n rel,\n type AnyTableDef,\n type AnyViewDef,\n type ColumnDef,\n type ColumnsShape,\n type CompiledTable,\n type DefaultRls,\n type NewTable,\n type RelationDef,\n type RelationsShape,\n type TableDescriptor,\n type TablePatch,\n type TableThunk,\n type WireColumnDef,\n type WireRelation\n} from \"@rebasepro/types\";\nimport {\n DEFAULT_SCHEMA_SPECIFIER,\n TABLE_KEY_ORDER,\n enumIdentifier,\n isSchemaDefinitionError,\n printColumn,\n printIndexModule,\n printRelation,\n printRls,\n printSchemaValue,\n printTableModule,\n tableIdentifier\n} from \"@rebasepro/common\";\n\nimport { compileSchemaDefs, isSchemaLoadError, loadBackendSchema } from \"../schema/load-schema\";\nimport { createSourceImporter } from \"../schema-edit/source-importer\";\nimport {\n applyEdits,\n deeper,\n insertListItem,\n itemText,\n listShape,\n reindent,\n removeListItem,\n removeStatement,\n replaceNode,\n type TextEdit\n} from \"../schema-edit/source-text\";\n\n/**\n * The Studio's schema editor: edits to `backend/schema/*.ts`, one\n * {@link TablePatch} at a time.\n *\n * It reads and writes the `defineTable` / `defineAuthTable` / `defineView`\n * calls the schema's index exports — their `columns` (each a `col.*` chain),\n * `relations` (`rel.*`), `rls` and table-level keys — and nothing else. Every\n * piece of text it writes comes from the one printer (`printColumn`,\n * `printRelation`, `printRls`, `printTableModule`…), and it writes by splicing\n * that text in at the position of what it replaces, so everything it does not\n * rewrite stays byte for byte: comments, hooks, `.transform()` bodies, the\n * other columns, the other rules.\n *\n * What it cannot read with confidence — a config that spreads another object,\n * a column built by a helper, rules held in a variable, a key computed at run\n * time — it calls *edited in code*: {@link TableSourceEditor.describe} reports\n * it read-only, and an edit that would write there is refused with the reason,\n * never guessed at.\n *\n * Every edit is applied to a copy of the text first and the result is\n * compiled — imported as it would be, through {@link loadBackendSchema} — and\n * an edit whose result does not compile is refused with the problems, having\n * written nothing.\n *\n * One edit at a time ({@link TableSourceEditor.run}): the source-only routes\n * and live schema editing's `/apply` share one editor per process, so an edit\n * never reads files another edit is halfway through writing.\n *\n * @group Schema\n */\nexport class TableSourceEditor {\n private settled: Promise<unknown> = Promise.resolve();\n readonly schemaDir: string;\n private readonly resolveBareFrom?: string;\n\n constructor(schemaDir: string, options: { resolveBareFrom?: string } = {}) {\n this.schemaDir = path.resolve(schemaDir);\n this.resolveBareFrom = options.resolveBareFrom;\n }\n\n /** Run `work` once every edit queued before it has finished. */\n run<T>(work: () => Promise<T>): Promise<T> {\n const result = this.settled.then(work);\n this.settled = result.then(() => undefined, () => undefined);\n return result;\n }\n\n /**\n * Apply `patches` to a copy of the schema's text and compile the result.\n * Writes nothing: the edit is refused (a {@link TableSourceEditError}) or\n * returned, with every file it changed and the schema it compiles to.\n */\n async preview(patches: readonly TablePatch[]): Promise<TableSourceEdit> {\n const workspace = Workspace.read(this.schemaDir);\n for (const [index, patch] of patches.entries()) {\n try {\n await applyPatch(workspace, patch, this);\n } catch (error) {\n throw asRefusal(error, index, patch);\n }\n }\n const files = workspace.changes();\n if (files.length === 0) {\n throw new TableSourceEditError(\"SCHEMA_EDIT_REFUSED\", \"The edit changes nothing in backend/schema.\", []);\n }\n const schema = await this.compile(workspace.texts());\n return { files, schema };\n }\n\n /** {@link preview}, then write the files — queued behind every other edit. */\n apply(patches: readonly TablePatch[]): Promise<TableSourceEdit> {\n return this.run(async () => {\n const edit = await this.preview(patches);\n await this.write(edit);\n return edit;\n });\n }\n\n /**\n * Write a previewed edit's files, refusing when one of them changed on\n * disk since the preview read it (an IDE save, another process): the edit\n * was made against the old text.\n */\n async write(edit: TableSourceEdit): Promise<void> {\n this.assertUnchanged(edit);\n for (const file of edit.files) {\n if (file.deleted) {\n await fsp.rm(file.path, { force: true });\n } else {\n await fsp.mkdir(path.dirname(file.path), { recursive: true });\n await fsp.writeFile(file.path, file.contents, \"utf8\");\n }\n }\n }\n\n /** Refuse when a file an edit rewrites is no longer what the edit read. */\n assertUnchanged(edit: TableSourceEdit): void {\n for (const file of edit.files) {\n const now = fs.existsSync(file.path) ? fs.readFileSync(file.path, \"utf8\") : undefined;\n if (now !== file.before) {\n throw new TableSourceEditError(\n \"SCHEMA_EDIT_STALE_FILE\",\n `${file.path} changed since the edit was prepared (it was saved by something else meanwhile). ` +\n \"Nothing was written: make the edit again against the file as it is now.\",\n []\n );\n }\n }\n }\n\n /**\n * Every table the schema's index exports, as the editor reads it: which\n * parts it can write, and why not where it cannot.\n */\n async describe(): Promise<TableSourceSummary[]> {\n return Workspace.read(this.schemaDir).tables().map(summarize);\n }\n\n /** The schema directory as it is on disk, compiled: the tables `backend/schema` declares now. */\n async compileCurrent(): Promise<EditedSchema> {\n return this.compile(Workspace.read(this.schemaDir).texts());\n }\n\n /** Compile the schema directory as `texts` would make it. */\n async compile(texts: ReadonlyMap<string, string>): Promise<EditedSchema> {\n const scratch = await fsp.realpath(await fsp.mkdtemp(path.join(os.tmpdir(), \"rebase-schema-edit-\")));\n try {\n for (const [file, text] of texts) {\n const target = path.join(scratch, path.relative(this.schemaDir, file));\n await fsp.mkdir(path.dirname(target), { recursive: true });\n await fsp.writeFile(target, text, \"utf8\");\n }\n const importModule = createSourceImporter({\n sources: texts,\n realDir: this.schemaDir,\n scratchDir: scratch,\n ...(this.resolveBareFrom ? { resolveBareFrom: this.resolveBareFrom } : {})\n });\n const loaded = await loadBackendSchema(scratch, { projectRoot: false, importModule });\n const compiled = compileSchemaDefs(loaded.defs, loaded.defaultRls);\n return { defs: loaded.defs, ...(loaded.defaultRls !== undefined ? { defaultRls: loaded.defaultRls } : {}), ...compiled };\n } catch (error) {\n throw compileRefusal(error, scratch, this.schemaDir);\n } finally {\n await fsp.rm(scratch, { recursive: true, force: true });\n }\n }\n}\n\n/**\n * One file an edit changed.\n *\n * @group Schema\n */\nexport interface TableSourceFile {\n /** Absolute path. */\n path: string;\n /** The new text. Empty for a deleted file. */\n contents: string;\n /** The edit deletes the file. */\n deleted?: true;\n /** The text the edit was made against; `undefined` for a file it creates. */\n before?: string;\n}\n\n/**\n * A schema as an edit leaves it: the definitions, and what they compile and\n * lower to — what a running server is refreshed with after an apply.\n *\n * @group Schema\n */\nexport interface EditedSchema {\n defs: (AnyTableDef | AnyViewDef)[];\n defaultRls?: DefaultRls;\n /**\n * The definitions compiled, as boot compiles its own: each descriptor\n * with its hooks, transforms and auth hooks — what the planner plans from\n * and what the server's registries serve after an apply.\n */\n tables: CompiledTable[];\n descriptors: TableDescriptor[];\n}\n\n/**\n * An edit, applied to a copy and compiled.\n *\n * @group Schema\n */\nexport interface TableSourceEdit {\n /** Every file the edit changes, in path order. */\n files: TableSourceFile[];\n /** What the schema compiles to with the edit. */\n schema: EditedSchema;\n}\n\n/**\n * What is wrong with an edit, or with what it would leave.\n *\n * @group Schema\n */\nexport interface TableSourceProblem {\n /** The table, by slug or name. */\n table: string;\n /** The column, relation or key, when there is one. */\n key?: string;\n message: string;\n}\n\n/**\n * Why the schema editor refused an edit:\n *\n * - `SCHEMA_EDIT_REFUSED` — the edit cannot be made as asked: the table is\n * edited in code there, the column does not exist, a slug rename.\n * - `SCHEMA_EDIT_DOES_NOT_COMPILE` — the edit can be made, and the schema it\n * leaves would not load: the problems say why.\n * - `SCHEMA_EDIT_STALE_FILE` — a file the edit rewrites changed on disk since\n * the edit was prepared (an IDE save, another process): reload it and make\n * the edit again.\n *\n * @group Schema\n */\nexport type SchemaEditRefusalCode = \"SCHEMA_EDIT_REFUSED\" | \"SCHEMA_EDIT_DOES_NOT_COMPILE\" | \"SCHEMA_EDIT_STALE_FILE\";\n\n/**\n * An edit the schema editor will not make, with its\n * {@link SchemaEditRefusalCode}. Nothing was written.\n *\n * @group Schema\n */\nexport class TableSourceEditError extends Error {\n constructor(\n readonly code: SchemaEditRefusalCode,\n message: string,\n readonly problems: readonly TableSourceProblem[]\n ) {\n super(message);\n this.name = \"TableSourceEditError\";\n }\n}\n\n/**\n * How the editor reads one table.\n *\n * @group Schema\n */\nexport interface TableSourceSummary {\n slug: string;\n name: string;\n kind: \"table\" | \"authTable\" | \"view\";\n /** The file holding it, absolute. */\n file: string;\n /** Why the table is read-only as a whole, when it is. */\n editedInCode?: string;\n /** Every column, and why one is read-only. */\n columns: { key: string; editedInCode?: string }[];\n /** Every relation, and why one is read-only. */\n relations: { name: string; editedInCode?: string }[];\n /** Why `rls` (or its rules) cannot be written, when it cannot. */\n rlsEditedInCode?: string;\n}\n\n// ── Reading the schema ──────────────────────────────────────────────────────\n\nconst MODULE_EXTENSIONS = [\".ts\", \".mts\", \".js\", \".mjs\"];\nconst INDEX_FILES = [\"index.ts\", \"index.mts\", \"index.js\", \"index.mjs\"];\nconst BUILDERS = new Set([\"defineTable\", \"defineAuthTable\", \"defineView\"]);\ntype BuilderName = \"defineTable\" | \"defineAuthTable\" | \"defineView\";\n\n/** The module files of a schema directory, as the loader lists them. */\nfunction moduleFiles(dir: string): string[] {\n const out: string[] = [];\n if (!fs.existsSync(dir)) return out;\n const walk = (current: string): void => {\n for (const entry of fs.readdirSync(current, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\" || entry.name === \"__tests__\") continue;\n const full = path.join(current, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && MODULE_EXTENSIONS.some(ext => entry.name.endsWith(ext))\n && !/\\.d\\.[mc]?ts$/.test(entry.name) && !/\\.(test|spec)\\./.test(entry.name)) {\n out.push(full);\n }\n }\n };\n walk(dir);\n return out.sort();\n}\n\n/** A table the index exports, located in its file. */\ninterface LocatedTable {\n slug: string;\n name: string;\n builder: BuilderName;\n /** Absolute path of the file declaring it. */\n file: string;\n /** The `const` it is bound to in that file. */\n variable: string;\n /** The name the index exports it under. */\n exportName: string;\n declaration: VariableDeclaration;\n /** The config object, when the editor can write it. */\n config?: ObjectLiteralExpression;\n /** Why it cannot, when it cannot. */\n editedInCode?: string;\n}\n\n/** The text of the schema directory during one edit. */\nclass Workspace {\n private readonly current = new Map<string, string>();\n private readonly original = new Map<string, string>();\n private project?: Project;\n\n private constructor(readonly dir: string) {}\n\n static read(dir: string): Workspace {\n const workspace = new Workspace(dir);\n for (const file of moduleFiles(dir)) {\n const text = fs.readFileSync(file, \"utf8\");\n workspace.current.set(file, text);\n workspace.original.set(file, text);\n }\n return workspace;\n }\n\n texts(): ReadonlyMap<string, string> {\n return this.current;\n }\n\n has(file: string): boolean {\n return this.current.has(file);\n }\n\n text(file: string): string {\n const text = this.current.get(file);\n if (text === undefined) throw new Error(`${file} is not a module of ${this.dir}.`);\n return text;\n }\n\n set(file: string, text: string): void {\n this.current.set(file, text);\n this.project = undefined;\n }\n\n edit(file: string, edits: readonly TextEdit[]): void {\n if (edits.length > 0) this.set(file, applyEdits(this.text(file), edits));\n }\n\n delete(file: string): void {\n this.current.delete(file);\n this.project = undefined;\n }\n\n /** Every file whose text differs from what was read, in path order. */\n changes(): TableSourceFile[] {\n const out: TableSourceFile[] = [];\n for (const [file, text] of this.current) {\n const before = this.original.get(file);\n if (before !== text) out.push({ path: file, contents: text, ...(before !== undefined ? { before } : {}) });\n }\n for (const [file, before] of this.original) {\n if (!this.current.has(file)) out.push({ path: file, contents: \"\", deleted: true, before });\n }\n return out.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n /** The current text parsed; rebuilt after every change, so nodes are never stale. */\n source(file: string): SourceFile {\n const project = this.parsed();\n const source = project.getSourceFile(file);\n if (!source) throw new Error(`${file} is not a module of ${this.dir}.`);\n return source;\n }\n\n private parsed(): Project {\n if (this.project) return this.project;\n const project = new Project({\n useInMemoryFileSystem: true,\n compilerOptions: { allowJs: true, noLib: true }\n });\n for (const [file, text] of this.current) project.createSourceFile(file, text, { overwrite: true });\n this.project = project;\n return project;\n }\n\n indexFile(): string | undefined {\n return INDEX_FILES.map(name => path.join(this.dir, name)).find(file => this.current.has(file));\n }\n\n /** Every table the index exports, each once. */\n tables(): LocatedTable[] {\n const indexPath = this.indexFile();\n if (!indexPath) return [];\n const index = this.source(indexPath);\n const out: LocatedTable[] = [];\n const seen = new Set<VariableDeclaration>();\n for (const [exportName, declarations] of index.getExportedDeclarations()) {\n for (const declaration of declarations) {\n if (!Node.isVariableDeclaration(declaration) || seen.has(declaration)) continue;\n const located = locate(declaration, exportName);\n if (located) {\n seen.add(declaration);\n out.push(located);\n }\n }\n }\n return out;\n }\n\n table(slug: string): LocatedTable {\n const found = this.tables().find(table => table.slug === slug);\n if (!found) {\n throw refusal(\n `No table with the slug \"${slug}\" is exported from ${path.join(path.basename(this.dir), \"index\")} as a ` +\n \"`defineTable` / `defineAuthTable` / `defineView` call the editor can read. If it is defined through a \" +\n \"helper or a variable, it is edited in code.\",\n slug\n );\n }\n return found;\n }\n\n /** The table at `slug`, with a config the editor may write. */\n writable(slug: string): LocatedTable & { config: ObjectLiteralExpression } {\n const table = this.table(slug);\n if (!table.config) throw refusal(`Table \"${slug}\" is edited in code: ${table.editedInCode}`, slug);\n return { ...table, config: table.config };\n }\n}\n\nexport function unwrapExpression(node: Node | undefined): Node | undefined {\n let current = node;\n while (current && (Node.isParenthesizedExpression(current) || Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current) || Node.isNonNullExpression(current) || Node.isTypeAssertion(current))) {\n current = current.getExpression();\n }\n return current;\n}\n\nexport function literalString(node: Node | undefined): string | undefined {\n if (node && (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node))) return node.getLiteralValue();\n return undefined;\n}\n\n/** The key a member of an object literal is written under, when it is written literally. */\nexport function memberName(member: Node): string | undefined {\n if (Node.isPropertyAssignment(member) || Node.isShorthandPropertyAssignment(member) || Node.isMethodDeclaration(member)) {\n const nameNode = member.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText();\n if (Node.isStringLiteral(nameNode) || Node.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();\n if (Node.isNumericLiteral(nameNode)) return nameNode.getText();\n }\n return undefined;\n}\n\n/** Why an object literal's members cannot be read one by one, when they cannot. */\nexport function opaqueMembers(object: ObjectLiteralExpression, what: string): string | undefined {\n for (const member of object.getProperties()) {\n if (Node.isSpreadAssignment(member)) return `${what} spreads \\`${member.getExpression().getText()}\\`, so any key may come from code.`;\n if (memberName(member) === undefined) return `${what} has a key computed at run time (\\`${member.getText().split(\":\")[0].trim()}\\`).`;\n }\n return undefined;\n}\n\n/** A member of an object literal: its assignment, or why it cannot be written. */\nexport type Member =\n | { kind: \"absent\" }\n | { kind: \"written\"; node: Node; value: Node; index: number }\n | { kind: \"code\"; reason: string };\n\nexport function member(object: ObjectLiteralExpression, key: string, what: string): Member {\n const members = object.getProperties();\n const opaque = opaqueMembers(object, what);\n for (const [index, each] of members.entries()) {\n if (memberName(each) !== key) continue;\n if (Node.isPropertyAssignment(each)) {\n const value = each.getInitializer();\n if (value) return { kind: \"written\", node: each, value, index };\n }\n return { kind: \"code\", reason: `\\`${key}\\` of ${what} is ${Node.isShorthandPropertyAssignment(each) ? \"a variable\" : \"a method\"}.` };\n }\n if (opaque) return { kind: \"code\", reason: opaque };\n return { kind: \"absent\" };\n}\n\nfunction locate(declaration: VariableDeclaration, exportName: string): LocatedTable | undefined {\n const call = unwrapExpression(declaration.getInitializer());\n if (!call || !Node.isCallExpression(call)) return undefined;\n const callee = call.getExpression().getText().split(\".\").pop() ?? \"\";\n if (!BUILDERS.has(callee)) return undefined;\n const builder: BuilderName = callee === \"defineAuthTable\" ? \"defineAuthTable\" : callee === \"defineView\" ? \"defineView\" : \"defineTable\";\n const [nameArg, configArg] = call.getArguments();\n const name = literalString(nameArg);\n if (name === undefined) return undefined;\n const base = {\n name,\n builder,\n file: declaration.getSourceFile().getFilePath(),\n variable: declaration.getName(),\n exportName,\n declaration\n };\n const config = unwrapExpression(configArg);\n if (!config || !Node.isObjectLiteralExpression(config)) {\n return { ...base, slug: name, editedInCode: \"its config is not an object literal written in the call.\" };\n }\n const opaque = opaqueMembers(config, \"its config\");\n const slugMember = member(config, \"slug\", \"its config\");\n if (slugMember.kind === \"written\") {\n const slug = literalString(slugMember.value);\n if (slug === undefined) return { ...base, slug: name, editedInCode: \"its `slug` is not a string literal.\" };\n return opaque ? { ...base, slug, editedInCode: opaque } : { ...base, slug, config };\n }\n return opaque ? { ...base, slug: name, editedInCode: opaque } : { ...base, slug: name, config };\n}\n\n/** Whether a node is a builder chain rooted at `root`: `col.text().notNull()`, `rel.belongsTo(…)`. */\nfunction isChainOf(node: Node, root: string): boolean {\n let current: Node | undefined = unwrapExpression(node);\n let calls = 0;\n while (current) {\n if (Node.isCallExpression(current)) {\n calls++;\n current = current.getExpression();\n } else if (Node.isPropertyAccessExpression(current)) {\n current = current.getExpression();\n } else {\n return calls > 0 && Node.isIdentifier(current) && current.getText() === root;\n }\n }\n return false;\n}\n\n/** The links of a chain, outermost last: `col.text().notNull()` → `[text(), notNull()]`. */\nfunction chainLinks(node: Node): { name: string; args: Node[] }[] {\n const links: { name: string; args: Node[] }[] = [];\n let current: Node | undefined = unwrapExpression(node);\n while (current && Node.isCallExpression(current)) {\n const callee = current.getExpression();\n if (!Node.isPropertyAccessExpression(callee)) break;\n links.unshift({ name: callee.getName(), args: current.getArguments() });\n current = callee.getExpression();\n }\n return links;\n}\n\n/** One `const <identifier> = pgEnum(\"<name>\", [...])` of a schema file. */\ninterface EnumBinding {\n identifier: string;\n enumName: string;\n values: string[];\n}\n\n/**\n * The `pgEnum` declarations of a file, by the identifier they are bound to: a\n * column chain may be rooted at one of them (`status: postStatus().notNull()`)\n * as well as at `col`. Only declarations the editor can read — a literal name\n * and a literal list of labels — count; anything else leaves the columns that\n * use it edited in code.\n */\nfunction enumBindings(source: SourceFile): Map<string, EnumBinding> {\n const local = builderImport(source)?.local.get(\"pgEnum\") ?? \"pgEnum\";\n const out = new Map<string, EnumBinding>();\n for (const statement of source.getVariableStatements()) {\n for (const declaration of statement.getDeclarations()) {\n const call = unwrapExpression(declaration.getInitializer());\n if (!call || !Node.isCallExpression(call) || call.getExpression().getText() !== local) continue;\n const [nameArg, valuesArg] = call.getArguments();\n const enumName = literalString(nameArg);\n const list = unwrapExpression(valuesArg);\n if (enumName === undefined || !list || !Node.isArrayLiteralExpression(list)) continue;\n const values = list.getElements().map(element => literalString(element));\n if (values.some(value => value === undefined)) continue;\n out.set(declaration.getName(), { identifier: declaration.getName(), enumName, values: values.filter((value): value is string => value !== undefined) });\n }\n }\n return out;\n}\n\n/** Whether a node is a column chain: rooted at `col`, or at a `pgEnum` binding of its file. */\nfunction isColumnChain(node: Node): boolean {\n if (isChainOf(node, \"col\")) return true;\n let root: Node | undefined = unwrapExpression(node);\n while (root && (Node.isCallExpression(root) || Node.isPropertyAccessExpression(root))) root = root.getExpression();\n return root !== undefined && Node.isIdentifier(root) && enumBindings(node.getSourceFile()).has(root.getText()) && isChainOf(node, root.getText());\n}\n\n/** Why a column's value cannot be rewritten, when it cannot. */\nfunction columnCode(value: Node, key: string): string | undefined {\n if (!isColumnChain(value)) {\n return `column \"${key}\" is not a \\`col.*\\` chain or a \\`pgEnum\\` column (it is built by \\`${value.getText().slice(0, 40)}\\`).`;\n }\n return undefined;\n}\n\n/** The source of the `.transform(…)` written on a column's own chain, and whether one hides deeper in it. */\nfunction columnTransforms(value: Node): { own?: string; nested: boolean } {\n const links = chainLinks(value);\n const ownLink = links.find(link => link.name === \"transform\");\n const own = ownLink?.args[0]?.getText();\n let total = 0;\n value.forEachDescendant(node => {\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n if (Node.isPropertyAccessExpression(callee) && callee.getName() === \"transform\") total++;\n }\n });\n return { ...(own !== undefined ? { own } : {}), nested: total > (ownLink ? 1 : 0) };\n}\n\nfunction summarize(table: LocatedTable): TableSourceSummary {\n const kind = table.builder === \"defineAuthTable\" ? \"authTable\" : table.builder === \"defineView\" ? \"view\" : \"table\";\n const summary: TableSourceSummary = { slug: table.slug, name: table.name, kind, file: table.file, columns: [], relations: [] };\n if (!table.config) return { ...summary, editedInCode: table.editedInCode };\n const listOf = (key: string, what: string, rootName: string) => {\n const found = member(table.config!, key, \"the config\");\n if (found.kind !== \"written\") return { entries: [], reason: found.kind === \"code\" ? found.reason : undefined };\n const object = unwrapExpression(found.value);\n if (!object || !Node.isObjectLiteralExpression(object)) return { entries: [], reason: `\\`${key}\\` is not an object literal.` };\n const opaque = opaqueMembers(object, `\\`${key}\\``);\n const entries = object.getProperties().flatMap(each => {\n const entryKey = memberName(each);\n if (entryKey === undefined) return [];\n const value = Node.isPropertyAssignment(each) ? each.getInitializer() : undefined;\n const reason = opaque\n ?? (!value ? `${what} \"${entryKey}\" is a variable.` : rootName === \"col\" ? columnCode(value, entryKey)\n : isChainOf(value, \"rel\") ? undefined : `${what} \"${entryKey}\" is not a \\`rel.*\\` call.`);\n return [{ key: entryKey, ...(reason ? { editedInCode: reason } : {}) }];\n });\n return { entries, reason: opaque };\n };\n const columns = listOf(\"columns\", \"column\", \"col\");\n const relations = listOf(\"relations\", \"relation\", \"rel\");\n const rls = member(table.config, \"rls\", \"the config\");\n let rlsEditedInCode: string | undefined;\n if (rls.kind === \"code\") rlsEditedInCode = rls.reason;\n if (rls.kind === \"written\") {\n const value = unwrapExpression(rls.value);\n if (!value || !(Node.isStringLiteral(value) || Node.isArrayLiteralExpression(value))) rlsEditedInCode = \"`rls` is not written in the call.\";\n else if (Node.isArrayLiteralExpression(value) && value.getElements().some(element => Node.isSpreadElement(element))) {\n rlsEditedInCode = \"`rls` spreads another list of rules.\";\n }\n }\n return {\n ...summary,\n columns: columns.entries.map(({ key, editedInCode }) => ({ key, ...(editedInCode ? { editedInCode } : {}) })),\n relations: relations.entries.map(({ key, editedInCode }) => ({ name: key, ...(editedInCode ? { editedInCode } : {}) })),\n ...(rlsEditedInCode ? { rlsEditedInCode } : {})\n };\n}\n\n// ── Writing ─────────────────────────────────────────────────────────────────\n\n/** An edit refused, naming the table and, where there is one, the key. */\nfunction refusal(message: string, table: string, key?: string): TableSourceEditError {\n return new TableSourceEditError(\"SCHEMA_EDIT_REFUSED\", message, [{ table, ...(key !== undefined ? { key } : {}), message }]);\n}\n\nfunction asRefusal(error: unknown, index: number, patch: TablePatch): TableSourceEditError {\n if (error instanceof TableSourceEditError) return error;\n const table = patch.op === \"createTable\" ? patch.table.name : patch.op === \"adoptTable\" ? patch.table.slug : patch.table;\n const message = error instanceof Error ? error.message : String(error);\n return refusal(`Edit ${index} (${patch.op} on \"${table}\"): ${message}`, table);\n}\n\nfunction compileRefusal(error: unknown, scratch: string, dir: string): TableSourceEditError {\n if (error instanceof TableSourceEditError) return error;\n const real = (text: string): string => text.split(scratch).join(dir);\n if (isSchemaDefinitionError(error)) {\n return new TableSourceEditError(\n \"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n `The edit was not written: ${real(error.message)}`,\n error.problems.map(problem => ({ table: problem.table, ...(problem.key !== undefined ? { key: problem.key } : {}), message: real(problem.message) }))\n );\n }\n const message = error instanceof Error ? real(error.message) : String(error);\n return new TableSourceEditError(\n \"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n isSchemaLoadError(error) ? `The edit was not written: ${message}` : `The edit was not written: the schema it leaves does not load: ${message}`,\n [{ table: \"\", message }]\n );\n}\n\nexport const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nexport const printKey = (key: string): string => (IDENTIFIER.test(key) ? key : JSON.stringify(key));\n\n/** The builder import of a file: the import declaration naming `defineTable` & co. */\nfunction builderImport(source: SourceFile): { declaration: ImportDeclaration; local: Map<string, string> } | undefined {\n for (const declaration of source.getImportDeclarations()) {\n const named = declaration.getNamedImports();\n const local = new Map(named.map(element => [element.getName(), element.getAliasNode()?.getText() ?? element.getName()]));\n if ([...BUILDERS, \"col\", \"rel\"].some(name => local.has(name)) && !declaration.isTypeOnly()) return { declaration, local };\n }\n return undefined;\n}\n\n/** Add the builders `printed` text uses (`col`, `rel`, `json`, `sql`, `pgEnum`) to the file's builder import. */\nfunction ensureBuilders(workspace: Workspace, file: string, needed: readonly (\"col\" | \"rel\" | \"json\" | \"sql\" | \"pgEnum\")[]): void {\n const source = workspace.source(file);\n const found = builderImport(source);\n if (!found) {\n throw refusal(`${file} has no import of the schema builders (\\`defineTable\\`, \\`col\\`…) to add ${needed.join(\", \")} to.`, path.basename(file));\n }\n const missing: string[] = [];\n for (const name of needed) {\n const local = found.local.get(name);\n if (local === undefined) missing.push(name);\n else if (local !== name) {\n throw refusal(`${file} imports \\`${name}\\` as \\`${local}\\`; the editor writes \\`${name}.…\\`. Import it under its own name.`, path.basename(file));\n }\n }\n if (missing.length === 0) return;\n const named = found.declaration.getNamedImports();\n const last = named[named.length - 1];\n workspace.edit(file, [{ start: last.getEnd(), end: last.getEnd(), text: missing.map(name => `, ${name}`).join(\"\") }]);\n}\n\n/** The module specifier `from` imports `to` by: `./users`, `../shared/users`. */\nfunction relativeSpecifier(from: string, to: string): string {\n const relative = path.relative(path.dirname(from), to).split(path.sep).join(\"/\").replace(/\\.[mc]?[jt]s$/, \"\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\n/** How `file` refers to `target`'s table, and the import it needs for that. */\nfunction bindingFor(workspace: Workspace, file: string, target: LocatedTable): string {\n if (target.file === file) return target.variable;\n const source = workspace.source(file);\n for (const declaration of source.getImportDeclarations()) {\n if (declaration.getModuleSpecifierSourceFile()?.getFilePath() !== target.file) continue;\n const element = declaration.getNamedImports().find(each => each.getName() === target.variable);\n if (element) return element.getAliasNode()?.getText() ?? element.getName();\n const named = declaration.getNamedImports();\n if (named.length > 0 && !declaration.isTypeOnly()) {\n const last = named[named.length - 1];\n workspace.edit(file, [{ start: last.getEnd(), end: last.getEnd(), text: `, ${target.variable}` }]);\n return target.variable;\n }\n }\n const imports = source.getImportDeclarations();\n const line = `import { ${target.variable} } from ${JSON.stringify(relativeSpecifier(file, target.file))};`;\n const at = imports.length > 0 ? imports[imports.length - 1].getEnd() : 0;\n workspace.edit(file, [{ start: at, end: at, text: imports.length > 0 ? `\\n${line}` : `${line}\\n` }]);\n return target.variable;\n}\n\n/** Drop the import of `identifier` from a file when nothing in it refers to it any more. */\nfunction dropUnusedImport(workspace: Workspace, file: string, identifier: string): void {\n const source = workspace.source(file);\n const used = source.getDescendants().some(node =>\n Node.isIdentifier(node) && node.getText() === identifier && !node.getFirstAncestor(Node.isImportDeclaration));\n if (used) return;\n for (const declaration of source.getImportDeclarations()) {\n const named = declaration.getNamedImports();\n const index = named.findIndex(element => (element.getAliasNode()?.getText() ?? element.getName()) === identifier);\n if (index === -1) continue;\n if (named.length === 1 && !declaration.getDefaultImport() && !declaration.getNamespaceImport()) {\n const statements = source.getStatements();\n const position = statements.indexOf(declaration);\n workspace.edit(file, [removeStatement(source.getFullText(), declaration, position > 0 ? statements[position - 1].getEnd() : 0)]);\n } else {\n const element = named[index];\n const edit: TextEdit = index < named.length - 1\n ? { start: element.getStart(), end: named[index + 1].getStart(), text: \"\" }\n : { start: named[index - 1]?.getEnd() ?? element.getStart(), end: element.getEnd(), text: \"\" };\n workspace.edit(file, [edit]);\n }\n return;\n }\n}\n\n/** The identifier a relation's thunk returns: `() => users` → `users`. */\nfunction thunkTarget(value: Node): string | undefined {\n const call = unwrapExpression(value);\n if (!call || !Node.isCallExpression(call)) return undefined;\n const thunk = call.getArguments()[0];\n if (!thunk || !Node.isArrowFunction(thunk)) return undefined;\n const body = unwrapExpression(thunk.getBody());\n return body && Node.isIdentifier(body) ? body.getText() : undefined;\n}\n\n/** A stand-in the printer reads a relation's target from: its name and slug, nothing else. */\nfunction targetStandIn(name: string, slug: string): AnyTableDef {\n return defineTable(name, { slug, columns: { id: col.uuid().primaryKey() }, rls: \"admin-only\" });\n}\n\n/** A wire relation as the `rel.*` result it describes, pointing at `target`. */\nfunction relationFromWire(relation: WireRelation, target: TableThunk): RelationDef {\n switch (relation.kind) {\n case \"belongsTo\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.belongsTo(target, options);\n }\n case \"hasOne\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.hasOne(target, options);\n }\n case \"hasMany\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.hasMany(target, options);\n }\n case \"manyToMany\": {\n const { kind: _kind, target: _target, pivot, ...options } = relation;\n void _kind; void _target;\n const columns = pivot !== undefined ? columnsFromWire(pivot) : undefined;\n return rel.manyToMany(target, { ...options, ...(columns ? { pivot: columns } : {}) });\n }\n case \"via\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.via(target, options);\n }\n }\n}\n\nfunction columnsFromWire(columns: Record<string, WireColumnDef>): ColumnsShape {\n const out: ColumnsShape = {};\n for (const [key, column] of Object.entries(columns)) out[key] = new ColumnBuilder(columnDefFromWire(column));\n return out;\n}\n\nconst usesJson = (def: ColumnDef): boolean => def.json !== undefined || (def.element !== undefined && usesJson(def.element));\n\nconst TEMPORAL_KINDS = new Set([\"timestamptz\", \"date\", \"time\"]);\n\n/** Whether the printed chain uses the `sql` tag: a SQL default other than `.defaultNow()`, or a generated expression. */\nconst usesSql = (def: ColumnDef): boolean =>\n def.generatedAs !== undefined ||\n (def.default?.kind === \"sql\" && !(def.default.expression === \"now()\" && TEMPORAL_KINDS.has(def.type.kind))) ||\n (def.element !== undefined && usesSql(def.element));\n\n/** The builders a printed column needs imported. */\nconst buildersOf = (def: ColumnDef): (\"col\" | \"json\" | \"sql\")[] =>\n [\"col\", ...(usesJson(def) ? [\"json\" as const] : []), ...(usesSql(def) ? [\"sql\" as const] : [])];\n\n/**\n * How a printed column names an enum type with a stated name: by the file's\n * `pgEnum` binding for it, declared above the table when the file has none.\n * Returns the binder for `printColumn` and the step that writes the\n * declarations it asked for, run after the column is spliced in.\n */\nfunction enumBinder(workspace: Workspace, slug: string): { bind: (enumName: string, values: readonly string[]) => string; declare: () => void } {\n const table = workspace.writable(slug);\n const source = workspace.source(table.file);\n const known = [...enumBindings(source).values()];\n const added: EnumBinding[] = [];\n const bind = (enumName: string, values: readonly string[]): string => {\n const existing = [...known, ...added].find(binding => binding.enumName === enumName);\n if (existing) {\n if (existing.values.join(\"\\u0000\") !== values.join(\"\\u0000\")) {\n throw refusal(\n `${path.basename(table.file)} declares the enum type \"${enumName}\" with the labels ${JSON.stringify(existing.values)}; ` +\n `the column lists ${JSON.stringify(values)}. Change the \\`pgEnum\\` declaration in code.`,\n slug\n );\n }\n return existing.identifier;\n }\n let identifier = enumIdentifier(enumName);\n const taken = (name: string): boolean => source.getVariableDeclaration(name) !== undefined ||\n source.getImportDeclarations().some(each => each.getNamedImports().some(element => (element.getAliasNode()?.getText() ?? element.getName()) === name)) ||\n added.some(binding => binding.identifier === name);\n while (taken(identifier)) identifier = `${identifier}Type`;\n added.push({ identifier, enumName, values: [...values] });\n return identifier;\n };\n const declare = (): void => {\n if (added.length === 0) return;\n const statement = workspace.writable(slug).declaration.getVariableStatement();\n const at = statement ? statement.getStart(true) : 0;\n const lines = added.map(binding => `const ${binding.identifier} = pgEnum(${JSON.stringify(binding.enumName)}, [${binding.values.map(value => JSON.stringify(value)).join(\", \")}]);`);\n workspace.edit(table.file, [{ start: at, end: at, text: `${lines.join(\"\\n\")}\\n\\n` }]);\n ensureBuilders(workspace, table.file, [\"pgEnum\"]);\n };\n return { bind, declare };\n}\n\n/** `key: <chain>`, printed by `printColumn`. */\nfunction printedColumn(\n key: string,\n column: WireColumnDef,\n transform: string | undefined,\n enumIdentifierOf: (enumName: string, values: readonly string[]) => string\n): { text: string; def: ColumnDef } {\n const def = columnDefFromWire(column);\n return { text: `${printKey(key)}: ${printColumn(def, { key, enumIdentifier: enumIdentifierOf, ...(transform !== undefined ? { transform } : {}) })}`, def };\n}\n\n/** The `columns` or `relations` object of a table, writable, or a refusal. */\nfunction mapOf(table: LocatedTable & { config: ObjectLiteralExpression }, key: \"columns\" | \"relations\"): ObjectLiteralExpression | undefined {\n const found = member(table.config, key, `table \"${table.slug}\"`);\n if (found.kind === \"absent\") return undefined;\n if (found.kind === \"code\") throw refusal(`Table \"${table.slug}\" is edited in code there: ${found.reason}`, table.slug, key);\n const object = unwrapExpression(found.value);\n if (!object || !Node.isObjectLiteralExpression(object)) {\n throw refusal(`The \\`${key}\\` of table \"${table.slug}\" is edited in code: it is not an object literal.`, table.slug, key);\n }\n const opaque = opaqueMembers(object, `the \\`${key}\\` of table \"${table.slug}\"`);\n if (opaque) throw refusal(`Table \"${table.slug}\" is edited in code there: ${opaque}`, table.slug, key);\n return object;\n}\n\n/** One entry of `columns` / `relations`, or a refusal naming what is missing. */\nfunction entryOf(object: ObjectLiteralExpression, key: string, table: string, what: \"column\" | \"relation\"): { node: Node; value: Node; index: number } {\n const found = member(object, key, `${what}s`);\n if (found.kind === \"written\") return found;\n if (found.kind === \"code\") throw refusal(`The ${what} \"${key}\" of table \"${table}\" is edited in code: ${found.reason}`, table, key);\n throw refusal(`Table \"${table}\" has no ${what} \"${key}\".`, table, key);\n}\n\n/** Insert a `key: value` member into a table's config at its place in the canonical key order. */\nfunction insertConfigMember(workspace: Workspace, table: LocatedTable & { config: ObjectLiteralExpression }, key: string, printed: string): void {\n const order: readonly string[] = TABLE_KEY_ORDER;\n const rank = order.indexOf(key);\n const members = table.config.getProperties();\n let index = members.findIndex(each => {\n const name = memberName(each);\n return name !== undefined && order.indexOf(name) > rank;\n });\n if (index === -1) index = members.length;\n const text = workspace.text(table.file);\n workspace.edit(table.file, insertListItem(text, listShape(table.config, members), index, `${printKey(key)}: ${printed}`, \"lines\"));\n}\n\nfunction removeMember(workspace: Workspace, file: string, object: ObjectLiteralExpression, index: number): void {\n workspace.edit(file, removeListItem(workspace.text(file), listShape(object, object.getProperties()), index));\n}\n\n/** Whether a node is plain data — what an option's value may be overwritten from. */\nexport function isData(node: Node): boolean {\n const value = unwrapExpression(node);\n if (!value) return false;\n if (Node.isStringLiteral(value) || Node.isNumericLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value) ||\n Node.isTrueLiteral(value) || Node.isFalseLiteral(value) || Node.isNullLiteral(value)) return true;\n if (Node.isPrefixUnaryExpression(value)) return Node.isNumericLiteral(value.getOperand());\n if (Node.isArrayLiteralExpression(value)) return value.getElements().every(isData);\n if (Node.isObjectLiteralExpression(value)) {\n return value.getProperties().every(each => Node.isPropertyAssignment(each) && memberName(each) !== undefined && isData(each.getInitializerOrThrow()));\n }\n return false;\n}\n\nasync function applyPatch(workspace: Workspace, patch: TablePatch, editor: TableSourceEditor): Promise<void> {\n switch (patch.op) {\n case \"createTable\":\n return createTable(workspace, patch.table);\n case \"adoptTable\":\n return adoptTable(workspace, patch.table);\n case \"deleteTable\":\n return deleteTable(workspace, patch.table, editor);\n case \"addColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no \\`columns\\` object to add to.`, patch.table, patch.key);\n if (member(columns, patch.key, \"columns\").kind !== \"absent\") {\n throw refusal(`Table \"${patch.table}\" already has a column \"${patch.key}\". Change it instead.`, patch.table, patch.key);\n }\n const members = columns.getProperties();\n const index = patch.before !== undefined ? entryOf(columns, patch.before, patch.table, \"column\").index : members.length;\n const enums = enumBinder(workspace, patch.table);\n const { text, def } = printedColumn(patch.key, patch.column, undefined, enums.bind);\n workspace.edit(table.file, insertListItem(workspace.text(table.file), listShape(columns, members), index, text, \"lines\"));\n enums.declare();\n ensureBuilders(workspace, table.file, buildersOf(def));\n return;\n }\n case \"changeColumn\":\n case \"renameColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no column \"${patch.key}\".`, patch.table, patch.key);\n const entry = entryOf(columns, patch.key, patch.table, \"column\");\n const code = columnCode(entry.value, patch.key);\n if (code) throw refusal(`The column \"${patch.key}\" of table \"${patch.table}\" is edited in code: ${code}`, patch.table, patch.key);\n const transforms = columnTransforms(entry.value);\n if (transforms.nested) {\n throw refusal(\n `The column \"${patch.key}\" of table \"${patch.table}\" has field-level transforms inside its JSON shape or items, ` +\n \"which the editor cannot carry over: edit it in code.\",\n patch.table,\n patch.key\n );\n }\n const key = patch.op === \"renameColumn\" ? patch.to : patch.key;\n if (patch.op === \"renameColumn\" && patch.to !== patch.key && member(columns, patch.to, \"columns\").kind !== \"absent\") {\n throw refusal(`Table \"${patch.table}\" already has a column \"${patch.to}\".`, patch.table, patch.to);\n }\n const enums = enumBinder(workspace, patch.table);\n const { text, def } = printedColumn(key, patch.column, transforms.own, enums.bind);\n const source = workspace.text(table.file);\n workspace.edit(table.file, [replaceNode(source, entry.node, text)]);\n enums.declare();\n ensureBuilders(workspace, table.file, buildersOf(def));\n return;\n }\n case \"removeColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no column \"${patch.key}\".`, patch.table, patch.key);\n const entry = entryOf(columns, patch.key, patch.table, \"column\");\n const code = columnCode(entry.value, patch.key);\n if (code) throw refusal(`The column \"${patch.key}\" of table \"${patch.table}\" is edited in code: ${code}`, patch.table, patch.key);\n removeMember(workspace, table.file, columns, entry.index);\n return;\n }\n case \"moveColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no column \"${patch.key}\".`, patch.table, patch.key);\n const entry = entryOf(columns, patch.key, patch.table, \"column\");\n if (patch.before === patch.key) return;\n if (patch.before !== undefined) entryOf(columns, patch.before, patch.table, \"column\");\n const moved = itemText(workspace.text(table.file), listShape(columns, columns.getProperties()), entry.index);\n removeMember(workspace, table.file, columns, entry.index);\n const again = mapOf(workspace.writable(patch.table), \"columns\");\n if (!again) return;\n const members = again.getProperties();\n const index = patch.before !== undefined ? entryOf(again, patch.before, patch.table, \"column\").index : members.length;\n workspace.edit(table.file, insertListItem(workspace.text(table.file), listShape(again, members), index, moved, \"lines\"));\n return;\n }\n case \"addRelation\":\n case \"changeRelation\":\n return writeRelation(workspace, patch.table, patch.name, patch.relation, patch.op === \"changeRelation\");\n case \"removeRelation\": {\n const table = workspace.writable(patch.table);\n const relations = mapOf(table, \"relations\");\n if (!relations) throw refusal(`Table \"${patch.table}\" has no relation \"${patch.name}\".`, patch.table, patch.name);\n const entry = entryOf(relations, patch.name, patch.table, \"relation\");\n if (!isChainOf(entry.value, \"rel\")) {\n throw refusal(`The relation \"${patch.name}\" of table \"${patch.table}\" is edited in code: it is not a \\`rel.*\\` call.`, patch.table, patch.name);\n }\n const previous = thunkTarget(entry.value);\n removeMember(workspace, table.file, relations, entry.index);\n if (previous) dropUnusedImport(workspace, table.file, previous);\n return;\n }\n case \"setRls\": {\n const table = workspace.writable(patch.table);\n if (table.builder === \"defineView\") throw refusal(`\"${patch.table}\" is a view: it has no \\`rls\\` of its own.`, patch.table, \"rls\");\n const found = member(table.config, \"rls\", `table \"${patch.table}\"`);\n const printed = printRls(patch.rls);\n if (found.kind === \"absent\") {\n insertConfigMember(workspace, table, \"rls\", printed);\n return;\n }\n if (found.kind === \"code\") throw refusal(`The \\`rls\\` of table \"${patch.table}\" is edited in code: ${found.reason}`, patch.table, \"rls\");\n const source = workspace.text(table.file);\n workspace.edit(table.file, [replaceNode(source, found.value, printed)]);\n return;\n }\n case \"addRule\":\n case \"replaceRule\":\n case \"removeRule\":\n return writeRule(workspace, patch);\n case \"setOption\": {\n const table = workspace.writable(patch.table);\n const found = member(table.config, patch.option, `table \"${patch.table}\"`);\n if (found.kind === \"code\") throw refusal(`\\`${patch.option}\\` of table \"${patch.table}\" is edited in code: ${found.reason}`, patch.table, patch.option);\n if (found.kind === \"written\" && !isData(found.value)) {\n throw refusal(\n `\\`${patch.option}\\` of table \"${patch.table}\" is edited in code: it is \\`${found.value.getText().slice(0, 40)}\\`, not a literal.`,\n patch.table,\n patch.option\n );\n }\n if (patch.value === null) {\n if (found.kind === \"written\") removeMember(workspace, table.file, table.config, found.index);\n return;\n }\n const printed = printSchemaValue(patch.value, `${patch.table}.${patch.option}`);\n if (found.kind === \"absent\") insertConfigMember(workspace, table, patch.option, printed);\n else workspace.edit(table.file, [replaceNode(workspace.text(table.file), found.value, printed)]);\n return;\n }\n }\n}\n\nfunction writeRelation(workspace: Workspace, slug: string, name: string, relation: WireRelation, change: boolean): void {\n const target = workspace.tables().find(table => table.slug === relation.target);\n if (!target) throw refusal(`The relation \"${name}\" of table \"${slug}\" targets \"${relation.target}\", which is not a table in backend/schema.`, slug, name);\n let table = workspace.writable(slug);\n const identifier = bindingFor(workspace, table.file, target);\n table = workspace.writable(slug);\n const def = relationFromWire(relation, () => targetStandIn(target.name, target.slug));\n const printed = printRelation(name, def, { resolveTarget: () => ({ identifier }) });\n const relations = mapOf(table, \"relations\");\n if (!relations) {\n if (change) throw refusal(`Table \"${slug}\" has no relation \"${name}\".`, slug, name);\n insertConfigMember(workspace, table, \"relations\", `{\\n${deeper(\"\")}${printKey(name)}: ${reindent(printed, deeper(\"\"))}\\n}`);\n } else if (change) {\n const entry = entryOf(relations, name, slug, \"relation\");\n if (!isChainOf(entry.value, \"rel\")) {\n throw refusal(`The relation \"${name}\" of table \"${slug}\" is edited in code: it is not a \\`rel.*\\` call.`, slug, name);\n }\n const previous = thunkTarget(entry.value);\n workspace.edit(table.file, [replaceNode(workspace.text(table.file), entry.node, `${printKey(name)}: ${printed}`)]);\n if (previous && previous !== identifier) dropUnusedImport(workspace, table.file, previous);\n } else {\n if (member(relations, name, \"relations\").kind !== \"absent\") {\n throw refusal(`Table \"${slug}\" already has a relation \"${name}\". Change it instead.`, slug, name);\n }\n const members = relations.getProperties();\n workspace.edit(table.file, insertListItem(workspace.text(table.file), listShape(relations, members), members.length, `${printKey(name)}: ${printed}`, \"lines\"));\n }\n const pivot = relation.kind === \"manyToMany\" && relation.pivot !== undefined ? Object.values(relation.pivot).map(columnDefFromWire) : [];\n ensureBuilders(workspace, table.file, pivot.length > 0 ? (pivot.some(usesJson) ? [\"rel\", \"col\", \"json\"] : [\"rel\", \"col\"]) : [\"rel\"]);\n}\n\n/** The `rls` rule list of a table, writable, or a refusal. */\nfunction rulesOf(table: LocatedTable & { config: ObjectLiteralExpression }): ArrayLiteralExpression {\n const found = member(table.config, \"rls\", `table \"${table.slug}\"`);\n if (found.kind === \"code\") throw refusal(`The \\`rls\\` of table \"${table.slug}\" is edited in code: ${found.reason}`, table.slug, \"rls\");\n const value = found.kind === \"written\" ? unwrapExpression(found.value) : undefined;\n if (!value || !Node.isArrayLiteralExpression(value)) {\n throw refusal(\n `The \\`rls\\` of table \"${table.slug}\" is ${value ? `\\`${value.getText().slice(0, 40)}\\`` : \"absent\"}, not a list of rules. ` +\n \"Set the rules with `setRls` first.\",\n table.slug,\n \"rls\"\n );\n }\n if (value.getElements().some(element => Node.isSpreadElement(element))) {\n throw refusal(`The \\`rls\\` of table \"${table.slug}\" is edited in code: it spreads another list of rules.`, table.slug, \"rls\");\n }\n return value;\n}\n\nfunction writeRule(workspace: Workspace, patch: Extract<TablePatch, { op: \"addRule\" | \"replaceRule\" | \"removeRule\" }>): void {\n const table = workspace.writable(patch.table);\n const rules = rulesOf(table);\n const elements = rules.getElements();\n const list = listShape(rules, elements);\n const source = workspace.text(table.file);\n const index = patch.index ?? elements.length;\n if (patch.op === \"addRule\") {\n if (index > elements.length) throw refusal(`Table \"${patch.table}\" has ${elements.length} rule(s); there is no position ${index}.`, patch.table, \"rls\");\n const printed = printSchemaValue(patch.rule, `${patch.table}.rls[${index}]`);\n workspace.edit(table.file, insertListItem(source, list, index, printed, \"lines\"));\n return;\n }\n if (index >= elements.length) throw refusal(`Table \"${patch.table}\" has ${elements.length} rule(s); there is no rule ${index}.`, patch.table, \"rls\");\n const element = elements[index];\n if (!Node.isObjectLiteralExpression(unwrapExpression(element) ?? element)) {\n throw refusal(`Rule ${index} of table \"${patch.table}\" is edited in code: it is \\`${element.getText().slice(0, 40)}\\`.`, patch.table, \"rls\");\n }\n if (patch.op === \"removeRule\") {\n if (elements.length === 1) {\n throw refusal(`Rule ${index} is the last rule of table \"${patch.table}\", and an empty list leaves nobody a policy. Set \\`rls\\` to \"admin-only\" instead.`, patch.table, \"rls\");\n }\n workspace.edit(table.file, removeListItem(source, list, index));\n return;\n }\n workspace.edit(table.file, [replaceNode(source, element, printSchemaValue(patch.rule, `${patch.table}.rls[${index}]`))]);\n}\n\n/** The builders' module specifier this project writes: whatever an existing table file imports them from. */\nfunction builderSpecifier(workspace: Workspace): string {\n for (const table of workspace.tables()) {\n const found = builderImport(workspace.source(table.file));\n if (found) return found.declaration.getModuleSpecifierValue();\n }\n return DEFAULT_SCHEMA_SPECIFIER;\n}\n\nfunction createTable(workspace: Workspace, spec: NewTable): void {\n const tables = workspace.tables();\n const slug = spec.slug ?? spec.name;\n const clash = tables.find(table => table.slug === slug || table.name === spec.name);\n if (clash) throw refusal(`There is already a table \"${clash.name}\" (slug \"${clash.slug}\") in backend/schema.`, spec.name);\n const file = path.join(workspace.dir, `${spec.name}.ts`);\n if (workspace.has(file) || fs.existsSync(file)) throw refusal(`${file} already exists.`, spec.name);\n const identifier = tableIdentifier(spec.name);\n if (tables.some(table => table.exportName === identifier)) {\n throw refusal(`The schema index already exports \\`${identifier}\\`, the name the new table would be exported as.`, spec.name);\n }\n\n // The new table, for a relation of its own: its thunk is read when printed.\n const self: { def?: AnyTableDef } = {};\n const relations: RelationsShape = {};\n for (const [name, relation] of Object.entries(spec.relations ?? {})) {\n if (relation.target === slug) {\n relations[name] = relationFromWire(relation, () => self.def);\n continue;\n }\n const target = tables.find(table => table.slug === relation.target);\n if (!target) throw refusal(`The relation \"${name}\" targets \"${relation.target}\", which is not a table in backend/schema.`, spec.name, name);\n relations[name] = relationFromWire(relation, () => targetStandIn(target.name, target.slug));\n }\n const { name: _name, slug: _slug, table: _table, schema: _schema, columns: _columns, relations: _relations, rls: _rls, ...options } = spec;\n void _name; void _slug; void _table; void _schema; void _columns; void _relations; void _rls;\n const created = defineTable(spec.name, {\n ...(spec.slug !== undefined ? { slug: spec.slug } : {}),\n ...(spec.table !== undefined ? { table: spec.table } : {}),\n ...(spec.schema !== undefined ? { schema: spec.schema } : {}),\n ...options,\n columns: columnsFromWire(spec.columns),\n ...(Object.keys(relations).length > 0 ? { relations } : {}),\n rls: spec.rls\n });\n self.def = created;\n const module = printTableModule(created, {\n identifier,\n specifier: builderSpecifier(workspace),\n resolveTarget: target => {\n const found = tables.find(table => table.slug === target.slug);\n if (!found) return { identifier: tableIdentifier(target.name ?? target.slug) };\n return { identifier: found.variable, importPath: relativeSpecifier(file, found.file) };\n }\n });\n workspace.set(file, module);\n exportFromIndex(workspace, identifier, file);\n}\n\n/**\n * Write a table the database already has from its description, through the\n * printer — every column type, default, key, foreign key and enum as\n * introspection read it, so planning it changes nothing — and export it.\n */\nfunction adoptTable(workspace: Workspace, descriptor: TableDescriptor): void {\n const tables = workspace.tables();\n const clash = tables.find(table => table.slug === descriptor.slug || table.name === descriptor.name);\n if (clash) throw refusal(`There is already a table \"${clash.name}\" (slug \"${clash.slug}\") in backend/schema.`, descriptor.slug);\n const file = path.join(workspace.dir, `${descriptor.name}.ts`);\n if (workspace.has(file) || fs.existsSync(file)) throw refusal(`${file} already exists.`, descriptor.slug);\n const identifier = tableIdentifier(descriptor.name);\n if (tables.some(table => table.exportName === identifier)) {\n throw refusal(`The schema index already exports \\`${identifier}\\`, the name the adopted table would be exported as.`, descriptor.slug);\n }\n for (const relation of descriptor.relations) {\n if (relation.target === descriptor.slug || tables.some(table => table.slug === relation.target)) continue;\n throw refusal(`The relation \"${relation.name}\" targets \"${relation.target}\", which is not a table in backend/schema.`, descriptor.slug, relation.name);\n }\n const module = printTableModule(descriptor, {\n identifier,\n specifier: builderSpecifier(workspace),\n resolveTarget: target => {\n const found = tables.find(table => table.slug === target.slug);\n if (!found) return { identifier };\n return { identifier: found.variable, importPath: relativeSpecifier(file, found.file) };\n }\n });\n workspace.set(file, module);\n exportFromIndex(workspace, identifier, file);\n}\n\n/** Export a table's file from the schema index, after the last export (creating the index when there is none). */\nfunction exportFromIndex(workspace: Workspace, identifier: string, file: string): void {\n const line = printIndexModule([{ identifier, importPath: relativeSpecifier(path.join(workspace.dir, \"index.ts\"), file) }]);\n const indexPath = workspace.indexFile();\n if (!indexPath) {\n workspace.set(path.join(workspace.dir, \"index.ts\"), line);\n return;\n }\n const index = workspace.source(indexPath);\n const exports = index.getExportDeclarations();\n const text = workspace.text(indexPath);\n if (exports.length > 0) {\n const at = exports[exports.length - 1].getEnd();\n workspace.edit(indexPath, [{ start: at, end: at, text: `\\n${line.trimEnd()}` }]);\n } else {\n workspace.edit(indexPath, [{ start: text.length, end: text.length, text: `${text.endsWith(\"\\n\") || text === \"\" ? \"\" : \"\\n\"}${line}` }]);\n }\n}\n\nasync function deleteTable(workspace: Workspace, slug: string, editor: TableSourceEditor): Promise<void> {\n const table = workspace.table(slug);\n // Who points at it, read from what the schema compiles to now: a relation's\n // target is a thunk, and only compiling resolves it to a table.\n const current = await editor.compile(workspace.texts());\n const referencing = current.descriptors.flatMap(descriptor =>\n descriptor.slug === slug ? [] : descriptor.relations\n .filter(relation => relation.target === slug)\n .map(relation => `${descriptor.slug}.${relation.name}`));\n if (referencing.length > 0) {\n throw refusal(\n `Table \"${slug}\" cannot be deleted while relations target it: ${referencing.join(\", \")}. ` +\n \"Remove or retarget those relations first.\",\n slug\n );\n }\n\n const source = workspace.source(table.file);\n const statement = table.declaration.getFirstAncestor(Node.isVariableStatement);\n if (!statement) throw refusal(`The definition of \"${slug}\" is not a top-level \\`const\\`.`, slug);\n const others = source.getStatements().filter(each => each !== statement && !Node.isImportDeclaration(each));\n const indexPath = workspace.indexFile();\n const definedInIndex = table.file === indexPath;\n if (others.length === 0 && !definedInIndex) {\n workspace.delete(table.file);\n } else {\n removeVariable(workspace, table.file, statement, table.declaration);\n }\n\n if (!indexPath || definedInIndex) return;\n const index = workspace.source(indexPath);\n const deletedFile = !workspace.has(table.file);\n for (const declaration of index.getExportDeclarations()) {\n const targetFile = declaration.getModuleSpecifierSourceFile()?.getFilePath();\n const named = declaration.getNamedExports();\n const position = index.getStatements().indexOf(declaration);\n const previousEnd = position > 0 ? index.getStatements()[position - 1].getEnd() : 0;\n if (named.length === 0) {\n if (deletedFile && targetFile === table.file) workspace.edit(indexPath, [removeStatement(index.getFullText(), declaration, previousEnd)]);\n continue;\n }\n const at = named.findIndex(element => (element.getAliasNode()?.getText() ?? element.getName()) === table.exportName);\n if (at === -1) continue;\n if (named.length === 1) {\n workspace.edit(indexPath, [removeStatement(index.getFullText(), declaration, previousEnd)]);\n } else {\n const element = named[at];\n workspace.edit(indexPath, [at < named.length - 1\n ? { start: element.getStart(), end: named[at + 1].getStart(), text: \"\" }\n : { start: named[at - 1].getEnd(), end: element.getEnd(), text: \"\" }]);\n }\n return;\n }\n}\n\nfunction removeVariable(workspace: Workspace, file: string, statement: VariableStatement, declaration: VariableDeclaration): void {\n const source = workspace.source(file);\n const declarations = statement.getDeclarations();\n if (declarations.length > 1) {\n throw refusal(`${file} declares \"${declaration.getName()}\" together with other constants in one statement: delete it in code.`, declaration.getName());\n }\n const statements = source.getStatements();\n const position = statements.indexOf(statement);\n workspace.edit(file, [removeStatement(source.getFullText(), statement, position > 0 ? statements[position - 1].getEnd() : 0)]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BtB,SAAgB,gBAAgB,WAA2B;CACvD,MAAM,QAAQ,UAAU,QAAQ,cAAc,GAAG,SAAiB,KAAK,YAAY,CAAC;CACpF,IAAI,cAAc,KAAK,KAAK,GAAG,OAAO;CAEtC,MAAM,YAAY,MAGb,QAAQ,mCAAmC,GAAG,SAC1C,OAAO,KAAK,YAAY,IAAI,EAAG,CAAC,CAGpC,QAAQ,YAAY,KAAK;CAE9B,OAAO,cAAc,KAAK,SAAS,IAAI,YAAY,IAAI;AAC3D;;;;;;;;ACjBA,SAAgB,sBAAsB,QAAqC;CACvE,MAAM,MAAiB;EACnB,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,SAAS,CAAC,OAAO;EACjB,YAAY,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AQ,SAAS;CAC7C,UAAU,KAAK,MAAM,CAAC,gBAAgB,OAAO,YAAY,GAAG,WAAW,WAAW,IAAI,WAAW,WAAW,EAAE,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC;AACjI"}
|
|
1
|
+
{"version":3,"file":"table-source-editor-D_zNDhEU.js","names":[],"sources":["../../common/src/util/relations.ts","../../common/src/schema/descriptor-to-def.ts","../../common/src/schema/print-doc.ts","../../common/src/schema/print-value.ts","../../common/src/schema/print-column.ts","../../common/src/schema/print-table.ts","../src/schema-edit/source-importer.ts","../src/schema-edit/source-text.ts","../src/api/table-source-editor.ts"],"sourcesContent":["/**\n * The names the schema generator gives a table's Drizzle variable and its enum\n * types. (The panel's relation helpers live in `@rebasepro/cms-types`.)\n *\n * @module\n */\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * A JavaScript identifier: what a generated `export const <name> =` needs.\n *\n * Deliberately the same shape the two schema generators already define\n * privately — this is the third place that needed it, and the first two guard\n * property keys and member accesses while nothing guarded the variable name\n * itself.\n */\nconst JS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * The variable name a generated table is bound to.\n *\n * Camel-cases underscores, and then guarantees the result is a legal\n * identifier. It did only the first, so a table name that is legal in Postgres\n * and not in JavaScript produced a `schema.generated.ts` that does not parse:\n *\n * `2024_archive` → `export const 2024Archive = pgTable(…)`\n * \"An identifier or keyword cannot immediately follow\n * a numeric literal\"\n * `reporting.events` → `export const reporting.events = pgTable(…)`\n * \"',' expected\"\n *\n * That file is imported by the server, so the failure is not one broken\n * collection — `rebase build` and `db push` fail at tsc for the whole\n * directory. And it is reachable from a documented flow: `rebase init` against\n * a database holding a table called `2024_archive` writes a collection file\n * that parses and a schema file that does not.\n *\n * **A no-op for every name that already worked**, which is what makes changing\n * a derived name safe here: the only inputs whose output changes are the ones\n * that produced a syntax error, and nothing can be running against those.\n * Separators become camel case rather than disappearing, so `reporting.events`\n * and `reporting_events` do not collide into one variable.\n */\nexport function getTableVarName(tableName: string): string {\n const camel = tableName.replace(/_([a-z])/g, (_, char: string) => char.toUpperCase());\n if (JS_IDENTIFIER.test(camel)) return camel;\n\n const sanitised = camel\n // Any other separator gets the same treatment `_` did, so two tables\n // differing only by separator keep differing.\n .replace(/[^A-Za-z0-9_$]+([A-Za-z0-9])?/g, (_, char?: string) =>\n (char ? char.toUpperCase() : \"\"))\n // A leading digit is legal in Postgres and not in JavaScript. Prefixed\n // rather than stripped, so `2024_archive` and `archive` stay distinct.\n .replace(/^([0-9])/, \"t$1\");\n\n return JS_IDENTIFIER.test(sanitised) ? sanitised : `t${sanitised}`;\n}\n\nexport function getEnumVarName(tableName: string, propName: string): string {\n const tableVar = getTableVarName(tableName);\n const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);\n return `${tableVar}${propVar}`;\n}\n","/**\n * From a {@link TableDescriptor} back to the definition that compiles to it.\n *\n * The printer reads descriptors and the lowering reads definitions; a\n * descriptor nobody authored — what `introspectTables` reports for a database\n * no project declared — reaches the lowering through here, at the same\n * boundary a declared table crosses at boot.\n *\n * The definition states every derived name explicitly (`localKey`,\n * `foreignKey`, `through`, …) rather than leaving it to be re-derived, so it\n * means exactly what the descriptor says. A foreign-key column the descriptor\n * marks `derived` is left to its relation, as the printer leaves it, with its\n * nullability and uniqueness on the relation.\n *\n * @module\n */\nimport {\n ColumnBuilder,\n defineTable,\n defineView,\n rel,\n type AnyColumn,\n type AnyTableDef,\n type AnyViewDef,\n type ColumnDef,\n type ColumnDescriptor,\n type RelationDef,\n type RelationDescriptor,\n type RlsDescriptor,\n type RlsPosture,\n type TableDescriptor\n} from \"@rebasepro/types\";\n\nimport { SchemaDefinitionError, type SchemaDefinitionProblem } from \"./errors\";\n\n/**\n * A descriptor column, as the definition that compiles to it.\n *\n * @group Schema\n */\nexport function columnDefOfDescriptor(column: ColumnDescriptor): ColumnDef {\n const def: ColumnDef = {\n type: column.type,\n column: column.column,\n notNull: !column.nullable,\n primaryKey: column.primaryKey === true,\n unique: column.unique === true,\n readOnly: column.readOnly === true,\n private: column.private === true\n };\n if (column.default !== undefined) def.default = column.default;\n if (column.generated !== undefined) def.generatedAs = column.generated.expression;\n if (column.access !== undefined) def.access = column.access;\n if (column.stamp !== undefined) def.stamp = column.stamp;\n if (column.validate !== undefined) def.validate = column.validate;\n if (column.oneOf !== undefined) def.oneOf = column.oneOf;\n if (column.description !== undefined) def.description = column.description;\n if (column.storage !== undefined) def.storage = column.storage;\n if (column.semantic !== undefined) def.semantic = column.semantic;\n if (column.vectorIndex !== undefined) def.vectorIndex = column.vectorIndex;\n if (column.json !== undefined) def.json = column.json;\n if (column.type.kind === \"array\") {\n const element: ColumnDef = {\n type: column.type.of,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n };\n if (column.element?.validate !== undefined) element.validate = column.element.validate;\n if (column.element?.oneOf !== undefined) element.oneOf = column.element.oneOf;\n if (column.element?.storage !== undefined) element.storage = column.element.storage;\n if (column.element?.semantic !== undefined) element.semantic = column.element.semantic;\n def.element = element;\n }\n return def;\n}\n\n/**\n * Options of {@link tableDefsFromDescriptors}.\n *\n * @group Schema\n */\nexport interface TableDefsFromDescriptorsOptions {\n /**\n * The `rls` each definition is given in place of the one its descriptor\n * states. For a caller whose tables' access the database decides and that\n * lowers them only to serve them — introspection, where Rebase generates no\n * policy, so the request-time collection carries no rule (`\"admin-only\"`\n * lowers to none) while the descriptor keeps stating the catalogue's.\n */\n rls?: (descriptor: TableDescriptor) => RlsPosture;\n}\n\n/** A descriptor column as a builder, so `defineTable` accepts it. */\nconst builderOf = (column: ColumnDescriptor): AnyColumn => new ColumnBuilder(columnDefOfDescriptor(column));\n\n/** Where a problem is, for the error. */\nclass ConversionProblem extends Error {\n constructor(readonly problem: SchemaDefinitionProblem) {\n super(problem.message);\n }\n}\n\n/**\n * A descriptor's row-level security as a definition's `rls` (and\n * `defaultPolicies`), or a problem when no definition can say it.\n */\nfunction rlsOf(descriptor: TableDescriptor, rls: RlsDescriptor): { rls: RlsPosture; defaultPolicies?: boolean } {\n const rules = rls.rules;\n const declared = rls.declaredDefaultPolicies ? { defaultPolicies: true } : {};\n if (rls.posture === \"admin-only\") return { rls: \"admin-only\", ...declared };\n if (rules.length > 0) {\n const posture: RlsPosture = [rules[0], ...rules.slice(1)];\n return rls.defaultPolicies ? { rls: posture, ...declared } : { rls: posture, defaultPolicies: false };\n }\n if (rls.defaultPolicies) return { rls: \"admin-only\", ...declared };\n throw new ConversionProblem({\n table: descriptor.name,\n message: \"has row-level security with no rule and no admin baseline, so nobody may read a row. \" +\n \"`defineTable` does not write a table nobody may read: list the rules that grant access, or say \\\"admin-only\\\".\"\n });\n}\n\n/** A descriptor relation as the `rel.*` definition that resolves to it. */\nfunction relationOf(\n relation: RelationDescriptor,\n owner: TableDescriptor,\n target: () => AnyTableDef | AnyViewDef\n): RelationDef {\n const access = {\n ...(relation.access !== undefined ? { access: relation.access } : {}),\n ...(relation.private === true ? { private: true } : {})\n };\n switch (relation.kind) {\n case \"belongsTo\": {\n const derived = owner.columns.find(column => column.key === relation.localField && column.derived === true);\n return rel.belongsTo(target, {\n localKey: relation.localKey,\n ...(derived && !derived.nullable ? { notNull: true } : {}),\n ...(derived?.unique ? { unique: true } : {}),\n ...(relation.onDelete !== undefined ? { onDelete: relation.onDelete } : {}),\n ...(relation.onUpdate !== undefined ? { onUpdate: relation.onUpdate } : {}),\n ...(relation.index ? {} : { index: false }),\n ...(relation.constraint ? {} : { constraint: false }),\n ...access\n });\n }\n case \"hasOne\":\n return rel.hasOne(target, {\n foreignKey: relation.foreignKey,\n ...(relation.sourceKey !== undefined ? { sourceKey: relation.sourceKey } : {}),\n ...access\n });\n case \"hasMany\":\n return rel.hasMany(target, {\n foreignKey: relation.foreignKey,\n ...(relation.sourceKey !== undefined ? { sourceKey: relation.sourceKey } : {}),\n ...(relation.orderBy !== undefined ? { orderBy: relation.orderBy } : {}),\n ...access\n });\n case \"manyToMany\": {\n const pivot: Record<string, AnyColumn> = {};\n for (const column of relation.through.pivot) pivot[column.key] = builderOf(column);\n return rel.manyToMany(target, {\n through: relation.through.table,\n sourceKey: relation.through.sourceKey,\n targetKey: relation.through.targetKey,\n ...(relation.through.pivot.length > 0 ? { pivot } : {}),\n ...(relation.onDelete !== undefined ? { onDelete: relation.onDelete } : {}),\n ...access\n });\n }\n case \"via\":\n return rel.via(target, { steps: relation.steps, cardinality: relation.cardinality, ...access });\n }\n}\n\n/** One descriptor as a definition, its relations' targets resolved through `resolve`. */\nfunction defOf(descriptor: TableDescriptor, resolve: (slug: string) => AnyTableDef | AnyViewDef, options: TableDefsFromDescriptorsOptions): AnyTableDef | AnyViewDef {\n if (descriptor.auth !== undefined) {\n throw new ConversionProblem({\n table: descriptor.name,\n message: \"is an auth table. `defineAuthTable` adds the auth columns and policies itself; print the descriptor instead of converting it.\"\n });\n }\n const declared = Object.keys(descriptor.hooks ?? {});\n if (declared.length > 0) {\n throw new ConversionProblem({\n table: descriptor.name,\n message: `declares hooks (${declared.join(\", \")}), whose code never leaves the server; a descriptor cannot be turned back into them.`\n });\n }\n const columns: Record<string, AnyColumn> = {};\n for (const column of descriptor.columns) {\n if (column.derived === true) continue;\n columns[column.key] = builderOf(column);\n }\n const relations: Record<string, RelationDef> = {};\n for (const relation of descriptor.relations) {\n relations[relation.name] = relationOf(relation, descriptor, () => resolve(relation.target));\n }\n const common = {\n ...(descriptor.slug !== descriptor.name ? { slug: descriptor.slug } : {}),\n ...(descriptor.table !== descriptor.name ? { table: descriptor.table } : {}),\n ...(descriptor.schema !== \"public\" ? { schema: descriptor.schema } : {}),\n ...(descriptor.database !== undefined ? { database: descriptor.database } : {}),\n ...(descriptor.description !== undefined ? { description: descriptor.description } : {}),\n columns,\n ...(descriptor.relations.length > 0 ? { relations } : {}),\n ...(descriptor.indexes !== undefined ? { indexes: descriptor.indexes } : {}),\n ...(descriptor.metadata !== undefined ? { metadata: descriptor.metadata } : {})\n };\n if (descriptor.kind === \"view\") {\n const view = descriptor.view;\n if (view?.query === undefined) {\n throw new ConversionProblem({\n table: descriptor.name,\n message: \"is a view whose descriptor carries no query (it is served to admins only). Convert a descriptor that includes it.\"\n });\n }\n return defineView(descriptor.name, {\n ...common,\n query: view.query,\n ...(view.materialized ? { materialized: true } : {}),\n ...(view.materialized && view.roles !== undefined ? { roles: view.roles } : {})\n });\n }\n const rls = options.rls ? { rls: options.rls(descriptor) } : rlsOf(descriptor, descriptor.rls);\n return defineTable(descriptor.name, {\n ...common,\n ...rls,\n ...(descriptor.tenant !== undefined ? { tenant: descriptor.tenant } : {}),\n ...(descriptor.softDelete !== undefined ? { softDelete: descriptor.softDelete } : {}),\n ...(descriptor.history !== undefined ? { history: descriptor.history } : {}),\n ...(descriptor.search !== undefined ? { search: descriptor.search } : {}),\n ...(descriptor.strictWrites === false ? { strictWrites: false } : {})\n });\n}\n\n/**\n * Definitions for a set of descriptors, in the order given: what\n * `compileTables` compiles back to the same descriptors (derived names and\n * defaults stated explicitly), and what the planner plans from.\n *\n * A relation's target is resolved by slug among `descriptors`, lazily, so two\n * tables may point at each other. Throws a {@link SchemaDefinitionError}\n * listing every descriptor no definition can state: an auth table, a table\n * with hooks, a view without its query, row-level security that grants nobody\n * anything (unless `options.rls` replaces it), and whatever `defineTable`\n * itself refuses. A target outside the set is a problem when the thunk is\n * called.\n *\n * @group Schema\n */\nexport function tableDefsFromDescriptors(\n descriptors: readonly TableDescriptor[],\n options: TableDefsFromDescriptorsOptions = {}\n): (AnyTableDef | AnyViewDef)[] {\n const bySlug = new Map<string, AnyTableDef | AnyViewDef>();\n const resolve = (slug: string): AnyTableDef | AnyViewDef => {\n const def = bySlug.get(slug);\n if (!def) {\n throw new SchemaDefinitionError([{ table: slug, message: \"is the target of a relation, and no descriptor in the set has that slug.\" }]);\n }\n return def;\n };\n const problems: SchemaDefinitionProblem[] = [];\n const out: (AnyTableDef | AnyViewDef)[] = [];\n for (const descriptor of descriptors) {\n try {\n const def = defOf(descriptor, resolve, options);\n bySlug.set(descriptor.slug, def);\n out.push(def);\n } catch (error) {\n if (error instanceof ConversionProblem) problems.push(error.problem);\n else problems.push({ table: descriptor.name, message: error instanceof Error ? error.message : String(error) });\n }\n }\n if (problems.length > 0) throw new SchemaDefinitionError(problems);\n return out;\n}\n","/**\n * The layout half of the schema printer: a tiny document model and the one\n * renderer that turns it into source text.\n *\n * Printing is split in two so that every printer (columns, JSON shapes,\n * relations, rules, whole modules) only says *what* it prints, and the line\n * breaking is decided in one place, the same way for all of them:\n *\n * - an object, array or call is printed on one line when it fits in\n * {@link PRINT_WIDTH} columns and none of its children must break;\n * - otherwise an object or array puts one entry per line, indented four\n * spaces; a call keeps its last argument hugged against the parenthesis\n * when that argument is an object, array or call (`col.jsonb(json.object({`),\n * and breaks one argument per line when it is not.\n *\n * No trailing commas (the repository's `comma-dangle` rule), double quotes,\n * four-space indentation. Pure: the same document always renders to the same\n * bytes.\n */\n\n/** The width a line may reach before an object, array or call is broken over several. */\nexport const PRINT_WIDTH = 120;\n\nconst INDENT = 4;\n\n/**\n * A piece of source, before layout.\n *\n * - `text` — printed as is. Text holding a newline (a hook's source) cannot\n * share a line with its siblings, so it forces its parents to break.\n * - `object` / `array` — a literal; `breaks` forces one entry per line.\n * - `call` — `callee(args)`.\n * - `concat` — pieces printed one after another (a builder chain).\n */\nexport type Doc =\n | { kind: \"text\"; text: string }\n | { kind: \"object\"; entries: ObjectEntry[]; breaks?: boolean }\n | { kind: \"array\"; items: Doc[]; breaks?: boolean }\n | { kind: \"call\"; callee: string; args: Doc[] }\n | { kind: \"concat\"; parts: Doc[] };\n\n/** One `key: value` of an object literal. `key` is already printed (quoted when it must be). */\nexport interface ObjectEntry {\n /** The printed key: a bare identifier, or a double-quoted string. */\n key: string;\n /** The printed value. */\n value: Doc;\n}\n\n/** A piece of literal source text. */\nexport const text = (value: string): Doc => ({ kind: \"text\", text: value });\n\n/** `callee(args)`. */\nexport const call = (callee: string, args: Doc[] = []): Doc => ({ kind: \"call\", callee, args });\n\n/** Pieces printed one after another. */\nexport const concat = (parts: Doc[]): Doc => ({ kind: \"concat\", parts });\n\n/** An array literal. */\nexport const array = (items: Doc[], breaks = false): Doc => ({ kind: \"array\", items, breaks });\n\n/** An object literal from `[key, value]` pairs, keys printed bare when they can be. */\nexport const object = (entries: readonly (readonly [string, Doc])[], breaks = false): Doc => ({\n kind: \"object\",\n entries: entries.map(([key, value]) => ({ key: printKey(key), value })),\n breaks\n});\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * An object key as written in source: bare when it is an identifier name\n * (reserved words included — they are legal property names), double-quoted\n * otherwise.\n */\nexport function printKey(key: string): string {\n return IDENTIFIER.test(key) ? key : printString(key);\n}\n\n/** A string literal, double-quoted. */\nexport function printString(value: string): string {\n return JSON.stringify(value);\n}\n\n/**\n * A string literal for text that may span lines (a view's query): a template\n * literal when it holds a newline, so the SQL reads as SQL, and a\n * double-quoted string otherwise.\n */\nexport function printMultilineString(value: string): string {\n if (!value.includes(\"\\n\")) return printString(value);\n return \"`\" + value.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$\\{/g, \"\\\\${\") + \"`\";\n}\n\n/** The text of a doc on one line, or `undefined` when it cannot be put on one. */\nfunction flat(doc: Doc): string | undefined {\n switch (doc.kind) {\n case \"text\":\n return doc.text.includes(\"\\n\") ? undefined : doc.text;\n case \"object\": {\n if (doc.entries.length === 0) return \"{}\";\n if (doc.breaks) return undefined;\n const parts: string[] = [];\n for (const entry of doc.entries) {\n const value = flat(entry.value);\n if (value === undefined) return undefined;\n parts.push(`${entry.key}: ${value}`);\n }\n return `{ ${parts.join(\", \")} }`;\n }\n case \"array\": {\n if (doc.items.length === 0) return \"[]\";\n if (doc.breaks) return undefined;\n const parts: string[] = [];\n for (const item of doc.items) {\n const value = flat(item);\n if (value === undefined) return undefined;\n parts.push(value);\n }\n return `[${parts.join(\", \")}]`;\n }\n case \"call\": {\n const parts: string[] = [];\n for (const arg of doc.args) {\n const value = flat(arg);\n if (value === undefined) return undefined;\n parts.push(value);\n }\n return `${doc.callee}(${parts.join(\", \")})`;\n }\n case \"concat\": {\n let out = \"\";\n for (const part of doc.parts) {\n const value = flat(part);\n if (value === undefined) return undefined;\n out += value;\n }\n return out;\n }\n }\n}\n\nconst pad = (width: number): string => \" \".repeat(width);\n\n/** The column the cursor stands at after printing `printed` from `column`. */\nfunction columnAfter(printed: string, column: number): number {\n const newline = printed.lastIndexOf(\"\\n\");\n return newline < 0 ? column + printed.length : printed.length - newline - 1;\n}\n\nconst huggable = (doc: Doc): boolean =>\n (doc.kind === \"object\" && doc.entries.length > 0) ||\n (doc.kind === \"array\" && doc.items.length > 0) ||\n (doc.kind === \"call\" && doc.args.length > 0);\n\n/**\n * Lay a doc out.\n *\n * @param indent The indentation of the line the doc starts on.\n * @param column The column the doc starts at on that line.\n */\nexport function render(doc: Doc, indent = 0, column = indent): string {\n const oneLine = flat(doc);\n if (oneLine !== undefined && (doc.kind === \"text\" || column + oneLine.length <= PRINT_WIDTH)) return oneLine;\n switch (doc.kind) {\n case \"text\":\n return doc.text;\n case \"object\": {\n const inner = indent + INDENT;\n const lines = doc.entries.map(entry =>\n `${pad(inner)}${entry.key}: ${render(entry.value, inner, inner + entry.key.length + 2)}`);\n return `{\\n${lines.join(\",\\n\")}\\n${pad(indent)}}`;\n }\n case \"array\": {\n const inner = indent + INDENT;\n const lines = doc.items.map(item => `${pad(inner)}${render(item, inner, inner)}`);\n return `[\\n${lines.join(\",\\n\")}\\n${pad(indent)}]`;\n }\n case \"call\":\n return renderCall(doc.callee, doc.args, indent, column);\n case \"concat\": {\n // A chain never breaks inside a link whose arguments fit on one\n // line (`.validate({ max: 60 })` at the end of a long chain stays\n // whole): only the type builder at its head is laid out by width.\n let out = \"\";\n let at = column;\n for (const [index, part] of doc.parts.entries()) {\n const partFlat = index > 0 ? flat(part) : undefined;\n const printed = partFlat ?? render(part, indent, at);\n out += printed;\n at = columnAfter(printed, at);\n }\n return out;\n }\n }\n}\n\nfunction renderCall(callee: string, args: Doc[], indent: number, column: number): string {\n const head = `${callee}(`;\n if (args.length === 0) return `${head})`;\n const flats = args.map(flat);\n const last = args[args.length - 1];\n // One argument that cannot break (a long string, a hook's source) gains\n // nothing from a line of its own.\n if (args.length === 1 && !huggable(last)) return `${head}${render(last, indent, column + head.length)})`;\n // Hug the last argument: `rel.belongsTo(() => users, {` … `})`.\n if (huggable(last) && flats.slice(0, -1).every(value => value !== undefined)) {\n const prefix = head + flats.slice(0, -1).map(value => `${value}, `).join(\"\");\n if (args.length === 1 || column + prefix.length <= PRINT_WIDTH) {\n return `${prefix}${render(last, indent, column + prefix.length)})`;\n }\n }\n // Hug the first: `json.object({` … `}, { additional: true })`.\n const first = args[0];\n if (args.length > 1 && huggable(first) && flats.slice(1).every(value => value !== undefined)) {\n const printed = render(first, indent, column + head.length);\n return `${head}${printed}, ${flats.slice(1).join(\", \")})`;\n }\n const inner = indent + INDENT;\n const lines = args.map(arg => `${pad(inner)}${render(arg, inner, inner)}`);\n return `${head}\\n${lines.join(\",\\n\")}\\n${pad(indent)})`;\n}\n","import { array, object, printString, text } from \"./print-doc\";\nimport type { Doc } from \"./print-doc\";\n\n/**\n * A definition the printer cannot turn into source without losing something:\n * a hook whose source was not supplied, a value that is not data, a column\n * shape no builder chain produces.\n *\n * The printer never drops what it cannot print — it refuses, naming where the\n * value sits and what to supply instead.\n *\n * @group Schema\n */\nexport class TablePrintError extends Error {\n\n readonly code = \"TABLE_PRINT_UNPRINTABLE\";\n\n constructor(\n /** Where the value sits: `posts.columns.title`, `posts.hooks.beforeSave`. */\n readonly path: string,\n message: string\n ) {\n super(`Cannot print ${path}: ${message}`);\n this.name = \"TablePrintError\";\n }\n}\n\nconst isPlainObject = (value: object): boolean => {\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/** A number literal, including the values JSON has no spelling for. */\nexport function printNumber(value: number): string {\n if (Object.is(value, -0)) return \"-0\";\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return String(value);\n}\n\n/**\n * A data value as a source literal: strings, numbers, booleans, `null`,\n * `bigint`, regular expressions, arrays and plain objects (keys in their own\n * order, `undefined` members left out as `JSON.stringify` leaves them out).\n *\n * Anything else — a function, a class instance, a `Date`, a symbol — has no\n * faithful literal and is refused with its path.\n *\n * @param path Where the value sits, for the refusal.\n */\nexport function valueDoc(value: unknown, path: string): Doc {\n switch (typeof value) {\n case \"string\":\n return text(printString(value));\n case \"number\":\n return text(printNumber(value));\n case \"boolean\":\n return text(String(value));\n case \"bigint\":\n return text(`${value.toString()}n`);\n case \"undefined\":\n return text(\"undefined\");\n case \"function\":\n throw new TablePrintError(path, \"it is a function, which is code rather than data. Supply its source text instead.\");\n case \"symbol\":\n throw new TablePrintError(path, \"it is a symbol, which has no source literal.\");\n case \"object\":\n break;\n }\n if (value === null) return text(\"null\");\n if (value instanceof RegExp) return text(String(value));\n if (Array.isArray(value)) {\n const items: Doc[] = [];\n value.forEach((item: unknown, index) => items.push(valueDoc(item, `${path}[${index}]`)));\n return array(items);\n }\n if (!isPlainObject(value)) {\n const name = value.constructor?.name ?? \"object\";\n throw new TablePrintError(path, `it is a \\`${name}\\` instance, which has no source literal. Pass plain data (strings, numbers, arrays, objects).`);\n }\n const entries: [string, Doc][] = [];\n for (const [key, member] of Object.entries(value)) {\n if (member === undefined) continue;\n entries.push([key, valueDoc(member, `${path}.${key}`)]);\n }\n return object(entries);\n}\n","import type {\n ColumnDef,\n ColumnStorage,\n ColumnTransform,\n ColumnType,\n ColumnValidation,\n JsonShapeDef\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\nimport { array, call, concat, object, printString, render, text } from \"./print-doc\";\nimport type { Doc } from \"./print-doc\";\nimport { TablePrintError, printNumber, valueDoc } from \"./print-value\";\n\n/**\n * Which builders a printed piece of source uses, so the module printer imports\n * exactly those.\n *\n * @group Schema\n */\nexport type SchemaBuilderName = \"defineTable\" | \"defineAuthTable\" | \"defineView\" | \"col\" | \"rel\" | \"json\" | \"pgEnum\" | \"sql\";\n\n/**\n * What the column and JSON-shape printers need besides the definition.\n * Internal: the public functions build it from their options.\n */\nexport interface ColumnPrintContext {\n /** Where the column sits, for refusals: `posts.columns.title`. */\n path: string;\n /**\n * The source of a field-level `transform`, by path relative to the column:\n * `\"\"` the column itself, `\"[]\"` an array column's element, `\"seo.title\"`\n * a field of its JSON shape, `\"[].image\"` a field inside a JSON array.\n */\n transforms: Readonly<Record<string, string>>;\n /** Collects the builders the printed source uses. */\n used: Set<SchemaBuilderName>;\n /** Where this context sits below the printed column (`\"\"`, `\"[]\"`), for the refusal's hint. */\n origin: string;\n /** How the caller supplies the source of the transform at a path below the printed column. */\n sourceHint: (relative: string) => string;\n /**\n * The identifier a named enum type is bound to by a `pgEnum(...)`\n * declaration the caller writes. Without it a named enum prints its\n * declaration inline: `pgEnum(\"status\", [...])()`.\n */\n enumIdentifier?: (enumName: string, values: readonly string[]) => string;\n}\n\n/** The hint of {@link printColumn}: its own options. */\nconst columnOptionHint = (relative: string): string =>\n relative === \"\" ? \"as `transform`\" : `under \\`transforms[\"${relative}\"]\\``;\n\n/**\n * Options of {@link printColumn}.\n *\n * @group Schema\n */\nexport interface PrintColumnOptions {\n /**\n * The column's key in `columns`. With it, the leading SQL name\n * (`col.text(\"legacy_title\")`) is left out when it is the snake_case of the\n * key (the builder's own default).\n */\n key?: string;\n /**\n * The identifier a named enum type is bound to (`const postStatus =\n * pgEnum(\"post_status\", [...])`), so the column prints `postStatus()`. The\n * caller writes the declaration. Without it the declaration is inlined.\n */\n enumIdentifier?: (enumName: string, values: readonly string[]) => string;\n /**\n * The source text of the column's `transform` (`\"{ beforeSave: ({ value }) => value.trim() }\"`),\n * printed verbatim. Required when the definition carries a transform: a\n * function cannot be printed from its value.\n */\n transform?: string;\n /**\n * Sources of transforms nested inside the column, by path relative to it:\n * `\"[]\"` an array column's element, `\"seo.title\"` a field of its JSON\n * shape, `\"[].image\"` a field inside a JSON array, `\"blocks.[].text\"` …\n * see {@link joinTransformPath}.\n */\n transforms?: Readonly<Record<string, string>>;\n}\n\n/**\n * The path of a nested transform: a JSON field is joined with `.`, an array\n * item is `[]`.\n *\n * @group Schema\n */\nexport function joinTransformPath(parent: string, segment: string): string {\n if (parent === \"\") return segment;\n if (segment === \"\") return parent;\n return segment === \"[]\" ? `${parent}[]` : `${parent}.${segment}`;\n}\n\nconst BYTE_UNITS: readonly [string, number][] = [\n [\"TB\", 1024 ** 4],\n [\"GB\", 1024 ** 3],\n [\"MB\", 1024 ** 2],\n [\"KB\", 1024]\n];\n\n/**\n * A byte size as it reads best: `\"10MB\"` when it is an exact multiple of a\n * binary unit (what `parseByteSize` reads back to the same number), the\n * number of bytes otherwise.\n *\n * @group Schema\n */\nexport function printByteSize(bytes: number): string {\n if (Number.isInteger(bytes) && bytes > 0) {\n for (const [unit, size] of BYTE_UNITS) {\n if (bytes % size === 0) return printString(`${bytes / size}${unit}`);\n }\n }\n return printNumber(bytes);\n}\n\nconst STORAGE_KEYS: readonly (keyof ColumnStorage)[] = [\n \"source\", \"path\", \"accept\", \"maxBytes\", \"imageResize\", \"public\", \"fileName\", \"metadata\", \"includeBucketUrl\", \"storeUrl\"\n];\n\nfunction storageDoc(storage: ColumnStorage, path: string): Doc {\n const known = new Set<string>(STORAGE_KEYS);\n for (const key of Object.keys(storage)) {\n if (!known.has(key)) throw new TablePrintError(`${path}.storage.${key}`, \"it is not a storage option `col.storage()` takes.\");\n }\n const entries: [string, Doc][] = [];\n for (const key of STORAGE_KEYS) {\n const value = storage[key];\n if (value === undefined) continue;\n entries.push([key, key === \"maxBytes\" && typeof value === \"number\" ? text(printByteSize(value)) : valueDoc(value, `${path}.storage.${key}`)]);\n }\n return object(entries);\n}\n\n/**\n * Whether a pattern prints as a RegExp literal: when it has flags (one\n * literal instead of `matches` + `matchesFlags`) or holds backslashes (which\n * a string would double), and the literal reads back to the same source.\n */\nfunction regexLiteral(matches: string, flags: string | undefined): string | undefined {\n if (flags === \"\") return undefined;\n if (flags === undefined && !matches.includes(\"\\\\\")) return undefined;\n try {\n const parsed = new RegExp(matches, flags);\n if (parsed.source !== matches) return undefined;\n return String(parsed);\n } catch {\n return undefined;\n }\n}\n\n/** `.validate({...})`'s argument: the rules in their own order, a pattern as a RegExp literal where it reads better. */\nfunction validationDoc(rules: ColumnValidation, path: string): Doc {\n const literal = typeof rules.matches === \"string\" ? regexLiteral(rules.matches, rules.matchesFlags) : undefined;\n const entries: [string, Doc][] = [];\n for (const [key, value] of Object.entries(rules)) {\n if (value === undefined) continue;\n if (literal !== undefined && key === \"matchesFlags\") continue;\n entries.push([key, literal !== undefined && key === \"matches\" ? text(literal) : valueDoc(value, `${path}.validate.${key}`)]);\n }\n return object(entries);\n}\n\n/** `.method(args)`, as a chain link. */\nconst link = (method: string, args: Doc[] = []): Doc => call(`.${method}`, args);\n\nconst hasFunction = (transform: ColumnTransform | undefined): boolean =>\n transform !== undefined && Object.values(transform).some(value => typeof value === \"function\");\n\n/**\n * The `.transform(...)` link, from the caller's source. A transform carrying a\n * function and no source is refused: dropping a hook silently would change\n * what the server does with every write.\n */\nfunction transformLink(declared: boolean, transform: ColumnTransform | undefined, relative: string, ctx: ColumnPrintContext): Doc | undefined {\n const source = ctx.transforms[relative];\n if (source !== undefined) return link(\"transform\", [text(source)]);\n if (declared || hasFunction(transform)) {\n const full = joinTransformPath(ctx.origin, relative);\n throw new TablePrintError(\n relative === \"\" ? `${ctx.path}.transform` : `${ctx.path} (transform at \"${relative}\")`,\n `the transform is a function, which cannot be printed from its value. Pass its source text ${ctx.sourceHint(full)}.`\n );\n }\n if (transform !== undefined) return link(\"transform\", [valueDoc(transform, `${ctx.path}.transform`)]);\n return undefined;\n}\n\n/** The column types `.defaultNow()` applies to. */\nconst TEMPORAL_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"timestamptz\", \"date\", \"time\"]);\n\n/** The column types `.userId()` applies to. */\nconst USER_ID_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"text\", \"varchar\", \"char\", \"uuid\"]);\n\n/** The flags and options every builder starts from: what is left out when printing. */\nconst isUntouchedElement = (element: ColumnDef): boolean =>\n element.column === undefined && !element.notNull && !element.primaryKey && !element.unique &&\n element.default === undefined && element.generatedAs === undefined && !element.readOnly && !element.private &&\n element.access === undefined && element.stamp === undefined && element.oneOf === undefined &&\n element.description === undefined && element.semantic === undefined && element.vectorIndex === undefined &&\n element.json === undefined && element.element === undefined && element.transform === undefined;\n\nconst sameData = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/** `sql\\`…\\``: the expression as a template literal whose cooked text is exactly the expression. */\nexport function printSqlTemplate(expression: string): string {\n return `sql\\`${expression.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$\\{/g, \"\\\\${\")}\\``;\n}\n\n/** The kinds whose `.oneOf()` is Drizzle's `{ enum: [...] }` config. */\nconst TEXT_ENUM_KINDS: ReadonlySet<ColumnType[\"kind\"]> = new Set([\"text\", \"varchar\", \"char\"]);\n\n/** Whether a column's `oneOf` prints inside its builder's config (`col.text({ enum })`) rather than as `.oneOf()`. */\nconst oneOfInConfig = (def: ColumnDef): boolean =>\n def.oneOf !== undefined && def.storage === undefined && def.semantic === undefined &&\n TEXT_ENUM_KINDS.has(def.type.kind) && def.oneOf.length > 0 && def.oneOf.every(value => typeof value === \"string\");\n\n/** `name` (the SQL column name, when there is one) and `config` as a builder's arguments. */\nconst builderArgs = (name: string | undefined, ...rest: (Doc | undefined)[]): Doc[] => {\n const args: Doc[] = name !== undefined ? [text(printString(name))] : [];\n for (const each of rest) if (each !== undefined) args.push(each);\n return args;\n};\n\nfunction simpleBuilder(def: ColumnDef, name: string | undefined, ctx: ColumnPrintContext): Doc {\n const { type } = def;\n switch (type.kind) {\n case \"text\":\n return call(\"col.text\", builderArgs(name, oneOfInConfig(def) ? object([[\"enum\", valueDoc(def.oneOf, `${ctx.path}.oneOf`)]]) : undefined));\n case \"uuid\":\n case \"smallint\":\n case \"integer\":\n case \"smallserial\":\n case \"serial\":\n case \"real\":\n case \"doublePrecision\":\n case \"boolean\":\n case \"date\":\n case \"time\":\n case \"bytea\":\n case \"json\":\n case \"jsonb\":\n return call(`col.${type.kind}`, builderArgs(name));\n case \"bigint\":\n case \"bigserial\":\n return call(`col.${type.kind}`, builderArgs(name, object([[\"mode\", text(printString(\"number\"))]])));\n case \"timestamptz\":\n return call(\"col.timestamp\", builderArgs(name, object([[\"withTimezone\", text(\"true\")]])));\n case \"varchar\":\n case \"char\": {\n const entries: [string, Doc][] = [[\"length\", text(printNumber(type.length))]];\n if (oneOfInConfig(def)) entries.push([\"enum\", valueDoc(def.oneOf, `${ctx.path}.oneOf`)]);\n return call(`col.${type.kind}`, builderArgs(name, object(entries)));\n }\n case \"numeric\": {\n const entries: [string, Doc][] = [];\n if (type.precision !== undefined) entries.push([\"precision\", text(printNumber(type.precision))]);\n if (type.scale !== undefined) entries.push([\"scale\", text(printNumber(type.scale))]);\n return call(\"col.numeric\", builderArgs(name, entries.length > 0 ? object(entries) : undefined));\n }\n case \"enum\": {\n const values = array(type.values.map(value => text(printString(value))));\n if (type.name === undefined) return call(\"col.enum\", builderArgs(name, values));\n const identifier = ctx.enumIdentifier?.(type.name, type.values);\n if (identifier !== undefined) return call(identifier, builderArgs(name));\n ctx.used.add(\"pgEnum\");\n return call(render(call(\"pgEnum\", [text(printString(type.name)), values])), builderArgs(name));\n }\n case \"vector\":\n return call(\"col.vector\", builderArgs(name, object([[\"dimensions\", text(printNumber(type.dimensions))]])));\n case \"array\":\n throw new TablePrintError(ctx.path, \"an array column needs its element definition to be printed.\");\n case \"other\":\n return call(\"col.custom\", builderArgs(name, object([[\"dataType\", text(printString(type.sqlType))]])));\n }\n}\n\n/**\n * The type builder of a column and the `ColumnDef` members it accounts for:\n * `col.storage(...)`, `col.geopoint()`, `col.jsonb(json…)`,\n * `col.vector({ dimensions, index })`, an array's item chain and `.array()`,\n * `col.storage(...).multiple()`, or the plain builder of the type — each with\n * the SQL column name as its leading argument when there is one.\n */\nfunction typeBuilder(def: ColumnDef, ctx: ColumnPrintContext, name: string | undefined): Doc {\n const { type } = def;\n if (def.semantic === \"geopoint\") {\n if (type.kind !== \"jsonb\" || def.json !== undefined) {\n throw new TablePrintError(ctx.path, `the meaning \"geopoint\" on a \\`${type.kind}\\` column has no builder.`);\n }\n return call(\"col.geopoint\", builderArgs(name));\n }\n if (def.semantic === \"user\" && (def.storage !== undefined || !USER_ID_KINDS.has(type.kind))) {\n throw new TablePrintError(\n ctx.path,\n `\\`.userId()\\` on ${def.storage !== undefined ? \"a storage column\" : `a \\`${type.kind}\\` column`}; it applies to text, varchar, char and uuid columns.`\n );\n }\n if (def.vectorIndex !== undefined && type.kind !== \"vector\") {\n throw new TablePrintError(ctx.path, \"a vector index on a column that is not `col.vector()`.\");\n }\n if (def.json !== undefined && type.kind !== \"json\" && type.kind !== \"jsonb\") {\n throw new TablePrintError(ctx.path, \"a JSON shape on a column that is not `col.json()` / `col.jsonb()`.\");\n }\n if (def.element !== undefined && type.kind !== \"array\") {\n throw new TablePrintError(ctx.path, \"an element definition on a column that is not an array.\");\n }\n switch (type.kind) {\n case \"text\":\n if (def.storage !== undefined) return call(\"col.storage\", builderArgs(name, storageDoc(def.storage, ctx.path)));\n break;\n case \"json\":\n case \"jsonb\":\n if (def.json !== undefined) {\n return call(`col.${type.kind}`, builderArgs(name, jsonShapeDoc(def.json, ctx, \"\")));\n }\n break;\n case \"vector\":\n if (def.vectorIndex !== undefined) {\n return call(\"col.vector\", builderArgs(name, object([\n [\"dimensions\", text(printNumber(type.dimensions))],\n [\"index\", valueDoc(def.vectorIndex, `${ctx.path}.vectorIndex`)]\n ])));\n }\n break;\n case \"array\":\n return arrayBuilder(def, type, ctx, name);\n default:\n break;\n }\n if (def.storage !== undefined) {\n throw new TablePrintError(ctx.path, `storage rules on a \\`${type.kind}\\` column; \\`col.storage()\\` is a text column.`);\n }\n return simpleBuilder(def, name, ctx);\n}\n\n/** What an array's item may not carry and still print before `.array()`: those describe a column. */\nconst ITEM_COLUMN_ONLY = (element: ColumnDef): boolean =>\n element.notNull || element.primaryKey || element.default !== undefined || element.readOnly || element.private;\n\nfunction arrayBuilder(def: ColumnDef, type: Extract<ColumnType, { kind: \"array\" }>, ctx: ColumnPrintContext, name: string | undefined): Doc {\n const element: ColumnDef = def.element ?? {\n type: type.of,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n };\n if (!sameData(element.type, type.of)) {\n throw new TablePrintError(ctx.path, \"the array's element definition is of another type than the array.\");\n }\n // `col.storage(...).multiple()`: TEXT[] of files, the element carrying the\n // storage rules and (only) the per-file validation.\n if (def.storage !== undefined && type.of.kind === \"text\" && element.storage !== undefined &&\n sameData(element.storage, def.storage) && isUntouchedElement(element) && ctx.transforms[\"[]\"] === undefined) {\n const parts: Doc[] = [call(\"col.storage\", builderArgs(name, storageDoc(def.storage, ctx.path)))];\n if (element.validate !== undefined) parts.push(link(\"validate\", [validationDoc(element.validate, `${ctx.path}[]`)]));\n parts.push(link(\"multiple\"));\n return concat(parts);\n }\n if (!sameData(def.storage, element.storage)) {\n throw new TablePrintError(\n ctx.path,\n \"the array's storage rules differ from its element's; `col.storage(...).array()` and `.multiple()` both keep them equal.\"\n );\n }\n if (ITEM_COLUMN_ONLY(element)) {\n throw new TablePrintError(\n `${ctx.path}[]`,\n \"the array's items carry `.notNull()`, a default, `.primaryKey()`, `.readOnly()` or `.private()`, which describe a column: put them on the array.\"\n );\n }\n if (element.column !== undefined) {\n throw new TablePrintError(`${ctx.path}[]`, \"the array's items carry a SQL column name; the name belongs to the array column.\");\n }\n const inner = columnChain(element, {\n ...ctx,\n path: `${ctx.path}[]`,\n transforms: nestedTransforms(ctx.transforms, \"[]\"),\n origin: joinTransformPath(ctx.origin, \"[]\")\n }, undefined, false, name);\n return concat([inner, link(\"array\")]);\n}\n\n/** The transforms under one nested path, re-rooted at it. */\nexport function nestedTransforms(transforms: Readonly<Record<string, string>>, prefix: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [path, source] of Object.entries(transforms)) {\n if (path === prefix) out[\"\"] = source;\n else if (path.startsWith(`${prefix}.`)) out[path.slice(prefix.length + 1)] = source;\n else if (path.startsWith(`${prefix}[]`)) out[path.slice(prefix.length)] = source;\n }\n return out;\n}\n\n/**\n * The canonical modifier order, after the type builder. Each step prints only\n * what differs from the builder's own default.\n *\n * The type builder spells the column as Drizzle does: the SQL column name as\n * its leading argument (left out when it is the snake_case of the key), then\n * Drizzle's config (`col.varchar({ length: 160 })`, `col.timestamp({ withTimezone: true })`,\n * `col.text({ enum: [...] })`). Then:\n *\n * 1. `.primaryKey()`\n * 2. `.notNull()` — left out when `.primaryKey()` implies it\n * 3. `.unique()`\n * 4. the default: `.default(v)` / `.default(sql\\`…\\`)` / `.defaultNow()` / `.defaultRandom()` /\n * `.generatedByDefaultAsIdentity()` / `.dbDefault()`\n * 5. `.generatedAlwaysAs(sql\\`…\\`)`\n * 6. the stamp: `.onCreateNow()` / `.onUpdateNow()` / `.onCreateUser()` / `.onUpdateUser()`\n * 7. `.userId()` — what the column holds, beside the stamp that may fill it\n * 8. `.oneOf([...])` — on a number column (a text column says `{ enum }`)\n * 9. `.validate({...})`\n * 10. `.transform(...)`\n * 11. `.readOnly()` — left out when `.generatedAlwaysAs()` implies it\n * 12. `.private()`\n * 13. `.access({...})`\n * 14. `.describe(text)`\n *\n * An array prints its item's chain, then `.array()`, then these modifiers.\n * `.multiple()` belongs to the type builder (`col.storage({...}).multiple()`):\n * every modifier after it applies to the `TEXT[]` column, and a per-file\n * `.validate()` sits before it.\n *\n * @group Schema\n */\nexport const COLUMN_MODIFIER_ORDER = [\n \"primaryKey\", \"notNull\", \"unique\", \"default\", \"generatedAlwaysAs\", \"stamp\", \"userId\",\n \"oneOf\", \"validate\", \"transform\", \"readOnly\", \"private\", \"access\", \"describe\"\n] as const;\n\nconst STAMP_LINKS: Record<string, string> = {\n \"create:now\": \"onCreateNow\",\n \"update:now\": \"onUpdateNow\",\n \"create:user\": \"onCreateUser\",\n \"update:user\": \"onUpdateUser\"\n};\n\n/**\n * The builder chain of one column, as a doc.\n *\n * @param key The column's key, to leave out a SQL name that only repeats its snake_case.\n * @param declaresTransform The column has a transform although `def.transform`\n * carries no function (a descriptor says so with a flag).\n * @param inheritedName For an array's item: the array column's SQL name, which\n * Drizzle's spelling writes on the item's builder (`col.text(\"tag_list\").array()`).\n */\nexport function columnChain(def: ColumnDef, ctx: ColumnPrintContext, key: string | undefined, declaresTransform: boolean, inheritedName?: string): Doc {\n ctx.used.add(\"col\");\n const name = inheritedName ?? (def.column !== undefined && !(key !== undefined && def.column === toSnakeCase(key)) ? def.column : undefined);\n const base = typeBuilder(def, ctx, name);\n const parts: Doc[] = [base];\n if (def.primaryKey) parts.push(link(\"primaryKey\"));\n if (def.notNull && !def.primaryKey) parts.push(link(\"notNull\"));\n if (def.unique) parts.push(link(\"unique\"));\n if (def.default !== undefined) {\n switch (def.default.kind) {\n case \"literal\":\n parts.push(link(\"default\", [valueDoc(def.default.value, `${ctx.path}.default`)]));\n break;\n case \"sql\":\n if (def.default.expression === \"now()\" && TEMPORAL_KINDS.has(def.type.kind)) {\n parts.push(link(\"defaultNow\"));\n } else {\n ctx.used.add(\"sql\");\n parts.push(link(\"default\", [text(printSqlTemplate(def.default.expression))]));\n }\n break;\n case \"random-uuid\":\n parts.push(link(\"defaultRandom\"));\n break;\n case \"identity\":\n parts.push(link(\"generatedByDefaultAsIdentity\"));\n break;\n case \"database\":\n parts.push(link(\"dbDefault\"));\n break;\n }\n }\n if (def.generatedAs !== undefined) {\n ctx.used.add(\"sql\");\n parts.push(link(\"generatedAlwaysAs\", [text(printSqlTemplate(def.generatedAs))]));\n }\n if (def.stamp !== undefined) {\n const method = STAMP_LINKS[`${def.stamp.on}:${def.stamp.value}`];\n if (method === undefined) throw new TablePrintError(`${ctx.path}.stamp`, `unknown stamp ${JSON.stringify(def.stamp)}.`);\n parts.push(link(method));\n }\n if (def.semantic === \"user\") parts.push(link(\"userId\"));\n if (def.oneOf !== undefined && !oneOfInConfig(def)) parts.push(link(\"oneOf\", [valueDoc(def.oneOf, `${ctx.path}.oneOf`)]));\n if (def.validate !== undefined) parts.push(link(\"validate\", [validationDoc(def.validate, ctx.path)]));\n const transform = transformLink(declaresTransform, def.transform, \"\", ctx);\n if (transform) parts.push(transform);\n if (def.readOnly && def.generatedAs === undefined) parts.push(link(\"readOnly\"));\n if (def.private) parts.push(link(\"private\"));\n if (def.access !== undefined) parts.push(link(\"access\", [valueDoc(def.access, `${ctx.path}.access`)]));\n if (def.description !== undefined) parts.push(link(\"describe\", [text(printString(def.description))]));\n return parts.length === 1 ? base : concat(parts);\n}\n\nconst JSON_SIMPLE: Readonly<Record<string, string>> = {\n number: \"json.number\",\n boolean: \"json.boolean\",\n date: \"json.date\",\n geopoint: \"json.geopoint\",\n unknown: \"json.unknown\"\n};\n\n/**\n * The builder of one node of a JSON shape, as a doc. Modifier order:\n * `.required()` → `.default(v)` → `.onCreateNow()` / `.onUpdateNow()` /\n * `.onCreateUser()` / `.onUpdateUser()` → `.userId()` → `.oneOf([...])` → `.validate({...})` → `.transform(...)` → `.describe(text)`.\n *\n * @param relative The node's path inside the column, for nested transforms.\n */\nexport function jsonShapeDoc(shape: JsonShapeDef, ctx: ColumnPrintContext, relative: string): Doc {\n ctx.used.add(\"json\");\n const here = relative === \"\" ? ctx.path : `${ctx.path} (at \"${relative}\")`;\n let base: Doc;\n switch (shape.kind) {\n case \"string\":\n base = shape.storage !== undefined ? call(\"json.storage\", [storageDoc(shape.storage, here)]) : call(\"json.string\");\n break;\n case \"object\": {\n const fields = Object.entries(shape.fields).map(([key, field]): [string, Doc] =>\n [key, jsonShapeDoc(field, ctx, joinTransformPath(relative, key))]);\n const args: Doc[] = [object(fields)];\n if (shape.additional === true) args.push(object([[\"additional\", text(\"true\")]]));\n base = call(\"json.object\", args);\n break;\n }\n case \"array\":\n base = call(\"json.array\", [jsonShapeDoc(shape.of, ctx, joinTransformPath(relative, \"[]\"))]);\n break;\n case \"oneOf\": {\n const variants = Object.entries(shape.variants).map(([key, variant]): [string, Doc] =>\n [key, jsonShapeDoc(variant, ctx, joinTransformPath(relative, key))]);\n const args: Doc[] = [object(variants)];\n const options: [string, Doc][] = [];\n if (shape.typeField !== \"type\") options.push([\"typeField\", text(printString(shape.typeField))]);\n if (shape.valueField !== \"value\") options.push([\"valueField\", text(printString(shape.valueField))]);\n if (options.length > 0) args.push(object(options));\n base = call(\"json.oneOf\", args);\n break;\n }\n default:\n base = call(JSON_SIMPLE[shape.kind]);\n break;\n }\n const parts: Doc[] = [base];\n if (shape.required === true) parts.push(link(\"required\"));\n if (shape.default !== undefined) parts.push(link(\"default\", [valueDoc(shape.default, `${here}.default`)]));\n if (shape.kind === \"date\" && shape.stamp !== undefined) parts.push(link(shape.stamp === \"create\" ? \"onCreateNow\" : \"onUpdateNow\"));\n if (shape.kind === \"string\" && shape.stamp !== undefined) parts.push(link(shape.stamp === \"createUser\" ? \"onCreateUser\" : \"onUpdateUser\"));\n if (shape.kind === \"string\" && shape.semantic === \"user\") {\n if (shape.storage !== undefined) throw new TablePrintError(here, \"`.userId()` on `json.storage()`; it applies to `json.string()`.\");\n parts.push(link(\"userId\"));\n }\n if ((shape.kind === \"string\" || shape.kind === \"number\") && shape.oneOf !== undefined) {\n parts.push(link(\"oneOf\", [valueDoc(shape.oneOf, `${here}.oneOf`)]));\n }\n if ((shape.kind === \"string\" || shape.kind === \"number\" || shape.kind === \"date\" || shape.kind === \"array\") && shape.validate !== undefined) {\n parts.push(link(\"validate\", [validationDoc(shape.validate, here)]));\n }\n const transform = transformLink(false, shape.transform, relative, ctx);\n if (transform) parts.push(transform);\n if (shape.description !== undefined) parts.push(link(\"describe\", [text(printString(shape.description))]));\n return parts.length === 1 ? base : concat(parts);\n}\n\n/**\n * The builder chain of one column: `col.uuid().primaryKey().defaultRandom()`.\n *\n * Deterministic, in the canonical modifier order ({@link COLUMN_MODIFIER_ORDER}),\n * printing only what differs from the builder's defaults. Throws a\n * {@link TablePrintError} for what no chain reproduces — a transform without\n * its source, a type with no builder.\n *\n * @group Schema\n */\nexport function printColumn(def: ColumnDef, options: PrintColumnOptions = {}): string {\n const transforms: Record<string, string> = { ...options.transforms };\n if (options.transform !== undefined) transforms[\"\"] = options.transform;\n const ctx: ColumnPrintContext = {\n path: options.key ?? \"column\",\n transforms,\n used: new Set(),\n origin: \"\",\n sourceHint: columnOptionHint,\n ...(options.enumIdentifier !== undefined ? { enumIdentifier: options.enumIdentifier } : {})\n };\n return render(columnChain(def, ctx, options.key, false));\n}\n\n/**\n * The builder of a JSON shape: `json.object({ title: json.string().required() })`.\n *\n * @param transforms Sources of the transforms inside the shape, by path\n * (`\"\"` the node itself, `\"title\"`, `\"[].text\"`).\n *\n * @group Schema\n */\nexport function printJsonShape(shape: JsonShapeDef, transforms: Readonly<Record<string, string>> = {}): string {\n const ctx: ColumnPrintContext = { path: \"json\", transforms, used: new Set(), origin: \"\", sourceHint: columnOptionHint };\n return render(jsonShapeDoc(shape, ctx, \"\"));\n}\n","import type {\n AnyTableDef,\n AnyViewDef,\n ColumnDef,\n ColumnDescriptor,\n DefaultRls,\n RelationDef,\n RelationDescriptor,\n RlsDescriptor,\n RlsPosture,\n TableDescriptor,\n TableIndex\n} from \"@rebasepro/types\";\nimport { isColumnBuilder, isTableDef, isViewDef, resourceKeyOf } from \"@rebasepro/types\";\n\nimport { getTableVarName } from \"../util/relations\";\nimport {\n deriveBelongsToLocalKey,\n deriveJunctionSourceKey,\n deriveJunctionTable,\n deriveJunctionTargetKey,\n deriveTargetForeignKey\n} from \"./derive-names\";\nimport { columnDefOfDescriptor } from \"./descriptor-to-def\";\nimport { columnChain, joinTransformPath, nestedTransforms } from \"./print-column\";\nimport type { ColumnPrintContext, SchemaBuilderName } from \"./print-column\";\nimport { array, call, object, printMultilineString, printString, render, text } from \"./print-doc\";\nimport type { Doc } from \"./print-doc\";\nimport { TablePrintError, valueDoc } from \"./print-value\";\n\nexport { TablePrintError } from \"./print-value\";\nexport {\n COLUMN_MODIFIER_ORDER,\n joinTransformPath,\n printByteSize,\n printColumn,\n printJsonShape,\n printSqlTemplate\n} from \"./print-column\";\nexport type { PrintColumnOptions, SchemaBuilderName } from \"./print-column\";\n\n/**\n * Turning a table back into `defineTable` source.\n *\n * One printer for every writer of `backend/schema/*.ts`: the migration codemod\n * (legacy collections → tables), database introspection (descriptors → tables)\n * and the Studio schema editor (one column or relation at a time). They bring\n * their own AST handling and call this for the text, so a column prints the\n * same whoever writes it.\n *\n * Deterministic: the same input is the same bytes — no dates, no environment.\n * Lossless or loud: a value that is code (a hook, a transform) is printed from\n * the source text the caller supplies, and refused with a\n * {@link TablePrintError} when none was supplied.\n */\n\n/** The import specifier the builders come from unless the caller names another. */\nexport const DEFAULT_SCHEMA_SPECIFIER = \"@rebasepro/server/schema\";\n\n/**\n * The table-level key order of a printed `defineTable` / `defineAuthTable`.\n * `auth` (from `defineAuthTable`) comes last.\n *\n * @group Schema\n */\nexport const TABLE_KEY_ORDER = [\n \"slug\", \"table\", \"schema\", \"database\", \"description\", \"columns\", \"relations\", \"rls\", \"defaultPolicies\",\n \"tenant\", \"softDelete\", \"history\", \"search\", \"indexes\", \"hooks\", \"strictWrites\", \"metadata\", \"auth\"\n] as const;\n\n/**\n * The key order of a printed `defineView`.\n *\n * @group Schema\n */\nexport const VIEW_KEY_ORDER = [\n \"slug\", \"table\", \"schema\", \"database\", \"description\", \"query\", \"materialized\", \"roles\", \"columns\", \"relations\",\n \"indexes\", \"hooks\", \"metadata\"\n] as const;\n\n/** The seven table hooks, in the order a descriptor's flags print. */\nconst HOOK_ORDER = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/**\n * The name of a table hook.\n *\n * @group Schema\n */\nexport type TableHookName = typeof HOOK_ORDER[number];\n\n/**\n * How a relation's target is written in the printed module.\n *\n * @group Schema\n */\nexport interface PrintTarget {\n /** The identifier the target table is bound to: what the thunk returns, `() => users`. */\n identifier: string;\n /** The module to import it from, `\"./users\"`. No import when absent (the same module). */\n importPath?: string;\n /**\n * The target's SQL table, when known. Lets a descriptor's junction table\n * be left out when it is the derived one; without it `through` is printed.\n */\n table?: string;\n /** Whether the target is a view. A view never gets a `FOREIGN KEY`, so `constraint: false` is not printed for it. */\n kind?: \"table\" | \"view\";\n}\n\n/**\n * Maps a relation's target to the identifier and module it is printed with.\n * A definition's target is known by name and slug; a descriptor's by slug.\n *\n * @group Schema\n */\nexport type PrintTargetResolver = (target: { name?: string; slug: string }) => PrintTarget;\n\n/**\n * Source text for what is code rather than data, printed verbatim.\n *\n * @group Schema\n */\nexport interface TableSources {\n /**\n * Field-level transforms by path: `\"title\"` the column, `\"tags[]\"` an array\n * column's element, `\"seo.title\"` a field of a JSON column,\n * `\"content[].image\"` inside a JSON array, `\"tags.pivot.note\"` a pivot\n * column of the relation `tags`.\n */\n transforms?: Readonly<Record<string, string>>;\n /**\n * The table hooks: the whole `hooks` expression as one string, or each\n * hook's source by name.\n */\n hooks?: string | Readonly<Partial<Record<TableHookName, string>>>;\n /** The user-lifecycle functions of `defineAuthTable`'s `auth`. */\n auth?: { onCreateUser?: string; onResetPassword?: string };\n}\n\n/**\n * Options of {@link printTableSource} and {@link printTableModule}.\n *\n * @group Schema\n */\nexport interface PrintTableOptions {\n /** The identifier of `export const <identifier>`. The camelCase of the table's name when omitted. */\n identifier?: string;\n /** Where the builders are imported from. {@link DEFAULT_SCHEMA_SPECIFIER} when omitted. */\n specifier?: string;\n /** How relation targets are written. `./<name>` exporting the camelCase of the name when omitted. */\n resolveTarget?: PrintTargetResolver;\n /** Source text of the hooks and transforms. */\n sources?: TableSources;\n /** Extra import lines, printed verbatim after the generated ones (what hook sources reference). */\n extraImports?: readonly string[];\n}\n\n/**\n * One table identifier imported for a relation thunk.\n *\n * @group Schema\n */\nexport interface PrintedTableImport {\n /** The bound name. */\n identifier: string;\n /** The module it comes from. */\n importPath: string;\n}\n\n/**\n * What a printed table needs imported.\n *\n * @group Schema\n */\nexport interface PrintedImports {\n /** The builders' module. */\n specifier: string;\n /** The builders used, in import order (`define*`, `col`, `rel`, `json`). */\n builders: SchemaBuilderName[];\n /** The related tables, in the order their relations are declared, each once. */\n tables: PrintedTableImport[];\n}\n\n/**\n * A printed table: the `export const` statement and what it needs imported.\n *\n * @group Schema\n */\nexport interface PrintedTable {\n /** The exported identifier. */\n identifier: string;\n /**\n * `export const <identifier> = defineTable(\"<name>\", { … });`, preceded by\n * a `const <name>Enum = pgEnum(\"<type>\", [...]);` for each named enum type\n * its columns use.\n */\n code: string;\n /** What the statement needs imported. */\n imports: PrintedImports;\n}\n\n/**\n * What {@link printRelation} needs besides the relation.\n *\n * @group Schema\n */\nexport interface PrintRelationContext {\n /** How the target is written. `./<name>` exporting the camelCase of the name when omitted. */\n resolveTarget?: PrintTargetResolver;\n /** For a descriptor: the table that declares the relation, to leave derived names out. */\n owner?: TableDescriptor;\n /** Transform sources of pivot columns, by `<relation>.pivot.<column>` path. */\n transforms?: Readonly<Record<string, string>>;\n}\n\n/** Anything the module printer takes. */\nexport type PrintableTable = AnyTableDef | AnyViewDef | TableDescriptor;\n\nconst BUILDER_ORDER: readonly SchemaBuilderName[] = [\"defineTable\", \"defineAuthTable\", \"defineView\", \"col\", \"rel\", \"json\", \"pgEnum\", \"sql\"];\n\nconst RESERVED = new Set([\n \"break\", \"case\", \"catch\", \"class\", \"const\", \"continue\", \"debugger\", \"default\", \"delete\", \"do\", \"else\", \"enum\",\n \"export\", \"extends\", \"false\", \"finally\", \"for\", \"function\", \"if\", \"import\", \"in\", \"instanceof\", \"new\", \"null\",\n \"return\", \"super\", \"switch\", \"this\", \"throw\", \"true\", \"try\", \"typeof\", \"var\", \"void\", \"while\", \"with\", \"yield\",\n \"let\", \"static\", \"implements\", \"interface\", \"package\", \"private\", \"protected\", \"public\", \"await\", \"arguments\",\n \"eval\", \"undefined\", \"NaN\", \"Infinity\",\n // The builders a printed module imports: a table bound to one would shadow it.\n ...BUILDER_ORDER\n]);\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * The identifier a table is exported as: the camelCase of its name, made a\n * valid identifier (a leading digit is prefixed), with `Table` appended when\n * it is a reserved word or the name of a builder the module imports.\n *\n * @group Schema\n */\nexport function tableIdentifier(name: string): string {\n const identifier = getTableVarName(name);\n return RESERVED.has(identifier) ? `${identifier}Table` : identifier;\n}\n\nfunction checkIdentifier(identifier: string, what: string): string {\n if (!IDENTIFIER.test(identifier) || RESERVED.has(identifier)) {\n throw new TablePrintError(what, `\"${identifier}\" is not a usable identifier: it must be a JavaScript identifier, not a reserved word or a builder's name.`);\n }\n return identifier;\n}\n\nconst defaultResolver: PrintTargetResolver = target => {\n const name = target.name ?? target.slug;\n return { identifier: tableIdentifier(name), importPath: `./${name}` };\n};\n\n/** Everything printing one table collects and consults. */\ninterface TableState {\n label: string;\n identifier: string;\n used: Set<SchemaBuilderName>;\n imports: PrintedTableImport[];\n transforms: Readonly<Record<string, string>>;\n resolve: PrintTargetResolver;\n /** Whether a relation target is the table being printed. */\n isSelf: (target: { def?: unknown; slug: string }) => boolean;\n /**\n * The named enum types the table's columns use, by type name: each is\n * declared once with `pgEnum` above the table. Absent when nothing is\n * printed above (a lone relation): a named enum then inlines its `pgEnum`.\n */\n enums?: Map<string, { identifier: string; values: readonly string[] }>;\n}\n\n/**\n * The identifier a named enum type is bound to in printed source: the\n * camelCase of its name with `Enum` appended (`post_status` → `postStatusEnum`,\n * `issue_status_enum` → `issueStatusEnum`), as Drizzle projects name theirs.\n *\n * @group Schema\n */\nexport function enumIdentifier(enumName: string): string {\n const camel = getTableVarName(enumName);\n const identifier = /Enum$/.test(camel) ? camel : `${camel}Enum`;\n return RESERVED.has(identifier) ? `${identifier}Type` : identifier;\n}\n\n/** Records a named enum the table uses and returns its binding; one name with two lists of values is refused. */\nfunction enumBinding(state: TableState, enums: NonNullable<TableState[\"enums\"]>, path: string): (enumName: string, values: readonly string[]) => string {\n return (enumName, values) => {\n const known = enums.get(enumName);\n if (known !== undefined) {\n if (known.values.join(\"\\u0000\") !== values.join(\"\\u0000\")) {\n throw new TablePrintError(path, `the enum type \"${enumName}\" is declared with two different lists of values in one table.`);\n }\n return known.identifier;\n }\n let identifier = enumIdentifier(enumName);\n const taken = new Set([state.identifier, ...state.imports.map(entry => entry.identifier), ...[...enums.values()].map(entry => entry.identifier)]);\n while (taken.has(identifier)) identifier = `${identifier}Type`;\n enums.set(enumName, { identifier, values });\n state.used.add(\"pgEnum\");\n return identifier;\n };\n}\n\nfunction columnContext(state: TableState, path: string, prefix: string): ColumnPrintContext {\n return {\n path,\n transforms: nestedTransforms(state.transforms, prefix),\n used: state.used,\n origin: \"\",\n sourceHint: relative => `as \\`sources.transforms[\"${relative === \"\" ? prefix : joinTransformPath(prefix, relative)}\"]\\``,\n ...(state.enums !== undefined ? { enumIdentifier: enumBinding(state, state.enums, path) } : {})\n };\n}\n\n/** A `columns` map (or a pivot) as a doc, one column per line. */\nfunction columnsDoc(columns: readonly { key: string; def: ColumnDef; declaresTransform: boolean }[], state: TableState, pathPrefix: string, transformPrefix: string): Doc {\n return object(\n columns.map(({ key, def, declaresTransform }): [string, Doc] => [\n key,\n columnChain(def, columnContext(state, `${pathPrefix}.${key}`, joinTransformPath(transformPrefix, key)), key, declaresTransform)\n ]),\n true\n );\n}\n\nfunction columnsOfDef(columns: object, path: string): { key: string; def: ColumnDef; declaresTransform: boolean }[] {\n return Object.entries(columns).map(([key, builder]: [string, unknown]) => {\n if (!isColumnBuilder(builder)) throw new TablePrintError(`${path}.${key}`, \"it is not a `col.*` builder.\");\n return { key, def: builder.def, declaresTransform: false };\n });\n}\n\nfunction columnsOfDescriptor(columns: readonly ColumnDescriptor[]): { key: string; def: ColumnDef; declaresTransform: boolean }[] {\n return columns\n .filter(column => column.derived !== true)\n .map(column => ({ key: column.key, def: columnDefOfDescriptor(column), declaresTransform: column.transforms !== undefined }));\n}\n\n// ── Relations ────────────────────────────────────────────────────────────────\n\n/** Each relation kind's options, in print order; the field rules every kind takes come last. */\nconst RELATION_KEYS: Readonly<Record<RelationDef[\"kind\"], readonly string[]>> = {\n belongsTo: [\"localKey\", \"notNull\", \"unique\", \"onDelete\", \"onUpdate\", \"index\", \"constraint\", \"access\", \"private\"],\n hasOne: [\"foreignKey\", \"sourceKey\", \"access\", \"private\"],\n hasMany: [\"foreignKey\", \"sourceKey\", \"orderBy\", \"access\", \"private\"],\n manyToMany: [\"through\", \"sourceKey\", \"targetKey\", \"pivot\", \"onDelete\", \"access\", \"private\"],\n via: [\"steps\", \"cardinality\", \"access\", \"private\"]\n};\n\n/**\n * The thunk `() => <identifier>`, recording the import it needs. Never\n * annotated: `rel.*` take a `TableThunk` (`() => void`), so tables that point\n * at each other compile as written.\n */\nfunction targetThunk(state: TableState, target: { name?: string; slug: string; def?: unknown }, path: string): { doc: Doc; printed: PrintTarget } {\n const self = state.isSelf(target);\n const printed: PrintTarget = self ? { identifier: state.identifier } : state.resolve({ name: target.name, slug: target.slug });\n if (!self) {\n checkIdentifier(printed.identifier, `${path} (target identifier)`);\n if (printed.importPath !== undefined && !state.imports.some(entry => entry.identifier === printed.identifier && entry.importPath === printed.importPath)) {\n state.imports.push({ identifier: printed.identifier, importPath: printed.importPath });\n }\n }\n return { doc: text(`() => ${printed.identifier}`), printed };\n}\n\nfunction relationOfDef(name: string, relation: RelationDef, state: TableState): Doc {\n const path = `${state.label}.relations.${name}`;\n state.used.add(\"rel\");\n let target: unknown;\n try {\n target = relation.target();\n } catch (error) {\n throw new TablePrintError(path, `its target thunk threw: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (!isTableDef(target) && !isViewDef(target)) {\n throw new TablePrintError(path, \"its target thunk does not return a `defineTable` / `defineView` result.\");\n }\n const { doc: thunk } = targetThunk(state, { name: target.name, slug: target.config.slug ?? target.name, def: target }, path);\n const known = RELATION_KEYS[relation.kind];\n for (const key of Object.keys(relation)) {\n if (key === \"brand\" || key === \"kind\" || key === \"target\") continue;\n if (!known.includes(key)) throw new TablePrintError(`${path}.${key}`, `it is not an option of \\`rel.${relation.kind}\\`.`);\n }\n const entries: [string, Doc][] = [];\n for (const key of known) {\n const value: unknown = Reflect.get(relation, key);\n if (value === undefined) continue;\n if (key === \"pivot\" && typeof value === \"object\" && value !== null) {\n const pivot = columnsOfDef(value, `${path}.pivot`);\n entries.push([key, columnsDoc(pivot, state, `${path}.pivot`, `${name}.pivot`)]);\n } else {\n entries.push([key, valueDoc(value, `${path}.${key}`)]);\n }\n }\n return call(`rel.${relation.kind}`, entries.length > 0 || relation.kind === \"via\" ? [thunk, object(entries)] : [thunk]);\n}\n\nfunction relationOfDescriptor(relation: RelationDescriptor, owner: TableDescriptor, state: TableState): Doc {\n const path = `${state.label}.relations.${relation.name}`;\n state.used.add(\"rel\");\n const { doc: thunk, printed } = targetThunk(state, { slug: relation.target }, path);\n const entries: [string, Doc][] = [];\n const str = (value: string): Doc => text(printString(value));\n switch (relation.kind) {\n case \"belongsTo\": {\n if (relation.localKey !== deriveBelongsToLocalKey(relation.name, undefined)) entries.push([\"localKey\", str(relation.localKey)]);\n const derived = owner.columns.find(column => column.key === relation.localField && column.derived === true);\n if (derived && !derived.nullable && !(owner.tenant?.field === derived.key)) entries.push([\"notNull\", text(\"true\")]);\n if (derived?.unique) entries.push([\"unique\", text(\"true\")]);\n if (relation.onDelete !== undefined) entries.push([\"onDelete\", str(relation.onDelete)]);\n if (relation.onUpdate !== undefined) entries.push([\"onUpdate\", str(relation.onUpdate)]);\n if (!relation.index) entries.push([\"index\", text(\"false\")]);\n const targetIsView = printed.kind === \"view\" || (state.isSelf({ slug: relation.target }) && owner.kind === \"view\");\n if (!relation.constraint && owner.kind === \"table\" && !targetIsView) entries.push([\"constraint\", text(\"false\")]);\n break;\n }\n case \"hasOne\":\n case \"hasMany\":\n if (relation.foreignKey !== deriveTargetForeignKey(owner.slug, undefined)) entries.push([\"foreignKey\", str(relation.foreignKey)]);\n if (relation.sourceKey !== undefined) entries.push([\"sourceKey\", str(relation.sourceKey)]);\n if (relation.kind === \"hasMany\" && relation.orderBy !== undefined) entries.push([\"orderBy\", valueDoc(relation.orderBy, `${path}.orderBy`)]);\n break;\n case \"manyToMany\": {\n const targetTable = state.isSelf({ slug: relation.target }) ? owner.table : printed.table;\n if (targetTable === undefined || relation.through.table !== deriveJunctionTable(owner.table, targetTable, undefined)) {\n entries.push([\"through\", str(relation.through.table)]);\n }\n if (relation.through.sourceKey !== deriveJunctionSourceKey(owner.slug, undefined)) entries.push([\"sourceKey\", str(relation.through.sourceKey)]);\n if (relation.through.targetKey !== deriveJunctionTargetKey(relation.name, undefined)) entries.push([\"targetKey\", str(relation.through.targetKey)]);\n if (relation.through.pivot.length > 0) {\n entries.push([\"pivot\", columnsDoc(columnsOfDescriptor(relation.through.pivot), state, `${path}.pivot`, `${relation.name}.pivot`)]);\n }\n if (relation.onDelete !== undefined) entries.push([\"onDelete\", str(relation.onDelete)]);\n break;\n }\n case \"via\":\n entries.push([\"steps\", valueDoc(relation.steps, `${path}.steps`)]);\n if (relation.cardinality === \"one\") entries.push([\"cardinality\", str(\"one\")]);\n break;\n }\n if (relation.access !== undefined) entries.push([\"access\", valueDoc(relation.access, `${path}.access`)]);\n if (relation.private === true) entries.push([\"private\", text(\"true\")]);\n return call(`rel.${relation.kind}`, entries.length > 0 ? [thunk, object(entries)] : [thunk]);\n}\n\n// ── rls, hooks, indexes ──────────────────────────────────────────────────────\n\n/** `rls` as a doc: a posture string, or one rule per line, each rule's keys in the order written. */\nfunction rlsDoc(rls: RlsPosture | DefaultRls | readonly unknown[], path: string): Doc {\n if (typeof rls === \"string\") return text(printString(rls));\n return array(rls.map((rule, index) => valueDoc(rule, `${path}[${index}]`)), true);\n}\n\nfunction rlsOfDescriptor(rls: RlsDescriptor, path: string): Doc {\n if (rls.inherited) return text(printString(\"inherit\"));\n if (rls.posture === \"admin-only\") return text(printString(\"admin-only\"));\n if (rls.posture === \"view\") {\n throw new TablePrintError(path, \"a view has no `rls` of its own: a plain view is governed by the tables it reads, a materialized one by `roles`. Print the view, not its rls.\");\n }\n if (rls.rules.length === 0) throw new TablePrintError(path, \"the descriptor has rule-based rls with no rules, which `defineTable` refuses. Say `\\\"admin-only\\\"` or list the rules.\");\n return rlsDoc(rls.rules, path);\n}\n\nfunction hooksDoc(hooks: object | undefined, flags: readonly TableHookName[], state: TableState, sources: TableSources[\"hooks\"]): Doc | undefined {\n const path = `${state.label}.hooks`;\n if (typeof sources === \"string\") return text(sources);\n const names: string[] = hooks !== undefined ? Object.keys(hooks) : [...flags];\n if (hooks === undefined && names.length === 0) return undefined;\n const entries: [string, Doc][] = [];\n for (const name of names) {\n const value: unknown = hooks !== undefined ? Reflect.get(hooks, name) : undefined;\n if (value === undefined && hooks !== undefined) continue;\n if (hooks !== undefined && typeof value !== \"function\") {\n throw new TablePrintError(`${path}.${name}`, \"a hook must be a function.\");\n }\n const source = sources !== undefined ? Reflect.get(sources, name) : undefined;\n if (typeof source !== \"string\") {\n throw new TablePrintError(`${path}.${name}`, `the hook is a function, which cannot be printed from its value. Pass its source text as \\`sources.hooks.${name}\\`.`);\n }\n entries.push([name, text(source)]);\n }\n return object(entries, true);\n}\n\n/**\n * The `rls` of a table as source: `\"admin-only\"`, `\"inherit\"`, or the rules,\n * one per line, each rule's keys in the order written (a policy's name is a\n * hash of its rule as written, so a rule is never reordered).\n *\n * @group Schema\n */\nexport function printRls(rls: RlsPosture | DefaultRls | RlsDescriptor): string {\n if (typeof rls === \"object\" && \"posture\" in rls) return render(rlsOfDescriptor(rls, \"rls\"));\n return render(rlsDoc(rls, \"rls\"));\n}\n\n/**\n * The `indexes` of a table as source.\n *\n * @group Schema\n */\nexport function printIndexes(indexes: readonly TableIndex[]): string {\n return render(valueDoc(indexes, \"indexes\"));\n}\n\n/**\n * A data value as source, the way the table printer writes every data-valued\n * key: a table-level option (`tenant`, `search`, `softDelete`, `metadata`…),\n * or one rule of an `rls` list. Objects keep the key order they were given (a\n * rule is never reordered: its policy's name is a hash of the rule as\n * written). Throws a {@link TablePrintError} for a function or a value with no\n * literal form.\n *\n * @param path Where the value sits, for the error: `posts.tenant`.\n *\n * @group Schema\n */\nexport function printSchemaValue(value: unknown, path: string): string {\n return render(valueDoc(value, path));\n}\n\n/**\n * One relation as source: `rel.belongsTo(() => users, { onDelete: \"restrict\" })`.\n *\n * A definition prints with the options it was written with; a descriptor\n * prints the options that differ from what the compiler derives (give\n * `context.owner`, the declaring table's descriptor).\n *\n * @group Schema\n */\nexport function printRelation(name: string, relation: RelationDef | RelationDescriptor, context: PrintRelationContext = {}): string {\n const state: TableState = {\n label: context.owner?.name ?? \"table\",\n identifier: context.owner ? tableIdentifier(context.owner.name) : \"table\",\n used: new Set(),\n imports: [],\n transforms: context.transforms ?? {},\n resolve: context.resolveTarget ?? defaultResolver,\n isSelf: target => context.owner !== undefined && target.def === undefined && target.slug === context.owner.slug\n };\n if (\"brand\" in relation) return render(relationOfDef(name, relation, state));\n if (!context.owner) {\n throw new TablePrintError(`relations.${name}`, \"a relation descriptor prints against the table that declares it: pass `context.owner`.\");\n }\n return render(relationOfDescriptor(relation, context.owner, state));\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────────\n\nconst TABLE_CONFIG_KEYS = new Set<string>(TABLE_KEY_ORDER);\nconst VIEW_CONFIG_KEYS = new Set<string>(VIEW_KEY_ORDER);\n\nfunction checkKnownKeys(config: object, known: ReadonlySet<string>, path: string, builder: string): void {\n for (const key of Object.keys(config)) {\n if (!known.has(key) || key === \"auth\") {\n if (Reflect.get(config, key) === undefined) continue;\n throw new TablePrintError(`${path}.${key}`, `it is not an option of \\`${builder}\\`.`);\n }\n }\n}\n\nfunction authDoc(auth: object, state: TableState, sources: TableSources[\"auth\"], declaredHooks: readonly AuthHookName[] = []): Doc | undefined {\n const entries: [string, Doc][] = [];\n const hookDoc = (key: AuthHookName): Doc => {\n const source = sources?.[key];\n if (source === undefined) {\n throw new TablePrintError(`${state.label}.auth.${key}`, `it is a function, which cannot be printed from its value. Pass its source text as \\`sources.auth.${key}\\`.`);\n }\n return text(source);\n };\n for (const [key, value] of Object.entries(auth)) {\n if (value === undefined) continue;\n if (typeof value === \"function\") {\n if (key !== \"onCreateUser\" && key !== \"onResetPassword\") {\n throw new TablePrintError(`${state.label}.auth.${key}`, \"it is a function, and only `onCreateUser` and `onResetPassword` are.\");\n }\n entries.push([key, hookDoc(key)]);\n } else {\n entries.push([key, valueDoc(value, `${state.label}.auth.${key}`)]);\n }\n }\n for (const key of declaredHooks) entries.push([key, hookDoc(key)]);\n return entries.length > 0 ? object(entries) : undefined;\n}\n\n/** A user-lifecycle hook of `defineAuthTable`'s `auth`. */\ntype AuthHookName = \"onCreateUser\" | \"onResetPassword\";\n\nfunction newState(name: string, identifier: string, options: PrintTableOptions, isSelf: TableState[\"isSelf\"]): TableState {\n return {\n label: name,\n identifier,\n used: new Set(),\n imports: [],\n transforms: options.sources?.transforms ?? {},\n resolve: options.resolveTarget ?? defaultResolver,\n isSelf,\n enums: new Map()\n };\n}\n\nfunction definitionDoc(def: AnyTableDef | AnyViewDef, state: TableState, options: PrintTableOptions): Doc {\n const config = def.config;\n const entries: [string, Doc][] = [];\n const put = (key: string, value: unknown): void => {\n if (value !== undefined) entries.push([key, valueDoc(value, `${state.label}.${key}`)]);\n };\n const columns = (): Doc => columnsDoc(columnsOfDef(config.columns, `${state.label}.columns`), state, `${state.label}.columns`, \"\");\n const relations = (): void => {\n if (config.relations === undefined) return;\n entries.push([\"relations\", object(\n Object.entries(config.relations).map(([name, relation]): [string, Doc] => [name, relationOfDef(name, relation, state)]),\n true\n )]);\n };\n const hooks = (): void => {\n const doc = hooksDoc(config.hooks, [], state, options.sources?.hooks);\n if (config.hooks !== undefined && doc) entries.push([\"hooks\", doc]);\n };\n const database = config.database !== undefined ? resourceKeyOf(config.database) : undefined;\n\n if (isViewDef(def)) {\n state.used.add(\"defineView\");\n checkKnownKeys(def.config, VIEW_CONFIG_KEYS, state.label, \"defineView\");\n const view = def.config;\n put(\"slug\", view.slug);\n put(\"table\", view.table);\n put(\"schema\", view.schema);\n put(\"database\", database);\n put(\"description\", view.description);\n entries.push([\"query\", text(printMultilineString(view.query))]);\n put(\"materialized\", view.materialized);\n put(\"roles\", view.roles);\n entries.push([\"columns\", columns()]);\n relations();\n put(\"indexes\", view.indexes);\n hooks();\n put(\"metadata\", view.metadata);\n return call(\"defineView\", [text(printString(def.name)), object(entries, true)]);\n }\n\n const table = def.config;\n const auth = def.auth !== undefined;\n state.used.add(auth ? \"defineAuthTable\" : \"defineTable\");\n checkKnownKeys(table, TABLE_CONFIG_KEYS, state.label, auth ? \"defineAuthTable\" : \"defineTable\");\n put(\"slug\", table.slug);\n put(\"table\", table.table);\n put(\"schema\", table.schema);\n put(\"database\", database);\n put(\"description\", table.description);\n entries.push([\"columns\", columns()]);\n relations();\n entries.push([\"rls\", rlsDoc(table.rls, `${state.label}.rls`)]);\n put(\"defaultPolicies\", table.defaultPolicies);\n put(\"tenant\", table.tenant);\n put(\"softDelete\", table.softDelete);\n put(\"history\", table.history);\n put(\"search\", table.search);\n put(\"indexes\", table.indexes);\n hooks();\n put(\"strictWrites\", table.strictWrites);\n put(\"metadata\", table.metadata);\n if (def.auth !== undefined) {\n const doc = authDoc(def.auth, state, options.sources?.auth);\n if (doc) entries.push([\"auth\", doc]);\n }\n return call(auth ? \"defineAuthTable\" : \"defineTable\", [text(printString(def.name)), object(entries, true)]);\n}\n\nfunction descriptorDoc(descriptor: TableDescriptor, state: TableState, options: PrintTableOptions): Doc {\n const entries: [string, Doc][] = [];\n const put = (key: string, value: unknown): void => {\n if (value !== undefined) entries.push([key, valueDoc(value, `${state.label}.${key}`)]);\n };\n const view = descriptor.kind === \"view\";\n put(\"slug\", descriptor.slug !== descriptor.name ? descriptor.slug : undefined);\n put(\"table\", descriptor.table !== descriptor.name ? descriptor.table : undefined);\n put(\"schema\", descriptor.schema !== \"public\" ? descriptor.schema : undefined);\n put(\"database\", descriptor.database);\n put(\"description\", descriptor.description);\n const columns = object(\n columnsOfDescriptor(descriptor.columns).map(({ key, def, declaresTransform }): [string, Doc] =>\n [key, columnChain(def, columnContext(state, `${state.label}.columns.${key}`, key), key, declaresTransform)]),\n true\n );\n const relations = descriptor.relations.length > 0\n ? object(descriptor.relations.map((relation): [string, Doc] => [relation.name, relationOfDescriptor(relation, descriptor, state)]), true)\n : undefined;\n const hookNames = HOOK_ORDER.filter(name => descriptor.hooks?.[name] === true);\n const hooks = hookNames.length > 0 ? hooksDoc(undefined, hookNames, state, options.sources?.hooks) : undefined;\n\n if (view) {\n state.used.add(\"defineView\");\n if (descriptor.view?.query === undefined) {\n throw new TablePrintError(`${state.label}.query`, \"the view's descriptor carries no query (it is served to admins only). Print from a descriptor that includes it.\");\n }\n entries.push([\"query\", text(printMultilineString(descriptor.view.query))]);\n if (descriptor.view.materialized) {\n put(\"materialized\", true);\n const roles = descriptor.view.roles;\n if (roles !== undefined && !(roles.length === 1 && roles[0] === \"admin\")) put(\"roles\", roles);\n }\n entries.push([\"columns\", columns]);\n if (relations) entries.push([\"relations\", relations]);\n put(\"indexes\", descriptor.indexes);\n if (hooks) entries.push([\"hooks\", hooks]);\n put(\"metadata\", descriptor.metadata);\n return call(\"defineView\", [text(printString(descriptor.name)), object(entries, true)]);\n }\n\n const auth = descriptor.auth !== undefined;\n state.used.add(auth ? \"defineAuthTable\" : \"defineTable\");\n entries.push([\"columns\", columns]);\n if (relations) entries.push([\"relations\", relations]);\n entries.push([\"rls\", rlsOfDescriptor(descriptor.rls, `${state.label}.rls`)]);\n if (!descriptor.rls.defaultPolicies && descriptor.rls.posture === \"rules\") put(\"defaultPolicies\", false);\n else if (descriptor.rls.declaredDefaultPolicies) put(\"defaultPolicies\", true);\n put(\"tenant\", descriptor.tenant);\n put(\"softDelete\", descriptor.softDelete);\n put(\"history\", descriptor.history);\n put(\"search\", descriptor.search);\n put(\"indexes\", descriptor.indexes);\n if (hooks) entries.push([\"hooks\", hooks]);\n put(\"strictWrites\", descriptor.strictWrites);\n put(\"metadata\", descriptor.metadata);\n if (descriptor.auth !== undefined) {\n // The hook flags stand for code that never left the server: printed from `sources.auth`.\n const { hooks: authHooks, ...authOptions } = descriptor.auth;\n const declared = ([\"onCreateUser\", \"onResetPassword\"] as const).filter(name => authHooks?.[name] === true);\n const doc = authDoc(authOptions, state, options.sources?.auth, declared);\n if (doc) entries.push([\"auth\", doc]);\n }\n return call(auth ? \"defineAuthTable\" : \"defineTable\", [text(printString(descriptor.name)), object(entries, true)]);\n}\n\n/**\n * One table as an `export const` statement, with what it needs imported.\n *\n * Takes an authored definition (`defineTable` / `defineAuthTable` /\n * `defineView`, printed as written) or a compiled {@link TableDescriptor}\n * (introspection's output: derived names and defaults are left out, derived\n * foreign-key columns are left to their relation).\n *\n * Keys in {@link TABLE_KEY_ORDER} / {@link VIEW_KEY_ORDER}, columns in the\n * canonical modifier order, four-space indentation, double quotes, no\n * trailing commas.\n *\n * @group Schema\n */\nexport function printTableSource(input: PrintableTable, options: PrintTableOptions = {}): PrintedTable {\n const name = input.name;\n const identifier = options.identifier !== undefined\n ? checkIdentifier(options.identifier, `${name} (identifier)`)\n : tableIdentifier(name);\n let state: TableState;\n let doc: Doc;\n if (isTableDef(input) || isViewDef(input)) {\n state = newState(name, identifier, options, target => target.def === input);\n doc = definitionDoc(input, state, options);\n } else {\n state = newState(name, identifier, options, target => target.def === undefined && target.slug === input.slug);\n doc = descriptorDoc(input, state, options);\n }\n const declarations = [...(state.enums ?? [])].map(([enumName, { identifier: binding, values }]) => {\n const prefix = `const ${binding} = `;\n return `${prefix}${render(call(\"pgEnum\", [text(printString(enumName)), array(values.map(value => text(printString(value))))]), 0, prefix.length)};`;\n });\n const statement = `export const ${identifier} = ${render(doc, 0, `export const ${identifier} = `.length)};`;\n const code = declarations.length > 0 ? `${declarations.join(\"\\n\")}\\n\\n${statement}` : statement;\n return {\n identifier,\n code,\n imports: {\n specifier: options.specifier ?? DEFAULT_SCHEMA_SPECIFIER,\n builders: BUILDER_ORDER.filter(builder => state.used.has(builder)),\n tables: state.imports\n }\n };\n}\n\n/** The import lines of a printed table: builders first, then related tables grouped by module. */\nexport function printImportLines(imports: PrintedImports): string[] {\n const lines = [`import { ${imports.builders.join(\", \")} } from ${printString(imports.specifier)};`];\n const byPath = new Map<string, string[]>();\n for (const entry of imports.tables) {\n const list = byPath.get(entry.importPath) ?? [];\n if (!list.includes(entry.identifier)) list.push(entry.identifier);\n byPath.set(entry.importPath, list);\n }\n for (const [importPath, identifiers] of byPath) lines.push(`import { ${identifiers.join(\", \")} } from ${printString(importPath)};`);\n return lines;\n}\n\n/**\n * One table as a whole module — what `backend/schema/<table>.ts` holds:\n *\n * ```ts\n * import { defineTable, col, rel } from \"@rebasepro/server/schema\";\n * import { users } from \"./users\";\n *\n * export const posts = defineTable(\"posts\", { … });\n * ```\n *\n * @group Schema\n */\nexport function printTableModule(input: PrintableTable, options: PrintTableOptions = {}): string {\n const printed = printTableSource(input, options);\n const imports = [...printImportLines(printed.imports), ...(options.extraImports ?? [])];\n return `${imports.join(\"\\n\")}\\n\\n${printed.code}\\n`;\n}\n\n/**\n * Options of {@link printIndexModule}.\n *\n * @group Schema\n */\nexport interface PrintIndexModuleOptions {\n /** The project's `defaultRls`, exported for every `rls: \"inherit\"` table. */\n defaultRls?: DefaultRls;\n}\n\n/**\n * `backend/schema/index.ts`: one re-export per table, in the order given, and\n * `defaultRls` when the project has one.\n *\n * @group Schema\n */\nexport function printIndexModule(tables: readonly PrintedTableImport[], options: PrintIndexModuleOptions = {}): string {\n const lines = tables.map(table => {\n checkIdentifier(table.identifier, `index (${table.importPath})`);\n return `export { ${table.identifier} } from ${printString(table.importPath)};`;\n });\n if (options.defaultRls !== undefined) {\n const prefix = \"export const defaultRls = \";\n lines.push(\"\", `${prefix}${render(rlsDoc(options.defaultRls, \"defaultRls\"), 0, prefix.length)} as const;`);\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n","/**\n * Importing a `backend/schema` directory as it *would be* after an edit.\n *\n * The schema editor refuses an edit whose result does not compile, and the\n * result is text that has not been written anywhere the project reads. So the\n * edited modules are evaluated from that text: each is transpiled to CommonJS\n * with the TypeScript that ships with ts-morph and run in this process, with\n * a `require` that serves the edited text for every module of the schema\n * directory and the disk for everything else.\n *\n * The builders a schema module imports (`@rebasepro/server/schema`, which\n * only re-exports `@rebasepro/types`) are served from this process's own\n * copy, so a definition evaluated here is the same kind of object the server\n * runs — the definitions it yields are what the server is refreshed with after\n * an apply.\n */\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport vm from \"node:vm\";\nimport { ts } from \"ts-morph\";\nimport * as schemaBuilders from \"@rebasepro/types\";\n\nimport type { SchemaModuleImporter } from \"../schema/load-schema\";\n\n/** The module specifiers served from this process's builders. */\nconst BUILDER_SPECIFIERS = new Set([\"@rebasepro/server/schema\", \"@rebasepro/types\"]);\n\n/** What a module file may be named, in the order an extensionless import tries them. */\nconst RESOLVE_SUFFIXES = [\".ts\", \".mts\", \".tsx\", \".js\", \".mjs\", \".cjs\", \".json\", \"/index.ts\", \"/index.mts\", \"/index.js\", \"/index.mjs\"];\nconst TRANSPILED = /\\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;\n\n/**\n * Options of {@link createSourceImporter}.\n */\nexport interface SourceImporterOptions {\n /** The edited text of every module of the schema directory, by real absolute path. */\n sources: ReadonlyMap<string, string>;\n /** The schema directory the edited text belongs to. */\n realDir: string;\n /**\n * The directory the loader is pointed at — a scratch copy of `realDir`\n * holding the edited files, so it can list them. Paths under it are read\n * as the same paths under `realDir`.\n */\n scratchDir: string;\n /**\n * Where a bare specifier (`slugify`, `@acme/lib`) is resolved from: the\n * importing module's real location when absent. A schema fetched from a\n * repository into a scratch directory has no `node_modules` above it, so\n * its caller names the runtime's own directory.\n */\n resolveBareFrom?: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n/**\n * A {@link SchemaModuleImporter} that sees the edited text.\n *\n * Modules are cached for the importer's lifetime, so the index and a sibling\n * that import the same table get the same object, as under Node.\n */\nexport function createSourceImporter(options: SourceImporterOptions): SchemaModuleImporter {\n const { sources, realDir, scratchDir } = options;\n const cache = new Map<string, { exports: unknown }>();\n const bareRequire = options.resolveBareFrom\n ? createRequire(path.join(options.resolveBareFrom, \"noop.js\"))\n : undefined;\n\n const realPathOf = (file: string): string => {\n const relative = path.relative(scratchDir, file);\n return relative.startsWith(\"..\") || path.isAbsolute(relative) ? file : path.join(realDir, relative);\n };\n\n const exists = (file: string): boolean =>\n sources.has(file) || (fs.existsSync(file) && fs.statSync(file).isFile());\n\n const resolveRelative = (specifier: string, from: string): string => {\n const base = path.resolve(path.dirname(from), specifier);\n const candidates = [base, ...RESOLVE_SUFFIXES.map(suffix => base + suffix)];\n // `./users.js` written for a `.ts` file, as TypeScript's own resolution allows.\n if (/\\.[mc]?js$/.test(base)) candidates.push(base.replace(/\\.([mc]?)js$/, \".$1ts\"));\n const found = candidates.find(exists);\n if (!found) throw new Error(`Cannot find module \"${specifier}\" imported from ${from}.`);\n return found;\n };\n\n const evaluate = (file: string): unknown => {\n const cached = cache.get(file);\n if (cached) return cached.exports;\n const text = sources.get(file) ?? fs.readFileSync(file, \"utf8\");\n if (file.endsWith(\".json\")) {\n const parsed: unknown = JSON.parse(text);\n cache.set(file, { exports: parsed });\n return parsed;\n }\n if (!TRANSPILED.test(file)) throw new Error(`Cannot import ${file}: not a module.`);\n const { outputText } = ts.transpileModule(text, {\n fileName: file,\n compilerOptions: {\n module: ts.ModuleKind.CommonJS,\n target: ts.ScriptTarget.ES2022,\n esModuleInterop: true,\n jsx: ts.JsxEmit.ReactJSX,\n sourceMap: false\n }\n });\n const module: { exports: unknown } = { exports: {} };\n cache.set(file, module);\n const localRequire = (specifier: string): unknown => {\n if (BUILDER_SPECIFIERS.has(specifier)) return schemaBuilders;\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) return evaluate(resolveRelative(specifier, file));\n return (bareRequire ?? createRequire(file))(specifier);\n };\n const wrapper: unknown = vm.runInThisContext(\n `(function (exports, require, module, __filename, __dirname) {${outputText}\\n})`,\n { filename: file }\n );\n if (typeof wrapper !== \"function\") throw new Error(`Could not evaluate ${file}.`);\n Reflect.apply(wrapper, undefined, [module.exports, localRequire, module, file, path.dirname(file)]);\n return module.exports;\n };\n\n return async (file: string): Promise<Record<string, unknown>> => {\n const exported = evaluate(realPathOf(file));\n return isRecord(exported) ? exported : { default: exported };\n };\n}\n","/**\n * Byte-preserving edits of a TypeScript module's text.\n *\n * The schema editor parses with ts-morph to find positions, and writes by\n * splicing text at those positions — never through ts-morph's manipulation\n * API, which reformats what it touches. Everything outside a spliced range is\n * the file as it was: comments, blank lines, trailing commas, quote style.\n *\n * The list helpers edit the members of an object literal (`columns`,\n * `relations`, a `defineTable` config) or the elements of an array literal\n * (`rls` rules) in the layout they are written in: one member per line, or\n * all on one line.\n */\nimport type { Node } from \"ts-morph\";\n\n/** One replacement of `[start, end)` by `text`. */\nexport interface TextEdit {\n start: number;\n end: number;\n text: string;\n}\n\n/** Apply non-overlapping edits to `text`. */\nexport function applyEdits(text: string, edits: readonly TextEdit[]): string {\n const sorted = [...edits].sort((a, b) => b.start - a.start || b.end - a.end);\n let out = text;\n let floor = Number.POSITIVE_INFINITY;\n for (const edit of sorted) {\n if (edit.end > floor) throw new Error(\"Overlapping source edits.\");\n out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);\n floor = edit.start;\n }\n return out;\n}\n\n/** The offset of the first character of the line holding `pos`. */\nexport function lineStart(text: string, pos: number): number {\n return text.lastIndexOf(\"\\n\", pos - 1) + 1;\n}\n\n/** The offset of the `\\n` ending the line holding `pos` (or the end of the text). */\nexport function lineEnd(text: string, pos: number): number {\n const end = text.indexOf(\"\\n\", pos);\n return end === -1 ? text.length : end;\n}\n\n/** The whitespace a line starts with. */\nexport function indentAt(text: string, pos: number): string {\n const start = lineStart(text, pos);\n return /^[ \\t]*/.exec(text.slice(start))?.[0] ?? \"\";\n}\n\n/** Whether only spaces and tabs stand between `from` and `to`. */\nconst blankBetween = (text: string, from: number, to: number): boolean => /^[ \\t]*$/.test(text.slice(from, to));\n\n/**\n * Text printed at indentation 0, shifted so its continuation lines sit under\n * a line indented by `indent`. The first line is placed by the caller.\n */\nexport function reindent(printed: string, indent: string): string {\n return printed.split(\"\\n\").map((line, index) => (index === 0 || line === \"\" ? line : indent + line)).join(\"\\n\");\n}\n\n/** The indentation one level deeper than `indent`, in its own unit (four spaces, or a tab). */\nexport function deeper(indent: string): string {\n return indent + (indent.includes(\"\\t\") ? \"\\t\" : \" \");\n}\n\n/**\n * Where an item's own text begins, its comments included: the leading\n * comments that sit on lines of their own above it. A comment on the line of\n * the previous token (`{ // note`) belongs to that token and is not counted.\n */\nexport function itemStart(text: string, item: Node, previousEnd: number): number {\n for (const range of item.getLeadingCommentRanges()) {\n const pos = range.getPos();\n if (text.slice(previousEnd, pos).includes(\"\\n\")) return pos;\n }\n return item.getStart();\n}\n\n/**\n * Past the separator and the same-line comment that follow an item: the comma\n * if there is one, then a `// …` or `/* … *\\/` on the same line.\n */\nfunction afterSeparator(text: string, pos: number): { end: number; comma: boolean } {\n let at = pos;\n while (at < text.length && (text[at] === \" \" || text[at] === \"\\t\")) at++;\n let comma = false;\n if (text[at] === \",\") {\n comma = true;\n at++;\n }\n let probe = at;\n while (probe < text.length && (text[probe] === \" \" || text[probe] === \"\\t\")) probe++;\n if (text.startsWith(\"//\", probe)) return { end: lineEnd(text, probe), comma };\n if (text.startsWith(\"/*\", probe)) {\n const close = text.indexOf(\"*/\", probe + 2);\n if (close !== -1 && !text.slice(probe, close).includes(\"\\n\")) return { end: close + 2, comma };\n }\n return { end: at, comma };\n}\n\n/** An object or array literal and its members, as the list helpers see it. */\nexport interface ListShape {\n /** Offset just after the opening bracket. */\n open: number;\n /** Offset of the closing bracket. */\n close: number;\n /** The members, in order. */\n items: readonly Node[];\n}\n\n/** The list shape of an object literal's properties or an array literal's elements. */\nexport function listShape(container: Node, items: readonly Node[]): ListShape {\n return { open: container.getStart() + 1, close: container.getEnd() - 1, items };\n}\n\n/** Whether the members are written one per line. */\nfunction isMultiline(text: string, list: ListShape): boolean {\n if (list.items.length === 0) return text.slice(list.open, list.close).includes(\"\\n\");\n const first = list.items[0];\n return text.slice(list.open, itemStart(text, first, list.open)).includes(\"\\n\");\n}\n\n/**\n * Insert `member` (printed at indentation 0) at `index` of the list.\n *\n * @param emptyStyle How an empty list is written to: `\"lines\"` opens it onto\n * its own lines (an object holding columns), `\"inline\"` keeps it on one.\n */\nexport function insertListItem(text: string, list: ListShape, index: number, member: string, emptyStyle: \"lines\" | \"inline\"): TextEdit[] {\n const { items } = list;\n if (items.length === 0) {\n const containerIndent = indentAt(text, list.open - 1);\n if (emptyStyle === \"lines\" || text.slice(list.open, list.close).includes(\"\\n\")) {\n const indent = deeper(containerIndent);\n return [{ start: list.open, end: list.close, text: `\\n${indent}${reindent(member, indent)}\\n${containerIndent}` }];\n }\n const brace = text[list.open - 1] === \"{\";\n return [{ start: list.open, end: list.close, text: brace ? ` ${member} ` : member }];\n }\n if (isMultiline(text, list)) {\n if (index < items.length) {\n const anchor = items[index];\n const previousEnd = index === 0 ? list.open : items[index - 1].getEnd();\n const start = lineStart(text, itemStart(text, anchor, previousEnd));\n const indent = indentAt(text, anchor.getStart());\n return [{ start, end: start, text: `${indent}${reindent(member, indent)},\\n` }];\n }\n const last = items[items.length - 1];\n const indent = indentAt(text, last.getStart());\n const after = afterSeparator(text, last.getEnd());\n if (after.comma) return [{ start: after.end, end: after.end, text: `\\n${indent}${reindent(member, indent)},` }];\n // No trailing comma: one after the last member, the new member on the\n // line after it (and after a comment that ends the last member's line).\n const placed = `\\n${indent}${reindent(member, indent)}`;\n if (after.end === last.getEnd()) return [{ start: last.getEnd(), end: last.getEnd(), text: `,${placed}` }];\n return [\n { start: last.getEnd(), end: last.getEnd(), text: \",\" },\n { start: after.end, end: after.end, text: placed }\n ];\n }\n if (index < items.length) {\n const anchor = items[index];\n return [{ start: anchor.getStart(), end: anchor.getStart(), text: `${member}, ` }];\n }\n const last = items[items.length - 1];\n return [{ start: last.getEnd(), end: last.getEnd(), text: `, ${member}` }];\n}\n\n/** Remove the member at `index` of the list, with its own comments and separator. */\nexport function removeListItem(text: string, list: ListShape, index: number): TextEdit[] {\n const { items } = list;\n const item = items[index];\n const previousEnd = index === 0 ? list.open : items[index - 1].getEnd();\n if (isMultiline(text, list)) {\n const start = lineStart(text, itemStart(text, item, previousEnd));\n const after = afterSeparator(text, item.getEnd());\n const end = blankBetween(text, after.end, lineEnd(text, after.end))\n ? Math.min(text.length, lineEnd(text, after.end) + 1)\n : after.end;\n return [{ start, end, text: \"\" }];\n }\n if (index < items.length - 1) return [{ start: item.getStart(), end: items[index + 1].getStart(), text: \"\" }];\n if (items.length > 1) {\n const after = afterSeparator(text, item.getEnd());\n return [{ start: items[index - 1].getEnd(), end: after.comma ? after.end : item.getEnd(), text: \"\" }];\n }\n const after = afterSeparator(text, item.getEnd());\n return [{ start: item.getStart(), end: after.comma ? after.end : item.getEnd(), text: \"\" }];\n}\n\n/** The member's whole text as written, its own leading comments included, for moving it. */\nexport function itemText(text: string, list: ListShape, index: number): string {\n const item = list.items[index];\n const previousEnd = index === 0 ? list.open : list.items[index - 1].getEnd();\n const start = itemStart(text, item, previousEnd);\n const indent = indentAt(text, item.getStart());\n // Dedent the continuation lines, so `insertListItem` can place them anew.\n return text.slice(start, item.getEnd()).split(\"\\n\")\n .map((line, i) => (i > 0 && line.startsWith(indent) ? line.slice(indent.length) : line))\n .join(\"\\n\");\n}\n\n/** Replace a node's text by `printed` (indentation 0), aligned under the line it sits on. */\nexport function replaceNode(text: string, node: Node, printed: string): TextEdit {\n return { start: node.getStart(), end: node.getEnd(), text: reindent(printed, indentAt(text, node.getStart())) };\n}\n\n/** Remove whole statements (with their own leading comment lines) from a module. */\nexport function removeStatement(text: string, statement: Node, previousEnd: number): TextEdit {\n const start = lineStart(text, itemStart(text, statement, previousEnd));\n const end = Math.min(text.length, lineEnd(text, statement.getEnd()) + 1);\n // Between two blank lines, take one of them too, so no gap of two is left.\n const blankBefore = start >= 2 && text[start - 2] === \"\\n\";\n const blankAfter = end < text.length && text[end] === \"\\n\";\n return { start, end: blankBefore && blankAfter ? end + 1 : end, text: \"\" };\n}\n","import fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n type ArrayLiteralExpression,\n type ImportDeclaration,\n type ObjectLiteralExpression,\n type SourceFile,\n type VariableDeclaration,\n type VariableStatement\n} from \"ts-morph\";\nimport {\n ColumnBuilder,\n col,\n columnDefFromWire,\n defineTable,\n rel,\n type AnyTableDef,\n type AnyViewDef,\n type ColumnDef,\n type ColumnsShape,\n type CompiledTable,\n type DefaultRls,\n type NewTable,\n type RelationDef,\n type RelationsShape,\n type TableDescriptor,\n type TablePatch,\n type TableThunk,\n type WireColumnDef,\n type WireRelation\n} from \"@rebasepro/types\";\nimport {\n DEFAULT_SCHEMA_SPECIFIER,\n TABLE_KEY_ORDER,\n enumIdentifier,\n isSchemaDefinitionError,\n printColumn,\n printIndexModule,\n printRelation,\n printRls,\n printSchemaValue,\n printTableModule,\n tableIdentifier\n} from \"@rebasepro/common\";\n\nimport { compileSchemaDefs, isSchemaLoadError, loadBackendSchema } from \"../schema/load-schema\";\nimport { createSourceImporter } from \"../schema-edit/source-importer\";\nimport {\n applyEdits,\n deeper,\n insertListItem,\n itemText,\n listShape,\n reindent,\n removeListItem,\n removeStatement,\n replaceNode,\n type TextEdit\n} from \"../schema-edit/source-text\";\n\n/**\n * The Studio's schema editor: edits to `backend/schema/*.ts`, one\n * {@link TablePatch} at a time.\n *\n * It reads and writes the `defineTable` / `defineAuthTable` / `defineView`\n * calls the schema's index exports — their `columns` (each a `col.*` chain),\n * `relations` (`rel.*`), `rls` and table-level keys — and nothing else. Every\n * piece of text it writes comes from the one printer (`printColumn`,\n * `printRelation`, `printRls`, `printTableModule`…), and it writes by splicing\n * that text in at the position of what it replaces, so everything it does not\n * rewrite stays byte for byte: comments, hooks, `.transform()` bodies, the\n * other columns, the other rules.\n *\n * What it cannot read with confidence — a config that spreads another object,\n * a column built by a helper, rules held in a variable, a key computed at run\n * time — it calls *edited in code*: {@link TableSourceEditor.describe} reports\n * it read-only, and an edit that would write there is refused with the reason,\n * never guessed at.\n *\n * Every edit is applied to a copy of the text first and the result is\n * compiled — imported as it would be, through {@link loadBackendSchema} — and\n * an edit whose result does not compile is refused with the problems, having\n * written nothing.\n *\n * One edit at a time ({@link TableSourceEditor.run}): the source-only routes\n * and live schema editing's `/apply` share one editor per process, so an edit\n * never reads files another edit is halfway through writing.\n *\n * @group Schema\n */\nexport class TableSourceEditor {\n private settled: Promise<unknown> = Promise.resolve();\n readonly schemaDir: string;\n private readonly resolveBareFrom?: string;\n\n constructor(schemaDir: string, options: { resolveBareFrom?: string } = {}) {\n this.schemaDir = path.resolve(schemaDir);\n this.resolveBareFrom = options.resolveBareFrom;\n }\n\n /** Run `work` once every edit queued before it has finished. */\n run<T>(work: () => Promise<T>): Promise<T> {\n const result = this.settled.then(work);\n this.settled = result.then(() => undefined, () => undefined);\n return result;\n }\n\n /**\n * Apply `patches` to a copy of the schema's text and compile the result.\n * Writes nothing: the edit is refused (a {@link TableSourceEditError}) or\n * returned, with every file it changed and the schema it compiles to.\n */\n async preview(patches: readonly TablePatch[]): Promise<TableSourceEdit> {\n const workspace = Workspace.read(this.schemaDir);\n for (const [index, patch] of patches.entries()) {\n try {\n await applyPatch(workspace, patch, this);\n } catch (error) {\n throw asRefusal(error, index, patch);\n }\n }\n const files = workspace.changes();\n if (files.length === 0) {\n throw new TableSourceEditError(\"SCHEMA_EDIT_REFUSED\", \"The edit changes nothing in backend/schema.\", []);\n }\n const schema = await this.compile(workspace.texts());\n return { files, schema };\n }\n\n /** {@link preview}, then write the files — queued behind every other edit. */\n apply(patches: readonly TablePatch[]): Promise<TableSourceEdit> {\n return this.run(async () => {\n const edit = await this.preview(patches);\n await this.write(edit);\n return edit;\n });\n }\n\n /**\n * Write a previewed edit's files, refusing when one of them changed on\n * disk since the preview read it (an IDE save, another process): the edit\n * was made against the old text.\n */\n async write(edit: TableSourceEdit): Promise<void> {\n this.assertUnchanged(edit);\n for (const file of edit.files) {\n if (file.deleted) {\n await fsp.rm(file.path, { force: true });\n } else {\n await fsp.mkdir(path.dirname(file.path), { recursive: true });\n await fsp.writeFile(file.path, file.contents, \"utf8\");\n }\n }\n }\n\n /** Refuse when a file an edit rewrites is no longer what the edit read. */\n assertUnchanged(edit: TableSourceEdit): void {\n for (const file of edit.files) {\n const now = fs.existsSync(file.path) ? fs.readFileSync(file.path, \"utf8\") : undefined;\n if (now !== file.before) {\n throw new TableSourceEditError(\n \"SCHEMA_EDIT_STALE_FILE\",\n `${file.path} changed since the edit was prepared (it was saved by something else meanwhile). ` +\n \"Nothing was written: make the edit again against the file as it is now.\",\n []\n );\n }\n }\n }\n\n /**\n * Every table the schema's index exports, as the editor reads it: which\n * parts it can write, and why not where it cannot.\n */\n async describe(): Promise<TableSourceSummary[]> {\n return Workspace.read(this.schemaDir).tables().map(summarize);\n }\n\n /** The schema directory as it is on disk, compiled: the tables `backend/schema` declares now. */\n async compileCurrent(): Promise<EditedSchema> {\n return this.compile(Workspace.read(this.schemaDir).texts());\n }\n\n /** Compile the schema directory as `texts` would make it. */\n async compile(texts: ReadonlyMap<string, string>): Promise<EditedSchema> {\n const scratch = await fsp.realpath(await fsp.mkdtemp(path.join(os.tmpdir(), \"rebase-schema-edit-\")));\n try {\n for (const [file, text] of texts) {\n const target = path.join(scratch, path.relative(this.schemaDir, file));\n await fsp.mkdir(path.dirname(target), { recursive: true });\n await fsp.writeFile(target, text, \"utf8\");\n }\n const importModule = createSourceImporter({\n sources: texts,\n realDir: this.schemaDir,\n scratchDir: scratch,\n ...(this.resolveBareFrom ? { resolveBareFrom: this.resolveBareFrom } : {})\n });\n const loaded = await loadBackendSchema(scratch, { projectRoot: false, importModule });\n const compiled = compileSchemaDefs(loaded.defs, loaded.defaultRls);\n return { defs: loaded.defs, ...(loaded.defaultRls !== undefined ? { defaultRls: loaded.defaultRls } : {}), ...compiled };\n } catch (error) {\n throw compileRefusal(error, scratch, this.schemaDir);\n } finally {\n await fsp.rm(scratch, { recursive: true, force: true });\n }\n }\n}\n\n/**\n * One file an edit changed.\n *\n * @group Schema\n */\nexport interface TableSourceFile {\n /** Absolute path. */\n path: string;\n /** The new text. Empty for a deleted file. */\n contents: string;\n /** The edit deletes the file. */\n deleted?: true;\n /** The text the edit was made against; `undefined` for a file it creates. */\n before?: string;\n}\n\n/**\n * A schema as an edit leaves it: the definitions, and what they compile and\n * lower to — what a running server is refreshed with after an apply.\n *\n * @group Schema\n */\nexport interface EditedSchema {\n defs: (AnyTableDef | AnyViewDef)[];\n defaultRls?: DefaultRls;\n /**\n * The definitions compiled, as boot compiles its own: each descriptor\n * with its hooks, transforms and auth hooks — what the planner plans from\n * and what the server's registries serve after an apply.\n */\n tables: CompiledTable[];\n descriptors: TableDescriptor[];\n}\n\n/**\n * An edit, applied to a copy and compiled.\n *\n * @group Schema\n */\nexport interface TableSourceEdit {\n /** Every file the edit changes, in path order. */\n files: TableSourceFile[];\n /** What the schema compiles to with the edit. */\n schema: EditedSchema;\n}\n\n/**\n * What is wrong with an edit, or with what it would leave.\n *\n * @group Schema\n */\nexport interface TableSourceProblem {\n /** The table, by slug or name. */\n table: string;\n /** The column, relation or key, when there is one. */\n key?: string;\n message: string;\n}\n\n/**\n * Why the schema editor refused an edit:\n *\n * - `SCHEMA_EDIT_REFUSED` — the edit cannot be made as asked: the table is\n * edited in code there, the column does not exist, a slug rename.\n * - `SCHEMA_EDIT_DOES_NOT_COMPILE` — the edit can be made, and the schema it\n * leaves would not load: the problems say why.\n * - `SCHEMA_EDIT_STALE_FILE` — a file the edit rewrites changed on disk since\n * the edit was prepared (an IDE save, another process): reload it and make\n * the edit again.\n *\n * @group Schema\n */\nexport type SchemaEditRefusalCode = \"SCHEMA_EDIT_REFUSED\" | \"SCHEMA_EDIT_DOES_NOT_COMPILE\" | \"SCHEMA_EDIT_STALE_FILE\";\n\n/**\n * An edit the schema editor will not make, with its\n * {@link SchemaEditRefusalCode}. Nothing was written.\n *\n * @group Schema\n */\nexport class TableSourceEditError extends Error {\n constructor(\n readonly code: SchemaEditRefusalCode,\n message: string,\n readonly problems: readonly TableSourceProblem[]\n ) {\n super(message);\n this.name = \"TableSourceEditError\";\n }\n}\n\n/**\n * How the editor reads one table.\n *\n * @group Schema\n */\nexport interface TableSourceSummary {\n slug: string;\n name: string;\n kind: \"table\" | \"authTable\" | \"view\";\n /** The file holding it, absolute. */\n file: string;\n /** Why the table is read-only as a whole, when it is. */\n editedInCode?: string;\n /** Every column, and why one is read-only. */\n columns: { key: string; editedInCode?: string }[];\n /** Every relation, and why one is read-only. */\n relations: { name: string; editedInCode?: string }[];\n /** Why `rls` (or its rules) cannot be written, when it cannot. */\n rlsEditedInCode?: string;\n}\n\n// ── Reading the schema ──────────────────────────────────────────────────────\n\nconst MODULE_EXTENSIONS = [\".ts\", \".mts\", \".js\", \".mjs\"];\nconst INDEX_FILES = [\"index.ts\", \"index.mts\", \"index.js\", \"index.mjs\"];\nconst BUILDERS = new Set([\"defineTable\", \"defineAuthTable\", \"defineView\"]);\ntype BuilderName = \"defineTable\" | \"defineAuthTable\" | \"defineView\";\n\n/** The module files of a schema directory, as the loader lists them. */\nfunction moduleFiles(dir: string): string[] {\n const out: string[] = [];\n if (!fs.existsSync(dir)) return out;\n const walk = (current: string): void => {\n for (const entry of fs.readdirSync(current, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\" || entry.name === \"__tests__\") continue;\n const full = path.join(current, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && MODULE_EXTENSIONS.some(ext => entry.name.endsWith(ext))\n && !/\\.d\\.[mc]?ts$/.test(entry.name) && !/\\.(test|spec)\\./.test(entry.name)) {\n out.push(full);\n }\n }\n };\n walk(dir);\n return out.sort();\n}\n\n/** A table the index exports, located in its file. */\ninterface LocatedTable {\n slug: string;\n name: string;\n builder: BuilderName;\n /** Absolute path of the file declaring it. */\n file: string;\n /** The `const` it is bound to in that file. */\n variable: string;\n /** The name the index exports it under. */\n exportName: string;\n declaration: VariableDeclaration;\n /** The config object, when the editor can write it. */\n config?: ObjectLiteralExpression;\n /** Why it cannot, when it cannot. */\n editedInCode?: string;\n}\n\n/** The text of the schema directory during one edit. */\nclass Workspace {\n private readonly current = new Map<string, string>();\n private readonly original = new Map<string, string>();\n private project?: Project;\n\n private constructor(readonly dir: string) {}\n\n static read(dir: string): Workspace {\n const workspace = new Workspace(dir);\n for (const file of moduleFiles(dir)) {\n const text = fs.readFileSync(file, \"utf8\");\n workspace.current.set(file, text);\n workspace.original.set(file, text);\n }\n return workspace;\n }\n\n texts(): ReadonlyMap<string, string> {\n return this.current;\n }\n\n has(file: string): boolean {\n return this.current.has(file);\n }\n\n text(file: string): string {\n const text = this.current.get(file);\n if (text === undefined) throw new Error(`${file} is not a module of ${this.dir}.`);\n return text;\n }\n\n set(file: string, text: string): void {\n this.current.set(file, text);\n this.project = undefined;\n }\n\n edit(file: string, edits: readonly TextEdit[]): void {\n if (edits.length > 0) this.set(file, applyEdits(this.text(file), edits));\n }\n\n delete(file: string): void {\n this.current.delete(file);\n this.project = undefined;\n }\n\n /** Every file whose text differs from what was read, in path order. */\n changes(): TableSourceFile[] {\n const out: TableSourceFile[] = [];\n for (const [file, text] of this.current) {\n const before = this.original.get(file);\n if (before !== text) out.push({ path: file, contents: text, ...(before !== undefined ? { before } : {}) });\n }\n for (const [file, before] of this.original) {\n if (!this.current.has(file)) out.push({ path: file, contents: \"\", deleted: true, before });\n }\n return out.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n /** The current text parsed; rebuilt after every change, so nodes are never stale. */\n source(file: string): SourceFile {\n const project = this.parsed();\n const source = project.getSourceFile(file);\n if (!source) throw new Error(`${file} is not a module of ${this.dir}.`);\n return source;\n }\n\n private parsed(): Project {\n if (this.project) return this.project;\n const project = new Project({\n useInMemoryFileSystem: true,\n compilerOptions: { allowJs: true, noLib: true }\n });\n for (const [file, text] of this.current) project.createSourceFile(file, text, { overwrite: true });\n this.project = project;\n return project;\n }\n\n indexFile(): string | undefined {\n return INDEX_FILES.map(name => path.join(this.dir, name)).find(file => this.current.has(file));\n }\n\n /** Every table the index exports, each once. */\n tables(): LocatedTable[] {\n const indexPath = this.indexFile();\n if (!indexPath) return [];\n const index = this.source(indexPath);\n const out: LocatedTable[] = [];\n const seen = new Set<VariableDeclaration>();\n for (const [exportName, declarations] of index.getExportedDeclarations()) {\n for (const declaration of declarations) {\n if (!Node.isVariableDeclaration(declaration) || seen.has(declaration)) continue;\n const located = locate(declaration, exportName);\n if (located) {\n seen.add(declaration);\n out.push(located);\n }\n }\n }\n return out;\n }\n\n table(slug: string): LocatedTable {\n const found = this.tables().find(table => table.slug === slug);\n if (!found) {\n throw refusal(\n `No table with the slug \"${slug}\" is exported from ${path.join(path.basename(this.dir), \"index\")} as a ` +\n \"`defineTable` / `defineAuthTable` / `defineView` call the editor can read. If it is defined through a \" +\n \"helper or a variable, it is edited in code.\",\n slug\n );\n }\n return found;\n }\n\n /** The table at `slug`, with a config the editor may write. */\n writable(slug: string): LocatedTable & { config: ObjectLiteralExpression } {\n const table = this.table(slug);\n if (!table.config) throw refusal(`Table \"${slug}\" is edited in code: ${table.editedInCode}`, slug);\n return { ...table, config: table.config };\n }\n}\n\nexport function unwrapExpression(node: Node | undefined): Node | undefined {\n let current = node;\n while (current && (Node.isParenthesizedExpression(current) || Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current) || Node.isNonNullExpression(current) || Node.isTypeAssertion(current))) {\n current = current.getExpression();\n }\n return current;\n}\n\nexport function literalString(node: Node | undefined): string | undefined {\n if (node && (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node))) return node.getLiteralValue();\n return undefined;\n}\n\n/** The key a member of an object literal is written under, when it is written literally. */\nexport function memberName(member: Node): string | undefined {\n if (Node.isPropertyAssignment(member) || Node.isShorthandPropertyAssignment(member) || Node.isMethodDeclaration(member)) {\n const nameNode = member.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText();\n if (Node.isStringLiteral(nameNode) || Node.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();\n if (Node.isNumericLiteral(nameNode)) return nameNode.getText();\n }\n return undefined;\n}\n\n/** Why an object literal's members cannot be read one by one, when they cannot. */\nexport function opaqueMembers(object: ObjectLiteralExpression, what: string): string | undefined {\n for (const member of object.getProperties()) {\n if (Node.isSpreadAssignment(member)) return `${what} spreads \\`${member.getExpression().getText()}\\`, so any key may come from code.`;\n if (memberName(member) === undefined) return `${what} has a key computed at run time (\\`${member.getText().split(\":\")[0].trim()}\\`).`;\n }\n return undefined;\n}\n\n/** A member of an object literal: its assignment, or why it cannot be written. */\nexport type Member =\n | { kind: \"absent\" }\n | { kind: \"written\"; node: Node; value: Node; index: number }\n | { kind: \"code\"; reason: string };\n\nexport function member(object: ObjectLiteralExpression, key: string, what: string): Member {\n const members = object.getProperties();\n const opaque = opaqueMembers(object, what);\n for (const [index, each] of members.entries()) {\n if (memberName(each) !== key) continue;\n if (Node.isPropertyAssignment(each)) {\n const value = each.getInitializer();\n if (value) return { kind: \"written\", node: each, value, index };\n }\n return { kind: \"code\", reason: `\\`${key}\\` of ${what} is ${Node.isShorthandPropertyAssignment(each) ? \"a variable\" : \"a method\"}.` };\n }\n if (opaque) return { kind: \"code\", reason: opaque };\n return { kind: \"absent\" };\n}\n\nfunction locate(declaration: VariableDeclaration, exportName: string): LocatedTable | undefined {\n const call = unwrapExpression(declaration.getInitializer());\n if (!call || !Node.isCallExpression(call)) return undefined;\n const callee = call.getExpression().getText().split(\".\").pop() ?? \"\";\n if (!BUILDERS.has(callee)) return undefined;\n const builder: BuilderName = callee === \"defineAuthTable\" ? \"defineAuthTable\" : callee === \"defineView\" ? \"defineView\" : \"defineTable\";\n const [nameArg, configArg] = call.getArguments();\n const name = literalString(nameArg);\n if (name === undefined) return undefined;\n const base = {\n name,\n builder,\n file: declaration.getSourceFile().getFilePath(),\n variable: declaration.getName(),\n exportName,\n declaration\n };\n const config = unwrapExpression(configArg);\n if (!config || !Node.isObjectLiteralExpression(config)) {\n return { ...base, slug: name, editedInCode: \"its config is not an object literal written in the call.\" };\n }\n const opaque = opaqueMembers(config, \"its config\");\n const slugMember = member(config, \"slug\", \"its config\");\n if (slugMember.kind === \"written\") {\n const slug = literalString(slugMember.value);\n if (slug === undefined) return { ...base, slug: name, editedInCode: \"its `slug` is not a string literal.\" };\n return opaque ? { ...base, slug, editedInCode: opaque } : { ...base, slug, config };\n }\n return opaque ? { ...base, slug: name, editedInCode: opaque } : { ...base, slug: name, config };\n}\n\n/** Whether a node is a builder chain rooted at `root`: `col.text().notNull()`, `rel.belongsTo(…)`. */\nfunction isChainOf(node: Node, root: string): boolean {\n let current: Node | undefined = unwrapExpression(node);\n let calls = 0;\n while (current) {\n if (Node.isCallExpression(current)) {\n calls++;\n current = current.getExpression();\n } else if (Node.isPropertyAccessExpression(current)) {\n current = current.getExpression();\n } else {\n return calls > 0 && Node.isIdentifier(current) && current.getText() === root;\n }\n }\n return false;\n}\n\n/** The links of a chain, outermost last: `col.text().notNull()` → `[text(), notNull()]`. */\nfunction chainLinks(node: Node): { name: string; args: Node[] }[] {\n const links: { name: string; args: Node[] }[] = [];\n let current: Node | undefined = unwrapExpression(node);\n while (current && Node.isCallExpression(current)) {\n const callee = current.getExpression();\n if (!Node.isPropertyAccessExpression(callee)) break;\n links.unshift({ name: callee.getName(), args: current.getArguments() });\n current = callee.getExpression();\n }\n return links;\n}\n\n/** One `const <identifier> = pgEnum(\"<name>\", [...])` of a schema file. */\ninterface EnumBinding {\n identifier: string;\n enumName: string;\n values: string[];\n}\n\n/**\n * The `pgEnum` declarations of a file, by the identifier they are bound to: a\n * column chain may be rooted at one of them (`status: postStatus().notNull()`)\n * as well as at `col`. Only declarations the editor can read — a literal name\n * and a literal list of labels — count; anything else leaves the columns that\n * use it edited in code.\n */\nfunction enumBindings(source: SourceFile): Map<string, EnumBinding> {\n const local = builderImport(source)?.local.get(\"pgEnum\") ?? \"pgEnum\";\n const out = new Map<string, EnumBinding>();\n for (const statement of source.getVariableStatements()) {\n for (const declaration of statement.getDeclarations()) {\n const call = unwrapExpression(declaration.getInitializer());\n if (!call || !Node.isCallExpression(call) || call.getExpression().getText() !== local) continue;\n const [nameArg, valuesArg] = call.getArguments();\n const enumName = literalString(nameArg);\n const list = unwrapExpression(valuesArg);\n if (enumName === undefined || !list || !Node.isArrayLiteralExpression(list)) continue;\n const values = list.getElements().map(element => literalString(element));\n if (values.some(value => value === undefined)) continue;\n out.set(declaration.getName(), { identifier: declaration.getName(), enumName, values: values.filter((value): value is string => value !== undefined) });\n }\n }\n return out;\n}\n\n/** Whether a node is a column chain: rooted at `col`, or at a `pgEnum` binding of its file. */\nfunction isColumnChain(node: Node): boolean {\n if (isChainOf(node, \"col\")) return true;\n let root: Node | undefined = unwrapExpression(node);\n while (root && (Node.isCallExpression(root) || Node.isPropertyAccessExpression(root))) root = root.getExpression();\n return root !== undefined && Node.isIdentifier(root) && enumBindings(node.getSourceFile()).has(root.getText()) && isChainOf(node, root.getText());\n}\n\n/** Why a column's value cannot be rewritten, when it cannot. */\nfunction columnCode(value: Node, key: string): string | undefined {\n if (!isColumnChain(value)) {\n return `column \"${key}\" is not a \\`col.*\\` chain or a \\`pgEnum\\` column (it is built by \\`${value.getText().slice(0, 40)}\\`).`;\n }\n return undefined;\n}\n\n/** The source of the `.transform(…)` written on a column's own chain, and whether one hides deeper in it. */\nfunction columnTransforms(value: Node): { own?: string; nested: boolean } {\n const links = chainLinks(value);\n const ownLink = links.find(link => link.name === \"transform\");\n const own = ownLink?.args[0]?.getText();\n let total = 0;\n value.forEachDescendant(node => {\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n if (Node.isPropertyAccessExpression(callee) && callee.getName() === \"transform\") total++;\n }\n });\n return { ...(own !== undefined ? { own } : {}), nested: total > (ownLink ? 1 : 0) };\n}\n\nfunction summarize(table: LocatedTable): TableSourceSummary {\n const kind = table.builder === \"defineAuthTable\" ? \"authTable\" : table.builder === \"defineView\" ? \"view\" : \"table\";\n const summary: TableSourceSummary = { slug: table.slug, name: table.name, kind, file: table.file, columns: [], relations: [] };\n if (!table.config) return { ...summary, editedInCode: table.editedInCode };\n const listOf = (key: string, what: string, rootName: string) => {\n const found = member(table.config!, key, \"the config\");\n if (found.kind !== \"written\") return { entries: [], reason: found.kind === \"code\" ? found.reason : undefined };\n const object = unwrapExpression(found.value);\n if (!object || !Node.isObjectLiteralExpression(object)) return { entries: [], reason: `\\`${key}\\` is not an object literal.` };\n const opaque = opaqueMembers(object, `\\`${key}\\``);\n const entries = object.getProperties().flatMap(each => {\n const entryKey = memberName(each);\n if (entryKey === undefined) return [];\n const value = Node.isPropertyAssignment(each) ? each.getInitializer() : undefined;\n const reason = opaque\n ?? (!value ? `${what} \"${entryKey}\" is a variable.` : rootName === \"col\" ? columnCode(value, entryKey)\n : isChainOf(value, \"rel\") ? undefined : `${what} \"${entryKey}\" is not a \\`rel.*\\` call.`);\n return [{ key: entryKey, ...(reason ? { editedInCode: reason } : {}) }];\n });\n return { entries, reason: opaque };\n };\n const columns = listOf(\"columns\", \"column\", \"col\");\n const relations = listOf(\"relations\", \"relation\", \"rel\");\n const rls = member(table.config, \"rls\", \"the config\");\n let rlsEditedInCode: string | undefined;\n if (rls.kind === \"code\") rlsEditedInCode = rls.reason;\n if (rls.kind === \"written\") {\n const value = unwrapExpression(rls.value);\n if (!value || !(Node.isStringLiteral(value) || Node.isArrayLiteralExpression(value))) rlsEditedInCode = \"`rls` is not written in the call.\";\n else if (Node.isArrayLiteralExpression(value) && value.getElements().some(element => Node.isSpreadElement(element))) {\n rlsEditedInCode = \"`rls` spreads another list of rules.\";\n }\n }\n return {\n ...summary,\n columns: columns.entries.map(({ key, editedInCode }) => ({ key, ...(editedInCode ? { editedInCode } : {}) })),\n relations: relations.entries.map(({ key, editedInCode }) => ({ name: key, ...(editedInCode ? { editedInCode } : {}) })),\n ...(rlsEditedInCode ? { rlsEditedInCode } : {})\n };\n}\n\n// ── Writing ─────────────────────────────────────────────────────────────────\n\n/** An edit refused, naming the table and, where there is one, the key. */\nfunction refusal(message: string, table: string, key?: string): TableSourceEditError {\n return new TableSourceEditError(\"SCHEMA_EDIT_REFUSED\", message, [{ table, ...(key !== undefined ? { key } : {}), message }]);\n}\n\nfunction asRefusal(error: unknown, index: number, patch: TablePatch): TableSourceEditError {\n if (error instanceof TableSourceEditError) return error;\n const table = patch.op === \"createTable\" ? patch.table.name : patch.op === \"adoptTable\" ? patch.table.slug : patch.table;\n const message = error instanceof Error ? error.message : String(error);\n return refusal(`Edit ${index} (${patch.op} on \"${table}\"): ${message}`, table);\n}\n\nfunction compileRefusal(error: unknown, scratch: string, dir: string): TableSourceEditError {\n if (error instanceof TableSourceEditError) return error;\n const real = (text: string): string => text.split(scratch).join(dir);\n if (isSchemaDefinitionError(error)) {\n return new TableSourceEditError(\n \"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n `The edit was not written: ${real(error.message)}`,\n error.problems.map(problem => ({ table: problem.table, ...(problem.key !== undefined ? { key: problem.key } : {}), message: real(problem.message) }))\n );\n }\n const message = error instanceof Error ? real(error.message) : String(error);\n return new TableSourceEditError(\n \"SCHEMA_EDIT_DOES_NOT_COMPILE\",\n isSchemaLoadError(error) ? `The edit was not written: ${message}` : `The edit was not written: the schema it leaves does not load: ${message}`,\n [{ table: \"\", message }]\n );\n}\n\nexport const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nexport const printKey = (key: string): string => (IDENTIFIER.test(key) ? key : JSON.stringify(key));\n\n/** The builder import of a file: the import declaration naming `defineTable` & co. */\nfunction builderImport(source: SourceFile): { declaration: ImportDeclaration; local: Map<string, string> } | undefined {\n for (const declaration of source.getImportDeclarations()) {\n const named = declaration.getNamedImports();\n const local = new Map(named.map(element => [element.getName(), element.getAliasNode()?.getText() ?? element.getName()]));\n if ([...BUILDERS, \"col\", \"rel\"].some(name => local.has(name)) && !declaration.isTypeOnly()) return { declaration, local };\n }\n return undefined;\n}\n\n/** Add the builders `printed` text uses (`col`, `rel`, `json`, `sql`, `pgEnum`) to the file's builder import. */\nfunction ensureBuilders(workspace: Workspace, file: string, needed: readonly (\"col\" | \"rel\" | \"json\" | \"sql\" | \"pgEnum\")[]): void {\n const source = workspace.source(file);\n const found = builderImport(source);\n if (!found) {\n throw refusal(`${file} has no import of the schema builders (\\`defineTable\\`, \\`col\\`…) to add ${needed.join(\", \")} to.`, path.basename(file));\n }\n const missing: string[] = [];\n for (const name of needed) {\n const local = found.local.get(name);\n if (local === undefined) missing.push(name);\n else if (local !== name) {\n throw refusal(`${file} imports \\`${name}\\` as \\`${local}\\`; the editor writes \\`${name}.…\\`. Import it under its own name.`, path.basename(file));\n }\n }\n if (missing.length === 0) return;\n const named = found.declaration.getNamedImports();\n const last = named[named.length - 1];\n workspace.edit(file, [{ start: last.getEnd(), end: last.getEnd(), text: missing.map(name => `, ${name}`).join(\"\") }]);\n}\n\n/** The module specifier `from` imports `to` by: `./users`, `../shared/users`. */\nfunction relativeSpecifier(from: string, to: string): string {\n const relative = path.relative(path.dirname(from), to).split(path.sep).join(\"/\").replace(/\\.[mc]?[jt]s$/, \"\");\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n}\n\n/** How `file` refers to `target`'s table, and the import it needs for that. */\nfunction bindingFor(workspace: Workspace, file: string, target: LocatedTable): string {\n if (target.file === file) return target.variable;\n const source = workspace.source(file);\n for (const declaration of source.getImportDeclarations()) {\n if (declaration.getModuleSpecifierSourceFile()?.getFilePath() !== target.file) continue;\n const element = declaration.getNamedImports().find(each => each.getName() === target.variable);\n if (element) return element.getAliasNode()?.getText() ?? element.getName();\n const named = declaration.getNamedImports();\n if (named.length > 0 && !declaration.isTypeOnly()) {\n const last = named[named.length - 1];\n workspace.edit(file, [{ start: last.getEnd(), end: last.getEnd(), text: `, ${target.variable}` }]);\n return target.variable;\n }\n }\n const imports = source.getImportDeclarations();\n const line = `import { ${target.variable} } from ${JSON.stringify(relativeSpecifier(file, target.file))};`;\n const at = imports.length > 0 ? imports[imports.length - 1].getEnd() : 0;\n workspace.edit(file, [{ start: at, end: at, text: imports.length > 0 ? `\\n${line}` : `${line}\\n` }]);\n return target.variable;\n}\n\n/** Drop the import of `identifier` from a file when nothing in it refers to it any more. */\nfunction dropUnusedImport(workspace: Workspace, file: string, identifier: string): void {\n const source = workspace.source(file);\n const used = source.getDescendants().some(node =>\n Node.isIdentifier(node) && node.getText() === identifier && !node.getFirstAncestor(Node.isImportDeclaration));\n if (used) return;\n for (const declaration of source.getImportDeclarations()) {\n const named = declaration.getNamedImports();\n const index = named.findIndex(element => (element.getAliasNode()?.getText() ?? element.getName()) === identifier);\n if (index === -1) continue;\n if (named.length === 1 && !declaration.getDefaultImport() && !declaration.getNamespaceImport()) {\n const statements = source.getStatements();\n const position = statements.indexOf(declaration);\n workspace.edit(file, [removeStatement(source.getFullText(), declaration, position > 0 ? statements[position - 1].getEnd() : 0)]);\n } else {\n const element = named[index];\n const edit: TextEdit = index < named.length - 1\n ? { start: element.getStart(), end: named[index + 1].getStart(), text: \"\" }\n : { start: named[index - 1]?.getEnd() ?? element.getStart(), end: element.getEnd(), text: \"\" };\n workspace.edit(file, [edit]);\n }\n return;\n }\n}\n\n/** The identifier a relation's thunk returns: `() => users` → `users`. */\nfunction thunkTarget(value: Node): string | undefined {\n const call = unwrapExpression(value);\n if (!call || !Node.isCallExpression(call)) return undefined;\n const thunk = call.getArguments()[0];\n if (!thunk || !Node.isArrowFunction(thunk)) return undefined;\n const body = unwrapExpression(thunk.getBody());\n return body && Node.isIdentifier(body) ? body.getText() : undefined;\n}\n\n/** A stand-in the printer reads a relation's target from: its name and slug, nothing else. */\nfunction targetStandIn(name: string, slug: string): AnyTableDef {\n return defineTable(name, { slug, columns: { id: col.uuid().primaryKey() }, rls: \"admin-only\" });\n}\n\n/** A wire relation as the `rel.*` result it describes, pointing at `target`. */\nfunction relationFromWire(relation: WireRelation, target: TableThunk): RelationDef {\n switch (relation.kind) {\n case \"belongsTo\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.belongsTo(target, options);\n }\n case \"hasOne\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.hasOne(target, options);\n }\n case \"hasMany\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.hasMany(target, options);\n }\n case \"manyToMany\": {\n const { kind: _kind, target: _target, pivot, ...options } = relation;\n void _kind; void _target;\n const columns = pivot !== undefined ? columnsFromWire(pivot) : undefined;\n return rel.manyToMany(target, { ...options, ...(columns ? { pivot: columns } : {}) });\n }\n case \"via\": {\n const { kind: _kind, target: _target, ...options } = relation;\n void _kind; void _target;\n return rel.via(target, options);\n }\n }\n}\n\nfunction columnsFromWire(columns: Record<string, WireColumnDef>): ColumnsShape {\n const out: ColumnsShape = {};\n for (const [key, column] of Object.entries(columns)) out[key] = new ColumnBuilder(columnDefFromWire(column));\n return out;\n}\n\nconst usesJson = (def: ColumnDef): boolean => def.json !== undefined || (def.element !== undefined && usesJson(def.element));\n\nconst TEMPORAL_KINDS = new Set([\"timestamptz\", \"date\", \"time\"]);\n\n/** Whether the printed chain uses the `sql` tag: a SQL default other than `.defaultNow()`, or a generated expression. */\nconst usesSql = (def: ColumnDef): boolean =>\n def.generatedAs !== undefined ||\n (def.default?.kind === \"sql\" && !(def.default.expression === \"now()\" && TEMPORAL_KINDS.has(def.type.kind))) ||\n (def.element !== undefined && usesSql(def.element));\n\n/** The builders a printed column needs imported. */\nconst buildersOf = (def: ColumnDef): (\"col\" | \"json\" | \"sql\")[] =>\n [\"col\", ...(usesJson(def) ? [\"json\" as const] : []), ...(usesSql(def) ? [\"sql\" as const] : [])];\n\n/**\n * How a printed column names an enum type with a stated name: by the file's\n * `pgEnum` binding for it, declared above the table when the file has none.\n * Returns the binder for `printColumn` and the step that writes the\n * declarations it asked for, run after the column is spliced in.\n */\nfunction enumBinder(workspace: Workspace, slug: string): { bind: (enumName: string, values: readonly string[]) => string; declare: () => void } {\n const table = workspace.writable(slug);\n const source = workspace.source(table.file);\n const known = [...enumBindings(source).values()];\n const added: EnumBinding[] = [];\n const bind = (enumName: string, values: readonly string[]): string => {\n const existing = [...known, ...added].find(binding => binding.enumName === enumName);\n if (existing) {\n if (existing.values.join(\"\\u0000\") !== values.join(\"\\u0000\")) {\n throw refusal(\n `${path.basename(table.file)} declares the enum type \"${enumName}\" with the labels ${JSON.stringify(existing.values)}; ` +\n `the column lists ${JSON.stringify(values)}. Change the \\`pgEnum\\` declaration in code.`,\n slug\n );\n }\n return existing.identifier;\n }\n let identifier = enumIdentifier(enumName);\n const taken = (name: string): boolean => source.getVariableDeclaration(name) !== undefined ||\n source.getImportDeclarations().some(each => each.getNamedImports().some(element => (element.getAliasNode()?.getText() ?? element.getName()) === name)) ||\n added.some(binding => binding.identifier === name);\n while (taken(identifier)) identifier = `${identifier}Type`;\n added.push({ identifier, enumName, values: [...values] });\n return identifier;\n };\n const declare = (): void => {\n if (added.length === 0) return;\n const statement = workspace.writable(slug).declaration.getVariableStatement();\n const at = statement ? statement.getStart(true) : 0;\n const lines = added.map(binding => `const ${binding.identifier} = pgEnum(${JSON.stringify(binding.enumName)}, [${binding.values.map(value => JSON.stringify(value)).join(\", \")}]);`);\n workspace.edit(table.file, [{ start: at, end: at, text: `${lines.join(\"\\n\")}\\n\\n` }]);\n ensureBuilders(workspace, table.file, [\"pgEnum\"]);\n };\n return { bind, declare };\n}\n\n/** `key: <chain>`, printed by `printColumn`. */\nfunction printedColumn(\n key: string,\n column: WireColumnDef,\n transform: string | undefined,\n enumIdentifierOf: (enumName: string, values: readonly string[]) => string\n): { text: string; def: ColumnDef } {\n const def = columnDefFromWire(column);\n return { text: `${printKey(key)}: ${printColumn(def, { key, enumIdentifier: enumIdentifierOf, ...(transform !== undefined ? { transform } : {}) })}`, def };\n}\n\n/** The `columns` or `relations` object of a table, writable, or a refusal. */\nfunction mapOf(table: LocatedTable & { config: ObjectLiteralExpression }, key: \"columns\" | \"relations\"): ObjectLiteralExpression | undefined {\n const found = member(table.config, key, `table \"${table.slug}\"`);\n if (found.kind === \"absent\") return undefined;\n if (found.kind === \"code\") throw refusal(`Table \"${table.slug}\" is edited in code there: ${found.reason}`, table.slug, key);\n const object = unwrapExpression(found.value);\n if (!object || !Node.isObjectLiteralExpression(object)) {\n throw refusal(`The \\`${key}\\` of table \"${table.slug}\" is edited in code: it is not an object literal.`, table.slug, key);\n }\n const opaque = opaqueMembers(object, `the \\`${key}\\` of table \"${table.slug}\"`);\n if (opaque) throw refusal(`Table \"${table.slug}\" is edited in code there: ${opaque}`, table.slug, key);\n return object;\n}\n\n/** One entry of `columns` / `relations`, or a refusal naming what is missing. */\nfunction entryOf(object: ObjectLiteralExpression, key: string, table: string, what: \"column\" | \"relation\"): { node: Node; value: Node; index: number } {\n const found = member(object, key, `${what}s`);\n if (found.kind === \"written\") return found;\n if (found.kind === \"code\") throw refusal(`The ${what} \"${key}\" of table \"${table}\" is edited in code: ${found.reason}`, table, key);\n throw refusal(`Table \"${table}\" has no ${what} \"${key}\".`, table, key);\n}\n\n/** Insert a `key: value` member into a table's config at its place in the canonical key order. */\nfunction insertConfigMember(workspace: Workspace, table: LocatedTable & { config: ObjectLiteralExpression }, key: string, printed: string): void {\n const order: readonly string[] = TABLE_KEY_ORDER;\n const rank = order.indexOf(key);\n const members = table.config.getProperties();\n let index = members.findIndex(each => {\n const name = memberName(each);\n return name !== undefined && order.indexOf(name) > rank;\n });\n if (index === -1) index = members.length;\n const text = workspace.text(table.file);\n workspace.edit(table.file, insertListItem(text, listShape(table.config, members), index, `${printKey(key)}: ${printed}`, \"lines\"));\n}\n\nfunction removeMember(workspace: Workspace, file: string, object: ObjectLiteralExpression, index: number): void {\n workspace.edit(file, removeListItem(workspace.text(file), listShape(object, object.getProperties()), index));\n}\n\n/** Whether a node is plain data — what an option's value may be overwritten from. */\nexport function isData(node: Node): boolean {\n const value = unwrapExpression(node);\n if (!value) return false;\n if (Node.isStringLiteral(value) || Node.isNumericLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value) ||\n Node.isTrueLiteral(value) || Node.isFalseLiteral(value) || Node.isNullLiteral(value)) return true;\n if (Node.isPrefixUnaryExpression(value)) return Node.isNumericLiteral(value.getOperand());\n if (Node.isArrayLiteralExpression(value)) return value.getElements().every(isData);\n if (Node.isObjectLiteralExpression(value)) {\n return value.getProperties().every(each => Node.isPropertyAssignment(each) && memberName(each) !== undefined && isData(each.getInitializerOrThrow()));\n }\n return false;\n}\n\nasync function applyPatch(workspace: Workspace, patch: TablePatch, editor: TableSourceEditor): Promise<void> {\n switch (patch.op) {\n case \"createTable\":\n return createTable(workspace, patch.table);\n case \"adoptTable\":\n return adoptTable(workspace, patch.table);\n case \"deleteTable\":\n return deleteTable(workspace, patch.table, editor);\n case \"addColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no \\`columns\\` object to add to.`, patch.table, patch.key);\n if (member(columns, patch.key, \"columns\").kind !== \"absent\") {\n throw refusal(`Table \"${patch.table}\" already has a column \"${patch.key}\". Change it instead.`, patch.table, patch.key);\n }\n const members = columns.getProperties();\n const index = patch.before !== undefined ? entryOf(columns, patch.before, patch.table, \"column\").index : members.length;\n const enums = enumBinder(workspace, patch.table);\n const { text, def } = printedColumn(patch.key, patch.column, undefined, enums.bind);\n workspace.edit(table.file, insertListItem(workspace.text(table.file), listShape(columns, members), index, text, \"lines\"));\n enums.declare();\n ensureBuilders(workspace, table.file, buildersOf(def));\n return;\n }\n case \"changeColumn\":\n case \"renameColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no column \"${patch.key}\".`, patch.table, patch.key);\n const entry = entryOf(columns, patch.key, patch.table, \"column\");\n const code = columnCode(entry.value, patch.key);\n if (code) throw refusal(`The column \"${patch.key}\" of table \"${patch.table}\" is edited in code: ${code}`, patch.table, patch.key);\n const transforms = columnTransforms(entry.value);\n if (transforms.nested) {\n throw refusal(\n `The column \"${patch.key}\" of table \"${patch.table}\" has field-level transforms inside its JSON shape or items, ` +\n \"which the editor cannot carry over: edit it in code.\",\n patch.table,\n patch.key\n );\n }\n const key = patch.op === \"renameColumn\" ? patch.to : patch.key;\n if (patch.op === \"renameColumn\" && patch.to !== patch.key && member(columns, patch.to, \"columns\").kind !== \"absent\") {\n throw refusal(`Table \"${patch.table}\" already has a column \"${patch.to}\".`, patch.table, patch.to);\n }\n const enums = enumBinder(workspace, patch.table);\n const { text, def } = printedColumn(key, patch.column, transforms.own, enums.bind);\n const source = workspace.text(table.file);\n workspace.edit(table.file, [replaceNode(source, entry.node, text)]);\n enums.declare();\n ensureBuilders(workspace, table.file, buildersOf(def));\n return;\n }\n case \"removeColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no column \"${patch.key}\".`, patch.table, patch.key);\n const entry = entryOf(columns, patch.key, patch.table, \"column\");\n const code = columnCode(entry.value, patch.key);\n if (code) throw refusal(`The column \"${patch.key}\" of table \"${patch.table}\" is edited in code: ${code}`, patch.table, patch.key);\n removeMember(workspace, table.file, columns, entry.index);\n return;\n }\n case \"moveColumn\": {\n const table = workspace.writable(patch.table);\n const columns = mapOf(table, \"columns\");\n if (!columns) throw refusal(`Table \"${patch.table}\" has no column \"${patch.key}\".`, patch.table, patch.key);\n const entry = entryOf(columns, patch.key, patch.table, \"column\");\n if (patch.before === patch.key) return;\n if (patch.before !== undefined) entryOf(columns, patch.before, patch.table, \"column\");\n const moved = itemText(workspace.text(table.file), listShape(columns, columns.getProperties()), entry.index);\n removeMember(workspace, table.file, columns, entry.index);\n const again = mapOf(workspace.writable(patch.table), \"columns\");\n if (!again) return;\n const members = again.getProperties();\n const index = patch.before !== undefined ? entryOf(again, patch.before, patch.table, \"column\").index : members.length;\n workspace.edit(table.file, insertListItem(workspace.text(table.file), listShape(again, members), index, moved, \"lines\"));\n return;\n }\n case \"addRelation\":\n case \"changeRelation\":\n return writeRelation(workspace, patch.table, patch.name, patch.relation, patch.op === \"changeRelation\");\n case \"removeRelation\": {\n const table = workspace.writable(patch.table);\n const relations = mapOf(table, \"relations\");\n if (!relations) throw refusal(`Table \"${patch.table}\" has no relation \"${patch.name}\".`, patch.table, patch.name);\n const entry = entryOf(relations, patch.name, patch.table, \"relation\");\n if (!isChainOf(entry.value, \"rel\")) {\n throw refusal(`The relation \"${patch.name}\" of table \"${patch.table}\" is edited in code: it is not a \\`rel.*\\` call.`, patch.table, patch.name);\n }\n const previous = thunkTarget(entry.value);\n removeMember(workspace, table.file, relations, entry.index);\n if (previous) dropUnusedImport(workspace, table.file, previous);\n return;\n }\n case \"setRls\": {\n const table = workspace.writable(patch.table);\n if (table.builder === \"defineView\") throw refusal(`\"${patch.table}\" is a view: it has no \\`rls\\` of its own.`, patch.table, \"rls\");\n const found = member(table.config, \"rls\", `table \"${patch.table}\"`);\n const printed = printRls(patch.rls);\n if (found.kind === \"absent\") {\n insertConfigMember(workspace, table, \"rls\", printed);\n return;\n }\n if (found.kind === \"code\") throw refusal(`The \\`rls\\` of table \"${patch.table}\" is edited in code: ${found.reason}`, patch.table, \"rls\");\n const source = workspace.text(table.file);\n workspace.edit(table.file, [replaceNode(source, found.value, printed)]);\n return;\n }\n case \"addRule\":\n case \"replaceRule\":\n case \"removeRule\":\n return writeRule(workspace, patch);\n case \"setOption\": {\n const table = workspace.writable(patch.table);\n const found = member(table.config, patch.option, `table \"${patch.table}\"`);\n if (found.kind === \"code\") throw refusal(`\\`${patch.option}\\` of table \"${patch.table}\" is edited in code: ${found.reason}`, patch.table, patch.option);\n if (found.kind === \"written\" && !isData(found.value)) {\n throw refusal(\n `\\`${patch.option}\\` of table \"${patch.table}\" is edited in code: it is \\`${found.value.getText().slice(0, 40)}\\`, not a literal.`,\n patch.table,\n patch.option\n );\n }\n if (patch.value === null) {\n if (found.kind === \"written\") removeMember(workspace, table.file, table.config, found.index);\n return;\n }\n const printed = printSchemaValue(patch.value, `${patch.table}.${patch.option}`);\n if (found.kind === \"absent\") insertConfigMember(workspace, table, patch.option, printed);\n else workspace.edit(table.file, [replaceNode(workspace.text(table.file), found.value, printed)]);\n return;\n }\n }\n}\n\nfunction writeRelation(workspace: Workspace, slug: string, name: string, relation: WireRelation, change: boolean): void {\n const target = workspace.tables().find(table => table.slug === relation.target);\n if (!target) throw refusal(`The relation \"${name}\" of table \"${slug}\" targets \"${relation.target}\", which is not a table in backend/schema.`, slug, name);\n let table = workspace.writable(slug);\n const identifier = bindingFor(workspace, table.file, target);\n table = workspace.writable(slug);\n const def = relationFromWire(relation, () => targetStandIn(target.name, target.slug));\n const printed = printRelation(name, def, { resolveTarget: () => ({ identifier }) });\n const relations = mapOf(table, \"relations\");\n if (!relations) {\n if (change) throw refusal(`Table \"${slug}\" has no relation \"${name}\".`, slug, name);\n insertConfigMember(workspace, table, \"relations\", `{\\n${deeper(\"\")}${printKey(name)}: ${reindent(printed, deeper(\"\"))}\\n}`);\n } else if (change) {\n const entry = entryOf(relations, name, slug, \"relation\");\n if (!isChainOf(entry.value, \"rel\")) {\n throw refusal(`The relation \"${name}\" of table \"${slug}\" is edited in code: it is not a \\`rel.*\\` call.`, slug, name);\n }\n const previous = thunkTarget(entry.value);\n workspace.edit(table.file, [replaceNode(workspace.text(table.file), entry.node, `${printKey(name)}: ${printed}`)]);\n if (previous && previous !== identifier) dropUnusedImport(workspace, table.file, previous);\n } else {\n if (member(relations, name, \"relations\").kind !== \"absent\") {\n throw refusal(`Table \"${slug}\" already has a relation \"${name}\". Change it instead.`, slug, name);\n }\n const members = relations.getProperties();\n workspace.edit(table.file, insertListItem(workspace.text(table.file), listShape(relations, members), members.length, `${printKey(name)}: ${printed}`, \"lines\"));\n }\n const pivot = relation.kind === \"manyToMany\" && relation.pivot !== undefined ? Object.values(relation.pivot).map(columnDefFromWire) : [];\n ensureBuilders(workspace, table.file, pivot.length > 0 ? (pivot.some(usesJson) ? [\"rel\", \"col\", \"json\"] : [\"rel\", \"col\"]) : [\"rel\"]);\n}\n\n/** The `rls` rule list of a table, writable, or a refusal. */\nfunction rulesOf(table: LocatedTable & { config: ObjectLiteralExpression }): ArrayLiteralExpression {\n const found = member(table.config, \"rls\", `table \"${table.slug}\"`);\n if (found.kind === \"code\") throw refusal(`The \\`rls\\` of table \"${table.slug}\" is edited in code: ${found.reason}`, table.slug, \"rls\");\n const value = found.kind === \"written\" ? unwrapExpression(found.value) : undefined;\n if (!value || !Node.isArrayLiteralExpression(value)) {\n throw refusal(\n `The \\`rls\\` of table \"${table.slug}\" is ${value ? `\\`${value.getText().slice(0, 40)}\\`` : \"absent\"}, not a list of rules. ` +\n \"Set the rules with `setRls` first.\",\n table.slug,\n \"rls\"\n );\n }\n if (value.getElements().some(element => Node.isSpreadElement(element))) {\n throw refusal(`The \\`rls\\` of table \"${table.slug}\" is edited in code: it spreads another list of rules.`, table.slug, \"rls\");\n }\n return value;\n}\n\nfunction writeRule(workspace: Workspace, patch: Extract<TablePatch, { op: \"addRule\" | \"replaceRule\" | \"removeRule\" }>): void {\n const table = workspace.writable(patch.table);\n const rules = rulesOf(table);\n const elements = rules.getElements();\n const list = listShape(rules, elements);\n const source = workspace.text(table.file);\n const index = patch.index ?? elements.length;\n if (patch.op === \"addRule\") {\n if (index > elements.length) throw refusal(`Table \"${patch.table}\" has ${elements.length} rule(s); there is no position ${index}.`, patch.table, \"rls\");\n const printed = printSchemaValue(patch.rule, `${patch.table}.rls[${index}]`);\n workspace.edit(table.file, insertListItem(source, list, index, printed, \"lines\"));\n return;\n }\n if (index >= elements.length) throw refusal(`Table \"${patch.table}\" has ${elements.length} rule(s); there is no rule ${index}.`, patch.table, \"rls\");\n const element = elements[index];\n if (!Node.isObjectLiteralExpression(unwrapExpression(element) ?? element)) {\n throw refusal(`Rule ${index} of table \"${patch.table}\" is edited in code: it is \\`${element.getText().slice(0, 40)}\\`.`, patch.table, \"rls\");\n }\n if (patch.op === \"removeRule\") {\n if (elements.length === 1) {\n throw refusal(`Rule ${index} is the last rule of table \"${patch.table}\", and an empty list leaves nobody a policy. Set \\`rls\\` to \"admin-only\" instead.`, patch.table, \"rls\");\n }\n workspace.edit(table.file, removeListItem(source, list, index));\n return;\n }\n workspace.edit(table.file, [replaceNode(source, element, printSchemaValue(patch.rule, `${patch.table}.rls[${index}]`))]);\n}\n\n/** The builders' module specifier this project writes: whatever an existing table file imports them from. */\nfunction builderSpecifier(workspace: Workspace): string {\n for (const table of workspace.tables()) {\n const found = builderImport(workspace.source(table.file));\n if (found) return found.declaration.getModuleSpecifierValue();\n }\n return DEFAULT_SCHEMA_SPECIFIER;\n}\n\nfunction createTable(workspace: Workspace, spec: NewTable): void {\n const tables = workspace.tables();\n const slug = spec.slug ?? spec.name;\n const clash = tables.find(table => table.slug === slug || table.name === spec.name);\n if (clash) throw refusal(`There is already a table \"${clash.name}\" (slug \"${clash.slug}\") in backend/schema.`, spec.name);\n const file = path.join(workspace.dir, `${spec.name}.ts`);\n if (workspace.has(file) || fs.existsSync(file)) throw refusal(`${file} already exists.`, spec.name);\n const identifier = tableIdentifier(spec.name);\n if (tables.some(table => table.exportName === identifier)) {\n throw refusal(`The schema index already exports \\`${identifier}\\`, the name the new table would be exported as.`, spec.name);\n }\n\n // The new table, for a relation of its own: its thunk is read when printed.\n const self: { def?: AnyTableDef } = {};\n const relations: RelationsShape = {};\n for (const [name, relation] of Object.entries(spec.relations ?? {})) {\n if (relation.target === slug) {\n relations[name] = relationFromWire(relation, () => self.def);\n continue;\n }\n const target = tables.find(table => table.slug === relation.target);\n if (!target) throw refusal(`The relation \"${name}\" targets \"${relation.target}\", which is not a table in backend/schema.`, spec.name, name);\n relations[name] = relationFromWire(relation, () => targetStandIn(target.name, target.slug));\n }\n const { name: _name, slug: _slug, table: _table, schema: _schema, columns: _columns, relations: _relations, rls: _rls, ...options } = spec;\n void _name; void _slug; void _table; void _schema; void _columns; void _relations; void _rls;\n const created = defineTable(spec.name, {\n ...(spec.slug !== undefined ? { slug: spec.slug } : {}),\n ...(spec.table !== undefined ? { table: spec.table } : {}),\n ...(spec.schema !== undefined ? { schema: spec.schema } : {}),\n ...options,\n columns: columnsFromWire(spec.columns),\n ...(Object.keys(relations).length > 0 ? { relations } : {}),\n rls: spec.rls\n });\n self.def = created;\n const module = printTableModule(created, {\n identifier,\n specifier: builderSpecifier(workspace),\n resolveTarget: target => {\n const found = tables.find(table => table.slug === target.slug);\n if (!found) return { identifier: tableIdentifier(target.name ?? target.slug) };\n return { identifier: found.variable, importPath: relativeSpecifier(file, found.file) };\n }\n });\n workspace.set(file, module);\n exportFromIndex(workspace, identifier, file);\n}\n\n/**\n * Write a table the database already has from its description, through the\n * printer — every column type, default, key, foreign key and enum as\n * introspection read it, so planning it changes nothing — and export it.\n */\nfunction adoptTable(workspace: Workspace, descriptor: TableDescriptor): void {\n const tables = workspace.tables();\n const clash = tables.find(table => table.slug === descriptor.slug || table.name === descriptor.name);\n if (clash) throw refusal(`There is already a table \"${clash.name}\" (slug \"${clash.slug}\") in backend/schema.`, descriptor.slug);\n const file = path.join(workspace.dir, `${descriptor.name}.ts`);\n if (workspace.has(file) || fs.existsSync(file)) throw refusal(`${file} already exists.`, descriptor.slug);\n const identifier = tableIdentifier(descriptor.name);\n if (tables.some(table => table.exportName === identifier)) {\n throw refusal(`The schema index already exports \\`${identifier}\\`, the name the adopted table would be exported as.`, descriptor.slug);\n }\n for (const relation of descriptor.relations) {\n if (relation.target === descriptor.slug || tables.some(table => table.slug === relation.target)) continue;\n throw refusal(`The relation \"${relation.name}\" targets \"${relation.target}\", which is not a table in backend/schema.`, descriptor.slug, relation.name);\n }\n const module = printTableModule(descriptor, {\n identifier,\n specifier: builderSpecifier(workspace),\n resolveTarget: target => {\n const found = tables.find(table => table.slug === target.slug);\n if (!found) return { identifier };\n return { identifier: found.variable, importPath: relativeSpecifier(file, found.file) };\n }\n });\n workspace.set(file, module);\n exportFromIndex(workspace, identifier, file);\n}\n\n/** Export a table's file from the schema index, after the last export (creating the index when there is none). */\nfunction exportFromIndex(workspace: Workspace, identifier: string, file: string): void {\n const line = printIndexModule([{ identifier, importPath: relativeSpecifier(path.join(workspace.dir, \"index.ts\"), file) }]);\n const indexPath = workspace.indexFile();\n if (!indexPath) {\n workspace.set(path.join(workspace.dir, \"index.ts\"), line);\n return;\n }\n const index = workspace.source(indexPath);\n const exports = index.getExportDeclarations();\n const text = workspace.text(indexPath);\n if (exports.length > 0) {\n const at = exports[exports.length - 1].getEnd();\n workspace.edit(indexPath, [{ start: at, end: at, text: `\\n${line.trimEnd()}` }]);\n } else {\n workspace.edit(indexPath, [{ start: text.length, end: text.length, text: `${text.endsWith(\"\\n\") || text === \"\" ? \"\" : \"\\n\"}${line}` }]);\n }\n}\n\nasync function deleteTable(workspace: Workspace, slug: string, editor: TableSourceEditor): Promise<void> {\n const table = workspace.table(slug);\n // Who points at it, read from what the schema compiles to now: a relation's\n // target is a thunk, and only compiling resolves it to a table.\n const current = await editor.compile(workspace.texts());\n const referencing = current.descriptors.flatMap(descriptor =>\n descriptor.slug === slug ? [] : descriptor.relations\n .filter(relation => relation.target === slug)\n .map(relation => `${descriptor.slug}.${relation.name}`));\n if (referencing.length > 0) {\n throw refusal(\n `Table \"${slug}\" cannot be deleted while relations target it: ${referencing.join(\", \")}. ` +\n \"Remove or retarget those relations first.\",\n slug\n );\n }\n\n const source = workspace.source(table.file);\n const statement = table.declaration.getFirstAncestor(Node.isVariableStatement);\n if (!statement) throw refusal(`The definition of \"${slug}\" is not a top-level \\`const\\`.`, slug);\n const others = source.getStatements().filter(each => each !== statement && !Node.isImportDeclaration(each));\n const indexPath = workspace.indexFile();\n const definedInIndex = table.file === indexPath;\n if (others.length === 0 && !definedInIndex) {\n workspace.delete(table.file);\n } else {\n removeVariable(workspace, table.file, statement, table.declaration);\n }\n\n if (!indexPath || definedInIndex) return;\n const index = workspace.source(indexPath);\n const deletedFile = !workspace.has(table.file);\n for (const declaration of index.getExportDeclarations()) {\n const targetFile = declaration.getModuleSpecifierSourceFile()?.getFilePath();\n const named = declaration.getNamedExports();\n const position = index.getStatements().indexOf(declaration);\n const previousEnd = position > 0 ? index.getStatements()[position - 1].getEnd() : 0;\n if (named.length === 0) {\n if (deletedFile && targetFile === table.file) workspace.edit(indexPath, [removeStatement(index.getFullText(), declaration, previousEnd)]);\n continue;\n }\n const at = named.findIndex(element => (element.getAliasNode()?.getText() ?? element.getName()) === table.exportName);\n if (at === -1) continue;\n if (named.length === 1) {\n workspace.edit(indexPath, [removeStatement(index.getFullText(), declaration, previousEnd)]);\n } else {\n const element = named[at];\n workspace.edit(indexPath, [at < named.length - 1\n ? { start: element.getStart(), end: named[at + 1].getStart(), text: \"\" }\n : { start: named[at - 1].getEnd(), end: element.getEnd(), text: \"\" }]);\n }\n return;\n }\n}\n\nfunction removeVariable(workspace: Workspace, file: string, statement: VariableStatement, declaration: VariableDeclaration): void {\n const source = workspace.source(file);\n const declarations = statement.getDeclarations();\n if (declarations.length > 1) {\n throw refusal(`${file} declares \"${declaration.getName()}\" together with other constants in one statement: delete it in code.`, declaration.getName());\n }\n const statements = source.getStatements();\n const position = statements.indexOf(statement);\n workspace.edit(file, [removeStatement(source.getFullText(), statement, position > 0 ? statements[position - 1].getEnd() : 0)]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,gBAAgB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