@palbase/backend 2.0.2 → 3.0.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.
Files changed (50) hide show
  1. package/dist/{chunk-4J3F32SH.js → chunk-B7EUJP5W.js} +38 -9
  2. package/dist/chunk-B7EUJP5W.js.map +1 -0
  3. package/dist/{chunk-L36JLUPO.js → chunk-PHAFZGHN.js} +43 -46
  4. package/dist/chunk-PHAFZGHN.js.map +1 -0
  5. package/dist/db/env.cjs +19 -0
  6. package/dist/db/env.cjs.map +1 -0
  7. package/dist/db/env.d.cts +45 -0
  8. package/dist/db/env.d.ts +45 -0
  9. package/dist/db/env.js +1 -0
  10. package/dist/db/env.js.map +1 -0
  11. package/dist/db/index.cjs +28 -231
  12. package/dist/db/index.cjs.map +1 -1
  13. package/dist/db/index.d.cts +4 -20
  14. package/dist/db/index.d.ts +4 -20
  15. package/dist/db/index.js +3 -233
  16. package/dist/db/index.js.map +1 -1
  17. package/dist/{endpoint-Djk5L6G2.d.ts → endpoint-DJ98tQd6.d.cts} +30 -68
  18. package/dist/{endpoint-BlcY2xNA.d.cts → endpoint-DJ98tQd6.d.ts} +30 -68
  19. package/dist/index-CXUs9iTQ.d.ts +294 -0
  20. package/dist/index-CZAwpQE1.d.cts +294 -0
  21. package/dist/index.cjs +229 -61
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +398 -154
  24. package/dist/index.d.ts +398 -154
  25. package/dist/index.js +147 -12
  26. package/dist/index.js.map +1 -1
  27. package/dist/test/index.cjs +41 -1
  28. package/dist/test/index.cjs.map +1 -1
  29. package/dist/test/index.d.cts +1 -2
  30. package/dist/test/index.d.ts +1 -2
  31. package/dist/test/index.js +1 -1
  32. package/docs/README.md +31 -10
  33. package/docs/background.md +19 -13
  34. package/docs/database.md +30 -17
  35. package/docs/endpoints.md +42 -24
  36. package/docs/errors.md +3 -4
  37. package/docs/events.md +25 -17
  38. package/docs/getting-started.md +25 -9
  39. package/docs/llms-full.txt +489 -164
  40. package/docs/llms.txt +3 -1
  41. package/docs/migrations.md +98 -0
  42. package/docs/resources.md +94 -0
  43. package/docs/routing.md +59 -26
  44. package/docs/schema.md +48 -38
  45. package/docs/services.md +5 -6
  46. package/package.json +11 -1
  47. package/dist/chunk-4J3F32SH.js.map +0 -1
  48. package/dist/chunk-L36JLUPO.js.map +0 -1
  49. package/dist/schema-BqfEhIC0.d.cts +0 -133
  50. package/dist/schema-BqfEhIC0.d.ts +0 -133
package/docs/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Palbase Backend SDK (`@palbase/backend`)
2
2
 
3
- > File-based TypeScript backend SDK. Endpoints use `req` (PBRequest) + imported service singletons (`Database`, `Cache`, …). Workers/jobs/hooks/webhooks use a `ctx` object. Not Express, not Supabase Edge Functions.
3
+ > File-based TypeScript backend SDK. All handler types import service singletons (`Database`, `Cache`, …). Trigger arg differs by type: endpoints use `req`, workers `(payload, meta)`, jobs `(meta)`, hooks/webhooks `(event, meta)`. Middleware is the one exception (`ctx`). Not Express, not Supabase Edge Functions.
4
4
 
5
5
  ## Docs
6
6
 
@@ -10,7 +10,9 @@
10
10
  - [endpoints](./endpoints.md)
11
11
  - [database](./database.md)
12
12
  - [schema](./schema.md)
13
+ - [migrations](./migrations.md)
13
14
  - [services](./services.md)
15
+ - [resources](./resources.md)
14
16
  - [errors](./errors.md)
15
17
  - [background](./background.md)
16
18
  - [events](./events.md)
@@ -0,0 +1,98 @@
1
+ # Migrations
2
+
3
+ `db/schema.ts` is the single source of truth for your Postgres schema. On every
4
+ deploy, Palbase diffs your declared schema against the live branch database and
5
+ reconciles it — but *how* it reconciles depends on whether the change is safe to
6
+ apply automatically.
7
+
8
+ ## Two kinds of change
9
+
10
+ ### 1. Additive — auto-applied, no migration file
11
+
12
+ A new table, or a new **nullable** or **defaulted** column, is additive: the
13
+ deploy applies it automatically (`CREATE TABLE` / `ADD COLUMN`) with no manual
14
+ step and no backfill risk. Just edit `db/schema.ts` and deploy.
15
+
16
+ ```ts
17
+ // before
18
+ todos: {
19
+ id: uuid().primaryKey().defaultRandom(),
20
+ title: text().notNull(),
21
+ }
22
+
23
+ // after — additive: `notes` (nullable) + `priority` (defaulted) auto-apply on deploy
24
+ todos: {
25
+ id: uuid().primaryKey().defaultRandom(),
26
+ title: text().notNull(),
27
+ notes: text().nullable(),
28
+ priority: text().nullable().default("normal"),
29
+ }
30
+ ```
31
+
32
+ > A new **NOT NULL column without a default** is NOT additive-safe on a table
33
+ > that already has rows (there is nothing to put in the existing rows). Make it
34
+ > `.nullable()`, give it a `.default(...)`, or apply it as an explicit migration
35
+ > (add nullable → backfill → set NOT NULL).
36
+
37
+ ### 2. Destructive / type-changing — needs an explicit migration
38
+
39
+ Renaming or dropping a column, changing a column's type, or adding a NOT NULL
40
+ constraint can lose or corrupt existing data — so the deploy's **drift-gate
41
+ blocks them** and the deploy fails until you provide an explicit migration.
42
+ Write the SQL yourself in `db/migrations/`:
43
+
44
+ ```
45
+ db/migrations/
46
+ 001_user_id_to_text.up.sql
47
+ 001_user_id_to_text.down.sql
48
+ ```
49
+
50
+ ```sql
51
+ -- 001_user_id_to_text.up.sql
52
+ ALTER TABLE todos ALTER COLUMN user_id TYPE text USING user_id::text;
53
+ ```
54
+
55
+ ```sql
56
+ -- 001_user_id_to_text.down.sql
57
+ ALTER TABLE todos ALTER COLUMN user_id TYPE uuid USING user_id::uuid;
58
+ ```
59
+
60
+ Migrations are golang-migrate style: numbered `NNN_name.up.sql` / `.down.sql`
61
+ pairs, applied in order and tracked so each runs exactly once (idempotent).
62
+ `db/schema.ts` always describes the **end state**; the migration describes **how
63
+ existing data gets there**. Keep the two in sync — after the migration lands,
64
+ `schema.ts` should already reflect the new column type.
65
+
66
+ ## The drift-gate
67
+
68
+ On deploy, Palbase compares `db/schema.ts` to the live database:
69
+
70
+ - **Additive** diffs → auto-applied.
71
+ - **Type-changing / destructive** diffs **with** a matching migration → the
72
+ migration runs.
73
+ - **Type-changing / destructive** diffs **without** a migration → the deploy
74
+ **aborts** and your currently-running version keeps serving.
75
+
76
+ This is deliberate: it stops an accidental column-type change from silently
77
+ dropping production data. A blocked deploy is a prompt to write the migration,
78
+ not a failure to work around.
79
+
80
+ ## Local dev: `palbase serve` uses the deployed database
81
+
82
+ `palbase serve` runs your controllers locally but proxies `Database` and
83
+ `ctx.*` to the **deployed** branch — it does **not** spin up a local Postgres or
84
+ apply migrations locally. So when your local `db/schema.ts` or `db/migrations/`
85
+ is ahead of what's deployed, serve prints a note: new tables/columns won't exist
86
+ until you push. Deploy to apply them.
87
+
88
+ ## Workflow
89
+
90
+ 1. Edit `db/schema.ts`.
91
+ 2. **Additive** change? → `git push`. It auto-migrates on deploy.
92
+ 3. **Type change / rename / drop?** → add `db/migrations/NNN_*.up.sql` (+
93
+ `.down.sql`), then `git push`. The runner applies it; without it the
94
+ drift-gate blocks the deploy.
95
+ 4. `palbase serve` warns locally until the change is deployed.
96
+
97
+ See [schema.md](./schema.md) for the column builders and typed
98
+ `Database.tables.*` access.
@@ -0,0 +1,94 @@
1
+ # Resources
2
+
3
+ A `Resource` models one external connection — a pooled datastore, a stateless
4
+ API client, or a per-user factory. You put it in `resources/`, export an
5
+ instance, and **do not register it**: the framework discovers it, sets it up
6
+ once at boot, and drains it on shutdown. On top of that lifecycle you expose
7
+ your own clean facade.
8
+
9
+ ```ts
10
+ import { Resource } from "@palbase/backend";
11
+ ```
12
+
13
+ ## Lifecycle (boot scope — not per request)
14
+
15
+ A resource is created once at process boot — NOT per request. The framework:
16
+
17
+ 1. calls `init(env)` **once**, with only the secrets the resource declared;
18
+ 2. (optionally) calls `shutdown()` on SIGTERM, in reverse boot order.
19
+
20
+ The instance lives for the whole process; your facade methods are called
21
+ per-request. This makes "reconnect on every request" structurally impossible.
22
+
23
+ ## Pooled datastore — `init` + `shutdown`
24
+
25
+ ```ts
26
+ import { Resource } from "@palbase/backend";
27
+ import neo4j, { type Driver, type Session } from "neo4j-driver";
28
+
29
+ export class Neo4jResource extends Resource {
30
+ static secrets = ["NEO4J_URL", "NEO4J_USER", "NEO4J_PASSWORD"] as const;
31
+ private driver!: Driver;
32
+ async init(env: { NEO4J_URL: string; NEO4J_USER: string; NEO4J_PASSWORD: string }) {
33
+ this.driver = neo4j.driver(env.NEO4J_URL, neo4j.auth.basic(env.NEO4J_USER, env.NEO4J_PASSWORD));
34
+ }
35
+ async shutdown() {
36
+ await this.driver.close();
37
+ }
38
+ session(): Session {
39
+ return this.driver.session();
40
+ }
41
+ }
42
+
43
+ export const graph = new Neo4jResource();
44
+ ```
45
+
46
+ ## Stateless API client — `init` only
47
+
48
+ ```ts
49
+ import { Resource } from "@palbase/backend";
50
+ import { Client } from "@googlemaps/google-maps-services-js";
51
+
52
+ export class GoogleResource extends Resource {
53
+ static secrets = ["GOOGLE_MAPS_KEY"] as const;
54
+ private client = new Client();
55
+ private key = "";
56
+ init(env: { GOOGLE_MAPS_KEY: string }) {
57
+ this.key = env.GOOGLE_MAPS_KEY;
58
+ }
59
+ nearby(lat: number, lng: number) {
60
+ return this.client.placesNearby({ params: { location: { lat, lng }, radius: 1500, key: this.key } });
61
+ }
62
+ }
63
+
64
+ export const google = new GoogleResource();
65
+ ```
66
+
67
+ A per-user (OAuth) resource adds a factory method on the base, e.g.
68
+ `github.forUser(token)` — the same single model covers pooled, stateless, and
69
+ per-user.
70
+
71
+ ## Secrets
72
+
73
+ `static secrets` is the contract:
74
+
75
+ - It **types** the `env` passed to `init` — only the declared names are
76
+ present, each a `string`. An undeclared key is a compile error.
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.
81
+
82
+ `secrets` is optional — a resource that needs none simply omits it and gets an
83
+ empty `env`.
84
+
85
+ ## Using a resource
86
+
87
+ Import the singleton and call your facade — services and handlers reach
88
+ resources the same way they reach `Database`:
89
+
90
+ ```ts
91
+ import { google } from "../resources/google.js";
92
+
93
+ const results = (await google.nearby(41.0, 29.0)).data.results;
94
+ ```
package/docs/routing.md CHANGED
@@ -1,34 +1,67 @@
1
- # File-based routing
1
+ # Routing
2
2
 
3
- The path of a file under `endpoints/` plus its filename determine the route.
4
- The filename is the HTTP method.
3
+ Routes are declared in code. A **handler** is one endpoint unit (schema + thin
4
+ logic) with NO route on it; a **controller** is a route map (method+path →
5
+ handler). Putting a controller file under `controllers/` mounts it — there is no
6
+ central router and no manual registration.
5
7
 
6
- | File | Route |
7
- |------|-------|
8
- | `endpoints/hello/get.ts` | `GET /hello` |
9
- | `endpoints/items/post.ts` | `POST /items` |
10
- | `endpoints/posts/[id]/get.ts` | `GET /posts/:id` |
11
- | `endpoints/posts/[id]/patch.ts` | `PATCH /posts/:id` |
12
- | `endpoints/rooms/[id]/sessions/post.ts` | `POST /rooms/:id/sessions` |
8
+ ```ts
9
+ import { defineController, route } from "@palbase/backend";
10
+ ```
13
11
 
14
- Rules:
12
+ ## Handlers — one endpoint per file, no route
13
+
14
+ A handler declares everything that types `req` (`auth`/`input`/`output`/
15
+ `errors`) and the logic; it has no method or path.
16
+
17
+ ```ts
18
+ // handlers/places/import-nearby.ts
19
+ import { defineHandler, z } from "@palbase/backend";
20
+ import { placeService } from "../../services/place.service.js";
21
+
22
+ export default defineHandler({
23
+ auth: { required: true },
24
+ input: z.object({ lat: z.number(), lng: z.number() }),
25
+ output: z.object({ imported: z.number() }),
26
+ errors: { quotaExceeded: { status: 429, code: "quota_exceeded" } },
27
+ handler: (req) => placeService.importNearby(req.input.lat, req.input.lng),
28
+ });
29
+ ```
30
+
31
+ ## Controllers — the route map
15
32
 
16
- - The method file name is one of `get`, `post`, `put`, `patch`, `delete` (`.ts`).
17
- - A `[segment]` directory becomes a `:segment` path param, read via `req.params.segment`.
18
- - Each method file `export default defineEndpoint({...})` — one endpoint per file.
19
- - There is no central router file and no manual registration. Adding a file adds a route.
33
+ A controller maps method+path to handlers with `route.get|post|put|patch|delete`.
34
+ The route-map KEY is authoring sugar only (it is NOT the operationId).
20
35
 
21
36
  ```ts
22
- // endpoints/posts/[id]/get.ts → GET /posts/:id
23
- import { defineEndpoint, z, Database, HttpError } from "@palbase/backend";
24
-
25
- export default defineEndpoint({
26
- method: "GET",
27
- output: z.object({ id: z.string(), title: z.string() }),
28
- handler: async (req) => {
29
- const post = await Database.findById("posts", req.params.id!);
30
- if (!post) throw new HttpError(404, "post_not_found", "No such post");
31
- return { id: post.id as string, title: post.title as string };
32
- },
37
+ // controllers/places.controller.ts
38
+ import { defineController, route } from "@palbase/backend";
39
+ import importNearby from "../handlers/places/import-nearby.js";
40
+ import addFavorite from "../handlers/places/add-favorite.js";
41
+ import listFavorites from "../handlers/places/list-favorites.js";
42
+
43
+ export default defineController("/places", {
44
+ importNearby: route.post("/import", importNearby),
45
+ addFavorite: route.post("/favorites", addFavorite),
46
+ listFavorites: route.get ("/favorites", listFavorites),
33
47
  });
34
48
  ```
49
+
50
+ | Map key (sugar) | Method | Full path | operationId (flat) |
51
+ |---|---|---|---|
52
+ | `importNearby` | POST | `/places/import` | `postPlacesImport` |
53
+ | `addFavorite` | POST | `/places/favorites` | `postPlacesFavorites` |
54
+ | `listFavorites` | GET | `/places/favorites` | `getPlacesFavorites` |
55
+
56
+ Rules:
57
+
58
+ - The full path of a route is `basePath + subpath` (`"/places" + "/import"`).
59
+ - A `{segment}` in a path becomes a route param, read via `req.params.segment`.
60
+ - Each route value MUST be a `route.*(...)` result — a bare handler is a
61
+ compile error, which keeps logic out of controllers.
62
+ - The operationId is derived FLAT from method + full path (`postPlacesImport`),
63
+ not from the map key. Change a verb with `route.post` → `route.put` — no file
64
+ rename.
65
+
66
+ See [endpoints.md](./endpoints.md) for the full `defineHandler` config (`req`,
67
+ auth, input/output, errors, middleware) reference.
package/docs/schema.md CHANGED
@@ -1,36 +1,43 @@
1
1
  # Schema & typed database access
2
2
 
3
3
  Declare your tables in `db/schema.ts` with `defineSchema`. This drives
4
- migrations and, via `typedDatabase`, a fully-typed `.tables.*` API.
4
+ [migrations](./migrations.md) (additive changes auto-apply on deploy; type
5
+ changes need an explicit migration) and makes `Database.tables.*` typed
6
+ everywhere — by default, with no import and no generic.
5
7
 
6
8
  ## Defining a schema
7
9
 
10
+ The table NAME comes from the object key under `tables` — there is one
11
+ canonical form.
12
+
8
13
  ```ts
9
14
  import {
10
- defineSchema, table,
15
+ defineSchema,
11
16
  uuid, text, integer, boolean, timestamp, jsonb, enumType,
12
17
  } from "@palbase/backend";
13
18
 
14
19
  export default defineSchema({
15
- rooms: table("rooms", {
16
- id: uuid().primaryKey().defaultRandom(),
17
- name: text().notNull(),
18
- capacity: integer().nullable(),
19
- is_active: boolean().default(true),
20
- created_at: timestamp().defaultNow(),
21
- }),
22
- sessions: table("sessions", {
23
- id: uuid().primaryKey().defaultRandom(),
24
- room_id: uuid().notNull().references("rooms", "id").onDelete("cascade"),
25
- user_id: uuid().notNull(),
26
- data: jsonb().nullable(),
27
- started_at: timestamp().defaultNow(),
28
- }),
29
- orders: table("orders", {
30
- id: uuid().primaryKey().defaultRandom(),
31
- status: enumType("order_status", ["pending", "paid", "shipped", "cancelled"]),
32
- amount: integer().notNull(),
33
- }),
20
+ tables: {
21
+ rooms: {
22
+ id: uuid().primaryKey().defaultRandom(),
23
+ name: text().notNull(),
24
+ capacity: integer().nullable(),
25
+ is_active: boolean().default(true),
26
+ created_at: timestamp().defaultNow(),
27
+ },
28
+ sessions: {
29
+ id: uuid().primaryKey().defaultRandom(),
30
+ room_id: uuid().notNull().references("rooms", "id").onDelete("cascade"),
31
+ user_id: uuid().notNull(),
32
+ data: jsonb().nullable(),
33
+ started_at: timestamp().defaultNow(),
34
+ },
35
+ orders: {
36
+ id: uuid().primaryKey().defaultRandom(),
37
+ status: enumType("order_status", ["pending", "paid", "shipped", "cancelled"]),
38
+ amount: integer().notNull(),
39
+ },
40
+ },
34
41
  });
35
42
  ```
36
43
 
@@ -51,32 +58,35 @@ Chainable modifiers: `.primaryKey()`, `.notNull()` (default), `.nullable()`,
51
58
  `.defaultNow()` (timestamp → `now()`), `.references(table, column)`,
52
59
  `.onDelete("cascade" | "set null" | "restrict" | "no action")`.
53
60
 
54
- ## Typed DB access
61
+ ## Typed DB access — by default
55
62
 
56
- `typedDatabase(schema)` returns a typed facade. `insert` demands the right
57
- columns; rows come back typed; nullable columns are `T | null`.
63
+ You do **not** wire anything per endpoint. Saving `db/schema.ts` regenerates
64
+ `palbase-env.d.ts`, which types `Database.tables.<name>` everywhere no import
65
+ of the schema, no generic, no cast:
58
66
 
59
67
  ```ts
60
- import { defineEndpoint, z, typedDatabase } from "@palbase/backend";
61
- import schema from "../../db/schema.js";
62
-
63
- const Db = typedDatabase(schema);
68
+ import { defineHandler, z, Database } from "@palbase/backend";
64
69
 
65
- export default defineEndpoint({
66
- method: "POST",
70
+ export default defineHandler({
67
71
  input: z.object({ name: z.string() }),
68
72
  output: z.object({ id: z.string(), name: z.string() }),
69
73
  handler: async (req) => {
70
- const room = await Db.tables.rooms.insert({ name: req.input.name });
71
- return { id: room.id, name: room.name };
74
+ const room = await Database.tables.rooms.insert({ name: req.input.name });
75
+ return { id: room.id, name: room.name }; // room.id: string ✓
76
+ // room.nope ← compile error
72
77
  },
73
78
  });
74
79
  ```
75
80
 
76
- Note the `.js` extension on `../../db/schema.js` even though the file is
77
- `db/schema.ts` this is standard ESM module resolution; you still author the
78
- file as `.ts`.
81
+ `Database.tables.<name>` exposes `insert`, `update(id, data)`, `delete(id)`,
82
+ `findById(id)`, `findMany(query?)`, and `Database.transaction(fn)` yields a `tx`
83
+ with the same typed tables. The raw string-keyed ops
84
+ (`Database.insert("rooms", …)`, `Database.query(…)`) are still available for
85
+ dynamic table names and read-only SQL.
79
86
 
80
- `Db.tables.<name>` exposes `insert`, `update(id, data)`, `delete(id)`,
81
- `findById(id)`, `findMany(query?)`, and `Db.transaction(fn)` mirrors the
82
- untyped transaction with typed tables.
87
+ If you want a row type explicitly, import it from the generated env module:
88
+
89
+ ```ts
90
+ import type { Tables } from "@palbase/backend/env";
91
+ type Room = Tables["rooms"]["row"];
92
+ ```
package/docs/services.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Services
2
2
 
3
- In **endpoints**, import service singletons from `@palbase/backend`. In
4
- **workers/jobs/hooks/webhooks**, the equivalents live on `ctx` (`ctx.cache`,
5
- `ctx.queue`, `ctx.log`, `ctx.db`).
3
+ Import service singletons from `@palbase/backend` in every handler type —
4
+ endpoints, workers, jobs, hooks, and webhooks all use the same imports. Only
5
+ **middleware** uses a `ctx` argument (`ctx.db`, `ctx.log`, etc.).
6
6
 
7
7
  Available singletons: `Database`, `Documents`, `Storage`, `Cache`, `Queue`,
8
8
  `Log`, `Notifications`, `Flags`.
@@ -90,10 +90,9 @@ await Notifications.sms.send({ /* PalbaseSmsSendParams */ });
90
90
  ## Flags
91
91
 
92
92
  ```ts
93
- import { defineEndpoint, z, Flags } from "@palbase/backend";
93
+ import { defineHandler, z, Flags } from "@palbase/backend";
94
94
 
95
- export default defineEndpoint({
96
- method: "GET",
95
+ export default defineHandler({
97
96
  auth: { required: true }, // req.user is non-null here
98
97
  output: z.object({ enabled: z.boolean() }),
99
98
  handler: async (req) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@palbase/backend",
3
- "version": "2.0.2",
3
+ "version": "3.0.0",
4
4
  "description": "Palbase Backend SDK — defineEndpoint, context types, schema DSL",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -42,6 +42,16 @@
42
42
  "types": "./dist/db/index.d.cts",
43
43
  "default": "./dist/db/index.cjs"
44
44
  }
45
+ },
46
+ "./env": {
47
+ "import": {
48
+ "types": "./dist/db/env.d.ts",
49
+ "default": "./dist/db/env.js"
50
+ },
51
+ "require": {
52
+ "types": "./dist/db/env.d.cts",
53
+ "default": "./dist/db/env.cjs"
54
+ }
45
55
  }
46
56
  },
47
57
  "files": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db/schema.ts","../src/db/columns.ts"],"sourcesContent":["import type { ColumnBuilder } from \"./columns.js\";\n\n/**\n * A table definition with its columns.\n *\n * The `C` type parameter preserves the precise per-column phantom types so\n * that downstream mapped types (InsertShape, RowShape) can discriminate on\n * them. The default `Record<string, ColumnBuilder>` keeps all existing call\n * sites that use `TableDef` without a type argument (generator.ts, etc.)\n * compiling unchanged.\n */\nexport interface TableDef<\n C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>,\n> {\n name: string;\n columns: C;\n}\n\n/**\n * A schema definition containing multiple tables.\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}\n\n/**\n * Define a table with a name and columns.\n *\n * The generic parameter `C` preserves each column's phantom type params so\n * that `InsertShape<T>` and `RowShape<T>` can derive precise TypeScript types\n * from the column builders. The runtime return shape is identical to before —\n * only the static type is widened.\n */\nexport function table<C extends Record<string, ColumnBuilder>>(\n name: string,\n columns: C,\n): TableDef<C> {\n return { name, columns };\n}\n\n/** Define a schema containing multiple tables. */\nexport function defineSchema<T extends Record<string, TableDef>>(\n tables: T,\n): SchemaDef<T> {\n return { tables };\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 = 'uuid' | 'text' | 'integer' | 'boolean' | 'timestamp' | 'jsonb' | '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}\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;\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 *\n * All four params have defaults so bare `ColumnBuilder` (no args) still\n * satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.\n *\n * The four `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> {\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\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> {\n this._def.primaryKey = true;\n return new ColumnBuilder<K, N, D, E>(this._def.type as K, this._def);\n }\n\n /** Mark this column as NOT NULL (default). */\n notNull(): ColumnBuilder<K, false, D, E> {\n this._def.nullable = false;\n return new ColumnBuilder<K, false, D, E>(this._def.type as K, this._def);\n }\n\n /** Allow NULL values. */\n nullable(): ColumnBuilder<K, true, D, E> {\n this._def.nullable = true;\n return new ColumnBuilder<K, true, D, E>(this._def.type as K, this._def);\n }\n\n /** Set a default value. */\n default(value: unknown): ColumnBuilder<K, N, true, E> {\n this._def.defaultValue = value;\n return new ColumnBuilder<K, N, true, E>(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> {\n this._def.defaultRandom = true;\n return new ColumnBuilder<K, N, true, E>(this._def.type as K, this._def);\n }\n\n /** Timestamp: default to now(). */\n defaultNow(): ColumnBuilder<K, N, true, E> {\n this._def.defaultNow = true;\n return new ColumnBuilder<K, N, true, E>(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> {\n this._def.references = { table, column };\n return new ColumnBuilder<K, N, D, E>(this._def.type as K, this._def);\n }\n\n /** Set the ON DELETE action for a foreign key reference. */\n onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E> {\n this._def.onDeleteAction = action;\n return new ColumnBuilder<K, N, D, E>(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\" → string (or string | null when N = true)\n * - \"integer\" → number\n * - \"boolean\" → boolean\n * - \"jsonb\" → unknown (opaque JSON)\n * - \"enum\" → E (the union of literal values)\n */\nexport type ColValue<C> =\n C extends ColumnBuilder<'uuid' | 'text' | 'timestamp', infer N, infer _D, infer _E>\n ? N extends true\n ? string | null\n : string\n : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E>\n ? N extends true\n ? number | null\n : number\n : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E>\n ? N extends true\n ? boolean | null\n : boolean\n : C extends ColumnBuilder<'jsonb', infer _N, infer _D, infer _E>\n ? unknown\n : C extends ColumnBuilder<'enum', infer N, infer _D, infer E>\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. */\nexport function integer(): ColumnBuilder<'integer', false, false, never> {\n return new ColumnBuilder('integer');\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/** Create a JSONB column. */\nexport function jsonb(): ColumnBuilder<'jsonb', false, false, never> {\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"],"mappings":";AAuCO,SAAS,MACd,MACA,SACa;AACb,SAAO,EAAE,MAAM,QAAQ;AACzB;AAGO,SAAS,aACd,QACc;AACd,SAAO,EAAE,OAAO;AAClB;;;ACPO,IAAM,gBAAN,MAAM,eAKX;AAAA,EASS;AAAA,EAET,YAAY,MAAS,aAAyB;AAC5C,SAAK,OAAO,eAAe;AAAA,MACzB;AAAA,MACA,UAAU;AAAA,MACV,YAAY;AA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AAS;AACpC;AAGO,SAAS,YAA6D;AAC3E,SAAO,IAAI,cAAc,WAAW;AACtC;AAGO,SAAS,QAAqD;AACnE,SAAO,IAAI,cAAc,OAAO;AAClC;AAQO,SAAS,SACd,MACA,QACgD;AAChD,QAAM,UAAU,IAAI,cAA+C,MAAM;AACzE,UAAQ,KAAK,WAAW;AACxB,UAAQ,KAAK,aAAa,CAAC,GAAG,MAAM;AACpC,SAAO;AACT;","names":["table"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/db/typed-db.ts","../src/runtime.ts"],"sourcesContent":["/**\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 { 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(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T>>;\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>>,\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 * runtime.ts — request-scoped service singletons.\n *\n * The backend SDK no longer threads a `ctx` god-object through every handler.\n * Instead, endpoint authors import PascalCase service singletons directly:\n *\n * import { Database, Documents, Cache } from \"@palbase/backend\";\n *\n * export default defineEndpoint({\n * method: \"POST\",\n * handler: async (req) => {\n * const row = await Database.insert(\"todos\", { title: req.input.title });\n * return row;\n * },\n * });\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client for the CURRENT request scope, resolved through {@link __getRuntime}.\n *\n * # Request-scope resolution (persistent app-server)\n *\n * The runtime is a long-running Node process that serves many concurrent\n * requests on one event loop (NOT a fresh subprocess per request). A single\n * module-global slot would let one in-flight request's services bleed into\n * another's. So the services are carried in an {@link AsyncLocalStorage} store\n * ({@link __requestALS}) that the runtime sets per request with\n * {@link __runWithRuntime}; every async continuation of that request reads its\n * own store. `__getRuntime` reads the ALS store first; the module-global slot\n * (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE\n * an ALS scope (dev-server, unit tests, the legacy single-shot path). Because\n * each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the\n * ALS store is what prevents cross-REQUEST leakage within the shared process.\n *\n * The seam that makes `import { Database } from \"@palbase/backend\"` resolve to\n * the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL\n * when the tenant bundle is built, and the package is installed globally in the\n * pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's\n * `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared\n * module instance — the ALS store and `__setRuntime` slot on that instance are\n * visible to the singletons the bundle imported.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n CacheClient,\n QueueClient,\n Logger,\n PalbaseDocsClient,\n} from \"./endpoint.js\";\nimport type {\n PalbaseStorageClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n} from \"./clients.js\";\nimport type { SchemaDef } from \"./db/schema.js\";\nimport type { TypedDB } from \"./db/typed-db.js\";\nimport { makeTypedDB } from \"./db/typed-db.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They\n * are not exposed as backend handler singletons (auth lives on the client SDK;\n * the rest are out of scope for backend endpoints). */\nexport interface RuntimeServices {\n Database: DBClient;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Queue: QueueClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n}\n\n/**\n * Per-request store. The persistent runtime runs each request inside\n * {@link __runWithRuntime}, so every async continuation of that request reads\n * its OWN `runtime` (and any other request-scoped fields the runtime adds).\n *\n * Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS\n * instance across the one module instance — two ALS instances would silently\n * not see each other's stores. NOT part of the public author-facing API.\n */\nexport const __requestALS = new AsyncLocalStorage<{ runtime: RuntimeServices }>();\n\n/** Process-global fallback slot. Used only OUTSIDE an ALS scope (dev-server,\n * unit tests, legacy single-shot worker). Inside the persistent server every\n * request runs in {@link __requestALS}, which takes precedence. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients in the process-global fallback slot.\n *\n * Persistent-server requests should use {@link __runWithRuntime} instead; this\n * remains for dev-server / tests / the legacy single-shot path that run without\n * an ALS scope. NOT part of the public author-facing API. */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Run `fn` with `services` bound as the request-scoped runtime.\n *\n * The persistent worker calls this once per request so concurrent requests\n * never share a services slot. NOT part of the public author-facing API. */\nexport function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T {\n return __requestALS.run({ runtime: services }, fn);\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * Resolves the ALS store first (persistent server, per-request), then the\n * process-global fallback (dev-server / tests). NOT part of the public\n * author-facing API — used by the runtime and the singleton Proxies. */\nexport function __getRuntime(): RuntimeServices {\n const scoped = __requestALS.getStore();\n if (scoped) return scoped.runtime;\n if (runtime === null) {\n throw new Error(\n \"Palbase services accessed outside a request scope. The Database/Documents/… \" +\n \"singletons are only available inside an endpoint handler (or after the \" +\n \"runtime has called __runWithRuntime / __setRuntime).\",\n );\n }\n return runtime;\n}\n\n/**\n * Build a Proxy singleton that forwards every property access to the live\n * client named `key` on the current runtime.\n *\n * The single `as RuntimeServices[K]` is the only contained cast in the surface:\n * `Reflect.get` on a typed object returns `unknown` for a `string | symbol`\n * key, but `prop` is constrained to keys of the client interface at the call\n * sites (the exported singletons are typed below), so the forward is sound.\n */\nfunction makeServiceProxy<K extends keyof RuntimeServices>(key: K): RuntimeServices[K] {\n const handler: ProxyHandler<RuntimeServices[K]> = {\n get(_target, prop, receiver) {\n const client = __getRuntime()[key];\n const value = Reflect.get(client as object, prop, receiver) as unknown;\n // Bind methods to their owning client so `this` stays correct when the\n // author destructures or calls `Database.query(...)`.\n return typeof value === \"function\" ? value.bind(client) : value;\n },\n };\n // The Proxy target is irrelevant (all access goes through `get`); the cast\n // names the surface type the singleton presents to authors.\n return new Proxy({} as RuntimeServices[K], handler);\n}\n\n/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +\n * `query`/`transaction`. For a typed `.tables.<name>` API, wrap with\n * {@link typedDatabase}. */\nexport const Database: DBClient = makeServiceProxy(\"Database\");\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/** Object storage client (buckets, signed URLs). */\nexport const Storage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n/** Background job queue. */\nexport const Queue: QueueClient = makeServiceProxy(\"Queue\");\n\n/** Structured logger. */\nexport const Log: Logger = makeServiceProxy(\"Log\");\n\n/** Push / email / SMS / in-app notifications. */\nexport const Notifications: PalbaseNotificationsClient = makeServiceProxy(\"Notifications\");\n\n/** Feature flags. */\nexport const Flags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Type the `Database` singleton against a `defineSchema()` result, returning a\n * facade with a typed `.tables.<name>.insert(...)` API alongside the raw\n * `query`/`transaction` ops.\n *\n * const Db = typedDatabase(schema);\n * const todo = await Db.tables.todos.insert({ title: \"x\" });\n *\n * This is per-endpoint (not global module augmentation), so one endpoint's\n * tables never leak into another's `Database` type.\n */\nexport function typedDatabase<TSchema extends SchemaDef>(\n schema: TSchema,\n): TypedDB<TSchema> & DBClient {\n // makeTypedDB wraps the raw DBClient with the typed `.tables` facade (and a\n // typed `transaction`). The full `& DBClient` surface also needs the raw ops\n // (query/insert/update/delete/findById/findMany), which we delegate straight\n // to the `Database` singleton — every call goes through its runtime Proxy.\n const typed = makeTypedDB(schema, Database);\n const rawOps: DBClient = {\n query: (sql, params) => Database.query(sql, params),\n insert: (table, data) => Database.insert(table, data),\n update: (table, id, data) => Database.update(table, id, data),\n delete: (table, id) => Database.delete(table, id),\n findById: (table, id) => Database.findById(table, id),\n findMany: (table, q) => Database.findMany(table, q),\n transaction: (fn) => Database.transaction(fn),\n };\n // typed.transaction (typed-tx) intentionally overrides rawOps.transaction so\n // the callback sees the typed `.tables` API.\n return Object.assign(rawOps, typed);\n}\n"],"mappings":";AAwGA,SAAS,eACP,MACA,KACe;AACf,SAAO;AAAA,IACL,QAAQ,CAAC,SACP,IAAI,OAAO,MAAM,IAA+B;AAAA,IAElD,QAAQ,CAAC,IAAY,SACnB,IAAI,OAAO,MAAM,IAAI,IAA+B;AAAA,IAEtD,QAAQ,CAAC,OAAe,IAAI,OAA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