@palbase/backend 9.0.1 → 10.1.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.
@@ -1,4 +1,4 @@
1
- import { D as DBClient, P as PBRequest, a as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-CGI5cZMg.cjs';
1
+ import { D as DBClient, P as PBRequest, a as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-Cn3ICGTf.cjs';
2
2
  import 'zod';
3
3
 
4
4
  /** Mock DB client with tracking and seed data support. */
@@ -1,4 +1,4 @@
1
- import { D as DBClient, P as PBRequest, a as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-CGI5cZMg.js';
1
+ import { D as DBClient, P as PBRequest, a as PalbaseModuleClients, L as Logger, C as CacheClient, Q as QueueClient, U as User } from '../endpoint-Cn3ICGTf.js';
2
2
  import 'zod';
3
3
 
4
4
  /** Mock DB client with tracking and seed data support. */
package/docs/README.md CHANGED
@@ -185,19 +185,21 @@ generated client surface) changes; the verb/path do not affect it.
185
185
  ### CLI workflow
186
186
 
187
187
  - `palbase serve` — run `controllers/` locally with hot reload (proxies
188
- `Database`/services to the deployed branch; runs `gen-types` on startup).
188
+ `Database`/services to the selected deployed Environment; runs `gen-types` on
189
+ startup).
189
190
  - `palbase gen-types` — regenerate `palbase-env.d.ts` from `db/schema.ts` so
190
191
  `Database.tables.*` is typed (no import, no generic). Standalone version of what
191
192
  `serve` runs.
192
- - **Deploy is GitHub-native** — `git push` triggers the deploy (there is no
193
- `palbase push`). Push a branch to deploy that branch.
194
- - `palbase secret set NAME=value` / `palbase secret list` — branch-scoped
193
+ - `palbase push` — deploy the current backend to the selected Environment. For a
194
+ GitHub-backed project it runs `git push`; the pushed source Git branch deploys
195
+ to the Environment configured for that branch.
196
+ - `palbase secret set NAME=value` / `palbase secret list` — Environment-scoped
195
197
  secrets (encrypted at rest), read in code via `process.env.NAME`.
196
- - `palbase secret pull` / `palbase secret push` — sync the branch's env vars with
197
- a local `.env.local` (gitignored). `pull` writes decrypted values for local dev
198
- (merging local-only keys); `push` uploads changed keys (new keys default to
199
- SECRET and need `--secret`/`--plain` classification, existing secrets are left
200
- untouched unless `--force-secrets`).
198
+ - `palbase secret pull` / `palbase secret push` — sync the selected Environment's
199
+ variables with a local `.env.local` (gitignored). `pull` writes decrypted
200
+ values for local dev (merging local-only keys); `push` uploads changed keys
201
+ (new keys default to SECRET and need `--secret`/`--plain` classification,
202
+ existing secrets are left untouched unless `--force-secrets`).
201
203
  - `tsconfig.json` needs `"experimentalDecorators": true` (the scaffold sets it).
202
204
 
203
205
  ## Mental model
@@ -219,7 +221,7 @@ The **only difference** is the trigger argument:
219
221
  | **Webhooks** (`webhooks/**`) | `(event, meta)` | typed event + `WebhookMeta` |
220
222
  | **Middleware** (`middleware/**`) | `(ctx, next)` | `MiddlewareContext` — the **one exception** |
221
223
 
222
- `meta` carries non-service data: `env` (branch env vars), `projectId`,
224
+ `meta` carries non-service data: `env` (Environment variables),
223
225
  `environmentId`, and for workers/webhooks `requestId`. Services always come from
224
226
  the imported singletons — not from `ctx` or any argument.
225
227
 
@@ -28,8 +28,8 @@ export default defineWorker<OrderPayload>({
28
28
  });
29
29
  ```
30
30
 
31
- `meta` shape: `{ env, user, requestId, projectId, environmentId }`. Branch env
32
- vars are in `meta.env`; services come from the imported singletons.
31
+ `meta` shape: `{ env, user, requestId, environmentId }`. Environment
32
+ variables are in `meta.env`; services come from the imported singletons.
33
33
 
34
34
  Enqueue from an endpoint:
35
35
 
@@ -53,10 +53,10 @@ export default defineJob({
53
53
  handler: async (meta) => {
54
54
  const expired = await Database.findMany("sessions", { expired: true });
55
55
  for (const s of expired) await Database.delete("sessions", s.id as string);
56
- Log.info(`cleaned ${expired.length} sessions in ${meta.projectId}`);
56
+ Log.info(`cleaned ${expired.length} sessions in ${meta.environmentId}`);
57
57
  },
58
58
  });
59
59
  ```
60
60
 
61
- `meta` shape: `{ env, projectId, environmentId }`. No `user` (jobs are
61
+ `meta` shape: `{ env, environmentId }`. No `user` (jobs are
62
62
  system-initiated).
package/docs/events.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Like workers/jobs, hooks and webhooks use the **singleton model** — the same
4
4
  imported service singletons as endpoints (`import { Database, Log } from
5
5
  "@palbase/backend"`). They do **not** receive a `req`. A second `meta` argument
6
- carries the non-service data (`env`, `projectId`, `environmentId`; webhooks also
6
+ carries the non-service data (`env`, `environmentId`; webhooks also
7
7
  get `requestId`).
8
8
 
9
9
  ## Hooks (platform events)
@@ -28,7 +28,7 @@ export const onSignIn = auth.onSignIn(async (event, meta) => {
28
28
  });
29
29
  ```
30
30
 
31
- `meta` shape: `{ env, projectId, environmentId }`. Branch env vars are in
31
+ `meta` shape: `{ env, environmentId }`. Environment variables are in
32
32
  `meta.env`; services come from the imported singletons.
33
33
 
34
34
  Available hook builders: `auth.onUserCreated`, `auth.onSignIn`, `auth.onSignOut`,
@@ -61,7 +61,7 @@ export default defineWebhook({
61
61
  ```
62
62
 
63
63
  The signing secret is resolved by the runtime from `secret: { env: "NAME" }`;
64
- your handlers access branch env vars via `meta.env`. The runtime verifies the
64
+ your handlers access Environment variables via `meta.env`. The runtime verifies the
65
65
  signature before dispatching to your event handlers.
66
66
 
67
- `meta` shape: `{ env, requestId, projectId, environmentId }`.
67
+ `meta` shape: `{ env, requestId, environmentId }`.
@@ -41,15 +41,16 @@ The controllers use **decorators**, so the `tsconfig.json` must set
41
41
 
42
42
  - `palbase serve` — run your backend locally with hot reload. It runs your
43
43
  `controllers/` locally but proxies `Database` and the service singletons to
44
- the **deployed** branch, so the branch must already be deployed (serve tells
45
- you to push first if it isn't). On startup it also runs `gen-types`. See
44
+ the selected deployed Environment, so that Environment must already have a
45
+ deployment (`serve` tells you to push first if it does not). On startup it
46
+ also runs `gen-types`. See
46
47
  [migrations.md](./migrations.md) for the schema/migration side of this.
47
48
  - `palbase gen-types` — regenerate `palbase-env.d.ts` from `db/schema.ts` so
48
49
  `Database.tables.*` is typed (no import, no generic). Run it standalone after
49
50
  editing the schema, or rely on `palbase serve` running it for you.
50
- - **Deploy is GitHub-native** — there is no `palbase push`. Commit and
51
- `git push` to your project's repo; the push triggers a deploy of the backend
52
- runtime. Push a **branch** to deploy that branch instead of `main`.
51
+ - `palbase push` deploys the current backend to the selected Environment. For a
52
+ GitHub-backed project it runs `git push`; Studio maps the pushed source Git
53
+ branch to its configured Environment.
53
54
 
54
55
  ## Your first endpoint
55
56
 
@@ -193,19 +193,21 @@ generated client surface) changes; the verb/path do not affect it.
193
193
  ### CLI workflow
194
194
 
195
195
  - `palbase serve` — run `controllers/` locally with hot reload (proxies
196
- `Database`/services to the deployed branch; runs `gen-types` on startup).
196
+ `Database`/services to the selected deployed Environment; runs `gen-types` on
197
+ startup).
197
198
  - `palbase gen-types` — regenerate `palbase-env.d.ts` from `db/schema.ts` so
198
199
  `Database.tables.*` is typed (no import, no generic). Standalone version of what
199
200
  `serve` runs.
200
- - **Deploy is GitHub-native** — `git push` triggers the deploy (there is no
201
- `palbase push`). Push a branch to deploy that branch.
202
- - `palbase secret set NAME=value` / `palbase secret list` — branch-scoped
201
+ - `palbase push` — deploy the current backend to the selected Environment. For a
202
+ GitHub-backed project it runs `git push`; the pushed source Git branch deploys
203
+ to the Environment configured for that branch.
204
+ - `palbase secret set NAME=value` / `palbase secret list` — Environment-scoped
203
205
  secrets (encrypted at rest), read in code via `process.env.NAME`.
204
- - `palbase secret pull` / `palbase secret push` — sync the branch's env vars with
205
- a local `.env.local` (gitignored). `pull` writes decrypted values for local dev
206
- (merging local-only keys); `push` uploads changed keys (new keys default to
207
- SECRET and need `--secret`/`--plain` classification, existing secrets are left
208
- untouched unless `--force-secrets`).
206
+ - `palbase secret pull` / `palbase secret push` — sync the selected Environment's
207
+ variables with a local `.env.local` (gitignored). `pull` writes decrypted
208
+ values for local dev (merging local-only keys); `push` uploads changed keys
209
+ (new keys default to SECRET and need `--secret`/`--plain` classification,
210
+ existing secrets are left untouched unless `--force-secrets`).
209
211
  - `tsconfig.json` needs `"experimentalDecorators": true` (the scaffold sets it).
210
212
 
211
213
  ## Mental model
@@ -227,7 +229,7 @@ The **only difference** is the trigger argument:
227
229
  | **Webhooks** (`webhooks/**`) | `(event, meta)` | typed event + `WebhookMeta` |
228
230
  | **Middleware** (`middleware/**`) | `(ctx, next)` | `MiddlewareContext` — the **one exception** |
229
231
 
230
- `meta` carries non-service data: `env` (branch env vars), `projectId`,
232
+ `meta` carries non-service data: `env` (Environment variables),
231
233
  `environmentId`, and for workers/webhooks `requestId`. Services always come from
232
234
  the imported singletons — not from `ctx` or any argument.
233
235
 
@@ -325,15 +327,16 @@ The controllers use **decorators**, so the `tsconfig.json` must set
325
327
 
326
328
  - `palbase serve` — run your backend locally with hot reload. It runs your
327
329
  `controllers/` locally but proxies `Database` and the service singletons to
328
- the **deployed** branch, so the branch must already be deployed (serve tells
329
- you to push first if it isn't). On startup it also runs `gen-types`. See
330
+ the selected deployed Environment, so that Environment must already have a
331
+ deployment (`serve` tells you to push first if it does not). On startup it
332
+ also runs `gen-types`. See
330
333
  [migrations.md](./migrations.md) for the schema/migration side of this.
331
334
  - `palbase gen-types` — regenerate `palbase-env.d.ts` from `db/schema.ts` so
332
335
  `Database.tables.*` is typed (no import, no generic). Run it standalone after
333
336
  editing the schema, or rely on `palbase serve` running it for you.
334
- - **Deploy is GitHub-native** — there is no `palbase push`. Commit and
335
- `git push` to your project's repo; the push triggers a deploy of the backend
336
- runtime. Push a **branch** to deploy that branch instead of `main`.
337
+ - `palbase push` deploys the current backend to the selected Environment. For a
338
+ GitHub-backed project it runs `git push`; Studio maps the pushed source Git
339
+ branch to its configured Environment.
337
340
 
338
341
  ## Your first endpoint
339
342
 
@@ -978,7 +981,7 @@ migrations in `db/migrations/`; nothing is auto-applied behind your back.
978
981
  ```bash
979
982
  # 1. Edit db/schema.ts (add a column, a table, a policy, …)
980
983
 
981
- # 2. Generate the migration from the diff (declared schema vs the live branch)
984
+ # 2. Generate the migration from the diff (declared schema vs the selected Environment)
982
985
  palbase db diff -f add_priority
983
986
  # → writes db/migrations/<timestamp>_add_priority.sql
984
987
 
@@ -987,10 +990,10 @@ palbase db diff -f add_priority
987
990
  git add db/migrations && git commit -m "add priority column" && git push
988
991
  ```
989
992
 
990
- `palbase db diff` introspects your **live branch database** (there is no local
991
- database — every branch runs on the server), diffs it against `db/schema.ts`, and
992
- writes one migration SQL file. If the schema is already in sync it writes nothing
993
- and tells you so.
993
+ `palbase db diff` introspects the selected Environment's live database (there is
994
+ no local database — each Environment runs on the server), diffs it against
995
+ `db/schema.ts`, and writes one migration SQL file. If the schema is already in
996
+ sync it writes nothing and tells you so.
994
997
 
995
998
  ## Additive vs destructive
996
999
 
@@ -1038,11 +1041,11 @@ You can't push a schema change without its migration:
1038
1041
  ## `palbase serve` uses the deployed database
1039
1042
 
1040
1043
  `palbase serve` runs your controllers locally but proxies `Database` and `ctx.*`
1041
- to the **deployed** branch — it does not spin up a local Postgres. So a schema
1042
- change in `db/schema.ts` doesn't exist in the database until you generate the
1043
- migration and push. Run `palbase gen-types` (or just `palbase serve`, which
1044
- regenerates on change) after editing the schema to refresh `palbase-env.d.ts` so
1045
- `Database.tables.<name>` is fully typed in your services.
1044
+ to the selected deployed Environment — it does not spin up a local Postgres. So
1045
+ a schema change in `db/schema.ts` does not exist in that database until you
1046
+ generate the migration and deploy it. Run `palbase gen-types` (or just
1047
+ `palbase serve`, which regenerates on change) after editing the schema to refresh
1048
+ `palbase-env.d.ts` so `Database.tables.<name>` is fully typed in your services.
1046
1049
 
1047
1050
  ## Hand-written migrations
1048
1051
 
@@ -1376,9 +1379,9 @@ per-user.
1376
1379
  - It **types** the `env` passed to `init` — only the declared names are
1377
1380
  present, each a `string`. An undeclared key is a compile error.
1378
1381
  - A declared secret that is **missing at boot fails the deploy**, naming the
1379
- secret. Secrets are branch-scoped; set them with `palbase secret set NAME ...`
1380
- or in Studio. A resource is initialised once at boot, so rotating a secret
1381
- needs a redeploy/restart.
1382
+ secret. Secrets are Environment-scoped; set them with
1383
+ `palbase secret set NAME ...` or in Studio. A resource is initialised once at
1384
+ boot, so rotating a secret needs a redeploy/restart.
1382
1385
 
1383
1386
  `secrets` is optional — a resource that needs none simply omits it and gets an
1384
1387
  empty `env`.
@@ -1487,8 +1490,8 @@ export default defineWorker<OrderPayload>({
1487
1490
  });
1488
1491
  ```
1489
1492
 
1490
- `meta` shape: `{ env, user, requestId, projectId, environmentId }`. Branch env
1491
- vars are in `meta.env`; services come from the imported singletons.
1493
+ `meta` shape: `{ env, user, requestId, environmentId }`. Environment
1494
+ variables are in `meta.env`; services come from the imported singletons.
1492
1495
 
1493
1496
  Enqueue from an endpoint:
1494
1497
 
@@ -1512,12 +1515,12 @@ export default defineJob({
1512
1515
  handler: async (meta) => {
1513
1516
  const expired = await Database.findMany("sessions", { expired: true });
1514
1517
  for (const s of expired) await Database.delete("sessions", s.id as string);
1515
- Log.info(`cleaned ${expired.length} sessions in ${meta.projectId}`);
1518
+ Log.info(`cleaned ${expired.length} sessions in ${meta.environmentId}`);
1516
1519
  },
1517
1520
  });
1518
1521
  ```
1519
1522
 
1520
- `meta` shape: `{ env, projectId, environmentId }`. No `user` (jobs are
1523
+ `meta` shape: `{ env, environmentId }`. No `user` (jobs are
1521
1524
  system-initiated).
1522
1525
 
1523
1526
 
@@ -1529,7 +1532,7 @@ system-initiated).
1529
1532
  Like workers/jobs, hooks and webhooks use the **singleton model** — the same
1530
1533
  imported service singletons as endpoints (`import { Database, Log } from
1531
1534
  "@palbase/backend"`). They do **not** receive a `req`. A second `meta` argument
1532
- carries the non-service data (`env`, `projectId`, `environmentId`; webhooks also
1535
+ carries the non-service data (`env`, `environmentId`; webhooks also
1533
1536
  get `requestId`).
1534
1537
 
1535
1538
  ## Hooks (platform events)
@@ -1554,7 +1557,7 @@ export const onSignIn = auth.onSignIn(async (event, meta) => {
1554
1557
  });
1555
1558
  ```
1556
1559
 
1557
- `meta` shape: `{ env, projectId, environmentId }`. Branch env vars are in
1560
+ `meta` shape: `{ env, environmentId }`. Environment variables are in
1558
1561
  `meta.env`; services come from the imported singletons.
1559
1562
 
1560
1563
  Available hook builders: `auth.onUserCreated`, `auth.onSignIn`, `auth.onSignOut`,
@@ -1587,7 +1590,7 @@ export default defineWebhook({
1587
1590
  ```
1588
1591
 
1589
1592
  The signing secret is resolved by the runtime from `secret: { env: "NAME" }`;
1590
- your handlers access branch env vars via `meta.env`. The runtime verifies the
1593
+ your handlers access Environment variables via `meta.env`. The runtime verifies the
1591
1594
  signature before dispatching to your event handlers.
1592
1595
 
1593
- `meta` shape: `{ env, requestId, projectId, environmentId }`.
1596
+ `meta` shape: `{ env, requestId, environmentId }`.
@@ -11,7 +11,7 @@ migrations in `db/migrations/`; nothing is auto-applied behind your back.
11
11
  ```bash
12
12
  # 1. Edit db/schema.ts (add a column, a table, a policy, …)
13
13
 
14
- # 2. Generate the migration from the diff (declared schema vs the live branch)
14
+ # 2. Generate the migration from the diff (declared schema vs the selected Environment)
15
15
  palbase db diff -f add_priority
16
16
  # → writes db/migrations/<timestamp>_add_priority.sql
17
17
 
@@ -20,10 +20,10 @@ palbase db diff -f add_priority
20
20
  git add db/migrations && git commit -m "add priority column" && git push
21
21
  ```
22
22
 
23
- `palbase db diff` introspects your **live branch database** (there is no local
24
- database — every branch runs on the server), diffs it against `db/schema.ts`, and
25
- writes one migration SQL file. If the schema is already in sync it writes nothing
26
- and tells you so.
23
+ `palbase db diff` introspects the selected Environment's live database (there is
24
+ no local database — each Environment runs on the server), diffs it against
25
+ `db/schema.ts`, and writes one migration SQL file. If the schema is already in
26
+ sync it writes nothing and tells you so.
27
27
 
28
28
  ## Additive vs destructive
29
29
 
@@ -71,11 +71,11 @@ You can't push a schema change without its migration:
71
71
  ## `palbase serve` uses the deployed database
72
72
 
73
73
  `palbase serve` runs your controllers locally but proxies `Database` and `ctx.*`
74
- to the **deployed** branch — it does not spin up a local Postgres. So a schema
75
- change in `db/schema.ts` doesn't exist in the database until you generate the
76
- migration and push. Run `palbase gen-types` (or just `palbase serve`, which
77
- regenerates on change) after editing the schema to refresh `palbase-env.d.ts` so
78
- `Database.tables.<name>` is fully typed in your services.
74
+ to the selected deployed Environment — it does not spin up a local Postgres. So
75
+ a schema change in `db/schema.ts` does not exist in that database until you
76
+ generate the migration and deploy it. Run `palbase gen-types` (or just
77
+ `palbase serve`, which regenerates on change) after editing the schema to refresh
78
+ `palbase-env.d.ts` so `Database.tables.<name>` is fully typed in your services.
79
79
 
80
80
  ## Hand-written migrations
81
81
 
package/docs/resources.md CHANGED
@@ -75,9 +75,9 @@ per-user.
75
75
  - It **types** the `env` passed to `init` — only the declared names are
76
76
  present, each a `string`. An undeclared key is a compile error.
77
77
  - A declared secret that is **missing at boot fails the deploy**, naming the
78
- secret. Secrets are branch-scoped; set them with `palbase secret set NAME ...`
79
- or in Studio. A resource is initialised once at boot, so rotating a secret
80
- needs a redeploy/restart.
78
+ secret. Secrets are Environment-scoped; set them with
79
+ `palbase secret set NAME ...` or in Studio. A resource is initialised once at
80
+ boot, so rotating a secret needs a redeploy/restart.
81
81
 
82
82
  `secrets` is optional — a resource that needs none simply omits it and gets an
83
83
  empty `env`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@palbase/backend",
3
- "version": "9.0.1",
3
+ "version": "10.1.0",
4
4
  "description": "Palbase Backend SDK — class controllers (@Controller/@Get/@Post + @Body/@QueryParams/@Param), error classes, schema DSL",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db/policy.ts","../src/db/schema.ts","../src/db/extensions.ts","../src/db/columns.ts","../src/db/raw.ts","../src/db/typed-db.ts"],"sourcesContent":["/**\n * policy.ts — the RLS policy authoring DSL.\n *\n * `policy(name)` returns a fluent builder that mirrors the `ColumnBuilder`\n * style in columns.ts: each chainable method mutates the underlying\n * definition and returns the builder so calls compose. The terminal value is\n * a plain {@link PolicyDef} — the exact JSON shape the runtime's\n * `schema_extract.js` reads off the bundled module and the Go side parses into\n * `PolicyJSON` (CONTRACT-POLICY).\n *\n * @example\n * import { policy } from \"@palbase/backend\";\n *\n * policy(\"owner_select\")\n * .for(\"select\")\n * .to(\"authenticated\")\n * .using(\"owner = (select auth.uid())\");\n */\n\n/** The SQL command a policy applies to. `\"all\"` covers SELECT/INSERT/UPDATE/DELETE. */\nexport type PolicyCommand = \"all\" | \"select\" | \"insert\" | \"update\" | \"delete\";\n\n/** Whether a policy is permissive (OR-combined, the default) or restrictive\n * (AND-combined). Mirrors Postgres `CREATE POLICY ... AS PERMISSIVE|RESTRICTIVE`. */\nexport type PolicyMode = \"permissive\" | \"restrictive\";\n\n/**\n * The compiled, serializable policy definition — the EXACT shape consumed by\n * `schema_extract.js` → Go `PolicyJSON` (CONTRACT-POLICY).\n *\n * - `roles`: the DB roles this policy applies to (`TO` clause). An empty array\n * means the policy applies to PUBLIC (all roles) — the Postgres default.\n * - `using`: the `USING (...)` row-visibility expression, or `null` when none.\n * - `withCheck`: the `WITH CHECK (...)` write-validation expression, or `null`.\n * - `permissive`: `true` for `AS PERMISSIVE` (default), `false` for restrictive.\n */\nexport interface PolicyDef {\n name: string;\n command: PolicyCommand;\n roles: string[];\n using: string | null;\n withCheck: string | null;\n permissive: boolean;\n}\n\n/**\n * Fluent RLS policy builder.\n *\n * Defaults (documented, applied at construction):\n * - `command`: `\"all\"` — applies to every SQL command unless `.for(...)` narrows it.\n * - `roles`: `[\"authenticated\"]` — the common case is \"rule applies to signed-in\n * users\". Call `.to(...)` to override; pass `.to()` with no roles (or never\n * call it after a reset) to target PUBLIC.\n * - `using` / `withCheck`: `null` — no row filter / write check until set.\n * - `permissive`: `true` — `AS PERMISSIVE` (policies OR together).\n *\n * Each method mutates `_def` in place and returns `this`, so the chain is a\n * single builder instance (no per-call allocation, like a tagged-template\n * compile target). The terminal `PolicyDef` is read directly off `_def` by\n * `schema_extract.js`.\n */\nexport class PolicyBuilder {\n readonly _def: PolicyDef;\n\n constructor(name: string) {\n this._def = {\n name,\n command: \"all\",\n roles: [\"authenticated\"],\n using: null,\n withCheck: null,\n permissive: true,\n };\n }\n\n /** Restrict the policy to a single SQL command (default `\"all\"`). */\n for(command: PolicyCommand): this {\n this._def.command = command;\n return this;\n }\n\n /**\n * Set the DB roles the policy applies to (the `TO` clause), replacing any\n * previously-set roles. Call with no arguments to target PUBLIC (all roles).\n *\n * @example\n * policy(\"p\").to(\"authenticated\")\n * policy(\"p\").to(\"authenticated\", \"service_role\")\n * policy(\"p\").to() // PUBLIC\n */\n to(...roles: string[]): this {\n this._def.roles = roles;\n return this;\n }\n\n /** Set the `USING (...)` row-visibility expression (raw SQL). */\n using(sqlExpr: string): this {\n this._def.using = sqlExpr;\n return this;\n }\n\n /** Set the `WITH CHECK (...)` write-validation expression (raw SQL). */\n withCheck(sqlExpr: string): this {\n this._def.withCheck = sqlExpr;\n return this;\n }\n\n /** Set the policy mode: `\"permissive\"` (default, OR-combined) or\n * `\"restrictive\"` (AND-combined). */\n as(mode: PolicyMode): this {\n this._def.permissive = mode === \"permissive\";\n return this;\n }\n}\n\n/**\n * Start authoring an RLS policy. Returns a {@link PolicyBuilder}; the resulting\n * `PolicyBuilder` is accepted directly in a table's `policies: [...]` array\n * (its `_def` is read at schema-extract time).\n *\n * @param name The policy name. Palbase reconciliation keys policies by\n * `(table, name)`, so names must be unique per table.\n */\nexport function policy(name: string): PolicyBuilder {\n return new PolicyBuilder(name);\n}\n","import type { ColumnBuilder } from \"./columns.js\";\nimport { PolicyBuilder } from \"./policy.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { PalbaseExtension } from \"./extensions.js\";\nimport type { RawConstraintDef } from \"./raw.js\";\n\n/**\n * A map of column builders keyed by column name — the value you write under\n * the `columns` key of `defineSchema({ tables: { <name>: { columns } } })`.\n *\n * The default `Record<string, ColumnBuilder>` keeps bare references compiling\n * without a type argument.\n */\nexport type ColumnMap = Record<string, ColumnBuilder>;\n\n/**\n * The author-facing value written under each table key:\n * `{ columns, rls?, policies? }`.\n *\n * - `columns`: the column map (required).\n * - `rls`: enable + FORCE row-level security on this table. Implied when\n * `policies` is non-empty; set it explicitly to enable RLS with no policies\n * yet (deny-all — useful only as an intermediate step).\n * - `policies`: the RLS policies for this table, authored with `policy(name)`.\n * Each entry may be a {@link PolicyBuilder} (the normal `policy(...)` chain)\n * or a raw {@link PolicyDef} object.\n *\n * The `C` type parameter preserves the precise per-column phantom types so the\n * typed `Database.tables.*` surface keeps inferring insert/row shapes.\n */\nexport interface TableInput<C extends ColumnMap = ColumnMap> {\n columns: C;\n rls?: boolean;\n policies?: (PolicyBuilder | PolicyDef)[];\n /** Composite/named primary key (ordered column names). Omit for single-column inline .primaryKey(). */\n primaryKey?: string[];\n /** Named multi-column UNIQUE constraints. */\n unique?: { name: string; columns: string[] }[];\n /** Named raw-SQL DDL objects (EXCLUDE, triggers, views) that the typed DSL cannot express. */\n raw?: RawConstraintDef[];\n /**\n * Named first-class CHECK constraints. Diffed by NAME with a BODY compare:\n * a changed `expr` (after pg normalization) recreates the constraint\n * (DROP + ADD). `expr` is trusted SQL emitted verbatim (like policy USING),\n * `name` is identifier-validated.\n */\n checks?: { name: string; expr: string }[];\n /**\n * Plain (non-unique) btree indexes over an ordered column list, emitted as\n * standalone `CREATE INDEX [IF NOT EXISTS] name ON table (col1, col2)`\n * statements (NOT a table clause — a separate migration statement category).\n * Structural compare by NAME (no expression normalization). `name` and each\n * column are identifier-validated by the Go differ.\n *\n * Scope: columns-only plain btree. Partial (`where`) and expression indexes\n * are a deliberate follow-up — modelling them needs the same raw-SQL\n * normalization round-trip CHECK uses (Task 10), so they are NOT in this\n * type yet to avoid a half-working partial-index path.\n */\n indexes?: { name: string; columns: string[] }[];\n}\n\n/**\n * A table definition — the runtime value the Go runtime's `schema_extract.js`\n * reads. It keys tables by `tableDef.name`, reads `tableDef.columns` for the\n * column DDL, and `tableDef.rls` + `tableDef.policies` for RLS.\n *\n * `defineSchema` derives `name` from the object key, so authors never repeat\n * the table name. `rls`/`policies` are always present after normalization\n * (defaulted to `false`/`[]`).\n *\n * The `C` type parameter preserves the precise per-column phantom types so that\n * downstream mapped types (InsertShape, RowShape) can discriminate on them.\n */\nexport interface TableDef<C extends ColumnMap = ColumnMap> {\n name: string;\n columns: C;\n rls: boolean;\n policies: PolicyDef[];\n primaryKey?: string[];\n unique?: { name: string; columns: string[] }[];\n /** Named raw-SQL DDL objects emitted verbatim on deploy. Tracked by name. */\n raw?: RawConstraintDef[];\n /** Named first-class CHECK constraints. Diffed by name + (normalized) body. */\n checks?: { name: string; expr: string }[];\n /** Plain btree indexes (columns-only), emitted as standalone CREATE INDEX. Diffed by name. */\n indexes?: { name: string; columns: string[] }[];\n}\n\n/**\n * A schema definition containing multiple tables, keyed by table name.\n *\n * The `T` type parameter preserves the exact `TableDef<...>` type for each\n * table so that `SchemaDef[\"tables\"][\"rooms\"]` resolves to the precise\n * `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.\n */\nexport interface SchemaDef<\n T extends Record<string, TableDef> = Record<string, TableDef>,\n> {\n tables: T;\n /** Postgres extensions to install on deploy. Normalized to `[]` when absent. */\n extensions: PalbaseExtension[];\n}\n\n/** The author-facing input to `defineSchema` — a `tables` map whose keys are\n * the table names and whose values are `{ columns, rls?, policies? }`, plus an\n * optional `extensions` allowlist. */\nexport interface SchemaInput<\n T extends Record<string, TableInput> = Record<string, TableInput>,\n> {\n tables: T;\n /**\n * Postgres extensions to enable for this project, e.g. `[\"vector\"]`.\n * Config-as-code: installed by the deploy (CREATE EXTENSION … SCHEMA\n * extensions) with the privileged deploy connection. The type is an\n * allowlist union, so unsupported names fail typecheck.\n */\n extensions?: PalbaseExtension[];\n}\n\n/** Map the author's `{ tables: { <name>: { columns } } }` input to the\n * `{ tables: { <name>: TableDef<columns> } }` runtime/type shape, threading the\n * per-table column map `T[K][\"columns\"]` so column-level inference survives. */\ntype TablesFromInput<T extends Record<string, TableInput>> = {\n [K in keyof T]: TableDef<T[K][\"columns\"]>;\n};\n\n/** Normalize a single `policies` entry into a plain `PolicyDef` (read off a\n * `PolicyBuilder._def`, or passed through when already a `PolicyDef`). */\nfunction toPolicyDef(p: PolicyBuilder | PolicyDef): PolicyDef {\n return p instanceof PolicyBuilder ? p._def : p;\n}\n\n/**\n * Define a schema. The table NAME comes from the object key. Each table value\n * is `{ columns, rls?, policies? }`:\n *\n * export default defineSchema({\n * tables: {\n * todos: {\n * columns: {\n * id: uuid().primaryKey().defaultRandom(),\n * owner: text().notNull(),\n * title: text().notNull(),\n * },\n * rls: true,\n * policies: [\n * policy(\"owner_all\").for(\"all\").to(\"authenticated\")\n * .using(\"owner = (select auth.uid())\")\n * .withCheck(\"owner = (select auth.uid())\"),\n * ],\n * },\n * },\n * });\n *\n * The returned value is\n * `{ tables: { todos: { name, columns, rls, policies } } }` — the exact shape\n * the runtime schema extractor parses. Per-column phantom types are preserved\n * so `Database.tables.todos.insert({...})` stays typed.\n *\n * RLS normalization: `rls` defaults to `false`, `policies` to `[]`. When\n * `policies` is non-empty, `rls` is forced on (ENABLE + FORCE) regardless of\n * the declared `rls` flag — a table with policies must have RLS enabled or the\n * policies would be inert.\n */\nexport function defineSchema<T extends Record<string, TableInput>>(\n input: SchemaInput<T>,\n): SchemaDef<TablesFromInput<T>> {\n const tables = {} as TablesFromInput<T>;\n for (const name of Object.keys(input.tables) as (keyof T)[]) {\n const table = input.tables[name];\n // `noUncheckedIndexedAccess` widens the index access to `… | undefined`,\n // but `name` comes straight from `Object.keys(input.tables)`, so the entry\n // always exists. Guard to narrow without a cast.\n if (table === undefined) continue;\n const policies = (table.policies ?? []).map(toPolicyDef);\n // A table with policies must have RLS enabled, otherwise the policies are\n // inert. Enabling RLS without policies (deny-all) is allowed explicitly.\n const rls = table.rls === true || policies.length > 0;\n const tableDef: TableDef<T[typeof name][\"columns\"]> = {\n name: name as string,\n columns: table.columns,\n rls,\n policies,\n };\n if (table.primaryKey !== undefined) tableDef.primaryKey = table.primaryKey;\n if (table.unique !== undefined) tableDef.unique = table.unique;\n if (table.raw !== undefined && table.raw.length > 0) tableDef.raw = table.raw.slice();\n if (table.checks !== undefined && table.checks.length > 0) tableDef.checks = table.checks.slice();\n if (table.indexes !== undefined && table.indexes.length > 0) tableDef.indexes = table.indexes.slice();\n tables[name] = tableDef;\n }\n // Dedupe + normalize extensions (order-independent; deploy resolves deps).\n const extensions = [...new Set(input.extensions ?? [])];\n return { tables, extensions };\n}\n","/**\n * Postgres extensions a Palbase project can enable from its schema.\n *\n * Extensions are config-as-code: declare them in `defineSchema({ extensions })`\n * and the deploy installs them (CREATE EXTENSION … SCHEMA extensions) using the\n * deploy path's privileged connection. They are NOT toggled live from Studio —\n * CREATE EXTENSION requires a superuser role that only the deploy path holds.\n *\n * The list is an allowlist (a string-literal union) so editors autocomplete the\n * supported names and a typo fails typecheck. It is intentionally extensible:\n * add a name here (+ confirm the base image ships it) to support more.\n */\nexport const PALBASE_EXTENSIONS = [\n // Search & text\n \"vector\", // pgvector: AI embeddings + vector similarity search (semantic search / RAG).\n // NB: the Postgres extension is named \"vector\", not \"pgvector\" — declare \"vector\".\n \"pg_trgm\", // trigram fuzzy / typo-tolerant text search\n \"unaccent\", // accent-insensitive text search\n \"citext\", // case-insensitive text type\n // Geospatial / location\n \"postgis\", // geospatial types + queries (maps, \"near me\")\n \"cube\", // multi-dimensional cubes (dependency of earthdistance)\n \"earthdistance\", // great-circle distance (needs cube)\n // Data types & structures\n \"hstore\", // key/value pairs in a single column\n \"ltree\", // hierarchical tree-structured labels\n // Indexing & constraints\n \"btree_gist\", // GiST operator classes for scalar types — needed for EXCLUDE\n // constraints that mix \"=\" with a range/&& overlap (e.g. no-double-booking).\n // Scheduling\n \"pg_cron\", // schedule jobs inside the database\n // Crypto / ids (also installed by default; listable for explicitness)\n \"pgcrypto\", // cryptographic functions (hashing, encryption)\n \"uuid-ossp\", // UUID generation functions\n] as const;\n\n/** A Postgres extension supported by Palbase (allowlist union). */\nexport type PalbaseExtension = (typeof PALBASE_EXTENSIONS)[number];\n\n/**\n * Extensions that depend on another extension. The deploy installs\n * dependencies first; declaring `earthdistance` without `cube` still works\n * because the deploy resolves the order, but listing both is clearer.\n */\nexport const EXTENSION_DEPENDENCIES: Partial<Record<PalbaseExtension, PalbaseExtension[]>> = {\n earthdistance: [\"cube\"],\n};\n\n/** Runtime guard: is `name` a supported Palbase extension? */\nexport function isPalbaseExtension(name: string): name is PalbaseExtension {\n return (PALBASE_EXTENSIONS as readonly string[]).includes(name);\n}\n","/** On delete action for foreign key references. */\nexport type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';\n\n/** Column type identifiers. */\nexport type ColumnType =\n | 'uuid'\n | 'text'\n | 'integer'\n | 'bigint'\n | 'numeric'\n | 'boolean'\n | 'timestamp'\n | 'jsonb'\n | 'enum';\n\n/** Base column definition shared by all column types. */\nexport interface ColumnDef {\n type: ColumnType;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n references?: { table: string; column: string };\n onDeleteAction?: OnDeleteAction;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n}\n\n// Phantom brand symbols — never have runtime values; exist only to force\n// TypeScript's structural type system to distinguish ColumnBuilder instances\n// with different type-param combinations. Without these, TS sees all\n// ColumnBuilder<K,...> as structurally identical and the first branch of\n// ColValue matches everything.\ndeclare const __colKind: unique symbol;\ndeclare const __colNullable: unique symbol;\ndeclare const __colHasDefault: unique symbol;\ndeclare const __colEnumValues: unique symbol;\ndeclare const __colPayload: unique symbol;\n\n/**\n * Fluent column builder with phantom type params:\n * K — ColumnType literal (e.g. \"text\", \"integer\")\n * N — boolean: true when nullable() has been called last (false = NOT NULL)\n * D — boolean: true when a default has been set\n * E — enum value union (never for non-enum columns)\n * P — jsonb payload shape (unknown unless jsonb<T>() supplied one)\n *\n * All five params have defaults so bare `ColumnBuilder` (no args) still\n * satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.\n *\n * The five `declare readonly` brand fields carry the phantom types into the\n * structural shape so that conditional types like ColValue<C> can discriminate\n * on K without requiring runtime values on those fields.\n */\nexport class ColumnBuilder<\n K extends ColumnType = ColumnType,\n N extends boolean = boolean,\n D extends boolean = boolean,\n E = unknown,\n P = unknown,\n> {\n // These fields exist only in the type layer (declared, never initialised at\n // runtime — TypeScript allows declared class members without an initializer\n // in strict mode as long as they're never read at runtime).\n declare readonly [__colKind]: K;\n declare readonly [__colNullable]: N;\n declare readonly [__colHasDefault]: D;\n declare readonly [__colEnumValues]: E;\n declare readonly [__colPayload]: P;\n\n readonly _def: ColumnDef;\n\n constructor(type: K, existingDef?: ColumnDef) {\n this._def = existingDef ?? {\n type,\n nullable: false,\n primaryKey: false,\n };\n }\n\n /** Mark this column as the primary key. */\n primaryKey(): ColumnBuilder<K, N, D, E, P> {\n this._def.primaryKey = true;\n return new ColumnBuilder<K, N, D, E, P>(this._def.type as K, this._def);\n }\n\n /** Mark this column as NOT NULL (default). */\n notNull(): ColumnBuilder<K, false, D, E, P> {\n this._def.nullable = false;\n return new ColumnBuilder<K, false, D, E, P>(this._def.type as K, this._def);\n }\n\n /** Allow NULL values. */\n nullable(): ColumnBuilder<K, true, D, E, P> {\n this._def.nullable = true;\n return new ColumnBuilder<K, true, D, E, P>(this._def.type as K, this._def);\n }\n\n /** Set a default value. */\n default(value: unknown): ColumnBuilder<K, N, true, E, P> {\n this._def.defaultValue = value;\n return new ColumnBuilder<K, N, true, E, P>(this._def.type as K, this._def);\n }\n\n /** UUID: generate a random default (gen_random_uuid()). */\n defaultRandom(): ColumnBuilder<K, N, true, E, P> {\n this._def.defaultRandom = true;\n return new ColumnBuilder<K, N, true, E, P>(this._def.type as K, this._def);\n }\n\n /** Timestamp: default to now(). */\n defaultNow(): ColumnBuilder<K, N, true, E, P> {\n this._def.defaultNow = true;\n return new ColumnBuilder<K, N, true, E, P>(this._def.type as K, this._def);\n }\n\n /** Add a foreign key reference. */\n references(table: string, column: string): ColumnBuilder<K, N, D, E, P> {\n this._def.references = { table, column };\n return new ColumnBuilder<K, N, D, E, P>(this._def.type as K, this._def);\n }\n\n /**\n * Add a real DB-level foreign key to the built-in auth users\n * (`REFERENCES auth.users(id)`), so a column like `user_id` gets true\n * database cascade/integrity instead of app-layer-only. Sugar for\n * `.references(\"auth.users\", \"id\")`.\n *\n * `auth.users` lives in the SAME tenant database (palauth-owned), so this is\n * a genuine cross-schema integrity constraint scoped to THIS tenant's users.\n * The referenced `auth.users.id` is `text` (palauth ids are `usr_<uuid>`), so\n * the referencing column must be `text()` too. Combine with `.onDelete(...)`\n * for cascade behaviour, e.g. a `user_id` column defined as\n * `text().notNull().referencesAuthUser().onDelete(\"cascade\")`.\n */\n referencesAuthUser(): ColumnBuilder<K, N, D, E, P> {\n return this.references('auth.users', 'id');\n }\n\n /** Set the ON DELETE action for a foreign key reference. */\n onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E, P> {\n this._def.onDeleteAction = action;\n return new ColumnBuilder<K, N, D, E, P>(this._def.type as K, this._def);\n }\n\n /** Add a single-column UNIQUE constraint. */\n unique(): ColumnBuilder<K, N, D, E, P> {\n this._def.unique = true;\n return new ColumnBuilder<K, N, D, E, P>(this._def.type as K, this._def);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type extractors — imported by Task 2 to derive insert/row shapes.\n// ---------------------------------------------------------------------------\n\n/**\n * Extracts the TypeScript value type for a column, respecting nullability.\n * - \"uuid\" | \"text\" | \"timestamp\" | \"bigint\" | \"numeric\" → string (or string | null when N = true)\n * Note: bigint/numeric surface as string — JS number loses precision past 2^53,\n * and pgx/PostgREST serialize int8/numeric as strings. App code uses\n * BigInt(row.amount) for bigint, or a decimal lib for numeric.\n * - \"integer\" → number\n * - \"boolean\" → boolean\n * - \"jsonb\" → P (the dev-supplied payload shape from jsonb<T>(), else unknown)\n * - \"enum\" → E (the union of literal values)\n */\nexport type ColValue<C> =\n C extends ColumnBuilder<'uuid' | 'text' | 'timestamp' | 'bigint' | 'numeric', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? string | null\n : string\n : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? number | null\n : number\n : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? boolean | null\n : boolean\n : C extends ColumnBuilder<'jsonb', infer N, infer _D, infer _E, infer P>\n ? N extends true\n ? P | null\n : P\n : C extends ColumnBuilder<'enum', infer N, infer _D, infer E, infer _P>\n ? N extends true\n ? E | null\n : E\n : never;\n\n/**\n * True when a column is optional on INSERT:\n * - nullable columns (N = true) — the DB allows NULL so the field may be omitted\n * - columns with a default (D = true) — the DB fills in the value when absent\n */\nexport type ColIsOptionalOnInsert<C> =\n C extends ColumnBuilder<infer _K, true, infer _D, infer _E>\n ? true\n : C extends ColumnBuilder<infer _K, infer _N, true, infer _E>\n ? true\n : false;\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/** Create a UUID column. */\nexport function uuid(): ColumnBuilder<'uuid', false, false, never> {\n return new ColumnBuilder('uuid');\n}\n\n/** Create a TEXT column. */\nexport function text(): ColumnBuilder<'text', false, false, never> {\n return new ColumnBuilder('text');\n}\n\n/** Create an INTEGER column. Emits int4 (max ~2.1B). */\nexport function integer(): ColumnBuilder<'integer', false, false, never> {\n return new ColumnBuilder('integer');\n}\n\n/**\n * Create a BIGINT column (Postgres int8, max ~9.2×10^18).\n * Surfaces as `string` in row/insert types — JS number loses precision past 2^53\n * and pgx/PostgREST serialize int8 as a JSON string. Use BigInt(row.column) in app code.\n */\nexport function bigint(): ColumnBuilder<'bigint', false, false, never> {\n return new ColumnBuilder('bigint');\n}\n\n/**\n * Create a NUMERIC column (Postgres `numeric`/`decimal`, arbitrary precision).\n * For exact fractional values (money with cents as a decimal, rates, weights)\n * where int4/int8 don't fit. Surfaces as `string` in row/insert types — JS\n * number can't hold arbitrary-precision decimals without rounding, and\n * pgx/PostgREST serialize numeric as a JSON string. Parse with a decimal lib\n * (or BigInt for scaled integers) in app code.\n */\nexport function numeric(): ColumnBuilder<'numeric', false, false, never> {\n return new ColumnBuilder('numeric');\n}\n\n/** Create a BOOLEAN column. */\nexport function boolean(): ColumnBuilder<'boolean', false, false, never> {\n return new ColumnBuilder('boolean');\n}\n\n/** Create a TIMESTAMP column. */\nexport function timestamp(): ColumnBuilder<'timestamp', false, false, never> {\n return new ColumnBuilder('timestamp');\n}\n\n/**\n * Create a JSONB column. Pass a payload type to make the generated row/insert\n * type concrete instead of `unknown`:\n *\n * tags: jsonb<string[]>() // row.tags: string[]\n * meta: jsonb<{ tier: string }>() // row.meta: { tier: string }\n * raw: jsonb() // row.raw: unknown (back-compat)\n *\n * The runtime accepts a plain JS object/array directly (no JSON.stringify); the\n * generic only refines the TYPE the env codegen emits.\n */\nexport function jsonb<T = unknown>(): ColumnBuilder<'jsonb', false, false, never, T> {\n return new ColumnBuilder('jsonb');\n}\n\n/**\n * Create an ENUM column.\n * @param name The PostgreSQL enum type name (used in DDL).\n * @param values A readonly tuple of valid string values — kept `const` so the\n * union `V[number]` is as narrow as possible.\n */\nexport function enumType<const V extends readonly string[]>(\n name: string,\n values: V,\n): ColumnBuilder<'enum', false, false, V[number]> {\n const builder = new ColumnBuilder<'enum', false, false, V[number]>('enum');\n builder._def.enumName = name;\n builder._def.enumValues = [...values];\n return builder;\n}\n","/**\n * A named raw-SQL DDL object declared in db/schema.ts for anything the typed DSL\n * cannot express (EXCLUDE, CHECK, partial/expression indexes, triggers, views).\n * The deploy emits `up` verbatim on the privileged DDL connection — same trust\n * posture as policy().using(). Tracked by NAME (not by diffing the body), so a\n * changed body needs a new name or an explicit drop+add.\n */\nexport interface RawConstraintDef {\n name: string;\n up: string;\n down?: string;\n}\n\nexport function raw(name: string, up: string, opts?: { down?: string }): RawConstraintDef {\n return { name, up, ...(opts?.down != null ? { down: opts.down } : {}) };\n}\n","/**\n * typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.\n *\n * Derives INSERT and full-row TypeScript types from a `defineSchema()` result\n * and wraps the untyped runtime `DBClient` with a typed facade.\n *\n * No value-any. No `as unknown as X`. The two narrow `as` casts in\n * `makeTypedTable` are safe because:\n * - `data as Record<string, unknown>`: InsertShape<T> maps string keys to\n * typed values; all value types are subsets of `unknown`, so the cast is\n * structurally sound.\n * - `result as RowShape<T>`: The runtime DBClient returns `Record<string,\n * unknown>` which is the erased form of the typed row; we're narrowing back\n * to the precise shape that the schema declared.\n * Both casts are narrowing only (not widening) and correctness is guaranteed\n * by the schema the caller provides.\n */\n\nimport type { ColValue, ColIsOptionalOnInsert, ColumnBuilder } from \"./columns.js\";\nimport type { TableDef, SchemaDef } from \"./schema.js\";\nimport type { Tables, TableTypes } from \"./env.js\";\nimport type { DBClient, TxClient } from \"../endpoint.js\";\n\n// ---------------------------------------------------------------------------\n// Key discriminators — split a column map into required vs optional keys.\n// ---------------------------------------------------------------------------\n\n/** Keys of C whose columns are required on INSERT (not nullable, no default). */\ntype RequiredKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;\n}[keyof C];\n\n/** Keys of C whose columns are optional on INSERT (nullable or has a default). */\ntype OptionalKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;\n}[keyof C];\n\n// ---------------------------------------------------------------------------\n// Public shape types — exported so callers can reference them directly.\n// ---------------------------------------------------------------------------\n\n/**\n * The TypeScript type for an INSERT payload for table `T`.\n * - Required: columns that are NOT NULL and have no DB-level default.\n * - Optional: columns that are nullable or carry a default.\n *\n * When all columns are optional, `RequiredKeys<C>` resolves to `never` and\n * the first part becomes `{}`, which is a neutral element for `&`.\n */\nexport type InsertShape<T extends TableDef> = {\n [K in RequiredKeys<T[\"columns\"]>]: ColValue<T[\"columns\"][K]>;\n} & {\n [K in OptionalKeys<T[\"columns\"]>]?: ColValue<T[\"columns\"][K]>;\n};\n\n/**\n * The TypeScript type for a full row returned by the DB for table `T`.\n * Every column is present; nullable columns resolve to `T | null`.\n */\nexport type RowShape<T extends TableDef> = {\n [K in keyof T[\"columns\"]]: ColValue<T[\"columns\"][K]>;\n};\n\n// ---------------------------------------------------------------------------\n// TypedTable + TypedDB interfaces.\n// ---------------------------------------------------------------------------\n\n/** A typed table accessor that mirrors the runtime DBClient surface. */\nexport interface TypedTable<T extends TableDef> {\n insert(data: InsertShape<T>): Promise<RowShape<T>>;\n /** Update the row by id; resolves to the updated row, or `null` if no row\n * matched (absent or RLS-hidden) — an idempotent outcome, mirroring\n * `findById`. The runtime returns a null row rather than throwing. */\n update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T> | null>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<RowShape<T> | null>;\n findMany(query?: Partial<RowShape<T>>): Promise<RowShape<T>[]>;\n}\n\n/** A typed DB facade covering all tables declared in schema `S`. */\nexport interface TypedDB<S extends SchemaDef> {\n tables: {\n [K in keyof S[\"tables\"]]: TypedTable<S[\"tables\"][K]>;\n };\n transaction<T>(fn: (tx: TypedTx<S>) => Promise<T>): Promise<T>;\n}\n\n/** Transaction-scoped typed facade: same typed tables, no nested transaction. */\nexport interface TypedTx<S extends SchemaDef> {\n tables: {\n [K in keyof S[\"tables\"]]: TypedTable<S[\"tables\"][K]>;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime factory.\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a typed table accessor that delegates every call to `raw` using the\n * runtime table name string. Two narrow `as` casts bridge the mapped-type\n * shapes to/from `Record<string, unknown>` — see module-level doc comment.\n *\n * The `raw` param is typed `TxClient` (the op surface shared by `DBClient` and\n * the transaction-scoped client) because this only ever calls the five\n * insert/update/delete/findById/findMany ops — never `transaction`. This lets\n * the same factory wrap both the top-level db and a tx without any cast.\n */\nfunction makeTypedTable<T extends TableDef<Record<string, ColumnBuilder>>>(\n name: string,\n raw: TxClient,\n): TypedTable<T> {\n return {\n insert: (data: InsertShape<T>) =>\n raw.insert(name, data as Record<string, unknown>) as Promise<RowShape<T>>,\n\n update: (id: string, data: Partial<InsertShape<T>>) =>\n raw.update(name, id, data as Record<string, unknown>) as Promise<RowShape<T> | null>,\n\n delete: (id: string) => raw.delete(name, id),\n\n findById: (id: string) =>\n raw.findById(name, id) as Promise<RowShape<T> | null>,\n\n findMany: (query?: Partial<RowShape<T>>) =>\n raw.findMany(name, query as Record<string, unknown> | undefined) as Promise<RowShape<T>[]>,\n };\n}\n\n/**\n * Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from\n * the provided schema. No behavior change — all calls delegate to `raw` with\n * the table name as a plain string.\n *\n * `buildTables` is the reusable factory that wraps any op-bearing client\n * (`TxClient` — the surface shared by `DBClient` and the transaction-scoped\n * client) into the typed tables map. It is used both for the top-level db\n * (wrapping `raw`) and inside `transaction`, where it wraps the raw `TxClient`\n * the runtime yields so the callback sees the same typed `.tables` API.\n *\n * `transaction` delegates straight to `raw.transaction`; the two narrow\n * `as TypedTx<S>` / `as TypedDB<S>` casts are single structural narrowings\n * from the dynamically-built tables object to the precise mapped type (TS\n * cannot infer through `Object.keys` iteration) — see module-level doc comment.\n */\nexport function makeTypedDB<S extends SchemaDef>(\n schema: S,\n raw: DBClient,\n): TypedDB<S> {\n function buildTables(client: TxClient): Record<string, TypedTable<TableDef>> {\n const tables = {} as Record<string, TypedTable<TableDef>>;\n for (const key of Object.keys(schema.tables)) {\n const tableDef = schema.tables[key];\n if (tableDef !== undefined) {\n tables[key] = makeTypedTable(tableDef.name, client);\n }\n }\n return tables;\n }\n\n const result = {\n tables: buildTables(raw),\n transaction: <T>(fn: (tx: TypedTx<S>) => Promise<T>): Promise<T> =>\n raw.transaction((rawTx) => fn({ tables: buildTables(rawTx) } as TypedTx<S>)),\n };\n\n // Narrow cast: `result.tables` is structurally identical to\n // TypedDB<S>[\"tables\"] — each key maps to a TypedTable for the matching\n // TableDef. TS cannot infer the mapped-type result through Object.keys\n // iteration, so a single `as` bridges the gap.\n return result as TypedDB<S>;\n}\n\n// ---------------------------------------------------------------------------\n// Env-augmentation-driven typed surface — the typed-by-default `Database`.\n//\n// These types read the globally-augmented `Tables` interface from\n// `@palbase/backend/env` (filled by the generated `palbase-env.d.ts`). They\n// back `Database.tables.<name>` so handler code is typed with no import and no\n// generic (C5). They DELIBERATELY do not reference `ColumnBuilder` — the env\n// `Tables` interface carries flat `row`/`insert` object types.\n// ---------------------------------------------------------------------------\n\n/** A typed table accessor derived from one env `Tables` entry's flat shapes. */\nexport interface EnvTypedTable<T extends TableTypes> {\n insert(data: T[\"insert\"]): Promise<T[\"row\"]>;\n /** Update the row by id; resolves to the updated row, or `null` if no row\n * matched (absent or RLS-hidden) — an idempotent outcome, mirroring\n * `findById`. The runtime returns a null row rather than throwing. */\n update(id: string, data: Partial<T[\"insert\"]>): Promise<T[\"row\"] | null>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<T[\"row\"] | null>;\n findMany(query?: Partial<T[\"row\"]>): Promise<T[\"row\"][]>;\n}\n\n/** The `tables` map exposed on `Database`/`tx`, keyed by the env `Tables`\n * interface. When no schema is declared `Tables` is empty, so `tables` is an\n * empty object — accessing `.tables.foo` is then a compile error (no member). */\nexport type EnvTables = {\n [K in keyof Tables]: EnvTypedTable<Tables[K]>;\n};\n\n/** Transaction-scoped typed facade for the env-augmented surface: same typed\n * tables, no nested transaction. */\nexport interface EnvTypedTx {\n tables: EnvTables;\n}\n\n/**\n * The RLS-bypass sibling returned by `Database.asService()`. Same typed surface\n * as {@link EnvTypedDatabase} — `tables`, the raw string ops, and a typed\n * `transaction` — but it does NOT re-expose `asService` (no double-bypass).\n * Every op it performs runs as the `service_role` (BYPASSRLS).\n */\nexport interface EnvServiceDatabase extends Omit<DBClient, \"transaction\" | \"asService\"> {\n tables: EnvTables;\n transaction<T>(fn: (tx: EnvTypedTx) => Promise<T>): Promise<T>;\n}\n\n/**\n * The typed-by-default Database surface: the raw string-keyed `DBClient` ops\n * PLUS a `tables` map typed against the project's generated `palbase-env.d.ts`,\n * a `transaction` whose callback receives the typed tables, and `asService()`\n * for the explicit RLS-bypass sibling.\n *\n * `transaction` is declared here (overriding `DBClient[\"transaction\"]`) so the\n * `tx` the callback receives carries the typed `.tables` API. `asService` is\n * re-typed to return the typed {@link EnvServiceDatabase} sibling.\n */\nexport interface EnvTypedDatabase extends Omit<DBClient, \"transaction\" | \"asService\"> {\n tables: EnvTables;\n transaction<T>(fn: (tx: EnvTypedTx) => Promise<T>): Promise<T>;\n /**\n * Return a sibling that bypasses RLS by running as the `service_role`. Use\n * sparingly and explicitly — the default `Database.*` path is RLS-enforced.\n *\n * @example\n * const all = await Database.asService().tables.todos.findMany({});\n * const rows = await Database.asService().query(\"SELECT * FROM todos\");\n */\n asService(): EnvServiceDatabase;\n}\n"],"mappings":";AA6DO,IAAM,gBAAN,MAAoB;AAAA,EAChB;AAAA,EAET,YAAY,MAAc;AACxB,SAAK,OAAO;AAAA,MACV;AAAA,MACA,SAAS;AAAA,MACT,OAAO,CAAC,eAAe;AAAA,MACvB,OAAO;AAAA,MACP,WAAW;AAAA,MACX,YAAY;AAAA,IACd;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,SAA8B;AAChC,SAAK,KAAK,UAAU;AACpB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,OAAuB;AAC3B,SAAK,KAAK,QAAQ;AAClB,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,SAAuB;AAC3B,SAAK,KAAK,QAAQ;AAClB,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,UAAU,SAAuB;AAC/B,SAAK,KAAK,YAAY;AACtB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA,EAIA,GAAG,MAAwB;AACzB,SAAK,KAAK,aAAa,SAAS;AAChC,WAAO;AAAA,EACT;AACF;AAUO,SAAS,OAAO,MAA6B;AAClD,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