@palbase/backend 33.0.2 → 34.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 (81) hide show
  1. package/dist/bin/palbase-backend.cjs +2020 -350
  2. package/dist/bin/palbase-backend.cjs.map +1 -1
  3. package/dist/bin/palbase-backend.js +9 -7
  4. package/dist/bin/palbase-backend.js.map +1 -1
  5. package/dist/{chunk-SI4KGEM3.js → chunk-FOWA7PF4.js} +97 -96
  6. package/dist/chunk-FOWA7PF4.js.map +1 -0
  7. package/dist/chunk-GHNC2UHS.js +20 -0
  8. package/dist/chunk-GHNC2UHS.js.map +1 -0
  9. package/dist/{chunk-AAT5G7KY.js → chunk-JJW3L62T.js} +2 -2
  10. package/dist/chunk-JJW3L62T.js.map +1 -0
  11. package/dist/{chunk-TVCCR6SO.js → chunk-LOGL2ZHD.js} +58 -9
  12. package/dist/chunk-LOGL2ZHD.js.map +1 -0
  13. package/dist/{chunk-C6COAB3E.js → chunk-MNGZE2MM.js} +1651 -186
  14. package/dist/chunk-MNGZE2MM.js.map +1 -0
  15. package/dist/{chunk-XOX6RFPZ.js → chunk-PRH45NZU.js} +46 -3
  16. package/dist/chunk-PRH45NZU.js.map +1 -0
  17. package/dist/{chunk-26GH54D2.js → chunk-RZLY4BOY.js} +5 -3
  18. package/dist/{chunk-26GH54D2.js.map → chunk-RZLY4BOY.js.map} +1 -1
  19. package/dist/{chunk-YIQ4RS4F.js → chunk-SEM36BWY.js} +283 -5
  20. package/dist/chunk-SEM36BWY.js.map +1 -0
  21. package/dist/{chunk-KATPXCJ5.js → chunk-UMESJJRS.js} +19 -40
  22. package/dist/chunk-UMESJJRS.js.map +1 -0
  23. package/dist/chunk-VXPNPVAG.js +40 -0
  24. package/dist/chunk-VXPNPVAG.js.map +1 -0
  25. package/dist/{chunk-WWUG2QXF.js → chunk-YX7UA7VC.js} +53 -4
  26. package/dist/chunk-YX7UA7VC.js.map +1 -0
  27. package/dist/db/env.cjs.map +1 -1
  28. package/dist/db/env.d.cts +2 -0
  29. package/dist/db/env.d.ts +2 -0
  30. package/dist/db/index.cjs +261 -2
  31. package/dist/db/index.cjs.map +1 -1
  32. package/dist/db/index.d.cts +46 -3
  33. package/dist/db/index.d.ts +46 -3
  34. package/dist/db/index.js +14 -5
  35. package/dist/{index-DMZG3kpo.d.ts → endpoint-DpNUx-ON.d.ts} +315 -57
  36. package/dist/{index-DB_nW-AV.d.cts → endpoint-kYgEHrrV.d.cts} +315 -57
  37. package/dist/engine/index.cjs +2026 -348
  38. package/dist/engine/index.cjs.map +1 -1
  39. package/dist/engine/index.d.cts +5 -5
  40. package/dist/engine/index.d.ts +5 -5
  41. package/dist/engine/index.js +17 -7
  42. package/dist/{index-D-3duy8Y.d.ts → index-JrHqNsjQ.d.ts} +108 -50
  43. package/dist/{index-DLveQoOf.d.cts → index-pnDsEfxJ.d.cts} +108 -50
  44. package/dist/index.cjs +616 -254
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.cts +7 -6
  47. package/dist/index.d.ts +7 -6
  48. package/dist/index.js +25 -15
  49. package/dist/index.js.map +1 -1
  50. package/dist/openapi/index.cjs +7 -0
  51. package/dist/openapi/index.cjs.map +1 -1
  52. package/dist/openapi/index.d.cts +3 -3
  53. package/dist/openapi/index.d.ts +3 -3
  54. package/dist/openapi/index.js +4 -3
  55. package/dist/openapi/index.js.map +1 -1
  56. package/dist/{registry-DSTThhKf.d.cts → registry-BcOd8Zhf.d.cts} +3 -1
  57. package/dist/{registry-JjF5lcj4.d.ts → registry-BoX5iNyY.d.ts} +3 -1
  58. package/dist/test/index.cjs +103 -66
  59. package/dist/test/index.cjs.map +1 -1
  60. package/dist/test/index.d.cts +3 -3
  61. package/dist/test/index.d.ts +3 -3
  62. package/dist/test/index.js +33 -7
  63. package/dist/test/index.js.map +1 -1
  64. package/docs/README.md +1 -1
  65. package/docs/database.md +308 -0
  66. package/docs/examples/check-query-contracts.ts +5 -0
  67. package/docs/examples/database-dx.contract.json +65 -0
  68. package/docs/examples/database-dx.ts +63 -0
  69. package/docs/examples/money-transfer.ts +73 -0
  70. package/docs/llms-full.txt +309 -1
  71. package/package.json +1 -2
  72. package/template/package.json +1 -1
  73. package/dist/chunk-AAT5G7KY.js.map +0 -1
  74. package/dist/chunk-C6COAB3E.js.map +0 -1
  75. package/dist/chunk-KATPXCJ5.js.map +0 -1
  76. package/dist/chunk-SI4KGEM3.js.map +0 -1
  77. package/dist/chunk-TVCCR6SO.js.map +0 -1
  78. package/dist/chunk-WWUG2QXF.js.map +0 -1
  79. package/dist/chunk-XOX6RFPZ.js.map +0 -1
  80. package/dist/chunk-YIQ4RS4F.js.map +0 -1
  81. package/stack-images.json +0 -24
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  __name
3
- } from "./chunk-KATPXCJ5.js";
3
+ } from "./chunk-VXPNPVAG.js";
4
4
 
5
5
  // src/db/columns.ts
6
6
  var CODECS = {
@@ -364,6 +364,46 @@ function installationRef(opts) {
364
364
  }
365
365
  __name(installationRef, "installationRef");
366
366
 
367
+ // src/db/query-contract.ts
368
+ function queryColumnContract(column) {
369
+ const def = column && typeof column === "object" && "_def" in column ? column._def : column;
370
+ if (!def?.type) throw new Error("Query contract requires declared column types");
371
+ if (def.transform !== void 0 && def.codec === void 0) throw new Error("Query contracts require a named codec instead of a free-form column transform");
372
+ return {
373
+ type: def.type,
374
+ nullable: def.nullable === true,
375
+ ...def.codec === void 0 ? {} : {
376
+ codec: def.codec
377
+ },
378
+ ...def.enumValues === void 0 ? {} : {
379
+ enumValues: [
380
+ ...def.enumValues
381
+ ]
382
+ },
383
+ ...def.dimensions === void 0 ? {} : {
384
+ dimensions: def.dimensions
385
+ }
386
+ };
387
+ }
388
+ __name(queryColumnContract, "queryColumnContract");
389
+ function stableContract(value) {
390
+ if (Array.isArray(value)) return `[${value.map(stableContract).join(",")}]`;
391
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableContract(value[key])}`).join(",")}}`;
392
+ return JSON.stringify(value) ?? "null";
393
+ }
394
+ __name(stableContract, "stableContract");
395
+ function assertReadContract(query, columns) {
396
+ if (!query.options.select.length || new Set(query.options.select).size !== query.options.select.length) {
397
+ throw new Error(`Query ${query.name}: select must contain distinct, explicit columns`);
398
+ }
399
+ for (const name of query.options.select) {
400
+ if (!columns || !Object.hasOwn(columns, name) || !Object.hasOwn(query.columns, name) || stableContract(queryColumnContract(columns[name])) !== stableContract(query.columns[name])) {
401
+ throw new Error(`Query ${query.name}: schema drift at ${query.table}.${name}; regenerate and review its response contract`);
402
+ }
403
+ }
404
+ }
405
+ __name(assertReadContract, "assertReadContract");
406
+
367
407
  export {
368
408
  CODECS,
369
409
  uuid,
@@ -378,6 +418,9 @@ export {
378
418
  vector,
379
419
  ownedByUser,
380
420
  userRef,
381
- installationRef
421
+ installationRef,
422
+ queryColumnContract,
423
+ stableContract,
424
+ assertReadContract
382
425
  };
383
- //# sourceMappingURL=chunk-XOX6RFPZ.js.map
426
+ //# sourceMappingURL=chunk-PRH45NZU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db/columns.ts","../src/db/query-contract.ts"],"sourcesContent":["/** On delete action for foreign key references. */\nexport type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';\n\n/**\n * The ON DELETE actions permitted on a foreign key to the built-in auth users\n * (`auth.users`). Both let a user's rows be removed (`cascade`) or detached\n * (`set null`) when the account is erased; `restrict` / `no action` would BLOCK\n * erasure and are therefore excluded. This is the CLIENT-SIDE mirror of the\n * server's auth-FK deletion policy — the server (validateAuthUserFK) is the real\n * boundary, this narrows the type so the common mistake is caught at compile time.\n */\nexport type AuthUserOnDelete = Extract<OnDeleteAction, 'cascade' | 'set null'>;\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 | 'vector';\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 /** Pending FK target, resolved by `defineSchema` once every binding exists. */\n referencesThunk?: () => ColumnBuilder;\n /** FK onto THIS table — no thunk needed, the target is the declaring table. */\n selfRefColumn?: string;\n /** This column OWNS the row: erasure, RLS and the `owner` relation read it. */\n owns?: true;\n /** Explicit name for the FORWARD relation (child → parent), when the one\n * derived from the column would be ambiguous or unclear. */\n refAs?: string;\n /**\n * Explicit name for the REVERSE relation (parent → children).\n *\n * Separate from {@link refAs} because the two directions are different facts:\n * the forward name describes the parent this row points at (`author`), the\n * reverse one describes the rows hanging off the parent (`posts`). One option\n * naming both made an ordinary schema undeclarable — `posts.author_id` and\n * `comments.author_id` both named `{ as: \"author\" }` collided on `users`, and\n * the refusal asked for the `{ as }` they had both already written.\n */\n reverseAs?: string;\n /** The table this column belongs to; set by `defineTable`. */\n ownerTable?: { name: string; columns: Record<string, ColumnBuilder> };\n /**\n * The name this column used to have. A diff cannot tell a rename from a drop and\n * an add — both leave one name gone and another present — so the intent has to be\n * declared. Without it, renaming a column loses its data.\n */\n renamedFrom?: string;\n /**\n * This release's PROMISE that it does not reference this column — neither\n * reads it nor writes it, and never names it in a filter, a sort or a SET.\n *\n * The contraction gate reads it and nothing else does: dropping a column is\n * refused while the RUNNING release's declaration still lacks this mark, so\n * removing a column is two deploys — mark it, ship, then drop it.\n *\n * The word is `ignored` and not `deprecated` deliberately: RFC 9745 defines\n * deprecation as changing NO behaviour, and this changes what a deploy will\n * accept. Rails calls the same thing `ignored_columns`.\n */\n ignored?: boolean;\n onDeleteAction?: OnDeleteAction;\n /** FR-044: yalnız AÇIKÇA `false` bildirilince var. Türev FK index'ini kapatır. */\n index?: boolean;\n /** FR-049: kolon `increment()` ile güncelleniyor. Plan HOT çakışmasını uyarır. */\n counter?: boolean;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n /**\n * The value is written by the DATABASE — a trigger, a rule, an identity — not by\n * the author and not by a DEFAULT this schema declares. It makes the column\n * optional on INSERT without putting a DEFAULT in the DDL.\n *\n * Before this existed the only way to keep a trigger-filled column off the\n * INSERT type was to give it a fake `default()`: a value the schema claimed to\n * write and the trigger immediately overwrote. That made the schema lie about\n * its own data.\n */\n dbAssigned?: boolean;\n /** vector(n): the declared dimension count — part of the TYPE (typmod), read\n * by the wire serializer and the deploy's auto-index (FR-001). */\n dimensions?: number;\n /**\n * How the stored value is projected in and out of this process (FR-009).\n *\n * NOT part of the DDL: the column's Postgres type is unchanged and this pair\n * is never serialized into a migration. It exists so the row surface can hand\n * back the type the application actually works with.\n */\n /**\n * The named codec this column declares (FR-001). Unlike `transform`, the NAME\n * survives into the runtime object, so `makeEnvDts` can emit the matching\n * TypeScript type instead of falling back to the storage type. Not part of\n * the DDL: the column's Postgres type is unchanged.\n */\n codec?: CodecName;\n transform?: ColumnTransform;\n}\n\n/**\n * The read/write pair a column may declare (FR-009).\n *\n * `fromDb` takes whatever the driver produced for this column and returns the\n * value the application sees; `toDb` is its inverse on the way out. Kept\n * deliberately unexported — a column declares one inline, nobody needs to name\n * the shape.\n */\ninterface ColumnTransform<T = unknown> {\n fromDb: (value: unknown) => T;\n toDb: (value: T) => unknown;\n}\n\n/**\n * The closed set of named column codecs (FR-001).\n *\n * WHY A CLOSED SET rather than `.transform<T>()`. A transform's target type is\n * a TYPE parameter — erased at runtime — so the generator that reads the\n * bundled schema object cannot learn it. `palbase-env.d.ts` therefore said\n * `string` while the engine handed the application a number, and a consumer\n * project wrote a hand-rolled codec module plus 141 call sites to compensate.\n *\n * A codec is NAMED instead of typed: the name lands in `_def.codec`, travels in\n * the runtime object to every reader, and BOTH the conversion and the emitted\n * TypeScript type are derived from it. One declaration, one truth, and no way\n * for the two to disagree.\n */\nexport type CodecName = 'number' | 'decimal';\n\nexport const CODECS: Record<\n CodecName,\n { fromDb: (value: unknown) => unknown; toDb: (value: unknown) => unknown; tsType: 'number' | 'string' }\n> = {\n // Exact-precision column → JS number. Safe below 2^53; a value above it is\n // not representable and the author wants `asDecimal()` instead.\n number: {\n fromDb: (v) => Number(v),\n // YAZMA YOLUNDA SESSİZ BOZULMA YOK. `toDb(9007199254740993)` bir zamanlar\n // \"9007199254740992\" yazıyordu: uygulamanın tuttuğundan BAŞKA bir sayı\n // kolona gidiyordu ve hiçbir şey söylemiyordu. `asNumber()`'ın JSDoc'u\n // \"2^53'ün altında güvenli\" diyordu ama bunu uygulayan bir şey yoktu.\n toDb: (v) => {\n if (typeof v === 'number' && !Number.isSafeInteger(v)) {\n throw new Error(\n `asNumber() cannot write ${v}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`,\n );\n }\n return String(v);\n },\n tsType: 'number',\n },\n // Exact-precision column → the string Postgres sent. It exists so the\n // DECLARATION is explicit: \"this column is a decimal I handle as text\",\n // rather than the ABSENCE of a declaration meaning the same thing by default.\n // NULL güvencesi ÇİFTİN KENDİSİNDE. Motor NULL'ı zaten atlıyor (üç ayrı\n // yerde), ama bir değişmez, onu koruyan üç `if`'in DIŞINDA yazılmalı: biri\n // düşerse `String(null)` kolonu \"null\" dizesine çevirirdi.\n decimal: {\n fromDb: (v) => (v === null || v === undefined ? v : String(v)),\n toDb: (v) => (v === null || v === undefined ? v : String(v)),\n tsType: 'string',\n },\n};\n\n/** FR-002: a vector column cannot carry keys/defaults/references — the modifier\n * is named in the error so the author fixes the right line. */\nfunction refuseOnVector(def: ColumnDef, modifier: string): void {\n if (def.type === 'vector') {\n throw new Error(`vector column: .${modifier}() is not supported (FR-002 — allowed: nullable()/notNull())`);\n }\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;\ndeclare const __colTransform: 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 * T — transform target type (`never` when the column declares no transform;\n * `never` is the sentinel because it is the only type that survives\n * `[T] extends [never]` and never collides with a real target type)\n *\n * All six params have defaults so bare `ColumnBuilder` (no args) still\n * satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.\n *\n * The six `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 // `unknown`, not `never`: the schema's own constraint is a BARE\n // `ColumnBuilder`, whose T lands on this default. With `never` there, a\n // column that declares `.transform<number>()` is not assignable to the\n // constraint at all — `number` does not extend `never` — so a transform\n // could not appear in a schema and the whole table's `RowShape` collapsed.\n // Measured: TS2322 on `defineSchema`.\n T = 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 declare readonly [__colTransform]: T;\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, T> {\n refuseOnVector(this._def, 'primaryKey');\n this._def.primaryKey = true;\n return new ColumnBuilder<K, N, D, E, P, T>(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, T> {\n this._def.nullable = false;\n return new ColumnBuilder<K, false, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Allow NULL values. */\n nullable(): ColumnBuilder<K, true, D, E, P, T> {\n this._def.nullable = true;\n return new ColumnBuilder<K, true, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Set a default value. */\n default(value: unknown): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'default');\n this._def.defaultValue = value;\n return new ColumnBuilder<K, N, true, E, P, T>(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, T> {\n refuseOnVector(this._def, 'defaultRandom');\n this._def.defaultRandom = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Timestamp: default to now(). */\n defaultNow(): ColumnBuilder<K, N, true, E, P, T> {\n refuseOnVector(this._def, 'defaultNow');\n this._def.defaultNow = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * The DATABASE assigns this column's value — a trigger, a rule, an identity.\n *\n * The column becomes optional on INSERT (the author has nothing to send) while\n * the DDL stays free of a DEFAULT this schema would not honour. It is NOT\n * `default()`: that declares a value the schema promises to write.\n *\n * Naming: deliberately not `generated()`. Postgres has GENERATED columns and\n * they are a different thing; borrowing the word would send a reader — or a\n * model writing a schema — to the wrong feature.\n */\n dbAssigned(): ColumnBuilder<K, N, true, E, P, T> {\n this._def.dbAssigned = true;\n return new ColumnBuilder<K, N, true, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Add a foreign key reference. */\n /**\n * Declares that this column used to be called `previous`.\n *\n * A schema diff sees one name gone and another present; it cannot know whether\n * you renamed a column or dropped one and added another, and the two are very\n * different — the second loses every value. Saying so here turns the plan into\n * `ALTER TABLE … RENAME COLUMN` instead.\n *\n * Once the rename has been applied the annotation is inert (the old name is no\n * longer there to rename), so it can be deleted at your leisure.\n */\n renamedFrom(previous: string): ColumnBuilder<K, N, D, E, P, T> {\n this._def.renamedFrom = previous;\n return this as unknown as ColumnBuilder<K, N, D, E, P, T>;\n }\n\n /**\n * See {@link ColumnDef.ignored}.\n *\n * COPIES the def rather than mutating it. The constructor takes an existing\n * def BY REFERENCE, so every builder derived from another shares one object —\n * `const a = slug.unique()` leaves `a._def === slug._def`. An in-place\n * `ignored = true` therefore marks every column sharing that def, including\n * one another table actively reads, and the gate would let THAT column be\n * dropped. Measured before this copy existed.\n *\n * The aliasing is older than this method and other fields leak through it too.\n * The reason this one cannot wait: every other leak produces a VISIBLE schema\n * difference — the plan shows it, the DDL shows it. This one is invisible by\n * design (no DDL, no diff, no plan line), so its only effect is to disarm a\n * safety gate in silence.\n */\n ignored(): ColumnBuilder<K, N, D, E, P, T> {\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, {\n ...this._def,\n ignored: true,\n });\n }\n\n /**\n * Foreign key onto another table's column.\n *\n * The target is a THUNK, not a direct reference. In a cycle (`x → y`, `y → x`)\n * the second table does not exist yet when the first is built; a direct\n * reference makes TypeScript chase its own tail (TS7022 — measured, and making\n * the return type independent of the target does NOT help). The thunk is\n * invoked in `defineSchema`, where every binding exists and every table\n * already knows its name.\n *\n * In a cycle, ONE side needs an explicit return type:\n * `references((): AnyColumn => y.id)`. One side is enough — measured.\n * For a self-reference use `selfReferences(column)`: no thunk, no annotation.\n *\n * `as` names the FORWARD relation (`author_id` → `author` by default);\n * `reverseAs` names the REVERSE one on the parent, whose default is this\n * table's own name (`users.posts`). Two foreign keys from one table onto one\n * parent therefore need a `reverseAs` on at least one of them — the reverse\n * names would otherwise both be this table's name.\n */\n references(\n target: () => AnyColumn,\n opts?: {\n as?: string;\n reverseAs?: string;\n onDelete?: OnDeleteAction;\n /**\n * Bu FK kolonu için TÜREVİ index üretilsin mi (FR-044). Varsayılan açık.\n *\n * Postgres bir foreign key'i otomatik indekslemez — yalnız hedef\n * taraftaki unique kısıt vardır. Bedeli FK üzerinden her JOIN'de ve her\n * `ON DELETE CASCADE`'de ödenir: bir parent silinirken child tablo tam\n * taranır.\n *\n * `false` demek gerçek bir ihtiyaç, nezaket değil (D-028): FK kolonu aynı\n * zamanda SIK GÜNCELLENEN bir kolonsa index HOT güncellemeyi kırar — ve\n * HOT, DEĞİŞEN kolon indeksliyse kırılır, tablo indeksli diye değil.\n */\n index?: boolean;\n },\n ): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'references');\n if (typeof target !== 'function') {\n // Fail where the mistake is. Storing a non-thunk here surfaces three\n // layers later as \"def.referencesThunk is not a function\", inside\n // defineSchema, naming neither the column nor the call that was wrong.\n throw new Error(\n `references(...) takes a callback: write references(() => otherTable.column). ` +\n `The two-string form references(\"table\", \"column\") is gone — a string cannot be type-checked ` +\n `and cannot point at a table that does not exist yet.`,\n );\n }\n this._def.referencesThunk = target;\n if (opts?.as !== undefined) this._def.refAs = opts.as;\n if (opts?.reverseAs !== undefined) this._def.reverseAs = opts.reverseAs;\n if (opts?.onDelete !== undefined) this._def.onDeleteAction = opts.onDelete;\n // Yalnız AÇIKÇA false bildirilince taşınıyor: `undefined` \"bildirilmedi,\n // türet\" demek ve wire'da hiç görünmemeli (bayt-aynılık).\n if (opts?.index === false) this._def.index = false;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Bu kolon `increment()` / `decrement()` ile güncelleniyor (FR-049).\n *\n * Deploy kontrolcü kodunu OKUMAZ, o yüzden bildirimin söylemesi gerekiyor —\n * ve söylediği anda plan bir şeyi görebiliyor: aynı kolon hem sayaç hem\n * indeksliyse her güncelleme HOT'u kaybeder.\n *\n * ZİNCİR (D-028+D-030): HOT kaybı → ölü tuple → autovacuum yükü → ve\n * autovacuum worker'ları KÜME GENELİNDE bir kaynak, yani bedeli başka\n * kiracıların tabloları da öder.\n *\n * Sektörde çare \"dokümana uyarı yaz\"dır, çünkü index'i ekleyen kişi\n * `increment()`'i yazan kişi değildir. Bu bildirimde ikisi de YAN YANA\n * duruyor.\n *\n * Uyarı, HATA DEĞİL: sayaç kolonunu indekslemek bazen doğru karardır.\n */\n counter(): ColumnBuilder<K, N, D, E, P, T> {\n this._def.counter = true;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Foreign key onto THIS table (`parent_id → id`) — category trees, comment\n * replies, org charts.\n *\n * No thunk and no type annotation: the target table is the one being declared,\n * so there is nothing to defer and nothing for TypeScript to chase in a circle.\n * Drizzle forces an explicit `(): AnyPgColumn =>` here because its reference\n * always goes through a callback; measured, we do not need one.\n */\n selfReferences(\n column: string,\n opts?: { as?: string; onDelete?: OnDeleteAction },\n ): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'selfReferences');\n this._def.selfRefColumn = column;\n if (opts?.as !== undefined) this._def.refAs = opts.as;\n if (opts?.onDelete !== undefined) this._def.onDeleteAction = opts.onDelete;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n\n\n /** Set the ON DELETE action for a foreign key reference. */\n onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E, P, T> {\n this._def.onDeleteAction = action;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /** Add a single-column UNIQUE constraint. */\n unique(): ColumnBuilder<K, N, D, E, P, T> {\n refuseOnVector(this._def, 'unique');\n this._def.unique = true;\n return new ColumnBuilder<K, N, D, E, P, T>(this._def.type as K, this._def);\n }\n\n /**\n * Declare how this column's value is projected in and out of the process.\n *\n * The DDL does not move: `numeric` stays `numeric`, and the driver still hands\n * back what Postgres sent. What changes is the type the row surface exposes —\n * it becomes `Target`:\n *\n * amount: numeric().transform<number>({ fromDb: Number, toDb: String })\n *\n * `numeric` surfacing as `string` is CORRECT (a JS number cannot hold\n * arbitrary precision), and that is exactly why this exists: application code\n * that does arithmetic on the column otherwise rewrites the same\n * `Number(row.amount)` / `String(x)` pair in every controller that touches it,\n * and each rewrite is a place the two directions can drift apart.\n *\n * A transform is a PROJECTION, never a constraint: it lives only in this\n * process, so it can neither validate nor migrate what is stored.\n */\n /**\n * Surface this exact-precision column as a JS `number` (FR-001).\n *\n * `numeric`/`bigint` arrive as strings because a JS number cannot hold their\n * full range — correct, and exactly why this exists: application code that\n * does arithmetic on the column otherwise rewrites the same `Number(row.x)` /\n * `String(v)` pair in every caller, and each rewrite is a place the two\n * directions can drift apart.\n */\n asNumber(): ColumnBuilder<K, N, D, E, P, number> {\n return this.withCodec<number>('number', 'asNumber');\n }\n\n /**\n * Surface this exact-precision column as a `string` — the value Postgres\n * sent, DECLARED rather than defaulted (FR-001).\n */\n asDecimal(): ColumnBuilder<K, N, D, E, P, string> {\n return this.withCodec<string>('decimal', 'asDecimal');\n }\n\n private withCodec<Target>(codec: CodecName, method: string): ColumnBuilder<K, N, D, E, P, Target> {\n if (this._def.type !== 'bigint' && this._def.type !== 'numeric') {\n throw new Error(\n `${this._def.type} column: .${method}() is only available on bigint()/numeric() — ` +\n `those are the exact-precision types that surface as string.`,\n );\n }\n if (this._def.transform !== undefined) {\n throw new Error(\n `.${method}() and .transform() are two ways to say the same thing on one column — keep .${method}().`,\n );\n }\n if (this._def.codec !== undefined) {\n throw new Error(\n `column already declares .as${this._def.codec === 'number' ? 'Number' : 'Decimal'}(); a column has ONE codec.`,\n );\n }\n // KOPYA, MUTASYON DEĞİL — `ignored()` gibi.\n //\n // `this._def.codec = codec` yazmak, ORTAK bir temelden çatallanan iki\n // kolonun ikisine de SON codec'i verirdi. Ölçüldü:\n // const money = numeric().notNull();\n // money.asNumber(); money.asDecimal();\n // → ikisinin de _def.codec === 'decimal', ve AYNI nesne.\n // Birincinin TİPİ `number`, üretecin bastığı tip `string` olurdu — yani bu\n // özelliğin kapatmak için var olduğu ayrışmanın ta kendisi.\n return new ColumnBuilder<K, N, D, E, P, Target>(this._def.type as K, {\n ...this._def,\n codec,\n });\n }\n\n transform<Target>(fns: ColumnTransform<Target>): ColumnBuilder<K, N, D, E, P, Target> {\n // AYNA KONTROLÜ. `asNumber()` mevcut bir transform'u reddediyor; burası da\n // mevcut bir codec'i reddetmeli, yoksa kapı TEK YÖNLÜ olur:\n // `numeric().asNumber().transform<Date>(…)` üç ayrı cevap üretirdi —\n // builder tipi `Date`, üretilen tip `number`, motor `Number()` uygular —\n // ve hiçbir şey adını söyleyerek reddetmezdi.\n if (this._def.codec !== undefined) {\n throw new Error(\n `column already declares a named codec; .transform() and .as*() are two ways to say the same thing — keep the codec.`,\n );\n }\n // The cast is the variance, not a shortcut: `toDb` takes `Target`, and a\n // `ColumnTransform<unknown>` would have to accept anything. The stored pair\n // is only ever called with this column's own values.\n return new ColumnBuilder<K, N, D, E, P, Target>(this._def.type as K, {\n ...this._def,\n transform: fns as ColumnTransform,\n });\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 *\n * A declared `.transform<T>()` OVERRIDES the table above: the column then\n * surfaces as T (or T | null when nullable), because that is the value the\n * application is handed. Nullability is still the column's, not the\n * transform's — `fromDb` is not called for a NULL.\n */\nexport type ColValue<C> =\n C extends ColumnBuilder<ColumnType, infer N, boolean, unknown, unknown, infer T>\n ? [unknown] extends [T]\n ? ColStoredValue<C>\n : N extends true\n ? T | null\n : T\n : never;\n\n/** The value as the DATABASE hands it over — the branch table above, before any\n * transform. This is what a column's `fromDb` receives. */\ntype ColStoredValue<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<'vector', infer N, infer _D, infer _E, infer _P>\n ? N extends true\n ? number[] | null\n : number[]\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<ColumnType, true, boolean, unknown, unknown, unknown>\n ? true\n : C extends ColumnBuilder<ColumnType, boolean, true, unknown, unknown, unknown>\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/** vector(n) — pgvector kolonu. n TİPİN parçasıdır (typmod) ve [1, 2000] —\n * 2000 = pgvector'ün HNSW-indekslenebilir tavanı; auto-index bu beyanla bağlı\n * (spec FR-001, D-3). */\nexport function vector(dimensions: number): ColumnBuilder<'vector', false, false, unknown, number[]> {\n if (!Number.isInteger(dimensions) || dimensions < 1 || dimensions > 2000) {\n throw new Error(`vector(): dimensions must be an integer in [1, 2000], got ${String(dimensions)}`);\n }\n const b = new ColumnBuilder('vector') as ColumnBuilder<'vector', false, false, unknown, number[]>;\n (b._def as { dimensions?: number }).dimensions = dimensions;\n return b;\n}\n\n/**\n * Any column, whatever its type parameters.\n *\n * Exported so a cycle can be broken from ONE side:\n * `references((): AnyColumn => y.id)`.\n */\nexport type AnyColumn = ColumnBuilder;\n\n/**\n * The column that OWNS this row: a `text` FK onto `auth.users(id)`, NOT NULL,\n * ON DELETE CASCADE.\n *\n * Ownership drives account erasure, so cascade is the only correct action and\n * takes no argument. The referencing column must be `text` (palauth ids are\n * `usr_<uuid>`) and NOT NULL — both are implied here rather than left to the\n * caller, so three rules the type could not express before become UNWRITABLE.\n *\n * At most ONE per table. The old shape let several columns reference\n * `auth.users` and picked the FIRST IN DECLARATION ORDER as the owner — moving a\n * `created_by` above a `user_id` silently changed which rows an account deletion\n * took with it. A second one is now rejected at push.\n *\n * For a column that merely POINTS at a user without owning the row\n * (`created_by`, `edited_by`), use `userRef({ onDelete })`.\n */\nexport function ownedByUser(): ColumnBuilder<'text', false, false, never> {\n const b = new ColumnBuilder<'text', false, false, never>('text');\n b._def.nullable = false;\n b._def.references = { table: 'auth.users', column: 'id' };\n b._def.onDeleteAction = 'cascade';\n b._def.owns = true;\n return b;\n}\n\n/**\n * A plain FK onto `auth.users(id)` that does NOT own the row.\n *\n * `created_by` / `edited_by`: deleting that user must not delete the row. ON\n * DELETE is required and limited to `cascade | set null` so an erasure request\n * is never blocked by a lingering FK; `set null` needs a nullable column.\n */\nexport function userRef(opts: { onDelete: AuthUserOnDelete; as?: string }): ColumnBuilder<'text', boolean, false, never> {\n const b = new ColumnBuilder<'text', boolean, false, never>('text');\n b._def.references = { table: 'auth.users', column: 'id' };\n b._def.onDeleteAction = opts.onDelete;\n if (opts.as !== undefined) b._def.refAs = opts.as;\n return b;\n}\n\n/**\n * A plain FK onto `auth.installations(id)` — the app-scoped verified-device\n * anchor.\n *\n * An installation is an APP INSTALL, not a user: this is NOT ownership. A\n * user-owned row still needs its own `ownedByUser()` so account erasure removes\n * it; an installation reference alone does not tie a row to a user's deletion.\n */\nexport function installationRef(opts: { onDelete: AuthUserOnDelete; as?: string }): ColumnBuilder<'text', boolean, false, never> {\n const b = new ColumnBuilder<'text', boolean, false, never>('text');\n b._def.references = { table: 'auth.installations', column: 'id' };\n b._def.onDeleteAction = opts.onDelete;\n if (opts.as !== undefined) b._def.refAs = opts.as;\n return b;\n}\n","/** Storage metadata that affects the declared response; defaults and unrelated\n * columns do not change an explicitly projected query's contract. */\nexport interface QueryColumnContract {\n type: string;\n nullable: boolean;\n codec?: string;\n enumValues?: readonly string[];\n dimensions?: number;\n}\n\nexport interface PreparedRead {\n name: string;\n table: string;\n columns: Record<string, QueryColumnContract>;\n where: Record<string, unknown>;\n options: {\n select: string[];\n orderBy?: { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" } |\n { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }[];\n limit?: number;\n };\n}\n\nexport interface CompiledRead { sql: string; params: unknown[] }\n\nexport interface QueryDatabase {\n readQuery(query: PreparedRead): Promise<Record<string, unknown>[]>;\n compileQuery(query: PreparedRead): CompiledRead;\n explainQuery(query: PreparedRead): Promise<unknown[]>;\n}\n\nexport interface EnvQueryDatabase {\n $readQuery: QueryDatabase[\"readQuery\"];\n $compileQuery: QueryDatabase[\"compileQuery\"];\n $explainQuery: QueryDatabase[\"explainQuery\"];\n}\n\nexport function queryColumnContract(column: unknown): QueryColumnContract {\n const def = (column && typeof column === \"object\" && \"_def\" in column ? column._def : column) as\n { type?: string; nullable?: boolean; codec?: string; enumValues?: string[]; dimensions?: number; transform?: unknown } | undefined;\n if (!def?.type) throw new Error(\"Query contract requires declared column types\");\n if (def.transform !== undefined && def.codec === undefined) throw new Error(\"Query contracts require a named codec instead of a free-form column transform\");\n return { type: def.type, nullable: def.nullable === true,\n ...(def.codec === undefined ? {} : { codec: def.codec }),\n ...(def.enumValues === undefined ? {} : { enumValues: [...def.enumValues] }),\n ...(def.dimensions === undefined ? {} : { dimensions: def.dimensions }) };\n}\n\nexport function stableContract(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableContract).join(\",\")}]`;\n if (value && typeof value === \"object\") return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableContract((value as Record<string, unknown>)[key])}`).join(\",\")}}`;\n return JSON.stringify(value) ?? \"null\";\n}\n\nexport function assertReadContract(query: PreparedRead, columns?: Record<string, unknown>): void {\n if (!query.options.select.length || new Set(query.options.select).size !== query.options.select.length) {\n throw new Error(`Query ${query.name}: select must contain distinct, explicit columns`);\n }\n for (const name of query.options.select) {\n if (!columns || !Object.hasOwn(columns, name) || !Object.hasOwn(query.columns, name) ||\n stableContract(queryColumnContract(columns[name])) !== stableContract(query.columns[name])) {\n throw new Error(`Query ${query.name}: schema drift at ${query.table}.${name}; regenerate and review its response contract`);\n }\n }\n}\n"],"mappings":";;;;;AAgJO,IAAMA,SAGT;;;EAGFC,QAAQ;IACNC,QAAQ,wBAACC,MAAMC,OAAOD,CAAAA,GAAd;;;;;IAKRE,MAAM,wBAACF,MAAAA;AACL,UAAI,OAAOA,MAAM,YAAY,CAACC,OAAOE,cAAcH,CAAAA,GAAI;AACrD,cAAM,IAAII,MACR,2BAA2BJ,CAAAA,uIAAwI;MAEvK;AACA,aAAOK,OAAOL,CAAAA;IAChB,GAPM;IAQNM,QAAQ;EACV;;;;;;;EAOAC,SAAS;IACPR,QAAQ,wBAACC,MAAOA,MAAM,QAAQA,MAAMQ,SAAYR,IAAIK,OAAOL,CAAAA,GAAnD;IACRE,MAAM,wBAACF,MAAOA,MAAM,QAAQA,MAAMQ,SAAYR,IAAIK,OAAOL,CAAAA,GAAnD;IACNM,QAAQ;EACV;AACF;A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AAKC,UAAUF,GAAAA,CAAAA,IAAQT,eAAgBC,MAAkCQ,GAAAA,CAAI,CAAA,EAAG,EAAEJ,KAAK,GAAA,CAAA;AAClL,SAAOK,KAAKC,UAAUV,KAAAA,KAAU;AAClC;AAJgBD;AAMT,SAASY,mBAAmBC,OAAqBC,SAAiC;AACvF,MAAI,CAACD,MAAME,QAAQC,OAAOC,UAAU,IAAIC,IAAIL,MAAME,QAAQC,MAAM,EAAEG,SAASN,MAAME,QAAQC,OAAOC,QAAQ;AACtG,UAAM,IAAIxB,MAAM,SAASoB,MAAMO,IAAI,kDAAkD;EACvF;AACA,aAAWA,QAAQP,MAAME,QAAQC,QAAQ;AACvC,QAAI,CAACF,WAAW,CAACR,OAAOe,OAAOP,SAASM,IAAAA,KAAS,CAACd,OAAOe,OAAOR,MAAMC,SAASM,IAAAA,KAC7EpB,eAAeZ,oBAAoB0B,QAAQM,IAAAA,CAAK,CAAA,MAAOpB,eAAea,MAAMC,QAAQM,IAAAA,CAAK,GAAG;AAC5F,YAAM,IAAI3B,MAAM,SAASoB,MAAMO,IAAI,qBAAqBP,MAAMS,KAAK,IAAIF,IAAAA,+CAAmD;IAC5H;EACF;AACF;AAVgBR;","names":["CODECS","number","fromDb","v","Number","toDb","isSafeInteger","Error","String","tsType","decimal","undefined","refuseOnVector","def","modifier","type","ColumnBuilder","_def","existingDef","nullable","primaryKey","notNull","default","value","defaultValue","defaultRandom","defaultNow","dbAssigned","renamedFrom","previous","ignored","references","target","opts","referencesThunk","as","refAs","reverseAs","onDelete","onDeleteAction","index","counter","selfReferences","column","selfRefColumn","action","unique","asNumber","withCodec","asDecimal","codec","method","transform","fns","uuid","text","integer","bigint","numeric","boolean","timestamp","jsonb","enumType","name","values","builder","enumName","enumValues","vector","dimensions","isInteger","b","ownedByUser","table","owns","userRef","installationRef","queryColumnContract","column","def","_def","type","Error","transform","undefined","codec","nullable","enumValues","dimensions","stableContract","value","Array","isArray","map","join","Object","keys","sort","key","JSON","stringify","assertReadContract","query","columns","options","select","length","Set","size","name","hasOwn","table"]}
@@ -1,7 +1,9 @@
1
1
  import {
2
- HttpError,
2
+ HttpError
3
+ } from "./chunk-UMESJJRS.js";
4
+ import {
3
5
  __name
4
- } from "./chunk-KATPXCJ5.js";
6
+ } from "./chunk-VXPNPVAG.js";
5
7
 
6
8
  // src/error-registry.ts
7
9
  import { OpenAPIRegistry, OpenApiGeneratorV31, extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi";
@@ -159,4 +161,4 @@ export {
159
161
  getErrorRegistry,
160
162
  defineError
161
163
  };
162
- //# sourceMappingURL=chunk-26GH54D2.js.map
164
+ //# sourceMappingURL=chunk-RZLY4BOY.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/error-registry.ts"],"sourcesContent":["// defineError — project-defined typed error classes + the module-global error\n// registry the OpenAPI spec twins join against.\n//\n// `defineError(code, status, dataSchema?)` returns an `HttpError` subclass whose\n// constructor is typed by the zod schema (`new TodoLocked({ retryAfter: 30 })`).\n// Each call self-registers `{ code, status, className, dataSchema }` in a\n// registry anchored on `globalThis` under `Symbol.for(...)` — mirroring the\n// ROUTES pattern — so the deploy bundle's registrations land on the single SDK\n// instance the extractor `require()`s. The registry is pre-seeded with the named\n// built-in classes (`NotFound`, `Conflict`, …) so throw inference can resolve\n// ad-hoc `throw new NotFound(...)` sites by their canonical wire codes.\n//\n// Duplicate code with a DIFFERENT shape (status OR converted data schema) is a\n// hard error at registration time (deploy fails loudly — error codes are\n// project-unique); structurally-identical re-registration is idempotent (each\n// controller BUNDLE carries its own copy of a shared models/errors.ts, so the\n// same defineError line legitimately runs once per bundle in one process).\nimport {\n OpenAPIRegistry,\n OpenApiGeneratorV31,\n extendZodWithOpenApi,\n} from \"@asteasolutions/zod-to-openapi\";\nimport { z, type ZodTypeAny } from \"zod\";\nimport { HttpError } from \"./errors.js\";\n\nextendZodWithOpenApi(z);\n\n/** One registered error: the wire code, HTTP status, the class name the\n * analyzer sees, the optional data payload schema, and whether it is one of the\n * pre-seeded built-in named classes. */\nexport interface RegisteredError {\n code: string;\n status: number;\n className: string;\n dataSchema?: ZodTypeAny;\n /** JSON.stringify of the converted JSON schema — equal digest ⇔ the spec\n * twins would emit an identical `data` schema for this error. */\n dataDigest?: string;\n builtin: boolean;\n}\n\n/** The cross-module-instance registry anchor (the pinned contract symbol). */\nconst ERROR_REGISTRY: unique symbol = Symbol.for(\"palbase.backend.errorRegistry\");\n\ninterface RegistryCarrier {\n [ERROR_REGISTRY]?: Map<string, RegisteredError>;\n}\n\n/** Get (creating + pre-seeding if absent) the project-global error registry,\n * keyed by wire code. Anchored on `globalThis` so every copy of the SDK in a\n * process shares the one registry. */\n/** The fixed data schemas the built-in named errors ship. Declared HERE (not in\n * errors.ts, which stays zod-free) because this is where the registry converts\n * them to JSON-schema for the spec — keying codegen's typed `error.data`. Only\n * the errors that semantically carry a payload have a schema; the rest are\n * data-less. `.int()` is preserved so the wire/codegen sees an integer. */\nconst BUILTIN_DATA_SCHEMAS: Record<string, ZodTypeAny> = {\n bad_request: z.object({\n fields: z.array(z.object({ field: z.string(), message: z.string() })),\n }),\n too_many_requests: z.object({ retryAfter: z.number().int() }),\n};\n\nexport function getErrorRegistry(): Map<string, RegisteredError> {\n const g = globalThis as RegistryCarrier;\n if (!g[ERROR_REGISTRY]) {\n const m = new Map<string, RegisteredError>();\n for (const [code, status, className] of [\n [\"bad_request\", 400, \"BadRequest\"],\n [\"unauthorized\", 401, \"Unauthorized\"],\n [\"forbidden\", 403, \"Forbidden\"],\n [\"not_found\", 404, \"NotFound\"],\n [\"conflict\", 409, \"Conflict\"],\n // The engine's own 23505 conversion (engine/db.ts) throws this, and an\n // author may too. Registered like every other built-in so the spec\n // emitter resolves it — an unregistered code is SKIPPED silently there\n // (openapi/convert.ts) and would degrade to the client's `.other` case.\n [\"unique_violation\", 409, \"UniqueViolation\"],\n [\"too_many_requests\", 429, \"TooManyRequests\"],\n ] as const) {\n const dataSchema = BUILTIN_DATA_SCHEMAS[code];\n m.set(code, {\n code,\n status,\n className,\n builtin: true,\n ...(dataSchema ? { dataSchema, dataDigest: digestOf(code, dataSchema) } : {}),\n });\n }\n g[ERROR_REGISTRY] = m;\n }\n return g[ERROR_REGISTRY];\n}\n\n/** Class returned for schema-bearing errors: ctor(data, message?). */\nexport interface DefinedErrorWithData<S extends ZodTypeAny> {\n new (data: z.input<S>, message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/** Class returned for schema-less errors: ctor(message?). */\nexport interface DefinedError {\n new (message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/**\n * Define a project error class. MUST be called with literal args (string\n * literal `code`, numeric literal `status`) at module top level — the deploy\n * stager's static analyzer reads those literals to resolve throw sites.\n *\n * @example\n * // models/todos/errors.ts\n * export const TodoLocked = defineError(\"todo_locked\", 409, z.object({ retryAfter: z.number() }));\n * // services/todo.service.ts\n * throw new TodoLocked({ retryAfter: 30 });\n */\nexport function defineError<S extends ZodTypeAny>(\n code: string,\n status: number,\n dataSchema: S,\n): DefinedErrorWithData<S>;\nexport function defineError(code: string, status: number): DefinedError;\nexport function defineError(code: string, status: number, dataSchema?: ZodTypeAny): unknown {\n if (!Number.isInteger(status) || status < 400 || status > 599) {\n throw new Error(\n `defineError: status for \"${code}\" must be a 4xx/5xx integer, got ${status} — ` +\n `error responses must not clobber success responses in the project spec.`,\n );\n }\n const registry = getErrorRegistry();\n const existing = registry.get(code);\n const className = defaultClassName(code);\n const dataDigest = dataSchema ? digestOf(code, dataSchema) : undefined;\n if (existing) {\n const sameShape =\n existing.status === status && !existing.builtin && existing.dataDigest === dataDigest;\n if (!sameShape) {\n throw new Error(\n `defineError: duplicate error code \"${code}\" with a different shape ` +\n `(existing: status ${existing.status}${existing.builtin ? \", built-in\" : \"\"}` +\n `${existing.status === status && !existing.builtin ? \", different data schema\" : \"\"}). ` +\n `Error codes are project-unique.`,\n );\n }\n }\n // Local factories so the class-constructor closures capture a NON-optional\n // schema binding (narrowing does not flow into closures created in a branch).\n const makeWithData = (schema: ZodTypeAny) =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(data: unknown, message?: string) {\n super(status, code, message ?? humanize(code), schema.parse(data));\n this.name = className;\n }\n };\n const makeWithoutData = () =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(message?: string) {\n super(status, code, message ?? humanize(code));\n this.name = className;\n }\n };\n const cls = dataSchema ? makeWithData(dataSchema) : makeWithoutData();\n Object.defineProperty(cls, \"name\", { value: className });\n registry.set(code, {\n code,\n status,\n className,\n builtin: false,\n ...(dataSchema ? { dataSchema } : {}),\n ...(dataDigest !== undefined ? { dataDigest } : {}),\n });\n return cls;\n}\n\n/** Convert a data schema through the SAME library the spec twins use and\n * return its JSON-schema digest (the duplicate-shape comparison key). Doubles\n * as the self-containment guard: a schema carrying `.openapi(refId)` metadata\n * (top-level or nested) converts to `$ref` pointers into components the\n * project spec never emits — a dangling ref every spec consumer would choke\n * on — so it is rejected here, at the definition site, with a fixable message. */\nfunction digestOf(code: string, dataSchema: ZodTypeAny): string {\n const TMP_REF = \"__PalbaseErrorDataDigest\";\n const tmpRegistry = new OpenAPIRegistry();\n // Wrap the schema as a property — exactly how the envelope embeds it — so a\n // TOP-LEVEL .openapi(refId) is not masked by the registration refId and\n // surfaces as the same $ref the real emission would produce.\n tmpRegistry.register(TMP_REF, z.object({ data: dataSchema }).openapi(TMP_REF));\n const generated = new OpenApiGeneratorV31(tmpRegistry.definitions).generateComponents();\n const out = generated.components?.schemas?.[TMP_REF];\n const digest = JSON.stringify(out ?? null);\n if (digest.includes('\"$ref\"')) {\n throw new Error(\n `defineError: dataSchema for \"${code}\" carries .openapi(refId) metadata — ` +\n `it would emit dangling $ref pointers in the project spec. ` +\n `Use a plain zod schema (z.object({...})) without .openapi(...).`,\n );\n }\n return digest;\n}\n\n/** \"todo_locked\" → \"TodoLocked\" (used as Error.name; the source class NAME the\n * analyzer sees is whatever the user assigned the const to — they should match\n * by convention, and the descriptor carries the analyzed const name anyway). */\nfunction defaultClassName(code: string): string {\n return code\n .split(\"_\")\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n}\n\n/** \"todo_locked\" → \"Todo locked\" — the default human-readable message. */\nfunction humanize(code: string): string {\n const s = code.replace(/_/g, \" \");\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n"],"mappings":";;;;;;AAiBA,SACEA,iBACAC,qBACAC,4BACK;AACP,SAASC,SAA0B;AAGnCC,qBAAqBC,CAAAA;AAiBrB,IAAMC,iBAAgCC,uBAAOC,IAAI,+BAAA;AAcjD,IAAMC,uBAAmD;EACvDC,aAAaL,EAAEM,OAAO;IACpBC,QAAQP,EAAEQ,MAAMR,EAAEM,OAAO;MAAEG,OAAOT,EAAEU,OAAM;MAAIC,SAASX,EAAEU,OAAM;IAAG,CAAA,CAAA;EACpE,CAAA;EACAE,mBAAmBZ,EAAEM,OAAO;IAAEO,YAAYb,EAAEc,OAAM,EAAGC,IAAG;EAAG,CAAA;AAC7D;AAEO,SAASC,mBAAAA;AACd,QAAMC,IAAIC;AACV,MAAI,CAACD,EAAEhB,cAAAA,GAAiB;AACtB,UAAMkB,IAAI,oBAAIC,IAAAA;AACd,eAAW,CAACC,MAAMC,QAAQC,SAAAA,KAAc;MACtC;QAAC;QAAe;QAAK;;MACrB;QAAC;QAAgB;QAAK;;MACtB;QAAC;QAAa;QAAK;;MACnB;QAAC;QAAa;QAAK;;MACnB;QAAC;QAAY;QAAK;;;;;;MAKlB;QAAC;QAAoB;QAAK;;MAC1B;QAAC;QAAqB;QAAK;;OACjB;AACV,YAAMC,aAAapB,qBAAqBiB,IAAAA;AACxCF,QAAEM,IAAIJ,MAAM;QACVA;QACAC;QACAC;QACAG,SAAS;QACT,GAAIF,aAAa;UAAEA;UAAYG,YAAYC,SAASP,MAAMG,UAAAA;QAAY,IAAI,CAAC;MAC7E,CAAA;IACF;AACAP,MAAEhB,cAAAA,IAAkBkB;EACtB;AACA,SAAOF,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O3B;EAAU,CAAA;AACtDU,WAASR,IAAIJ,MAAM;IACjBA;IACAC;IACAC;IACAG,SAAS;IACT,GAAIF,aAAa;MAAEA;IAAW,IAAI,CAAC;IACnC,GAAIG,eAAeU,SAAY;MAAEV;IAAW,IAAI,CAAC;EACnD,CAAA;AACA,SAAOoB;AACT;AAtDgBlB;AA8DhB,SAASD,SAASP,MAAcG,YAAsB;AACpD,QAAM2B,UAAU;AAChB,QAAMC,cAAc,IAAIC,gBAAAA;AAIxBD,cAAYE,SAASH,SAASnD,EAAEM,OAAO;IAAEoC,MAAMlB;EAAW,CAAA,EAAG+B,QAAQJ,OAAAA,CAAAA;AACrE,QAAMK,YAAY,IAAIC,oBAAoBL,YAAYM,WAAW,EAAEC,mBAAkB;AACrF,QAAMC,MAAMJ,UAAUK,YAAYC,UAAUX,OAAAA;AAC5C,QAAMY,SAASC,KAAKC,UAAUL,OAAO,IAAA;AACrC,MAAIG,OAAOG,SAAS,QAAA,GAAW;AAC7B,UAAM,IAAIlC,MACR,gCAAgCX,IAAAA,qKAEmC;EAEvE;AACA,SAAO0C;AACT;AAlBSnC;AAuBT,SAASQ,iBAAiBf,MAAY;AACpC,SAAOA,KACJ8C,MAAM,GAAA,EACNC,IAAI,CAACC,MAAMA,EAAEC,OAAO,CAAA,EAAGC,YAAW,IAAKF,EAAEG,MAAM,CAAA,CAAA,EAC/CC,KAAK,EAAA;AACV;AALSrC;AAQT,SAASO,SAAStB,MAAY;AAC5B,QAAMqD,IAAIrD,KAAKsD,QAAQ,MAAM,GAAA;AAC7B,SAAOD,EAAEJ,OAAO,CAAA,EAAGC,YAAW,IAAKG,EAAEF,MAAM,CAAA;AAC7C;AAHS7B;","names":["OpenAPIRegistry","OpenApiGeneratorV31","extendZodWithOpenApi","z","extendZodWithOpenApi","z","ERROR_REGISTRY","Symbol","for","BUILTIN_DATA_SCHEMAS","bad_request","object","fields","array","field","string","message","too_many_requests","retryAfter","number","int","getErrorRegistry","g","globalThis","m","Map","code","status","className","dataSchema","set","builtin","dataDigest","digestOf","defineError","Number","isInteger","Error","registry","existing","get","defaultClassName","undefined","sameShape","makeWithData","schema","HttpError","data","humanize","parse","name","makeWithoutData","cls","Object","defineProperty","value","TMP_REF","tmpRegistry","OpenAPIRegistry","register","openapi","generated","OpenApiGeneratorV31","definitions","generateComponents","out","components","schemas","digest","JSON","stringify","includes","split","map","p","charAt","toUpperCase","slice","join","s","replace"]}
1
+ {"version":3,"sources":["../src/error-registry.ts"],"sourcesContent":["// defineError — project-defined typed error classes + the module-global error\n// registry the OpenAPI spec twins join against.\n//\n// `defineError(code, status, dataSchema?)` returns an `HttpError` subclass whose\n// constructor is typed by the zod schema (`new TodoLocked({ retryAfter: 30 })`).\n// Each call self-registers `{ code, status, className, dataSchema }` in a\n// registry anchored on `globalThis` under `Symbol.for(...)` — mirroring the\n// ROUTES pattern — so the deploy bundle's registrations land on the single SDK\n// instance the extractor `require()`s. The registry is pre-seeded with the named\n// built-in classes (`NotFound`, `Conflict`, …) so throw inference can resolve\n// ad-hoc `throw new NotFound(...)` sites by their canonical wire codes.\n//\n// Duplicate code with a DIFFERENT shape (status OR converted data schema) is a\n// hard error at registration time (deploy fails loudly — error codes are\n// project-unique); structurally-identical re-registration is idempotent (each\n// controller BUNDLE carries its own copy of a shared models/errors.ts, so the\n// same defineError line legitimately runs once per bundle in one process).\nimport {\n OpenAPIRegistry,\n OpenApiGeneratorV31,\n extendZodWithOpenApi,\n} from \"@asteasolutions/zod-to-openapi\";\nimport { z, type ZodTypeAny } from \"zod\";\nimport { HttpError } from \"./errors.js\";\n\nextendZodWithOpenApi(z);\n\n/** One registered error: the wire code, HTTP status, the class name the\n * analyzer sees, the optional data payload schema, and whether it is one of the\n * pre-seeded built-in named classes. */\nexport interface RegisteredError {\n code: string;\n status: number;\n className: string;\n dataSchema?: ZodTypeAny;\n /** JSON.stringify of the converted JSON schema — equal digest ⇔ the spec\n * twins would emit an identical `data` schema for this error. */\n dataDigest?: string;\n builtin: boolean;\n}\n\n/** The cross-module-instance registry anchor (the pinned contract symbol). */\nconst ERROR_REGISTRY: unique symbol = Symbol.for(\"palbase.backend.errorRegistry\");\n\ninterface RegistryCarrier {\n [ERROR_REGISTRY]?: Map<string, RegisteredError>;\n}\n\n/** Get (creating + pre-seeding if absent) the project-global error registry,\n * keyed by wire code. Anchored on `globalThis` so every copy of the SDK in a\n * process shares the one registry. */\n/** The fixed data schemas the built-in named errors ship. Declared HERE (not in\n * errors.ts, which stays zod-free) because this is where the registry converts\n * them to JSON-schema for the spec — keying codegen's typed `error.data`. Only\n * the errors that semantically carry a payload have a schema; the rest are\n * data-less. `.int()` is preserved so the wire/codegen sees an integer. */\nconst BUILTIN_DATA_SCHEMAS: Record<string, ZodTypeAny> = {\n bad_request: z.object({\n fields: z.array(z.object({ field: z.string(), message: z.string() })),\n }),\n too_many_requests: z.object({ retryAfter: z.number().int() }),\n};\n\nexport function getErrorRegistry(): Map<string, RegisteredError> {\n const g = globalThis as RegistryCarrier;\n if (!g[ERROR_REGISTRY]) {\n const m = new Map<string, RegisteredError>();\n for (const [code, status, className] of [\n [\"bad_request\", 400, \"BadRequest\"],\n [\"unauthorized\", 401, \"Unauthorized\"],\n [\"forbidden\", 403, \"Forbidden\"],\n [\"not_found\", 404, \"NotFound\"],\n [\"conflict\", 409, \"Conflict\"],\n // The engine's own 23505 conversion (engine/db.ts) throws this, and an\n // author may too. Registered like every other built-in so the spec\n // emitter resolves it — an unregistered code is SKIPPED silently there\n // (openapi/convert.ts) and would degrade to the client's `.other` case.\n [\"unique_violation\", 409, \"UniqueViolation\"],\n [\"too_many_requests\", 429, \"TooManyRequests\"],\n ] as const) {\n const dataSchema = BUILTIN_DATA_SCHEMAS[code];\n m.set(code, {\n code,\n status,\n className,\n builtin: true,\n ...(dataSchema ? { dataSchema, dataDigest: digestOf(code, dataSchema) } : {}),\n });\n }\n g[ERROR_REGISTRY] = m;\n }\n return g[ERROR_REGISTRY];\n}\n\n/** Class returned for schema-bearing errors: ctor(data, message?). */\nexport interface DefinedErrorWithData<S extends ZodTypeAny> {\n new (data: z.input<S>, message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/** Class returned for schema-less errors: ctor(message?). */\nexport interface DefinedError {\n new (message?: string): HttpError;\n readonly code: string;\n readonly status: number;\n}\n\n/**\n * Define a project error class. MUST be called with literal args (string\n * literal `code`, numeric literal `status`) at module top level — the deploy\n * stager's static analyzer reads those literals to resolve throw sites.\n *\n * @example\n * // models/todos/errors.ts\n * export const TodoLocked = defineError(\"todo_locked\", 409, z.object({ retryAfter: z.number() }));\n * // services/todo.service.ts\n * throw new TodoLocked({ retryAfter: 30 });\n */\nexport function defineError<S extends ZodTypeAny>(\n code: string,\n status: number,\n dataSchema: S,\n): DefinedErrorWithData<S>;\nexport function defineError(code: string, status: number): DefinedError;\nexport function defineError(code: string, status: number, dataSchema?: ZodTypeAny): unknown {\n if (!Number.isInteger(status) || status < 400 || status > 599) {\n throw new Error(\n `defineError: status for \"${code}\" must be a 4xx/5xx integer, got ${status} — ` +\n `error responses must not clobber success responses in the project spec.`,\n );\n }\n const registry = getErrorRegistry();\n const existing = registry.get(code);\n const className = defaultClassName(code);\n const dataDigest = dataSchema ? digestOf(code, dataSchema) : undefined;\n if (existing) {\n const sameShape =\n existing.status === status && !existing.builtin && existing.dataDigest === dataDigest;\n if (!sameShape) {\n throw new Error(\n `defineError: duplicate error code \"${code}\" with a different shape ` +\n `(existing: status ${existing.status}${existing.builtin ? \", built-in\" : \"\"}` +\n `${existing.status === status && !existing.builtin ? \", different data schema\" : \"\"}). ` +\n `Error codes are project-unique.`,\n );\n }\n }\n // Local factories so the class-constructor closures capture a NON-optional\n // schema binding (narrowing does not flow into closures created in a branch).\n const makeWithData = (schema: ZodTypeAny) =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(data: unknown, message?: string) {\n super(status, code, message ?? humanize(code), schema.parse(data));\n this.name = className;\n }\n };\n const makeWithoutData = () =>\n class extends HttpError {\n static readonly code = code;\n static readonly status = status;\n constructor(message?: string) {\n super(status, code, message ?? humanize(code));\n this.name = className;\n }\n };\n const cls = dataSchema ? makeWithData(dataSchema) : makeWithoutData();\n Object.defineProperty(cls, \"name\", { value: className });\n registry.set(code, {\n code,\n status,\n className,\n builtin: false,\n ...(dataSchema ? { dataSchema } : {}),\n ...(dataDigest !== undefined ? { dataDigest } : {}),\n });\n return cls;\n}\n\n/** Convert a data schema through the SAME library the spec twins use and\n * return its JSON-schema digest (the duplicate-shape comparison key). Doubles\n * as the self-containment guard: a schema carrying `.openapi(refId)` metadata\n * (top-level or nested) converts to `$ref` pointers into components the\n * project spec never emits — a dangling ref every spec consumer would choke\n * on — so it is rejected here, at the definition site, with a fixable message. */\nfunction digestOf(code: string, dataSchema: ZodTypeAny): string {\n const TMP_REF = \"__PalbaseErrorDataDigest\";\n const tmpRegistry = new OpenAPIRegistry();\n // Wrap the schema as a property — exactly how the envelope embeds it — so a\n // TOP-LEVEL .openapi(refId) is not masked by the registration refId and\n // surfaces as the same $ref the real emission would produce.\n tmpRegistry.register(TMP_REF, z.object({ data: dataSchema }).openapi(TMP_REF));\n const generated = new OpenApiGeneratorV31(tmpRegistry.definitions).generateComponents();\n const out = generated.components?.schemas?.[TMP_REF];\n const digest = JSON.stringify(out ?? null);\n if (digest.includes('\"$ref\"')) {\n throw new Error(\n `defineError: dataSchema for \"${code}\" carries .openapi(refId) metadata — ` +\n `it would emit dangling $ref pointers in the project spec. ` +\n `Use a plain zod schema (z.object({...})) without .openapi(...).`,\n );\n }\n return digest;\n}\n\n/** \"todo_locked\" → \"TodoLocked\" (used as Error.name; the source class NAME the\n * analyzer sees is whatever the user assigned the const to — they should match\n * by convention, and the descriptor carries the analyzed const name anyway). */\nfunction defaultClassName(code: string): string {\n return code\n .split(\"_\")\n .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n .join(\"\");\n}\n\n/** \"todo_locked\" → \"Todo locked\" — the default human-readable message. */\nfunction humanize(code: string): string {\n const s = code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nD,CAAA;AACA,SAAOoB;AACT;AAtDgBlB;AA8DhB,SAASD,SAASP,MAAcG,YAAsB;AACpD,QAAM2B,UAAU;AAChB,QAAMC,cAAc,IAAIC,gBAAAA;AAIxBD,cAAYE,SAASH,SAASnD,EAAEM,OAAO;IAAEoC,MAAMlB;EAAW,CAAA,EAAG+B,QAAQJ,OAAAA,CAAAA;AACrE,QAAMK,YAAY,IAAIC,oBAAoBL,YAAYM,WAAW,EAAEC,mBAAkB;AACrF,QAAMC,MAAMJ,UAAUK,YAAYC,UAAUX,OAAAA;AAC5C,QAAMY,SAASC,KAAKC,UAAUL,OAAO,IAAA;AACrC,MAAIG,OAAOG,SAAS,QAAA,GAAW;AAC7B,UAAM,IAAIlC,MACR,gCAAgCX,IAAAA,qKAEmC;EAEvE;AACA,SAAO0C;AACT;AAlBSnC;AAuBT,SAASQ,iBAAiBf,MAAY;AACpC,SAAOA,KACJ8C,MAAM,GAAA,EACNC,IAAI,CAACC,MAAMA,EAAEC,OAAO,CAAA,EAAGC,YAAW,IAAKF,EAAEG,MAAM,CAAA,CAAA,EAC/CC,KAAK,EAAA;AACV;AALSrC;AAQT,SAASO,SAAStB,MAAY;AAC5B,QAAMqD,IAAIrD,KAAKsD,QAAQ,MAAM,GAAA;AAC7B,SAAOD,EAAEJ,OAAO,CAAA,EAAGC,YAAW,IAAKG,EAAEF,MAAM,CAAA;AAC7C;AAHS7B;","names":["OpenAPIRegistry","OpenApiGeneratorV31","extendZodWithOpenApi","z","extendZodWithOpenApi","z","ERROR_REGISTRY","Symbol","for","BUILTIN_DATA_SCHEMAS","bad_request","object","fields","array","field","string","message","too_many_requests","retryAfter","number","int","getErrorRegistry","g","globalThis","m","Map","code","status","className","dataSchema","set","builtin","dataDigest","digestOf","defineError","Number","isInteger","Error","registry","existing","get","defaultClassName","undefined","sameShape","makeWithData","schema","HttpError","data","humanize","parse","name","makeWithoutData","cls","Object","defineProperty","value","TMP_REF","tmpRegistry","OpenAPIRegistry","register","openapi","generated","OpenApiGeneratorV31","definitions","generateComponents","out","components","schemas","digest","JSON","stringify","includes","split","map","p","charAt","toUpperCase","slice","join","s","replace"]}
@@ -1,9 +1,20 @@
1
1
  import {
2
- qualifiedTableKey
3
- } from "./chunk-SI4KGEM3.js";
2
+ queryColumnContract,
3
+ stableContract
4
+ } from "./chunk-PRH45NZU.js";
5
+ import {
6
+ TxPlanBuilder,
7
+ brandRef,
8
+ qualifiedTableKey,
9
+ retryBudget,
10
+ runTxPlan
11
+ } from "./chunk-FOWA7PF4.js";
12
+ import {
13
+ isRetryable
14
+ } from "./chunk-UMESJJRS.js";
4
15
  import {
5
16
  __name
6
- } from "./chunk-KATPXCJ5.js";
17
+ } from "./chunk-VXPNPVAG.js";
7
18
 
8
19
  // src/db/schema.ts
9
20
  var IndexBuilder = class {
@@ -168,6 +179,13 @@ function defineTable(name, input) {
168
179
  }
169
180
  __name(defineTable, "defineTable");
170
181
  var declaringSchemaOf = /* @__PURE__ */ new WeakMap();
182
+ function declaredTableKey(table) {
183
+ const metadata = table[TABLE_META];
184
+ const schema = declaringSchemaOf.get(metadata);
185
+ if (schema === void 0) throw new Error(`defineQuery: table ${metadata.name} must belong to defineSchema before defining its query`);
186
+ return qualifiedTableKey(schema, metadata.name);
187
+ }
188
+ __name(declaredTableKey, "declaredTableKey");
171
189
  function resolveReferences(tables, schemaName) {
172
190
  for (const table of Object.values(tables)) {
173
191
  for (const [colName, builder] of Object.entries(table.columns)) {
@@ -559,6 +577,259 @@ var openai = {
559
577
  }
560
578
  };
561
579
 
580
+ // src/db/typed-db.ts
581
+ function makeTypedTable(name, raw2) {
582
+ return {
583
+ insert: /* @__PURE__ */ __name((data) => raw2.insert(name, data), "insert"),
584
+ aggregate: /* @__PURE__ */ __name((q) => raw2.aggregate(name, q), "aggregate"),
585
+ insertMany: /* @__PURE__ */ __name((rows, opts) => raw2.insertMany(name, rows, opts), "insertMany"),
586
+ put: /* @__PURE__ */ __name((q) => raw2.put(name, q.data, {
587
+ onConflict: q.onConflict
588
+ }), "put"),
589
+ update: /* @__PURE__ */ __name((q) => raw2.update(name, q.where.id, q.set), "update"),
590
+ delete: /* @__PURE__ */ __name((id) => raw2.delete(name, id), "delete"),
591
+ findUnique: /* @__PURE__ */ __name((q) => raw2.findUnique(name, q.where, {
592
+ select: q.select
593
+ }), "findUnique"),
594
+ findById: /* @__PURE__ */ __name((id) => raw2.findById(name, id), "findById"),
595
+ page: /* @__PURE__ */ __name((q) => {
596
+ const { where, ...opts } = q ?? {};
597
+ return raw2.page(name, where, opts);
598
+ }, "page"),
599
+ findMany: /* @__PURE__ */ __name((q) => {
600
+ const { where, ...opts } = q ?? {};
601
+ return raw2.findMany(name, where, opts);
602
+ }, "findMany"),
603
+ updateMany: /* @__PURE__ */ __name((q) => raw2.updateMany(name, q.where, q.set, q.returning === void 0 ? void 0 : {
604
+ returning: q.returning
605
+ }), "updateMany"),
606
+ deleteMany: /* @__PURE__ */ __name((q) => raw2.deleteMany(name, q.where), "deleteMany"),
607
+ count: /* @__PURE__ */ __name((q) => raw2.count(name, q?.where), "count")
608
+ };
609
+ }
610
+ __name(makeTypedTable, "makeTypedTable");
611
+ function makeTypedDB(schema, raw2) {
612
+ const tables = {};
613
+ for (const key of Object.keys(schema.tables)) {
614
+ const tableDef = schema.tables[key];
615
+ if (tableDef !== void 0) {
616
+ tables[key] = makeTypedTable(qualifiedTableKey(schema.name, tableDef.name), raw2);
617
+ }
618
+ }
619
+ const result = {
620
+ tables,
621
+ diagnostics: /* @__PURE__ */ __name(() => raw2.diagnostics(), "diagnostics"),
622
+ readQuery: /* @__PURE__ */ __name((query) => raw2.readQuery(query), "readQuery"),
623
+ compileQuery: /* @__PURE__ */ __name((query) => raw2.compileQuery(query), "compileQuery"),
624
+ explainQuery: /* @__PURE__ */ __name((query) => raw2.explainQuery(query), "explainQuery"),
625
+ command(fn, options) {
626
+ const builder = new TxPlanBuilder();
627
+ const planTables = Object.fromEntries(Object.entries(schema.tables).map(([key, table]) => [
628
+ key,
629
+ builder.table(qualifiedTableKey(schema.name, table.name))
630
+ ]));
631
+ return runTxPlan({
632
+ txPlan: /* @__PURE__ */ __name((plan) => raw2.command(plan, options), "txPlan")
633
+ }, {
634
+ tables: planTables
635
+ }, builder, fn);
636
+ },
637
+ transaction(fn) {
638
+ const builder = new TxPlanBuilder();
639
+ const planTables = {};
640
+ for (const key of Object.keys(schema.tables)) {
641
+ const tableDef = schema.tables[key];
642
+ if (tableDef !== void 0) planTables[key] = builder.table(qualifiedTableKey(schema.name, tableDef.name));
643
+ }
644
+ return runTxPlan(raw2, {
645
+ tables: planTables
646
+ }, builder, fn);
647
+ }
648
+ };
649
+ return result;
650
+ }
651
+ __name(makeTypedDB, "makeTypedDB");
652
+ function col(name) {
653
+ return brandRef({
654
+ $col: name
655
+ }, "col");
656
+ }
657
+ __name(col, "col");
658
+ async function withRetry(fn, opts = {}) {
659
+ const budget = retryBudget(opts.retry);
660
+ let attempt = 0;
661
+ for (; ; ) {
662
+ try {
663
+ return await fn();
664
+ } catch (e) {
665
+ if (attempt >= budget || !isRetryable(e)) throw e;
666
+ attempt += 1;
667
+ }
668
+ }
669
+ }
670
+ __name(withRetry, "withRetry");
671
+ function sqlFragment(strings, ...values) {
672
+ return brandRef({
673
+ $sql: {
674
+ text: [
675
+ ...strings
676
+ ],
677
+ values
678
+ }
679
+ }, "sql");
680
+ }
681
+ __name(sqlFragment, "sqlFragment");
682
+
683
+ // src/db/query.ts
684
+ import { z } from "zod";
685
+ import { OpenAPIRegistry, OpenApiGeneratorV31, extendZodWithOpenApi } from "@asteasolutions/zod-to-openapi";
686
+ extendZodWithOpenApi(z);
687
+ function responseColumn(column, validator) {
688
+ const contract = queryColumnContract(column);
689
+ let schema;
690
+ if (validator) return validator;
691
+ if (contract.codec === "number") schema = z.number().finite();
692
+ else if (contract.codec === "decimal") schema = z.string();
693
+ else switch (contract.type) {
694
+ case "integer":
695
+ schema = z.number().int().min(-2147483648).max(2147483647);
696
+ break;
697
+ case "boolean":
698
+ schema = z.boolean();
699
+ break;
700
+ case "vector":
701
+ schema = z.array(z.number().finite());
702
+ break;
703
+ case "enum": {
704
+ const values = contract.enumValues;
705
+ if (!values?.length) throw new Error("Query response requires declared enum values");
706
+ schema = z.enum(values);
707
+ break;
708
+ }
709
+ case "uuid":
710
+ case "text":
711
+ case "timestamp":
712
+ case "numeric":
713
+ case "bigint":
714
+ schema = z.string();
715
+ break;
716
+ case "jsonb":
717
+ throw new Error("Query response requires a fields validator for a selected jsonb column: its TypeScript payload is erased at runtime");
718
+ default:
719
+ throw new Error(`Query response does not support column type ${contract.type}`);
720
+ }
721
+ return contract.nullable ? schema.nullable() : schema;
722
+ }
723
+ __name(responseColumn, "responseColumn");
724
+ function defineQuery(name, options) {
725
+ if (typeof name !== "string" || !/^[A-Za-z][A-Za-z0-9_]{0,127}$/.test(name)) throw new Error("defineQuery requires a stable name of 1\u2013128 letters, digits or underscores");
726
+ const table = declaredTableKey(options.table);
727
+ const select = [
728
+ ...options.select
729
+ ];
730
+ if (!select.length || new Set(select).size !== select.length) throw new Error(`Query ${name}: select must be explicit, nonempty and distinct`);
731
+ const shape = {}, columns = {};
732
+ for (const key of select) {
733
+ if (!Object.hasOwn(options.table[TABLE_META].columns, key)) throw new Error(`Query ${name}: unknown column ${key}`);
734
+ columns[key] = queryColumnContract(options.table[key]);
735
+ shape[key] = responseColumn(options.table[key], options.fields?.[key]);
736
+ }
737
+ const response = z.array(z.object(shape).strict());
738
+ const queryInput = options.input, where = options.where, limit = options.limit;
739
+ const orderBy = options.orderBy === void 0 ? void 0 : JSON.parse(JSON.stringify(options.orderBy));
740
+ const prepare = /* @__PURE__ */ __name((input) => {
741
+ const parsed = queryInput.parse(input);
742
+ const filter = where === void 0 ? {} : where(parsed);
743
+ if (!filter || typeof filter !== "object" || Array.isArray(filter) || typeof filter.then === "function") {
744
+ throw new Error(`Query ${name}: where must return a synchronous filter object`);
745
+ }
746
+ const size = typeof limit === "function" ? limit(parsed) : limit;
747
+ if (limit !== void 0 && (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0)) throw new Error(`Query ${name}: limit must produce a nonnegative safe integer`);
748
+ return {
749
+ name,
750
+ table,
751
+ columns: JSON.parse(JSON.stringify(columns)),
752
+ where: filter,
753
+ options: {
754
+ select: [
755
+ ...select
756
+ ],
757
+ ...orderBy === void 0 ? {} : {
758
+ orderBy: structuredClone(orderBy)
759
+ },
760
+ ...limit === void 0 ? {} : {
761
+ limit: size
762
+ }
763
+ }
764
+ };
765
+ }, "prepare");
766
+ const attach = /* @__PURE__ */ __name((schema) => {
767
+ const api = {
768
+ queryName: name,
769
+ input: queryInput,
770
+ prepare,
771
+ async run(database, input) {
772
+ const request = prepare(input);
773
+ const rows = await ("$readQuery" in database ? database.$readQuery(request) : database.readQuery(request));
774
+ return schema.parse(rows);
775
+ },
776
+ sql(database, input) {
777
+ const request = prepare(input);
778
+ return "$compileQuery" in database ? database.$compileQuery(request) : database.compileQuery(request);
779
+ },
780
+ explain(database, input) {
781
+ const request = prepare(input);
782
+ return "$explainQuery" in database ? database.$explainQuery(request) : database.explainQuery(request);
783
+ },
784
+ contract() {
785
+ const registry = new OpenAPIRegistry();
786
+ registry.register(`${name}Input`, queryInput);
787
+ registry.register(`${name}Response`, schema);
788
+ return JSON.parse(JSON.stringify({
789
+ name,
790
+ table,
791
+ select,
792
+ columns,
793
+ components: new OpenApiGeneratorV31(registry.definitions).generateComponents().components
794
+ }));
795
+ }
796
+ };
797
+ for (const key of [
798
+ "min",
799
+ "max",
800
+ "length",
801
+ "describe",
802
+ "openapi"
803
+ ]) {
804
+ const modify = schema[key].bind(schema);
805
+ Object.defineProperty(schema, key, {
806
+ value: /* @__PURE__ */ __name((...args) => attach(modify(...args)), "value"),
807
+ configurable: true
808
+ });
809
+ }
810
+ return Object.assign(schema, api);
811
+ }, "attach");
812
+ return attach(response);
813
+ }
814
+ __name(defineQuery, "defineQuery");
815
+ function queryManifest(queries) {
816
+ const sorted = [
817
+ ...queries
818
+ ].sort((a, b) => a.queryName.localeCompare(b.queryName));
819
+ if (new Set(sorted.map((query) => query.queryName)).size !== sorted.length) throw new Error("Query manifest contains duplicate names");
820
+ return JSON.parse(stableContract({
821
+ version: 1,
822
+ queries: sorted.map((query) => query.contract())
823
+ }));
824
+ }
825
+ __name(queryManifest, "queryManifest");
826
+ function assertQueryManifest(queries, baseline) {
827
+ if (stableContract(queryManifest(queries)) !== stableContract(baseline)) {
828
+ throw new Error("Query contract drift: compare queryManifest() with the committed manifest and review the API/client changes before updating it");
829
+ }
830
+ }
831
+ __name(assertQueryManifest, "assertQueryManifest");
832
+
562
833
  export {
563
834
  PolicyExprRef,
564
835
  exprCtx,
@@ -573,6 +844,13 @@ export {
573
844
  EXTENSION_DEPENDENCIES,
574
845
  isPalbaseExtension,
575
846
  raw,
576
- openai
847
+ openai,
848
+ makeTypedDB,
849
+ col,
850
+ withRetry,
851
+ sqlFragment,
852
+ defineQuery,
853
+ queryManifest,
854
+ assertQueryManifest
577
855
  };
578
- //# sourceMappingURL=chunk-YIQ4RS4F.js.map
856
+ //# sourceMappingURL=chunk-SEM36BWY.js.map