@theokit/orm 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - f5fb7b3: `@Transactional` refuses a synchronous SQLite driver with `OrmConfigurationError` before the method
8
+ body runs (usetheokit/theokit-di#76).
9
+
10
+ On better-sqlite3 an async `@Transactional` method used to run outside any transaction. The driver
11
+ rejects an async callback with `TypeError: Transaction function cannot return a promise`, but only
12
+ after the callback returned, so the method had already started. Measured on better-sqlite3 with a
13
+ method that inserts a row and then throws: the caller got the `TypeError`, the method's own error
14
+ escaped as an unhandled rejection, and the row stayed in the table.
15
+
16
+ The decorator now reads drizzle's `resultKind` on the db handle and refuses `"sync"` drivers
17
+ (better-sqlite3, bun:sqlite, sql.js, expo-sqlite) before calling the method. Nothing is written and
18
+ nothing escapes. A transaction on one synchronous connection cannot stay open across an `await`
19
+ without taking in whatever else runs on that connection meanwhile, so emulating it with a manual
20
+ `BEGIN`/`COMMIT` was rejected. libSQL, D1, Postgres and MySQL drivers are unaffected.
21
+
22
+ The README's Transactions example now binds the DataSource, which it never did, so copying it no
23
+ longer ends in `OrmConfigurationError` (usetheokit/theokit-di#75). The suite runs that example
24
+ against a real Postgres engine, so it cannot drift again.
25
+
26
+ ## 0.2.1
27
+
28
+ ### Patch Changes
29
+
30
+ - 302a9eb: O peer range do `@theokit/di` deixa de prometer versões em que o pacote não funciona.
31
+
32
+ `0.2.0` declarava `^0.1.0 || ^0.2.0`, e nenhuma 0.1.x atende ao que o `src/` usa. Um consumidor
33
+ que resolvesse para o piso instalava sem `ERESOLVE` e sem aviso de peer, e partia depois — em
34
+ `0.1.0`, com `TypeError: decorator is not a function` dentro do `reflect-metadata`, longe do range
35
+ que causou; em `0.1.1`, com `OrmConfigurationError: @Transactional run: no DataSource bound to
36
+ instance`.
37
+
38
+ Medido versão a versão rodando a suíte contra cada piso, não deduzido da presença de um símbolo:
39
+ `0.1.0` não exporta `PostConstruct`, `0.1.1` exporta mas o `@Transactional` gerido pelo container
40
+ ainda quebra, `0.2.0` passa. O range passa a ser `^0.2.0` (usetheokit/theokit-di#44).
41
+
3
42
  All notable changes to `@theokit/orm` are documented in this file.
4
43
 
5
44
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
@@ -7,6 +46,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
46
 
8
47
  ## [Unreleased]
9
48
 
49
+ ### Fixed
50
+
51
+ - `@Transactional` refuses a synchronous SQLite driver (better-sqlite3, bun:sqlite, sql.js,
52
+ expo-sqlite) with `OrmConfigurationError` before the method body runs. It used to hand the driver
53
+ an async callback, which the driver rejects with `TypeError: Transaction function cannot return a
54
+ promise` only after the method had started: the method kept running outside any transaction, its
55
+ writes committed, and its own error escaped as an unhandled rejection that ends a Node process by
56
+ default. A transaction on one synchronous connection cannot stay open across an `await`, so the
57
+ decorator now says so instead. Asynchronous drivers, libSQL and D1 included, are unaffected (#76)
58
+
59
+ - The declared peer range on `@theokit/di` no longer promises versions this package does not work
60
+ with. It read `^0.1.0 || ^0.2.0`, but no `0.1.x` release supports a container-managed
61
+ `@Transactional` class. `0.1.0` does not export `PostConstruct` at all, so defining the class
62
+ threw `TypeError: decorator is not a function`; `0.1.1` exports it, but the container never
63
+ calls it, so the hook that binds the DataSource silently never ran and the first transactional
64
+ method raised `OrmConfigurationError: no DataSource bound to instance`. The container only began
65
+ invoking the hook in `@theokit/di@0.2.0`. Both installs resolved without a peer warning. The
66
+ range is now `^0.2.0`, which is the whole of what actually works (#44)
67
+
10
68
  ## [0.2.0] - 2026-08-21
11
69
 
12
70
  ### Added
@@ -36,7 +94,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
36
94
  - `@Transactional` no longer claims the container binds its DataSource automatically. Nothing ever did. The error message now names `bindDataSourceToInstance`, the one call that fixes it, and the docs show the container recipe: inject `ORM_DATA_SOURCE_TOKEN` and bind in a `@PostConstruct` hook (#4).
37
95
  - **Breaking:** `@Transactional({ isolationLevel })` was accepted and silently ignored — the options parameter was never read. The level is now passed to the driver, and rejected with an `OrmConfigurationError` on `sqlite`, which has no per-transaction isolation level to set. Code that passed a level on sqlite and appeared to work was never getting one; it now fails instead of pretending (#4).
38
96
 
39
-
40
97
  ## [0.1.0] - 2026-06-22
41
98
 
42
99
  ### Added
package/README.md CHANGED
@@ -77,22 +77,87 @@ await withAgentContext({ agentId: "agent-123", runId: "run-456" }, async () => {
77
77
 
78
78
  ## Transactions
79
79
 
80
+ `@Transactional()` runs a method inside `db.transaction(...)`. Repository calls made during that
81
+ method, at any depth of `await`, go through the transaction, and a throw rolls all of them back.
82
+
83
+ The decorator has no container to ask for a DataSource, so the class injects one and puts it on the
84
+ instance with `bindDataSourceToInstance` in a `@PostConstruct` hook. Without that call, the first
85
+ transactional method rejects with `OrmConfigurationError`.
86
+
80
87
  ```typescript
81
- import { Transactional } from "@theokit/orm";
88
+ import { Inject, Injectable, PostConstruct } from "@theokit/di";
89
+ import { integer, pgTable, text } from "drizzle-orm/pg-core";
90
+ import {
91
+ bindDataSourceToInstance,
92
+ type DataSource,
93
+ InjectRepository,
94
+ ORM_DATA_SOURCE_TOKEN,
95
+ type Repository,
96
+ Transactional,
97
+ } from "@theokit/orm";
98
+
99
+ const accounts = pgTable("accounts", {
100
+ id: text("id").primaryKey(),
101
+ balance: integer("balance").notNull(),
102
+ });
82
103
 
83
104
  @Injectable()
84
105
  class TransferService {
85
106
  constructor(
86
107
  @InjectRepository(accounts) private readonly accountsRepo: Repository<typeof accounts>,
108
+ @Inject(ORM_DATA_SOURCE_TOKEN) private readonly dataSource: DataSource,
87
109
  ) {}
88
110
 
111
+ @PostConstruct
112
+ bindTransactions() {
113
+ bindDataSourceToInstance(this, this.dataSource);
114
+ }
115
+
89
116
  @Transactional()
90
117
  async transfer(from: string, to: string, amount: number) {
91
- // rollback automatically on throw
118
+ const source = await this.accountsRepo.findById(from);
119
+ const target = await this.accountsRepo.findById(to);
120
+ if (!source || !target) throw new Error("unknown account");
121
+
122
+ await this.accountsRepo.update(from, { balance: source.balance - amount });
123
+ // Throwing here rolls back the debit above.
124
+ if (source.balance < amount) throw new Error("insufficient funds");
125
+ await this.accountsRepo.update(to, { balance: target.balance + amount });
92
126
  }
93
127
  }
94
128
  ```
95
129
 
130
+ Register it with a driver whose transactions are asynchronous, such as `node-postgres`:
131
+
132
+ ```typescript
133
+ import { Container } from "@theokit/di";
134
+ import { OrmModule } from "@theokit/orm";
135
+ import { drizzle } from "drizzle-orm/node-postgres";
136
+
137
+ const db = drizzle(process.env.DATABASE_URL!, { schema: { accounts } });
138
+
139
+ const container = new Container({
140
+ providers: [
141
+ ...OrmModule.forRoot({ schema: { accounts }, dialect: "pg", db }),
142
+ ...OrmModule.forFeature([accounts]),
143
+ TransferService,
144
+ ],
145
+ });
146
+
147
+ await container.resolve(TransferService).transfer("alice", "bob", 30);
148
+ ```
149
+
150
+ The first block is executed by the test suite against a real Postgres engine, so it stays runnable.
151
+
152
+ ### Synchronous SQLite drivers
153
+
154
+ `better-sqlite3`, `bun:sqlite`, `sql.js` and `expo-sqlite` run transactions synchronously, and a
155
+ transaction on one synchronous connection cannot stay open across an `await`. `@Transactional`
156
+ refuses these drivers with `OrmConfigurationError` before the method body runs, so nothing is
157
+ written outside a transaction. Asynchronous SQLite drivers (libSQL, D1) are supported. On a
158
+ synchronous driver, call `db.transaction((tx) => { ... })` yourself with synchronous statements
159
+ inside.
160
+
96
161
  ## Schema export (polyglot)
97
162
 
98
163
  ```typescript
package/dist/index.cjs CHANGED
@@ -357,6 +357,9 @@ function resolveTransactionFn(instance, propertyKey, opts) {
357
357
  if (typeof db.transaction !== "function") {
358
358
  throw new OrmConfigurationError(`${where}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`);
359
359
  }
360
+ if (db.resultKind === "sync") {
361
+ throw new OrmConfigurationError(`${where}: the ${ds.dialect} driver behind DataSource "${ds.name}" runs transactions synchronously (better-sqlite3, bun:sqlite, sql.js, expo-sqlite), and a synchronous transaction cannot stay open across an await. Use an asynchronous driver, or call db.transaction((tx) => { ... }) directly with synchronous statements inside.`);
362
+ }
360
363
  return db.transaction.bind(db);
361
364
  }
362
365
  __name(resolveTransactionFn, "resolveTransactionFn");
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/als-context.ts","../src/errors.ts","../src/tokens.ts","../src/inject-repository.ts","../src/internal/data-source.ts","../src/internal/agent-column-filler.ts","../src/internal/tx-context.ts","../src/repository.ts","../src/types.ts","../src/module.ts","../src/transactional.ts"],"names":["als","AsyncLocalStorage","withAgentContext","ctx","fn","Promise","resolve","run","getAgentContext","getStore","OrmError","Error","name","OrmConfigurationError","OrmValidationError","OrmSchemaExportError","DEFAULT_DS","DRIZZLE_NAME_SYMBOL","Symbol","for","resolveEntityName","entity","undefined","ent","symbolName","length","inner","_","getRepositoryToken","dataSourceName","entityName","InjectRepository","Inject","createDataSource","opts","dialect","schema","db","TRACKED_COLS","warnedTables","WeakSet","getTableColumnNames","table","Object","keys","getTableColumns","fillAgentColumns","row","columns","hasAnyTrackedCol","some","c","includes","process","env","NODE_ENV","has","add","console","warn","filled","col","txAls","withTxContext","tx","getTxContext","resolveTableName","sym","detectPrimaryKey","tableName","colName","entries","meta","primary","isPrimaryKey","primaryKey","column","id","assertValidId","method","Repository","pkColumn","pkName","defaultDb","pk","findById","rows","select","from","where","eq","limit","findMany","q","insert","values","op","returning","update","patch","set","delete","query","_primaryKeyName","createRepository","ORM_DATA_SOURCE_TOKEN","registeredDataSources","Set","dataSourceTokenFor","entityArrayOrThrow","entities","Array","isArray","OrmModule","forRoot","dataSource","token","provide","useValue","forFeature","ents","dsToken","map","inject","useFactory","ds","_resetForTesting","clear","DATA_SOURCE_KEY","bindDataSourceToInstance","instance","readDataSourceFromInstance","v","DIALECTS_WITH_ISOLATION_LEVEL","Transactional","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","resolveTransactionFn","apply","isolationLevel","bind"],"mappings":";;;;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,6BAAAA,EAAAA;AAcT,SAASC,gBAAAA,CAAoBC,KAAmBC,EAAAA,EAAwB;AAC7E,EAAA,OAAOC,QAAQC,OAAAA,CAAQN,GAAAA,CAAIO,GAAAA,CAAIJ,GAAAA,EAAKC,EAAAA,CAAAA,CAAAA;AACtC;AAFgBF,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA;AAUT,SAASM,eAAAA,GAAAA;AACd,EAAA,OAAOR,IAAIS,QAAAA,EAAQ;AACrB;AAFgBD,MAAAA,CAAAA,eAAAA,EAAAA,iBAAAA,CAAAA;;;ACpBT,IAAME,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC;AAUO,IAAMC,qBAAAA,GAAN,cAAoCH,QAAAA,CAAAA;EAnB3C;;;EAoBoBE,IAAAA,GAAO,uBAAA;AAC3B;AASO,IAAME,kBAAAA,GAAN,cAAiCJ,QAAAA,CAAAA;EA9BxC;;;EA+BoBE,IAAAA,GAAO,oBAAA;AAC3B;AASO,IAAMG,oBAAAA,GAAN,cAAmCL,QAAAA,CAAAA;EAzC1C;;;EA0CoBE,IAAAA,GAAO,sBAAA;AAC3B;;;ACzCA,IAAMI,UAAAA,GAAa,SAAA;AAEnB,IAAMC,mBAAAA,mBAAsBC,MAAAA,CAAOC,GAAAA,CAAI,cAAA,CAAA;AAEvC,SAASC,kBAAkBC,MAAAA,EAAe;AACxC,EAAA,IAAIA,MAAAA,KAAW,IAAA,IAAQA,MAAAA,KAAWC,MAAAA,EAAW;AAC3C,IAAA,MAAM,IAAIT,sBACR,kFAAA,CAAA;AAEJ,EAAA;AACA,EAAA,MAAMU,GAAAA,GAAMF,MAAAA;AACZ,EAAA,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C,CAAA;AAE1C,EAAA;AAEA,EAAA,IAAIvD,IAAAA,CAAKiH,mBAAmB7H,MAAAA,IAAa,CAAC+G,8BAA8B7E,GAAAA,CAAIqE,EAAAA,CAAG1F,OAAO,CAAA,EAAG;AACvF,IAAA,MAAM,IAAItB,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,kBAAAA,EAA0BvD,KAAKiH,cAAc,CAAA,sBAAA,EAAyBtB,EAAAA,CAAG1F,OAAO,CAAA,4EAAA,CACL,CAAA;AAElF,EAAA;AAEA,EAAA,MAAME,KAAKwF,EAAAA,CAAGxF,EAAAA;AACd,EAAA,IAAI,OAAOA,EAAAA,CAAG2G,WAAAA,KAAgB,UAAA,EAAY;AACxC,IAAA,MAAM,IAAInI,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,wFAAAA,CACyC,CAAA;AAEhD,EAAA;AAEA,EAAA,OAAOpD,EAAAA,CAAG2G,WAAAA,CAAYI,IAAAA,CAAK/G,EAAAA,CAAAA;AAC7B;AAjCS4G,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"index.cjs","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\n/**\n * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without\n * the caller threading the ids through every function in between.\n *\n * The context follows the async chain rather than the call stack, so it survives every `await`\n * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`\n * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment\n * of it.\n *\n * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`\n * are called the same way.\n */\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\n/**\n * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.\n *\n * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves\n * them unset rather than refusing the write, because plain application code has no agent to name.\n */\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle\n * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import { OrmConfigurationError } from \"./errors.js\";\n\nconst DEFAULT_DS = \"default\";\n\nconst DRIZZLE_NAME_SYMBOL = Symbol.for(\"drizzle:Name\");\n\nfunction resolveEntityName(entity: unknown): string {\n if (entity === null || entity === undefined) {\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: entity is null/undefined. Pass a Drizzle table object.\",\n );\n }\n const ent = entity as Record<string | symbol, unknown>;\n const symbolName = ent[DRIZZLE_NAME_SYMBOL];\n if (typeof symbolName === \"string\" && symbolName.length > 0) return symbolName;\n const inner = ent._ as { name?: unknown } | undefined;\n if (inner && typeof inner.name === \"string\" && inner.name.length > 0) {\n return inner.name;\n }\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: cannot resolve entity name. Pass a Drizzle table (must have either Symbol.for('drizzle:Name') or _.name).\",\n );\n}\n\n/**\n * The container token under which one table's {@link Repository} is registered.\n *\n * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring\n * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from\n * the key it has in your schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`.\n *\n * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable\n * Drizzle name. Deriving a token from an unnameable entity would register the repository under a\n * token nothing could ask for.\n */\nexport function getRepositoryToken(entity: unknown, dataSourceName: string = DEFAULT_DS): string {\n const entityName = resolveEntityName(entity);\n return dataSourceName === DEFAULT_DS\n ? `REPO:${entityName}`\n : `REPO:${dataSourceName}:${entityName}`;\n}\n","import { Inject } from \"@theokit/di\";\nimport { getRepositoryToken } from \"./tokens.js\";\n\n/**\n * Inject the {@link Repository} for one table.\n *\n * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have\n * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails\n * with `TokenNotFoundError` naming the token.\n *\n * @param entity a Drizzle table object\n * @param dataSourceName the data source this table belongs to; omit for the default one\n * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the\n * token is derived from the table's name, so an unnameable entity cannot produce one.\n */\nexport function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator {\n return Inject(getRepositoryToken(entity, dataSourceName));\n}\n","import type { AnyTable, DataSource, OrmRootOptions } from \"../types.js\";\n\nexport function createDataSource<TSchema extends Record<string, AnyTable>>(\n opts: OrmRootOptions<TSchema>,\n): DataSource<TSchema> {\n const name = opts.dataSourceName ?? \"default\";\n return {\n name,\n dialect: opts.dialect,\n schema: opts.schema,\n db: opts.db,\n };\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { getAgentContext } from \"../als-context.js\";\n\nconst TRACKED_COLS = [\"agentId\", \"runId\", \"conversationId\"] as const;\n\nconst warnedTables = new WeakSet<object>();\n\nfunction getTableColumnNames(table: unknown): string[] {\n if (table === null || typeof table !== \"object\") return [];\n try {\n return Object.keys(getTableColumns(table as Parameters<typeof getTableColumns>[0]));\n } catch {\n return [];\n }\n}\n\nexport function fillAgentColumns<T extends Record<string, unknown>>(table: unknown, row: T): T {\n const columns = getTableColumnNames(table);\n const hasAnyTrackedCol = TRACKED_COLS.some((c) => columns.includes(c));\n if (!hasAnyTrackedCol) return row;\n\n const ctx = getAgentContext();\n if (!ctx) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof table === \"object\" &&\n table !== null &&\n !warnedTables.has(table)\n ) {\n warnedTables.add(table);\n console.warn(\n `[@theokit/orm] Table has agentId/runId/conversationId column(s) but no AgentContext set. Wrap calls with withAgentContext({...}, () => ...) to auto-fill.`,\n );\n }\n return row;\n }\n\n const filled: Record<string, unknown> = { ...row };\n for (const col of TRACKED_COLS) {\n if (columns.includes(col) && filled[col] === undefined && ctx[col] !== undefined) {\n filled[col] = ctx[col];\n }\n }\n return filled as T;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst txAls = new AsyncLocalStorage<unknown>();\n\nexport function withTxContext<R>(tx: unknown, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(txAls.run(tx, fn));\n}\n\nexport function getTxContext(): unknown | undefined {\n return txAls.getStore();\n}\n","import type { Column, InferInsertModel, InferSelectModel, SQL, Table } from \"drizzle-orm\";\nimport { eq, getTableColumns } from \"drizzle-orm\";\nimport { OrmConfigurationError, OrmValidationError } from \"./errors.js\";\nimport { fillAgentColumns } from \"./internal/agent-column-filler.js\";\nimport { getTxContext } from \"./internal/tx-context.js\";\n\ninterface DrizzleColumnMeta {\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n name?: string;\n}\n\nfunction resolveTableName(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction detectPrimaryKey(table: Table): { name: string; column: Column } {\n const columns = getTableColumns(table) as Record<string, Column>;\n const tableName = resolveTableName(table);\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as DrizzleColumnMeta;\n if (meta.primary === true || meta.isPrimaryKey === true || meta.primaryKey === true) {\n return { name: colName, column: col };\n }\n }\n if (\"id\" in columns) {\n return { name: \"id\", column: columns.id as Column };\n }\n throw new OrmConfigurationError(\n `Entity \"${tableName}\" has no primary key. v0.1 requires a single-column PK named \"id\" or marked .primaryKey(). Use repo.query() for composite/custom keys.`,\n );\n}\n\nfunction assertValidId(method: string, id: unknown): asserts id is string | number {\n if (id === undefined || id === null) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-null (received ${id === null ? \"null\" : \"undefined\"}).`,\n );\n }\n if (typeof id === \"string\" && id.length === 0) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-empty (received empty string).`,\n );\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw new OrmValidationError(\n `Repository.${method}: id must be string or number (received ${typeof id}).`,\n );\n }\n}\n\ninterface DialectAwareDb {\n insert: (table: unknown) => {\n values: (v: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n get?: () => unknown;\n };\n };\n update: (table: unknown) => {\n set: (v: unknown) => {\n where: (w: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n };\n };\n };\n delete: (table: unknown) => {\n where: (w: unknown) => Promise<unknown> | { run?: () => unknown };\n };\n select: () => { from: (table: unknown) => unknown };\n}\n\n/**\n * CRUD over one Drizzle table, with the six methods most application code needs.\n *\n * Resolve one per table with {@link InjectRepository}, or build one directly with\n * {@link createRepository} when you want no container at all. Anything the six methods do not cover\n * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible\n * without this class growing a second query language.\n *\n * Two guards are deliberate. The constructor refuses a table with no primary key, because every\n * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is\n * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable\n * looks exactly like one that matched every row, and only afterwards.\n *\n * When an agent context is active (see {@link withAgentContext}) and the table declares the\n * matching columns, `insert` and `update` fill them in.\n */\nexport class Repository<T extends Table> {\n private readonly pkColumn: Column;\n private readonly pkName: string;\n private readonly tableName: string;\n\n constructor(\n private readonly defaultDb: unknown,\n private readonly table: T,\n ) {\n const pk = detectPrimaryKey(table);\n this.pkColumn = pk.column;\n this.pkName = pk.name;\n this.tableName = resolveTableName(table);\n }\n\n private get db(): DialectAwareDb {\n const tx = getTxContext();\n return (tx ?? this.defaultDb) as DialectAwareDb;\n }\n\n async findById(id: string | number): Promise<InferSelectModel<T> | null> {\n assertValidId(\"findById\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const rows = (await (this.db.select().from(this.table) as any)\n .where(eq(this.pkColumn, id))\n .limit(1)) as unknown[];\n return (rows[0] as InferSelectModel<T>) ?? null;\n }\n\n async findMany(where?: SQL): Promise<InferSelectModel<T>[]> {\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const q = this.db.select().from(this.table) as any;\n const rows = (where ? await q.where(where) : await q) as unknown[];\n return rows as InferSelectModel<T>[];\n }\n\n async insert(values: InferInsertModel<T>): Promise<InferSelectModel<T>> {\n const filled = fillAgentColumns(this.table, values as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.insert(this.table).values(filled) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.insert on \"${this.tableName}\" returned zero rows. Driver may not support .returning() (MySQL?). Use repo.query() with manual fetch for that dialect.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.insert on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch the inserted row.`,\n );\n }\n\n async update(\n id: string | number,\n patch: Partial<InferInsertModel<T>>,\n ): Promise<InferSelectModel<T>> {\n assertValidId(\"update\", id);\n const filled = fillAgentColumns(this.table, patch as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.update(this.table).set(filled).where(eq(this.pkColumn, id)) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.update on \"${this.tableName}\" id=\"${id}\": no row matched.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.update on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch.`,\n );\n }\n\n async delete(id: string | number): Promise<void> {\n assertValidId(\"delete\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n await (this.db.delete(this.table) as any).where(eq(this.pkColumn, id));\n }\n\n query() {\n return this.db.select().from(this.table);\n }\n\n /** @internal exposed for tests */\n get _primaryKeyName(): string {\n return this.pkName;\n }\n}\n\n/**\n * Non-DI factory for {@link Repository}. The `Repository` constructor is\n * already DI-free (`new Repository(db, table)`); this factory makes the non-DI\n * path explicit and discoverable, so consumers do NOT need `@theokit/di`,\n * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`\n * requires a bound DataSource. Works with any drizzle `db` (incl. better-sqlite3,\n * whose query builders are awaitable).\n *\n * @public\n */\nexport function createRepository<T extends Table>(db: unknown, table: T): Repository<T> {\n return new Repository(db, table);\n}\n","import type { Table } from \"drizzle-orm\";\n\n/** Any Drizzle table. The alias exists so this package's signatures name the domain concept\n * rather than repeating a dependency's type everywhere a table is accepted. */\nexport type AnyTable = Table;\n\n/**\n * The SQL dialect a data source speaks.\n *\n * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`\n * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level\n * to set, and accepting one there would drop it silently.\n */\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\n\n/**\n * What {@link OrmModule.forRoot} needs to build a data source.\n *\n * `db` is the Drizzle handle you already built — this package never opens a connection of its own,\n * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names\n * this source when an application has more than one; omit it and it is `\"default\"`.\n */\nexport interface OrmRootOptions<\n TSchema extends Record<string, AnyTable> = Record<string, AnyTable>,\n> {\n schema: TSchema;\n dialect: Dialect;\n db: unknown;\n dataSourceName?: string;\n}\n\n/**\n * A configured database handle plus the schema and dialect it belongs to.\n *\n * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle\n * handle — running a query no repository covers, or binding it for `@Transactional`.\n */\nexport interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {\n readonly name: string;\n readonly dialect: Dialect;\n readonly schema: TSchema;\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle db handle has driver-specific shape (BetterSQLite3Database vs PgDatabase vs MySqlDatabase); narrow types come at use-site via Repository<T> generic\n readonly db: any;\n}\n\n/**\n * Container token for the default {@link DataSource}.\n *\n * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own\n * token, so this one resolves the source registered without a `dataSourceName`.\n */\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\n\n/**\n * Who is acting, for the duration of one async chain.\n *\n * Repositories copy these into agent-aware columns on insert and update when the table declares\n * them, so a row records which agent and which run produced it without the call sites passing ids\n * down. Established with {@link withAgentContext}; every field is optional because a partial\n * context is more useful than none.\n */\nexport interface AgentContext {\n agentId?: string;\n runId?: string;\n conversationId?: string;\n}\n","import type { Provider } from \"@theokit/di\";\nimport { OrmConfigurationError } from \"./errors.js\";\nimport { createDataSource } from \"./internal/data-source.js\";\nimport { Repository } from \"./repository.js\";\nimport { getRepositoryToken } from \"./tokens.js\";\nimport {\n type AnyTable,\n type DataSource,\n ORM_DATA_SOURCE_TOKEN,\n type OrmRootOptions,\n} from \"./types.js\";\n\nconst registeredDataSources = new Set<string>();\n\nfunction dataSourceTokenFor(name: string): string {\n return name === \"default\" ? ORM_DATA_SOURCE_TOKEN : `${ORM_DATA_SOURCE_TOKEN}:${name}`;\n}\n\nfunction entityArrayOrThrow(entities: unknown): readonly unknown[] {\n if (!Array.isArray(entities)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature: entities must be an array of Drizzle tables. Got ${typeof entities}`,\n );\n }\n if (entities.length === 0) {\n throw new OrmConfigurationError(\n \"OrmModule.forFeature: entities array is empty. Provide at least one Drizzle table.\",\n );\n }\n return entities;\n}\n\n/**\n * Provider builders that put a data source and its repositories into a container.\n *\n * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The\n * split is what lets a feature module declare the tables it needs without repeating the connection\n * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —\n * otherwise the failure would surface as a missing token at the first query, far from its cause.\n */\nexport const OrmModule = {\n forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[] {\n if (opts === null || typeof opts !== \"object\") {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: options is required. Pass { schema, dialect, db }.\",\n );\n }\n if (opts.db === undefined || opts.db === null) {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: opts.db is required. Pass the Drizzle db instance (e.g. drizzle(client, { schema })).\",\n );\n }\n if (![\"sqlite\", \"pg\", \"mysql\"].includes(opts.dialect)) {\n throw new OrmConfigurationError(\n `OrmModule.forRoot: opts.dialect must be one of \"sqlite\" | \"pg\" | \"mysql\". Got \"${opts.dialect}\".`,\n );\n }\n const name = opts.dataSourceName ?? \"default\";\n const dataSource = createDataSource(opts);\n const token = dataSourceTokenFor(name);\n\n registeredDataSources.add(name);\n\n return [\n {\n provide: token,\n useValue: dataSource,\n },\n ];\n },\n\n forFeature(entities: readonly unknown[], dataSourceName: string = \"default\"): Provider[] {\n const ents = entityArrayOrThrow(entities);\n\n if (!registeredDataSources.has(dataSourceName)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature called${\n dataSourceName === \"default\" ? \"\" : ` for dataSource=\"${dataSourceName}\"`\n } before OrmModule.forRoot. Call OrmModule.forRoot(opts) first in your Container providers array.`,\n );\n }\n\n const dsToken = dataSourceTokenFor(dataSourceName);\n\n return ents.map((entity) => ({\n provide: getRepositoryToken(entity, dataSourceName),\n inject: [dsToken],\n useFactory: (ds: DataSource) => new Repository(ds.db, entity as AnyTable),\n }));\n },\n\n /** @internal — testing escape hatch to reset module-level state */\n _resetForTesting(): void {\n registeredDataSources.clear();\n },\n};\n","import { OrmConfigurationError } from \"./errors.js\";\nimport { withTxContext } from \"./internal/tx-context.js\";\nimport type { DataSource } from \"./types.js\";\n\nconst DATA_SOURCE_KEY = Symbol.for(\"Theo:orm:dataSource\");\n\n/**\n * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.\n *\n * `@Transactional` is a method decorator: it runs at class-definition time and has no\n * container to ask, so the DataSource has to be put on the instance before the method is\n * called. Nothing does that for you — not `OrmModule`, not the container.\n *\n * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which\n * runs after construction with every dependency already in place:\n *\n * @example\n * ```ts\n * @Injectable()\n * class TransferService {\n * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}\n *\n * @PostConstruct\n * bindTransactions() {\n * bindDataSourceToInstance(this, this.ds);\n * }\n *\n * @Transactional()\n * async transfer() { ... }\n * }\n * ```\n *\n * Without the container, call it directly on the instance before invoking the method.\n */\nexport function bindDataSourceToInstance(instance: object, ds: DataSource): void {\n (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY] = ds;\n}\n\nfunction readDataSourceFromInstance(instance: object): DataSource | undefined {\n const v = (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY];\n return (v as DataSource | undefined) ?? undefined;\n}\n\n/** Options for {@link Transactional}. */\nexport interface TransactionalOptions {\n /**\n * Isolation level for the transaction, passed straight to the driver.\n *\n * Rejected on `sqlite`, which has no per-transaction isolation level to set — see\n * the note in {@link Transactional}.\n */\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\n\n/**\n * Dialects that accept an isolation level on `db.transaction(cb, config)`.\n *\n * SQLite is deliberately absent. Its transactions take a `behavior` (deferred, immediate,\n * exclusive), not an isolation level, so a level passed there would be dropped on the\n * floor — and a silently ignored isolation level is the kind of thing that looks fine in\n * review and corrupts data under load.\n */\nconst DIALECTS_WITH_ISOLATION_LEVEL: ReadonlySet<DataSource[\"dialect\"]> = new Set([\"pg\", \"mysql\"]);\n\n/**\n * `@Transactional(options?)` — run a method inside a database transaction.\n *\n * The wrapped method executes within `db.transaction(...)`, and the transaction handle is\n * published on the async context so `getTxContext()` inside the call returns it. The\n * method's resolved value is returned; anything it throws rolls the transaction back.\n *\n * The instance must carry a DataSource before the method runs — see\n * {@link bindDataSourceToInstance}, which is the only thing that puts one there.\n */\nexport function Transactional(opts: TransactionalOptions = {}): MethodDecorator {\n return function transactionalDecorator(\n _target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const original = descriptor.value;\n if (typeof original !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional on ${String(propertyKey)}: target is not a method.`,\n );\n }\n\n descriptor.value = async function transactionalWrapper(\n this: object,\n ...args: unknown[]\n ): Promise<unknown> {\n const transaction = resolveTransactionFn(this, propertyKey, opts);\n\n const run = (tx: unknown): Promise<unknown> =>\n withTxContext(tx, () => original.apply(this, args));\n\n // Only pass a config when one was asked for: drivers differ on what an empty\n // config object means, and the no-options case must stay byte-identical to before.\n return opts.isolationLevel === undefined\n ? transaction(run)\n : transaction(run, { isolationLevel: opts.isolationLevel });\n };\n\n return descriptor;\n };\n}\n\ntype TransactionFn = (cb: (tx: unknown) => Promise<unknown>, config?: unknown) => Promise<unknown>;\n\n/**\n * Everything that has to be true before a transaction can start, checked in one place so\n * the wrapper above stays readable: an instance carries a DataSource, the dialect can\n * honour the requested isolation level, and the driver exposes `transaction()`.\n */\nfunction resolveTransactionFn(\n instance: object,\n propertyKey: string | symbol,\n opts: TransactionalOptions,\n): TransactionFn {\n const where = `@Transactional ${String(propertyKey)}`;\n\n const ds = readDataSourceFromInstance(instance);\n if (!ds) {\n throw new OrmConfigurationError(\n `${where}: no DataSource bound to instance. ` +\n `Call bindDataSourceToInstance(this, dataSource) before invoking the method — ` +\n `from a @PostConstruct hook when the class is container-managed, or directly ` +\n `after construction when it is not.`,\n );\n }\n\n if (opts.isolationLevel !== undefined && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {\n throw new OrmConfigurationError(\n `${where}: isolationLevel \"${opts.isolationLevel}\" is not supported on ${ds.dialect}. ` +\n `Remove the option, or use a dialect that has isolation levels (pg, mysql).`,\n );\n }\n\n const db = ds.db as { transaction?: TransactionFn };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `${where}: DataSource.db does not expose .transaction(). ` +\n `Ensure you passed a Drizzle db instance.`,\n );\n }\n\n return db.transaction.bind(db);\n}\n"]}
1
+ {"version":3,"sources":["../src/als-context.ts","../src/errors.ts","../src/tokens.ts","../src/inject-repository.ts","../src/internal/data-source.ts","../src/internal/agent-column-filler.ts","../src/internal/tx-context.ts","../src/repository.ts","../src/types.ts","../src/module.ts","../src/transactional.ts"],"names":["als","AsyncLocalStorage","withAgentContext","ctx","fn","Promise","resolve","run","getAgentContext","getStore","OrmError","Error","name","OrmConfigurationError","OrmValidationError","OrmSchemaExportError","DEFAULT_DS","DRIZZLE_NAME_SYMBOL","Symbol","for","resolveEntityName","entity","undefined","ent","symbolName","length","inner","_","getRepositoryToken","dataSourceName","entityName","InjectRepository","Inject","createDataSource","opts","dialect","schema","db","TRACKED_COLS","warnedTables","WeakSet","getTableColumnNames","table","Object","keys","getTableColumns","fillAgentColumns","row","columns","hasAnyTrackedCol","some","c","includes","process","env","NODE_ENV","has","add","console","warn","filled","col","txAls","withTxContext","tx","getTxContext","resolveTableName","sym","detectPrimaryKey","tableName","colName","entries","meta","primary","isPrimaryKey","primaryKey","column","id","assertValidId","method","Repository","pkColumn","pkName","defaultDb","pk","findById","rows","select","from","where","eq","limit","findMany","q","insert","values","op","returning","update","patch","set","delete","query","_primaryKeyName","createRepository","ORM_DATA_SOURCE_TOKEN","registeredDataSources","Set","dataSourceTokenFor","entityArrayOrThrow","entities","Array","isArray","OrmModule","forRoot","dataSource","token","provide","useValue","forFeature","ents","dsToken","map","inject","useFactory","ds","_resetForTesting","clear","DATA_SOURCE_KEY","bindDataSourceToInstance","instance","readDataSourceFromInstance","v","DIALECTS_WITH_ISOLATION_LEVEL","Transactional","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","resolveTransactionFn","apply","isolationLevel","resultKind","bind"],"mappings":";;;;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,6BAAAA,EAAAA;AAcT,SAASC,gBAAAA,CAAoBC,KAAmBC,EAAAA,EAAwB;AAC7E,EAAA,OAAOC,QAAQC,OAAAA,CAAQN,GAAAA,CAAIO,GAAAA,CAAIJ,GAAAA,EAAKC,EAAAA,CAAAA,CAAAA;AACtC;AAFgBF,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA;AAUT,SAASM,eAAAA,GAAAA;AACd,EAAA,OAAOR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,UAAA,EAAY;AACxC,IAAA,MAAM,IAAInI,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,wFAAAA,CACyC,CAAA;AAEhD,EAAA;AAKA,EAAA,IAAIpD,EAAAA,CAAG+G,eAAe,MAAA,EAAQ;AAC5B,IAAA,MAAM,IAAIvI,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,MAAAA,EAAcoC,GAAG1F,OAAO,CAAA,2BAAA,EAA8B0F,EAAAA,CAAGjH,IAAI,CAAA,qQAAA,CAGgB,CAAA;AAEpF,EAAA;AAEA,EAAA,OAAOyB,EAAAA,CAAG2G,WAAAA,CAAYK,IAAAA,CAAKhH,EAAAA,CAAAA;AAC7B;AA7CS4G,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"index.cjs","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\n/**\n * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without\n * the caller threading the ids through every function in between.\n *\n * The context follows the async chain rather than the call stack, so it survives every `await`\n * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`\n * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment\n * of it.\n *\n * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`\n * are called the same way.\n */\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\n/**\n * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.\n *\n * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves\n * them unset rather than refusing the write, because plain application code has no agent to name.\n */\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, when the handle\n * passed as `db` does not expose `transaction()`, or when that handle is a synchronous SQLite\n * driver whose transactions cannot span an `await`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import { OrmConfigurationError } from \"./errors.js\";\n\nconst DEFAULT_DS = \"default\";\n\nconst DRIZZLE_NAME_SYMBOL = Symbol.for(\"drizzle:Name\");\n\nfunction resolveEntityName(entity: unknown): string {\n if (entity === null || entity === undefined) {\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: entity is null/undefined. Pass a Drizzle table object.\",\n );\n }\n const ent = entity as Record<string | symbol, unknown>;\n const symbolName = ent[DRIZZLE_NAME_SYMBOL];\n if (typeof symbolName === \"string\" && symbolName.length > 0) return symbolName;\n const inner = ent._ as { name?: unknown } | undefined;\n if (inner && typeof inner.name === \"string\" && inner.name.length > 0) {\n return inner.name;\n }\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: cannot resolve entity name. Pass a Drizzle table (must have either Symbol.for('drizzle:Name') or _.name).\",\n );\n}\n\n/**\n * The container token under which one table's {@link Repository} is registered.\n *\n * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring\n * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from\n * the key it has in your schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`.\n *\n * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable\n * Drizzle name. Deriving a token from an unnameable entity would register the repository under a\n * token nothing could ask for.\n */\nexport function getRepositoryToken(entity: unknown, dataSourceName: string = DEFAULT_DS): string {\n const entityName = resolveEntityName(entity);\n return dataSourceName === DEFAULT_DS\n ? `REPO:${entityName}`\n : `REPO:${dataSourceName}:${entityName}`;\n}\n","import { Inject } from \"@theokit/di\";\nimport { getRepositoryToken } from \"./tokens.js\";\n\n/**\n * Inject the {@link Repository} for one table.\n *\n * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have\n * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails\n * with `TokenNotFoundError` naming the token.\n *\n * @param entity a Drizzle table object\n * @param dataSourceName the data source this table belongs to; omit for the default one\n * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the\n * token is derived from the table's name, so an unnameable entity cannot produce one.\n */\nexport function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator {\n return Inject(getRepositoryToken(entity, dataSourceName));\n}\n","import type { AnyTable, DataSource, OrmRootOptions } from \"../types.js\";\n\nexport function createDataSource<TSchema extends Record<string, AnyTable>>(\n opts: OrmRootOptions<TSchema>,\n): DataSource<TSchema> {\n const name = opts.dataSourceName ?? \"default\";\n return {\n name,\n dialect: opts.dialect,\n schema: opts.schema,\n db: opts.db,\n };\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { getAgentContext } from \"../als-context.js\";\n\nconst TRACKED_COLS = [\"agentId\", \"runId\", \"conversationId\"] as const;\n\nconst warnedTables = new WeakSet<object>();\n\nfunction getTableColumnNames(table: unknown): string[] {\n if (table === null || typeof table !== \"object\") return [];\n try {\n return Object.keys(getTableColumns(table as Parameters<typeof getTableColumns>[0]));\n } catch {\n return [];\n }\n}\n\nexport function fillAgentColumns<T extends Record<string, unknown>>(table: unknown, row: T): T {\n const columns = getTableColumnNames(table);\n const hasAnyTrackedCol = TRACKED_COLS.some((c) => columns.includes(c));\n if (!hasAnyTrackedCol) return row;\n\n const ctx = getAgentContext();\n if (!ctx) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof table === \"object\" &&\n table !== null &&\n !warnedTables.has(table)\n ) {\n warnedTables.add(table);\n console.warn(\n `[@theokit/orm] Table has agentId/runId/conversationId column(s) but no AgentContext set. Wrap calls with withAgentContext({...}, () => ...) to auto-fill.`,\n );\n }\n return row;\n }\n\n const filled: Record<string, unknown> = { ...row };\n for (const col of TRACKED_COLS) {\n if (columns.includes(col) && filled[col] === undefined && ctx[col] !== undefined) {\n filled[col] = ctx[col];\n }\n }\n return filled as T;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst txAls = new AsyncLocalStorage<unknown>();\n\nexport function withTxContext<R>(tx: unknown, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(txAls.run(tx, fn));\n}\n\nexport function getTxContext(): unknown | undefined {\n return txAls.getStore();\n}\n","import type { Column, InferInsertModel, InferSelectModel, SQL, Table } from \"drizzle-orm\";\nimport { eq, getTableColumns } from \"drizzle-orm\";\nimport { OrmConfigurationError, OrmValidationError } from \"./errors.js\";\nimport { fillAgentColumns } from \"./internal/agent-column-filler.js\";\nimport { getTxContext } from \"./internal/tx-context.js\";\n\ninterface DrizzleColumnMeta {\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n name?: string;\n}\n\nfunction resolveTableName(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction detectPrimaryKey(table: Table): { name: string; column: Column } {\n const columns = getTableColumns(table) as Record<string, Column>;\n const tableName = resolveTableName(table);\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as DrizzleColumnMeta;\n if (meta.primary === true || meta.isPrimaryKey === true || meta.primaryKey === true) {\n return { name: colName, column: col };\n }\n }\n if (\"id\" in columns) {\n return { name: \"id\", column: columns.id as Column };\n }\n throw new OrmConfigurationError(\n `Entity \"${tableName}\" has no primary key. v0.1 requires a single-column PK named \"id\" or marked .primaryKey(). Use repo.query() for composite/custom keys.`,\n );\n}\n\nfunction assertValidId(method: string, id: unknown): asserts id is string | number {\n if (id === undefined || id === null) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-null (received ${id === null ? \"null\" : \"undefined\"}).`,\n );\n }\n if (typeof id === \"string\" && id.length === 0) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-empty (received empty string).`,\n );\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw new OrmValidationError(\n `Repository.${method}: id must be string or number (received ${typeof id}).`,\n );\n }\n}\n\ninterface DialectAwareDb {\n insert: (table: unknown) => {\n values: (v: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n get?: () => unknown;\n };\n };\n update: (table: unknown) => {\n set: (v: unknown) => {\n where: (w: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n };\n };\n };\n delete: (table: unknown) => {\n where: (w: unknown) => Promise<unknown> | { run?: () => unknown };\n };\n select: () => { from: (table: unknown) => unknown };\n}\n\n/**\n * CRUD over one Drizzle table, with the six methods most application code needs.\n *\n * Resolve one per table with {@link InjectRepository}, or build one directly with\n * {@link createRepository} when you want no container at all. Anything the six methods do not cover\n * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible\n * without this class growing a second query language.\n *\n * Two guards are deliberate. The constructor refuses a table with no primary key, because every\n * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is\n * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable\n * looks exactly like one that matched every row, and only afterwards.\n *\n * When an agent context is active (see {@link withAgentContext}) and the table declares the\n * matching columns, `insert` and `update` fill them in.\n */\nexport class Repository<T extends Table> {\n private readonly pkColumn: Column;\n private readonly pkName: string;\n private readonly tableName: string;\n\n constructor(\n private readonly defaultDb: unknown,\n private readonly table: T,\n ) {\n const pk = detectPrimaryKey(table);\n this.pkColumn = pk.column;\n this.pkName = pk.name;\n this.tableName = resolveTableName(table);\n }\n\n private get db(): DialectAwareDb {\n const tx = getTxContext();\n return (tx ?? this.defaultDb) as DialectAwareDb;\n }\n\n async findById(id: string | number): Promise<InferSelectModel<T> | null> {\n assertValidId(\"findById\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const rows = (await (this.db.select().from(this.table) as any)\n .where(eq(this.pkColumn, id))\n .limit(1)) as unknown[];\n return (rows[0] as InferSelectModel<T>) ?? null;\n }\n\n async findMany(where?: SQL): Promise<InferSelectModel<T>[]> {\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const q = this.db.select().from(this.table) as any;\n const rows = (where ? await q.where(where) : await q) as unknown[];\n return rows as InferSelectModel<T>[];\n }\n\n async insert(values: InferInsertModel<T>): Promise<InferSelectModel<T>> {\n const filled = fillAgentColumns(this.table, values as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.insert(this.table).values(filled) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.insert on \"${this.tableName}\" returned zero rows. Driver may not support .returning() (MySQL?). Use repo.query() with manual fetch for that dialect.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.insert on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch the inserted row.`,\n );\n }\n\n async update(\n id: string | number,\n patch: Partial<InferInsertModel<T>>,\n ): Promise<InferSelectModel<T>> {\n assertValidId(\"update\", id);\n const filled = fillAgentColumns(this.table, patch as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.update(this.table).set(filled).where(eq(this.pkColumn, id)) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.update on \"${this.tableName}\" id=\"${id}\": no row matched.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.update on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch.`,\n );\n }\n\n async delete(id: string | number): Promise<void> {\n assertValidId(\"delete\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n await (this.db.delete(this.table) as any).where(eq(this.pkColumn, id));\n }\n\n query() {\n return this.db.select().from(this.table);\n }\n\n /** @internal exposed for tests */\n get _primaryKeyName(): string {\n return this.pkName;\n }\n}\n\n/**\n * Non-DI factory for {@link Repository}. The `Repository` constructor is\n * already DI-free (`new Repository(db, table)`); this factory makes the non-DI\n * path explicit and discoverable, so consumers do NOT need `@theokit/di`,\n * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`\n * requires a bound DataSource. Works with any drizzle `db` (incl. better-sqlite3,\n * whose query builders are awaitable).\n *\n * @public\n */\nexport function createRepository<T extends Table>(db: unknown, table: T): Repository<T> {\n return new Repository(db, table);\n}\n","import type { Table } from \"drizzle-orm\";\n\n/** Any Drizzle table. The alias exists so this package's signatures name the domain concept\n * rather than repeating a dependency's type everywhere a table is accepted. */\nexport type AnyTable = Table;\n\n/**\n * The SQL dialect a data source speaks.\n *\n * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`\n * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level\n * to set, and accepting one there would drop it silently.\n */\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\n\n/**\n * What {@link OrmModule.forRoot} needs to build a data source.\n *\n * `db` is the Drizzle handle you already built — this package never opens a connection of its own,\n * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names\n * this source when an application has more than one; omit it and it is `\"default\"`.\n */\nexport interface OrmRootOptions<\n TSchema extends Record<string, AnyTable> = Record<string, AnyTable>,\n> {\n schema: TSchema;\n dialect: Dialect;\n db: unknown;\n dataSourceName?: string;\n}\n\n/**\n * A configured database handle plus the schema and dialect it belongs to.\n *\n * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle\n * handle — running a query no repository covers, or binding it for `@Transactional`.\n */\nexport interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {\n readonly name: string;\n readonly dialect: Dialect;\n readonly schema: TSchema;\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle db handle has driver-specific shape (BetterSQLite3Database vs PgDatabase vs MySqlDatabase); narrow types come at use-site via Repository<T> generic\n readonly db: any;\n}\n\n/**\n * Container token for the default {@link DataSource}.\n *\n * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own\n * token, so this one resolves the source registered without a `dataSourceName`.\n */\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\n\n/**\n * Who is acting, for the duration of one async chain.\n *\n * Repositories copy these into agent-aware columns on insert and update when the table declares\n * them, so a row records which agent and which run produced it without the call sites passing ids\n * down. Established with {@link withAgentContext}; every field is optional because a partial\n * context is more useful than none.\n */\nexport interface AgentContext {\n agentId?: string;\n runId?: string;\n conversationId?: string;\n}\n","import type { Provider } from \"@theokit/di\";\nimport { OrmConfigurationError } from \"./errors.js\";\nimport { createDataSource } from \"./internal/data-source.js\";\nimport { Repository } from \"./repository.js\";\nimport { getRepositoryToken } from \"./tokens.js\";\nimport {\n type AnyTable,\n type DataSource,\n ORM_DATA_SOURCE_TOKEN,\n type OrmRootOptions,\n} from \"./types.js\";\n\nconst registeredDataSources = new Set<string>();\n\nfunction dataSourceTokenFor(name: string): string {\n return name === \"default\" ? ORM_DATA_SOURCE_TOKEN : `${ORM_DATA_SOURCE_TOKEN}:${name}`;\n}\n\nfunction entityArrayOrThrow(entities: unknown): readonly unknown[] {\n if (!Array.isArray(entities)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature: entities must be an array of Drizzle tables. Got ${typeof entities}`,\n );\n }\n if (entities.length === 0) {\n throw new OrmConfigurationError(\n \"OrmModule.forFeature: entities array is empty. Provide at least one Drizzle table.\",\n );\n }\n return entities;\n}\n\n/**\n * Provider builders that put a data source and its repositories into a container.\n *\n * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The\n * split is what lets a feature module declare the tables it needs without repeating the connection\n * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —\n * otherwise the failure would surface as a missing token at the first query, far from its cause.\n */\nexport const OrmModule = {\n forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[] {\n if (opts === null || typeof opts !== \"object\") {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: options is required. Pass { schema, dialect, db }.\",\n );\n }\n if (opts.db === undefined || opts.db === null) {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: opts.db is required. Pass the Drizzle db instance (e.g. drizzle(client, { schema })).\",\n );\n }\n if (![\"sqlite\", \"pg\", \"mysql\"].includes(opts.dialect)) {\n throw new OrmConfigurationError(\n `OrmModule.forRoot: opts.dialect must be one of \"sqlite\" | \"pg\" | \"mysql\". Got \"${opts.dialect}\".`,\n );\n }\n const name = opts.dataSourceName ?? \"default\";\n const dataSource = createDataSource(opts);\n const token = dataSourceTokenFor(name);\n\n registeredDataSources.add(name);\n\n return [\n {\n provide: token,\n useValue: dataSource,\n },\n ];\n },\n\n forFeature(entities: readonly unknown[], dataSourceName: string = \"default\"): Provider[] {\n const ents = entityArrayOrThrow(entities);\n\n if (!registeredDataSources.has(dataSourceName)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature called${\n dataSourceName === \"default\" ? \"\" : ` for dataSource=\"${dataSourceName}\"`\n } before OrmModule.forRoot. Call OrmModule.forRoot(opts) first in your Container providers array.`,\n );\n }\n\n const dsToken = dataSourceTokenFor(dataSourceName);\n\n return ents.map((entity) => ({\n provide: getRepositoryToken(entity, dataSourceName),\n inject: [dsToken],\n useFactory: (ds: DataSource) => new Repository(ds.db, entity as AnyTable),\n }));\n },\n\n /** @internal — testing escape hatch to reset module-level state */\n _resetForTesting(): void {\n registeredDataSources.clear();\n },\n};\n","import { OrmConfigurationError } from \"./errors.js\";\nimport { withTxContext } from \"./internal/tx-context.js\";\nimport type { DataSource } from \"./types.js\";\n\nconst DATA_SOURCE_KEY = Symbol.for(\"Theo:orm:dataSource\");\n\n/**\n * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.\n *\n * `@Transactional` is a method decorator: it runs at class-definition time and has no\n * container to ask, so the DataSource has to be put on the instance before the method is\n * called. Nothing does that for you — not `OrmModule`, not the container.\n *\n * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which\n * runs after construction with every dependency already in place:\n *\n * @example\n * ```ts\n * @Injectable()\n * class TransferService {\n * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}\n *\n * @PostConstruct\n * bindTransactions() {\n * bindDataSourceToInstance(this, this.ds);\n * }\n *\n * @Transactional()\n * async transfer() { ... }\n * }\n * ```\n *\n * Without the container, call it directly on the instance before invoking the method.\n */\nexport function bindDataSourceToInstance(instance: object, ds: DataSource): void {\n (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY] = ds;\n}\n\nfunction readDataSourceFromInstance(instance: object): DataSource | undefined {\n const v = (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY];\n return (v as DataSource | undefined) ?? undefined;\n}\n\n/** Options for {@link Transactional}. */\nexport interface TransactionalOptions {\n /**\n * Isolation level for the transaction, passed straight to the driver.\n *\n * Rejected on `sqlite`, which has no per-transaction isolation level to set — see\n * the note in {@link Transactional}.\n */\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\n\n/**\n * Dialects that accept an isolation level on `db.transaction(cb, config)`.\n *\n * SQLite is deliberately absent. Its transactions take a `behavior` (deferred, immediate,\n * exclusive), not an isolation level, so a level passed there would be dropped on the\n * floor — and a silently ignored isolation level is the kind of thing that looks fine in\n * review and corrupts data under load.\n */\nconst DIALECTS_WITH_ISOLATION_LEVEL: ReadonlySet<DataSource[\"dialect\"]> = new Set([\"pg\", \"mysql\"]);\n\n/**\n * `@Transactional(options?)` — run a method inside a database transaction.\n *\n * The wrapped method executes within `db.transaction(...)`, and the transaction handle is\n * published on the async context, so every `Repository` call made during the method, at\n * any depth of `await`, runs on the transaction. The method's resolved value is returned;\n * anything it throws rolls the transaction back.\n *\n * The instance must carry a DataSource before the method runs — see\n * {@link bindDataSourceToInstance}, which is the only thing that puts one there.\n *\n * The driver must run transactions asynchronously. Drizzle's synchronous SQLite drivers\n * (better-sqlite3, bun:sqlite, sql.js, expo-sqlite) are refused with\n * {@link OrmConfigurationError} before the method body runs: a transaction on one synchronous\n * connection cannot stay open across an `await`, and the method would otherwise run, and\n * write, outside any transaction. libSQL and D1 are asynchronous and supported.\n */\nexport function Transactional(opts: TransactionalOptions = {}): MethodDecorator {\n return function transactionalDecorator(\n _target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const original = descriptor.value;\n if (typeof original !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional on ${String(propertyKey)}: target is not a method.`,\n );\n }\n\n descriptor.value = async function transactionalWrapper(\n this: object,\n ...args: unknown[]\n ): Promise<unknown> {\n const transaction = resolveTransactionFn(this, propertyKey, opts);\n\n const run = (tx: unknown): Promise<unknown> =>\n withTxContext(tx, () => original.apply(this, args));\n\n // Only pass a config when one was asked for: drivers differ on what an empty\n // config object means, and the no-options case must stay byte-identical to before.\n return opts.isolationLevel === undefined\n ? transaction(run)\n : transaction(run, { isolationLevel: opts.isolationLevel });\n };\n\n return descriptor;\n };\n}\n\ntype TransactionFn = (cb: (tx: unknown) => Promise<unknown>, config?: unknown) => Promise<unknown>;\n\n/**\n * Everything that has to be true before a transaction can start, checked in one place so\n * the wrapper above stays readable: an instance carries a DataSource, the dialect can\n * honour the requested isolation level, and the driver exposes `transaction()`.\n */\nfunction resolveTransactionFn(\n instance: object,\n propertyKey: string | symbol,\n opts: TransactionalOptions,\n): TransactionFn {\n const where = `@Transactional ${String(propertyKey)}`;\n\n const ds = readDataSourceFromInstance(instance);\n if (!ds) {\n throw new OrmConfigurationError(\n `${where}: no DataSource bound to instance. ` +\n `Call bindDataSourceToInstance(this, dataSource) before invoking the method — ` +\n `from a @PostConstruct hook when the class is container-managed, or directly ` +\n `after construction when it is not.`,\n );\n }\n\n if (opts.isolationLevel !== undefined && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {\n throw new OrmConfigurationError(\n `${where}: isolationLevel \"${opts.isolationLevel}\" is not supported on ${ds.dialect}. ` +\n `Remove the option, or use a dialect that has isolation levels (pg, mysql).`,\n );\n }\n\n const db = ds.db as { transaction?: TransactionFn; resultKind?: unknown };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `${where}: DataSource.db does not expose .transaction(). ` +\n `Ensure you passed a Drizzle db instance.`,\n );\n }\n\n // Checked before the method runs, because afterwards is too late: a synchronous driver throws\n // \"Transaction function cannot return a promise\" only once the callback has returned, by which\n // point the method has started and keeps running, and writing, with no transaction around it.\n if (db.resultKind === \"sync\") {\n throw new OrmConfigurationError(\n `${where}: the ${ds.dialect} driver behind DataSource \"${ds.name}\" runs transactions ` +\n `synchronously (better-sqlite3, bun:sqlite, sql.js, expo-sqlite), and a synchronous ` +\n `transaction cannot stay open across an await. Use an asynchronous driver, or call ` +\n `db.transaction((tx) => { ... }) directly with synchronous statements inside.`,\n );\n }\n\n return db.transaction.bind(db);\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -93,8 +93,9 @@ declare class OrmError extends Error {
93
93
  * The wiring is wrong, and no input will make the call succeed.
94
94
  *
95
95
  * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data
96
- * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle
97
- * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in
96
+ * source, when `@Transactional` finds no DataSource bound to the instance, when the handle
97
+ * passed as `db` does not expose `transaction()`, or when that handle is a synchronous SQLite
98
+ * driver whose transactions cannot span an `await`. Every case is a mistake in setup rather than in
98
99
  * the data, so it fails at the earliest point that can see it rather than at the first query.
99
100
  */
100
101
  declare class OrmConfigurationError extends OrmError {
@@ -250,11 +251,18 @@ interface TransactionalOptions {
250
251
  * `@Transactional(options?)` — run a method inside a database transaction.
251
252
  *
252
253
  * The wrapped method executes within `db.transaction(...)`, and the transaction handle is
253
- * published on the async context so `getTxContext()` inside the call returns it. The
254
- * method's resolved value is returned; anything it throws rolls the transaction back.
254
+ * published on the async context, so every `Repository` call made during the method, at
255
+ * any depth of `await`, runs on the transaction. The method's resolved value is returned;
256
+ * anything it throws rolls the transaction back.
255
257
  *
256
258
  * The instance must carry a DataSource before the method runs — see
257
259
  * {@link bindDataSourceToInstance}, which is the only thing that puts one there.
260
+ *
261
+ * The driver must run transactions asynchronously. Drizzle's synchronous SQLite drivers
262
+ * (better-sqlite3, bun:sqlite, sql.js, expo-sqlite) are refused with
263
+ * {@link OrmConfigurationError} before the method body runs: a transaction on one synchronous
264
+ * connection cannot stay open across an `await`, and the method would otherwise run, and
265
+ * write, outside any transaction. libSQL and D1 are asynchronous and supported.
258
266
  */
259
267
  declare function Transactional(opts?: TransactionalOptions): MethodDecorator;
260
268
 
package/dist/index.d.ts CHANGED
@@ -93,8 +93,9 @@ declare class OrmError extends Error {
93
93
  * The wiring is wrong, and no input will make the call succeed.
94
94
  *
95
95
  * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data
96
- * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle
97
- * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in
96
+ * source, when `@Transactional` finds no DataSource bound to the instance, when the handle
97
+ * passed as `db` does not expose `transaction()`, or when that handle is a synchronous SQLite
98
+ * driver whose transactions cannot span an `await`. Every case is a mistake in setup rather than in
98
99
  * the data, so it fails at the earliest point that can see it rather than at the first query.
99
100
  */
100
101
  declare class OrmConfigurationError extends OrmError {
@@ -250,11 +251,18 @@ interface TransactionalOptions {
250
251
  * `@Transactional(options?)` — run a method inside a database transaction.
251
252
  *
252
253
  * The wrapped method executes within `db.transaction(...)`, and the transaction handle is
253
- * published on the async context so `getTxContext()` inside the call returns it. The
254
- * method's resolved value is returned; anything it throws rolls the transaction back.
254
+ * published on the async context, so every `Repository` call made during the method, at
255
+ * any depth of `await`, runs on the transaction. The method's resolved value is returned;
256
+ * anything it throws rolls the transaction back.
255
257
  *
256
258
  * The instance must carry a DataSource before the method runs — see
257
259
  * {@link bindDataSourceToInstance}, which is the only thing that puts one there.
260
+ *
261
+ * The driver must run transactions asynchronously. Drizzle's synchronous SQLite drivers
262
+ * (better-sqlite3, bun:sqlite, sql.js, expo-sqlite) are refused with
263
+ * {@link OrmConfigurationError} before the method body runs: a transaction on one synchronous
264
+ * connection cannot stay open across an `await`, and the method would otherwise run, and
265
+ * write, outside any transaction. libSQL and D1 are asynchronous and supported.
258
266
  */
259
267
  declare function Transactional(opts?: TransactionalOptions): MethodDecorator;
260
268
 
package/dist/index.js CHANGED
@@ -355,6 +355,9 @@ function resolveTransactionFn(instance, propertyKey, opts) {
355
355
  if (typeof db.transaction !== "function") {
356
356
  throw new OrmConfigurationError(`${where}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`);
357
357
  }
358
+ if (db.resultKind === "sync") {
359
+ throw new OrmConfigurationError(`${where}: the ${ds.dialect} driver behind DataSource "${ds.name}" runs transactions synchronously (better-sqlite3, bun:sqlite, sql.js, expo-sqlite), and a synchronous transaction cannot stay open across an await. Use an asynchronous driver, or call db.transaction((tx) => { ... }) directly with synchronous statements inside.`);
360
+ }
358
361
  return db.transaction.bind(db);
359
362
  }
360
363
  __name(resolveTransactionFn, "resolveTransactionFn");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/als-context.ts","../src/errors.ts","../src/tokens.ts","../src/inject-repository.ts","../src/internal/data-source.ts","../src/internal/agent-column-filler.ts","../src/internal/tx-context.ts","../src/repository.ts","../src/types.ts","../src/module.ts","../src/transactional.ts"],"names":["als","AsyncLocalStorage","withAgentContext","ctx","fn","Promise","resolve","run","getAgentContext","getStore","OrmError","Error","name","OrmConfigurationError","OrmValidationError","OrmSchemaExportError","DEFAULT_DS","DRIZZLE_NAME_SYMBOL","Symbol","for","resolveEntityName","entity","undefined","ent","symbolName","length","inner","_","getRepositoryToken","dataSourceName","entityName","InjectRepository","Inject","createDataSource","opts","dialect","schema","db","TRACKED_COLS","warnedTables","WeakSet","getTableColumnNames","table","Object","keys","getTableColumns","fillAgentColumns","row","columns","hasAnyTrackedCol","some","c","includes","process","env","NODE_ENV","has","add","console","warn","filled","col","txAls","withTxContext","tx","getTxContext","resolveTableName","sym","detectPrimaryKey","tableName","colName","entries","meta","primary","isPrimaryKey","primaryKey","column","id","assertValidId","method","Repository","pkColumn","pkName","defaultDb","pk","findById","rows","select","from","where","eq","limit","findMany","q","insert","values","op","returning","update","patch","set","delete","query","_primaryKeyName","createRepository","ORM_DATA_SOURCE_TOKEN","registeredDataSources","Set","dataSourceTokenFor","entityArrayOrThrow","entities","Array","isArray","OrmModule","forRoot","dataSource","token","provide","useValue","forFeature","ents","dsToken","map","inject","useFactory","ds","_resetForTesting","clear","DATA_SOURCE_KEY","bindDataSourceToInstance","instance","readDataSourceFromInstance","v","DIALECTS_WITH_ISOLATION_LEVEL","Transactional","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","resolveTransactionFn","apply","isolationLevel","bind"],"mappings":";;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,iBAAAA,EAAAA;AAcT,SAASC,gBAAAA,CAAoBC,KAAmBC,EAAAA,EAAwB;AAC7E,EAAA,OAAOC,QAAQC,OAAAA,CAAQN,GAAAA,CAAIO,GAAAA,CAAIJ,GAAAA,EAAKC,EAAAA,CAAAA,CAAAA;AACtC;AAFgBF,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA;AAUT,SAASM,eAAAA,GAAAA;AACd,EAAA,OAAOR,IAAIS,QAAAA,EAAQ;AACrB;AAFgBD,MAAAA,CAAAA,eAAAA,EAAAA,iBAAAA,CAAAA;;;ACpBT,IAAME,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC;AAUO,IAAMC,qBAAAA,GAAN,cAAoCH,QAAAA,CAAAA;EAnB3C;;;EAoBoBE,IAAAA,GAAO,uBAAA;AAC3B;AASO,IAAME,kBAAAA,GAAN,cAAiCJ,QAAAA,CAAAA;EA9BxC;;;EA+BoBE,IAAAA,GAAO,oBAAA;AAC3B;AASO,IAAMG,oBAAAA,GAAN,cAAmCL,QAAAA,CAAAA;EAzC1C;;;EA0CoBE,IAAAA,GAAO,sBAAA;AAC3B;;;ACzCA,IAAMI,UAAAA,GAAa,SAAA;AAEnB,IAAMC,mBAAAA,mBAAsBC,MAAAA,CAAOC,GAAAA,CAAI,cAAA,CAAA;AAEvC,SAASC,kBAAkBC,MAAAA,EAAe;AACxC,EAAA,IAAIA,MAAAA,KAAW,IAAA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KM,2BAA2BD,QAAAA,CAAAA;AACtC,EAAA,IAAI,CAACL,EAAAA,EAAI;AACP,IAAA,MAAM,IAAIhH,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,mOAAAA,CAGmC,CAAA;AAE1C,EAAA;AAEA,EAAA,IAAIvD,IAAAA,CAAKiH,mBAAmB7H,MAAAA,IAAa,CAAC+G,8BAA8B7E,GAAAA,CAAIqE,EAAAA,CAAG1F,OAAO,CAAA,EAAG;AACvF,IAAA,MAAM,IAAItB,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,kBAAAA,EAA0BvD,KAAKiH,cAAc,CAAA,sBAAA,EAAyBtB,EAAAA,CAAG1F,OAAO,CAAA,4EAAA,CACL,CAAA;AAElF,EAAA;AAEA,EAAA,MAAME,KAAKwF,EAAAA,CAAGxF,EAAAA;AACd,EAAA,IAAI,OAAOA,EAAAA,CAAG2G,WAAAA,KAAgB,UAAA,EAAY;AACxC,IAAA,MAAM,IAAInI,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,wFAAAA,CACyC,CAAA;AAEhD,EAAA;AAEA,EAAA,OAAOpD,EAAAA,CAAG2G,WAAAA,CAAYI,IAAAA,CAAK/G,EAAAA,CAAAA;AAC7B;AAjCS4G,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"index.js","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\n/**\n * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without\n * the caller threading the ids through every function in between.\n *\n * The context follows the async chain rather than the call stack, so it survives every `await`\n * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`\n * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment\n * of it.\n *\n * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`\n * are called the same way.\n */\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\n/**\n * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.\n *\n * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves\n * them unset rather than refusing the write, because plain application code has no agent to name.\n */\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle\n * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import { OrmConfigurationError } from \"./errors.js\";\n\nconst DEFAULT_DS = \"default\";\n\nconst DRIZZLE_NAME_SYMBOL = Symbol.for(\"drizzle:Name\");\n\nfunction resolveEntityName(entity: unknown): string {\n if (entity === null || entity === undefined) {\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: entity is null/undefined. Pass a Drizzle table object.\",\n );\n }\n const ent = entity as Record<string | symbol, unknown>;\n const symbolName = ent[DRIZZLE_NAME_SYMBOL];\n if (typeof symbolName === \"string\" && symbolName.length > 0) return symbolName;\n const inner = ent._ as { name?: unknown } | undefined;\n if (inner && typeof inner.name === \"string\" && inner.name.length > 0) {\n return inner.name;\n }\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: cannot resolve entity name. Pass a Drizzle table (must have either Symbol.for('drizzle:Name') or _.name).\",\n );\n}\n\n/**\n * The container token under which one table's {@link Repository} is registered.\n *\n * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring\n * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from\n * the key it has in your schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`.\n *\n * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable\n * Drizzle name. Deriving a token from an unnameable entity would register the repository under a\n * token nothing could ask for.\n */\nexport function getRepositoryToken(entity: unknown, dataSourceName: string = DEFAULT_DS): string {\n const entityName = resolveEntityName(entity);\n return dataSourceName === DEFAULT_DS\n ? `REPO:${entityName}`\n : `REPO:${dataSourceName}:${entityName}`;\n}\n","import { Inject } from \"@theokit/di\";\nimport { getRepositoryToken } from \"./tokens.js\";\n\n/**\n * Inject the {@link Repository} for one table.\n *\n * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have\n * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails\n * with `TokenNotFoundError` naming the token.\n *\n * @param entity a Drizzle table object\n * @param dataSourceName the data source this table belongs to; omit for the default one\n * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the\n * token is derived from the table's name, so an unnameable entity cannot produce one.\n */\nexport function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator {\n return Inject(getRepositoryToken(entity, dataSourceName));\n}\n","import type { AnyTable, DataSource, OrmRootOptions } from \"../types.js\";\n\nexport function createDataSource<TSchema extends Record<string, AnyTable>>(\n opts: OrmRootOptions<TSchema>,\n): DataSource<TSchema> {\n const name = opts.dataSourceName ?? \"default\";\n return {\n name,\n dialect: opts.dialect,\n schema: opts.schema,\n db: opts.db,\n };\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { getAgentContext } from \"../als-context.js\";\n\nconst TRACKED_COLS = [\"agentId\", \"runId\", \"conversationId\"] as const;\n\nconst warnedTables = new WeakSet<object>();\n\nfunction getTableColumnNames(table: unknown): string[] {\n if (table === null || typeof table !== \"object\") return [];\n try {\n return Object.keys(getTableColumns(table as Parameters<typeof getTableColumns>[0]));\n } catch {\n return [];\n }\n}\n\nexport function fillAgentColumns<T extends Record<string, unknown>>(table: unknown, row: T): T {\n const columns = getTableColumnNames(table);\n const hasAnyTrackedCol = TRACKED_COLS.some((c) => columns.includes(c));\n if (!hasAnyTrackedCol) return row;\n\n const ctx = getAgentContext();\n if (!ctx) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof table === \"object\" &&\n table !== null &&\n !warnedTables.has(table)\n ) {\n warnedTables.add(table);\n console.warn(\n `[@theokit/orm] Table has agentId/runId/conversationId column(s) but no AgentContext set. Wrap calls with withAgentContext({...}, () => ...) to auto-fill.`,\n );\n }\n return row;\n }\n\n const filled: Record<string, unknown> = { ...row };\n for (const col of TRACKED_COLS) {\n if (columns.includes(col) && filled[col] === undefined && ctx[col] !== undefined) {\n filled[col] = ctx[col];\n }\n }\n return filled as T;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst txAls = new AsyncLocalStorage<unknown>();\n\nexport function withTxContext<R>(tx: unknown, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(txAls.run(tx, fn));\n}\n\nexport function getTxContext(): unknown | undefined {\n return txAls.getStore();\n}\n","import type { Column, InferInsertModel, InferSelectModel, SQL, Table } from \"drizzle-orm\";\nimport { eq, getTableColumns } from \"drizzle-orm\";\nimport { OrmConfigurationError, OrmValidationError } from \"./errors.js\";\nimport { fillAgentColumns } from \"./internal/agent-column-filler.js\";\nimport { getTxContext } from \"./internal/tx-context.js\";\n\ninterface DrizzleColumnMeta {\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n name?: string;\n}\n\nfunction resolveTableName(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction detectPrimaryKey(table: Table): { name: string; column: Column } {\n const columns = getTableColumns(table) as Record<string, Column>;\n const tableName = resolveTableName(table);\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as DrizzleColumnMeta;\n if (meta.primary === true || meta.isPrimaryKey === true || meta.primaryKey === true) {\n return { name: colName, column: col };\n }\n }\n if (\"id\" in columns) {\n return { name: \"id\", column: columns.id as Column };\n }\n throw new OrmConfigurationError(\n `Entity \"${tableName}\" has no primary key. v0.1 requires a single-column PK named \"id\" or marked .primaryKey(). Use repo.query() for composite/custom keys.`,\n );\n}\n\nfunction assertValidId(method: string, id: unknown): asserts id is string | number {\n if (id === undefined || id === null) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-null (received ${id === null ? \"null\" : \"undefined\"}).`,\n );\n }\n if (typeof id === \"string\" && id.length === 0) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-empty (received empty string).`,\n );\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw new OrmValidationError(\n `Repository.${method}: id must be string or number (received ${typeof id}).`,\n );\n }\n}\n\ninterface DialectAwareDb {\n insert: (table: unknown) => {\n values: (v: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n get?: () => unknown;\n };\n };\n update: (table: unknown) => {\n set: (v: unknown) => {\n where: (w: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n };\n };\n };\n delete: (table: unknown) => {\n where: (w: unknown) => Promise<unknown> | { run?: () => unknown };\n };\n select: () => { from: (table: unknown) => unknown };\n}\n\n/**\n * CRUD over one Drizzle table, with the six methods most application code needs.\n *\n * Resolve one per table with {@link InjectRepository}, or build one directly with\n * {@link createRepository} when you want no container at all. Anything the six methods do not cover\n * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible\n * without this class growing a second query language.\n *\n * Two guards are deliberate. The constructor refuses a table with no primary key, because every\n * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is\n * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable\n * looks exactly like one that matched every row, and only afterwards.\n *\n * When an agent context is active (see {@link withAgentContext}) and the table declares the\n * matching columns, `insert` and `update` fill them in.\n */\nexport class Repository<T extends Table> {\n private readonly pkColumn: Column;\n private readonly pkName: string;\n private readonly tableName: string;\n\n constructor(\n private readonly defaultDb: unknown,\n private readonly table: T,\n ) {\n const pk = detectPrimaryKey(table);\n this.pkColumn = pk.column;\n this.pkName = pk.name;\n this.tableName = resolveTableName(table);\n }\n\n private get db(): DialectAwareDb {\n const tx = getTxContext();\n return (tx ?? this.defaultDb) as DialectAwareDb;\n }\n\n async findById(id: string | number): Promise<InferSelectModel<T> | null> {\n assertValidId(\"findById\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const rows = (await (this.db.select().from(this.table) as any)\n .where(eq(this.pkColumn, id))\n .limit(1)) as unknown[];\n return (rows[0] as InferSelectModel<T>) ?? null;\n }\n\n async findMany(where?: SQL): Promise<InferSelectModel<T>[]> {\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const q = this.db.select().from(this.table) as any;\n const rows = (where ? await q.where(where) : await q) as unknown[];\n return rows as InferSelectModel<T>[];\n }\n\n async insert(values: InferInsertModel<T>): Promise<InferSelectModel<T>> {\n const filled = fillAgentColumns(this.table, values as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.insert(this.table).values(filled) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.insert on \"${this.tableName}\" returned zero rows. Driver may not support .returning() (MySQL?). Use repo.query() with manual fetch for that dialect.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.insert on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch the inserted row.`,\n );\n }\n\n async update(\n id: string | number,\n patch: Partial<InferInsertModel<T>>,\n ): Promise<InferSelectModel<T>> {\n assertValidId(\"update\", id);\n const filled = fillAgentColumns(this.table, patch as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.update(this.table).set(filled).where(eq(this.pkColumn, id)) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.update on \"${this.tableName}\" id=\"${id}\": no row matched.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.update on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch.`,\n );\n }\n\n async delete(id: string | number): Promise<void> {\n assertValidId(\"delete\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n await (this.db.delete(this.table) as any).where(eq(this.pkColumn, id));\n }\n\n query() {\n return this.db.select().from(this.table);\n }\n\n /** @internal exposed for tests */\n get _primaryKeyName(): string {\n return this.pkName;\n }\n}\n\n/**\n * Non-DI factory for {@link Repository}. The `Repository` constructor is\n * already DI-free (`new Repository(db, table)`); this factory makes the non-DI\n * path explicit and discoverable, so consumers do NOT need `@theokit/di`,\n * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`\n * requires a bound DataSource. Works with any drizzle `db` (incl. better-sqlite3,\n * whose query builders are awaitable).\n *\n * @public\n */\nexport function createRepository<T extends Table>(db: unknown, table: T): Repository<T> {\n return new Repository(db, table);\n}\n","import type { Table } from \"drizzle-orm\";\n\n/** Any Drizzle table. The alias exists so this package's signatures name the domain concept\n * rather than repeating a dependency's type everywhere a table is accepted. */\nexport type AnyTable = Table;\n\n/**\n * The SQL dialect a data source speaks.\n *\n * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`\n * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level\n * to set, and accepting one there would drop it silently.\n */\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\n\n/**\n * What {@link OrmModule.forRoot} needs to build a data source.\n *\n * `db` is the Drizzle handle you already built — this package never opens a connection of its own,\n * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names\n * this source when an application has more than one; omit it and it is `\"default\"`.\n */\nexport interface OrmRootOptions<\n TSchema extends Record<string, AnyTable> = Record<string, AnyTable>,\n> {\n schema: TSchema;\n dialect: Dialect;\n db: unknown;\n dataSourceName?: string;\n}\n\n/**\n * A configured database handle plus the schema and dialect it belongs to.\n *\n * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle\n * handle — running a query no repository covers, or binding it for `@Transactional`.\n */\nexport interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {\n readonly name: string;\n readonly dialect: Dialect;\n readonly schema: TSchema;\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle db handle has driver-specific shape (BetterSQLite3Database vs PgDatabase vs MySqlDatabase); narrow types come at use-site via Repository<T> generic\n readonly db: any;\n}\n\n/**\n * Container token for the default {@link DataSource}.\n *\n * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own\n * token, so this one resolves the source registered without a `dataSourceName`.\n */\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\n\n/**\n * Who is acting, for the duration of one async chain.\n *\n * Repositories copy these into agent-aware columns on insert and update when the table declares\n * them, so a row records which agent and which run produced it without the call sites passing ids\n * down. Established with {@link withAgentContext}; every field is optional because a partial\n * context is more useful than none.\n */\nexport interface AgentContext {\n agentId?: string;\n runId?: string;\n conversationId?: string;\n}\n","import type { Provider } from \"@theokit/di\";\nimport { OrmConfigurationError } from \"./errors.js\";\nimport { createDataSource } from \"./internal/data-source.js\";\nimport { Repository } from \"./repository.js\";\nimport { getRepositoryToken } from \"./tokens.js\";\nimport {\n type AnyTable,\n type DataSource,\n ORM_DATA_SOURCE_TOKEN,\n type OrmRootOptions,\n} from \"./types.js\";\n\nconst registeredDataSources = new Set<string>();\n\nfunction dataSourceTokenFor(name: string): string {\n return name === \"default\" ? ORM_DATA_SOURCE_TOKEN : `${ORM_DATA_SOURCE_TOKEN}:${name}`;\n}\n\nfunction entityArrayOrThrow(entities: unknown): readonly unknown[] {\n if (!Array.isArray(entities)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature: entities must be an array of Drizzle tables. Got ${typeof entities}`,\n );\n }\n if (entities.length === 0) {\n throw new OrmConfigurationError(\n \"OrmModule.forFeature: entities array is empty. Provide at least one Drizzle table.\",\n );\n }\n return entities;\n}\n\n/**\n * Provider builders that put a data source and its repositories into a container.\n *\n * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The\n * split is what lets a feature module declare the tables it needs without repeating the connection\n * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —\n * otherwise the failure would surface as a missing token at the first query, far from its cause.\n */\nexport const OrmModule = {\n forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[] {\n if (opts === null || typeof opts !== \"object\") {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: options is required. Pass { schema, dialect, db }.\",\n );\n }\n if (opts.db === undefined || opts.db === null) {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: opts.db is required. Pass the Drizzle db instance (e.g. drizzle(client, { schema })).\",\n );\n }\n if (![\"sqlite\", \"pg\", \"mysql\"].includes(opts.dialect)) {\n throw new OrmConfigurationError(\n `OrmModule.forRoot: opts.dialect must be one of \"sqlite\" | \"pg\" | \"mysql\". Got \"${opts.dialect}\".`,\n );\n }\n const name = opts.dataSourceName ?? \"default\";\n const dataSource = createDataSource(opts);\n const token = dataSourceTokenFor(name);\n\n registeredDataSources.add(name);\n\n return [\n {\n provide: token,\n useValue: dataSource,\n },\n ];\n },\n\n forFeature(entities: readonly unknown[], dataSourceName: string = \"default\"): Provider[] {\n const ents = entityArrayOrThrow(entities);\n\n if (!registeredDataSources.has(dataSourceName)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature called${\n dataSourceName === \"default\" ? \"\" : ` for dataSource=\"${dataSourceName}\"`\n } before OrmModule.forRoot. Call OrmModule.forRoot(opts) first in your Container providers array.`,\n );\n }\n\n const dsToken = dataSourceTokenFor(dataSourceName);\n\n return ents.map((entity) => ({\n provide: getRepositoryToken(entity, dataSourceName),\n inject: [dsToken],\n useFactory: (ds: DataSource) => new Repository(ds.db, entity as AnyTable),\n }));\n },\n\n /** @internal — testing escape hatch to reset module-level state */\n _resetForTesting(): void {\n registeredDataSources.clear();\n },\n};\n","import { OrmConfigurationError } from \"./errors.js\";\nimport { withTxContext } from \"./internal/tx-context.js\";\nimport type { DataSource } from \"./types.js\";\n\nconst DATA_SOURCE_KEY = Symbol.for(\"Theo:orm:dataSource\");\n\n/**\n * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.\n *\n * `@Transactional` is a method decorator: it runs at class-definition time and has no\n * container to ask, so the DataSource has to be put on the instance before the method is\n * called. Nothing does that for you — not `OrmModule`, not the container.\n *\n * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which\n * runs after construction with every dependency already in place:\n *\n * @example\n * ```ts\n * @Injectable()\n * class TransferService {\n * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}\n *\n * @PostConstruct\n * bindTransactions() {\n * bindDataSourceToInstance(this, this.ds);\n * }\n *\n * @Transactional()\n * async transfer() { ... }\n * }\n * ```\n *\n * Without the container, call it directly on the instance before invoking the method.\n */\nexport function bindDataSourceToInstance(instance: object, ds: DataSource): void {\n (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY] = ds;\n}\n\nfunction readDataSourceFromInstance(instance: object): DataSource | undefined {\n const v = (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY];\n return (v as DataSource | undefined) ?? undefined;\n}\n\n/** Options for {@link Transactional}. */\nexport interface TransactionalOptions {\n /**\n * Isolation level for the transaction, passed straight to the driver.\n *\n * Rejected on `sqlite`, which has no per-transaction isolation level to set — see\n * the note in {@link Transactional}.\n */\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\n\n/**\n * Dialects that accept an isolation level on `db.transaction(cb, config)`.\n *\n * SQLite is deliberately absent. Its transactions take a `behavior` (deferred, immediate,\n * exclusive), not an isolation level, so a level passed there would be dropped on the\n * floor — and a silently ignored isolation level is the kind of thing that looks fine in\n * review and corrupts data under load.\n */\nconst DIALECTS_WITH_ISOLATION_LEVEL: ReadonlySet<DataSource[\"dialect\"]> = new Set([\"pg\", \"mysql\"]);\n\n/**\n * `@Transactional(options?)` — run a method inside a database transaction.\n *\n * The wrapped method executes within `db.transaction(...)`, and the transaction handle is\n * published on the async context so `getTxContext()` inside the call returns it. The\n * method's resolved value is returned; anything it throws rolls the transaction back.\n *\n * The instance must carry a DataSource before the method runs — see\n * {@link bindDataSourceToInstance}, which is the only thing that puts one there.\n */\nexport function Transactional(opts: TransactionalOptions = {}): MethodDecorator {\n return function transactionalDecorator(\n _target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const original = descriptor.value;\n if (typeof original !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional on ${String(propertyKey)}: target is not a method.`,\n );\n }\n\n descriptor.value = async function transactionalWrapper(\n this: object,\n ...args: unknown[]\n ): Promise<unknown> {\n const transaction = resolveTransactionFn(this, propertyKey, opts);\n\n const run = (tx: unknown): Promise<unknown> =>\n withTxContext(tx, () => original.apply(this, args));\n\n // Only pass a config when one was asked for: drivers differ on what an empty\n // config object means, and the no-options case must stay byte-identical to before.\n return opts.isolationLevel === undefined\n ? transaction(run)\n : transaction(run, { isolationLevel: opts.isolationLevel });\n };\n\n return descriptor;\n };\n}\n\ntype TransactionFn = (cb: (tx: unknown) => Promise<unknown>, config?: unknown) => Promise<unknown>;\n\n/**\n * Everything that has to be true before a transaction can start, checked in one place so\n * the wrapper above stays readable: an instance carries a DataSource, the dialect can\n * honour the requested isolation level, and the driver exposes `transaction()`.\n */\nfunction resolveTransactionFn(\n instance: object,\n propertyKey: string | symbol,\n opts: TransactionalOptions,\n): TransactionFn {\n const where = `@Transactional ${String(propertyKey)}`;\n\n const ds = readDataSourceFromInstance(instance);\n if (!ds) {\n throw new OrmConfigurationError(\n `${where}: no DataSource bound to instance. ` +\n `Call bindDataSourceToInstance(this, dataSource) before invoking the method — ` +\n `from a @PostConstruct hook when the class is container-managed, or directly ` +\n `after construction when it is not.`,\n );\n }\n\n if (opts.isolationLevel !== undefined && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {\n throw new OrmConfigurationError(\n `${where}: isolationLevel \"${opts.isolationLevel}\" is not supported on ${ds.dialect}. ` +\n `Remove the option, or use a dialect that has isolation levels (pg, mysql).`,\n );\n }\n\n const db = ds.db as { transaction?: TransactionFn };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `${where}: DataSource.db does not expose .transaction(). ` +\n `Ensure you passed a Drizzle db instance.`,\n );\n }\n\n return db.transaction.bind(db);\n}\n"]}
1
+ {"version":3,"sources":["../src/als-context.ts","../src/errors.ts","../src/tokens.ts","../src/inject-repository.ts","../src/internal/data-source.ts","../src/internal/agent-column-filler.ts","../src/internal/tx-context.ts","../src/repository.ts","../src/types.ts","../src/module.ts","../src/transactional.ts"],"names":["als","AsyncLocalStorage","withAgentContext","ctx","fn","Promise","resolve","run","getAgentContext","getStore","OrmError","Error","name","OrmConfigurationError","OrmValidationError","OrmSchemaExportError","DEFAULT_DS","DRIZZLE_NAME_SYMBOL","Symbol","for","resolveEntityName","entity","undefined","ent","symbolName","length","inner","_","getRepositoryToken","dataSourceName","entityName","InjectRepository","Inject","createDataSource","opts","dialect","schema","db","TRACKED_COLS","warnedTables","WeakSet","getTableColumnNames","table","Object","keys","getTableColumns","fillAgentColumns","row","columns","hasAnyTrackedCol","some","c","includes","process","env","NODE_ENV","has","add","console","warn","filled","col","txAls","withTxContext","tx","getTxContext","resolveTableName","sym","detectPrimaryKey","tableName","colName","entries","meta","primary","isPrimaryKey","primaryKey","column","id","assertValidId","method","Repository","pkColumn","pkName","defaultDb","pk","findById","rows","select","from","where","eq","limit","findMany","q","insert","values","op","returning","update","patch","set","delete","query","_primaryKeyName","createRepository","ORM_DATA_SOURCE_TOKEN","registeredDataSources","Set","dataSourceTokenFor","entityArrayOrThrow","entities","Array","isArray","OrmModule","forRoot","dataSource","token","provide","useValue","forFeature","ents","dsToken","map","inject","useFactory","ds","_resetForTesting","clear","DATA_SOURCE_KEY","bindDataSourceToInstance","instance","readDataSourceFromInstance","v","DIALECTS_WITH_ISOLATION_LEVEL","Transactional","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","resolveTransactionFn","apply","isolationLevel","resultKind","bind"],"mappings":";;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,iBAAAA,EAAAA;AAcT,SAASC,gBAAAA,CAAoBC,KAAmBC,EAAAA,EAAwB;AAC7E,EAAA,OAAOC,QAAQC,OAAAA,CAAQN,GAAAA,CAAIO,GAAAA,CAAIJ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,CAAA,4EAAA,CACL,CAAA;AAElF,EAAA;AAEA,EAAA,MAAME,KAAKwF,EAAAA,CAAGxF,EAAAA;AACd,EAAA,IAAI,OAAOA,EAAAA,CAAG2G,WAAAA,KAAgB,UAAA,EAAY;AACxC,IAAA,MAAM,IAAInI,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,wFAAAA,CACyC,CAAA;AAEhD,EAAA;AAKA,EAAA,IAAIpD,EAAAA,CAAG+G,eAAe,MAAA,EAAQ;AAC5B,IAAA,MAAM,IAAIvI,qBAAAA,CACR,CAAA,EAAG4E,KAAAA,CAAAA,MAAAA,EAAcoC,GAAG1F,OAAO,CAAA,2BAAA,EAA8B0F,EAAAA,CAAGjH,IAAI,CAAA,qQAAA,CAGgB,CAAA;AAEpF,EAAA;AAEA,EAAA,OAAOyB,EAAAA,CAAG2G,WAAAA,CAAYK,IAAAA,CAAKhH,EAAAA,CAAAA;AAC7B;AA7CS4G,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"index.js","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\n/**\n * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without\n * the caller threading the ids through every function in between.\n *\n * The context follows the async chain rather than the call stack, so it survives every `await`\n * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`\n * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment\n * of it.\n *\n * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`\n * are called the same way.\n */\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\n/**\n * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.\n *\n * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves\n * them unset rather than refusing the write, because plain application code has no agent to name.\n */\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, when the handle\n * passed as `db` does not expose `transaction()`, or when that handle is a synchronous SQLite\n * driver whose transactions cannot span an `await`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import { OrmConfigurationError } from \"./errors.js\";\n\nconst DEFAULT_DS = \"default\";\n\nconst DRIZZLE_NAME_SYMBOL = Symbol.for(\"drizzle:Name\");\n\nfunction resolveEntityName(entity: unknown): string {\n if (entity === null || entity === undefined) {\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: entity is null/undefined. Pass a Drizzle table object.\",\n );\n }\n const ent = entity as Record<string | symbol, unknown>;\n const symbolName = ent[DRIZZLE_NAME_SYMBOL];\n if (typeof symbolName === \"string\" && symbolName.length > 0) return symbolName;\n const inner = ent._ as { name?: unknown } | undefined;\n if (inner && typeof inner.name === \"string\" && inner.name.length > 0) {\n return inner.name;\n }\n throw new OrmConfigurationError(\n \"[orm] getRepositoryToken: cannot resolve entity name. Pass a Drizzle table (must have either Symbol.for('drizzle:Name') or _.name).\",\n );\n}\n\n/**\n * The container token under which one table's {@link Repository} is registered.\n *\n * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring\n * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from\n * the key it has in your schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`.\n *\n * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable\n * Drizzle name. Deriving a token from an unnameable entity would register the repository under a\n * token nothing could ask for.\n */\nexport function getRepositoryToken(entity: unknown, dataSourceName: string = DEFAULT_DS): string {\n const entityName = resolveEntityName(entity);\n return dataSourceName === DEFAULT_DS\n ? `REPO:${entityName}`\n : `REPO:${dataSourceName}:${entityName}`;\n}\n","import { Inject } from \"@theokit/di\";\nimport { getRepositoryToken } from \"./tokens.js\";\n\n/**\n * Inject the {@link Repository} for one table.\n *\n * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have\n * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails\n * with `TokenNotFoundError` naming the token.\n *\n * @param entity a Drizzle table object\n * @param dataSourceName the data source this table belongs to; omit for the default one\n * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the\n * token is derived from the table's name, so an unnameable entity cannot produce one.\n */\nexport function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator {\n return Inject(getRepositoryToken(entity, dataSourceName));\n}\n","import type { AnyTable, DataSource, OrmRootOptions } from \"../types.js\";\n\nexport function createDataSource<TSchema extends Record<string, AnyTable>>(\n opts: OrmRootOptions<TSchema>,\n): DataSource<TSchema> {\n const name = opts.dataSourceName ?? \"default\";\n return {\n name,\n dialect: opts.dialect,\n schema: opts.schema,\n db: opts.db,\n };\n}\n","import { getTableColumns } from \"drizzle-orm\";\nimport { getAgentContext } from \"../als-context.js\";\n\nconst TRACKED_COLS = [\"agentId\", \"runId\", \"conversationId\"] as const;\n\nconst warnedTables = new WeakSet<object>();\n\nfunction getTableColumnNames(table: unknown): string[] {\n if (table === null || typeof table !== \"object\") return [];\n try {\n return Object.keys(getTableColumns(table as Parameters<typeof getTableColumns>[0]));\n } catch {\n return [];\n }\n}\n\nexport function fillAgentColumns<T extends Record<string, unknown>>(table: unknown, row: T): T {\n const columns = getTableColumnNames(table);\n const hasAnyTrackedCol = TRACKED_COLS.some((c) => columns.includes(c));\n if (!hasAnyTrackedCol) return row;\n\n const ctx = getAgentContext();\n if (!ctx) {\n if (\n process.env.NODE_ENV !== \"production\" &&\n typeof table === \"object\" &&\n table !== null &&\n !warnedTables.has(table)\n ) {\n warnedTables.add(table);\n console.warn(\n `[@theokit/orm] Table has agentId/runId/conversationId column(s) but no AgentContext set. Wrap calls with withAgentContext({...}, () => ...) to auto-fill.`,\n );\n }\n return row;\n }\n\n const filled: Record<string, unknown> = { ...row };\n for (const col of TRACKED_COLS) {\n if (columns.includes(col) && filled[col] === undefined && ctx[col] !== undefined) {\n filled[col] = ctx[col];\n }\n }\n return filled as T;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst txAls = new AsyncLocalStorage<unknown>();\n\nexport function withTxContext<R>(tx: unknown, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(txAls.run(tx, fn));\n}\n\nexport function getTxContext(): unknown | undefined {\n return txAls.getStore();\n}\n","import type { Column, InferInsertModel, InferSelectModel, SQL, Table } from \"drizzle-orm\";\nimport { eq, getTableColumns } from \"drizzle-orm\";\nimport { OrmConfigurationError, OrmValidationError } from \"./errors.js\";\nimport { fillAgentColumns } from \"./internal/agent-column-filler.js\";\nimport { getTxContext } from \"./internal/tx-context.js\";\n\ninterface DrizzleColumnMeta {\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n name?: string;\n}\n\nfunction resolveTableName(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction detectPrimaryKey(table: Table): { name: string; column: Column } {\n const columns = getTableColumns(table) as Record<string, Column>;\n const tableName = resolveTableName(table);\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as DrizzleColumnMeta;\n if (meta.primary === true || meta.isPrimaryKey === true || meta.primaryKey === true) {\n return { name: colName, column: col };\n }\n }\n if (\"id\" in columns) {\n return { name: \"id\", column: columns.id as Column };\n }\n throw new OrmConfigurationError(\n `Entity \"${tableName}\" has no primary key. v0.1 requires a single-column PK named \"id\" or marked .primaryKey(). Use repo.query() for composite/custom keys.`,\n );\n}\n\nfunction assertValidId(method: string, id: unknown): asserts id is string | number {\n if (id === undefined || id === null) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-null (received ${id === null ? \"null\" : \"undefined\"}).`,\n );\n }\n if (typeof id === \"string\" && id.length === 0) {\n throw new OrmValidationError(\n `Repository.${method}: id is required and non-empty (received empty string).`,\n );\n }\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n throw new OrmValidationError(\n `Repository.${method}: id must be string or number (received ${typeof id}).`,\n );\n }\n}\n\ninterface DialectAwareDb {\n insert: (table: unknown) => {\n values: (v: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n get?: () => unknown;\n };\n };\n update: (table: unknown) => {\n set: (v: unknown) => {\n where: (w: unknown) => {\n returning?: () => Promise<unknown[]>;\n run?: () => unknown;\n };\n };\n };\n delete: (table: unknown) => {\n where: (w: unknown) => Promise<unknown> | { run?: () => unknown };\n };\n select: () => { from: (table: unknown) => unknown };\n}\n\n/**\n * CRUD over one Drizzle table, with the six methods most application code needs.\n *\n * Resolve one per table with {@link InjectRepository}, or build one directly with\n * {@link createRepository} when you want no container at all. Anything the six methods do not cover\n * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible\n * without this class growing a second query language.\n *\n * Two guards are deliberate. The constructor refuses a table with no primary key, because every\n * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is\n * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable\n * looks exactly like one that matched every row, and only afterwards.\n *\n * When an agent context is active (see {@link withAgentContext}) and the table declares the\n * matching columns, `insert` and `update` fill them in.\n */\nexport class Repository<T extends Table> {\n private readonly pkColumn: Column;\n private readonly pkName: string;\n private readonly tableName: string;\n\n constructor(\n private readonly defaultDb: unknown,\n private readonly table: T,\n ) {\n const pk = detectPrimaryKey(table);\n this.pkColumn = pk.column;\n this.pkName = pk.name;\n this.tableName = resolveTableName(table);\n }\n\n private get db(): DialectAwareDb {\n const tx = getTxContext();\n return (tx ?? this.defaultDb) as DialectAwareDb;\n }\n\n async findById(id: string | number): Promise<InferSelectModel<T> | null> {\n assertValidId(\"findById\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const rows = (await (this.db.select().from(this.table) as any)\n .where(eq(this.pkColumn, id))\n .limit(1)) as unknown[];\n return (rows[0] as InferSelectModel<T>) ?? null;\n }\n\n async findMany(where?: SQL): Promise<InferSelectModel<T>[]> {\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const q = this.db.select().from(this.table) as any;\n const rows = (where ? await q.where(where) : await q) as unknown[];\n return rows as InferSelectModel<T>[];\n }\n\n async insert(values: InferInsertModel<T>): Promise<InferSelectModel<T>> {\n const filled = fillAgentColumns(this.table, values as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.insert(this.table).values(filled) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.insert on \"${this.tableName}\" returned zero rows. Driver may not support .returning() (MySQL?). Use repo.query() with manual fetch for that dialect.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.insert on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch the inserted row.`,\n );\n }\n\n async update(\n id: string | number,\n patch: Partial<InferInsertModel<T>>,\n ): Promise<InferSelectModel<T>> {\n assertValidId(\"update\", id);\n const filled = fillAgentColumns(this.table, patch as Record<string, unknown>);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n const op = this.db.update(this.table).set(filled).where(eq(this.pkColumn, id)) as any;\n if (typeof op.returning === \"function\") {\n const rows = (await op.returning()) as unknown[];\n const row = rows[0];\n if (row === undefined) {\n throw new OrmValidationError(\n `Repository.update on \"${this.tableName}\" id=\"${id}\": no row matched.`,\n );\n }\n return row as InferSelectModel<T>;\n }\n throw new OrmConfigurationError(\n `Repository.update on \"${this.tableName}\": driver does not expose .returning(). v0.1 supports SQLite/Postgres. For MySQL, use repo.query() and manually fetch.`,\n );\n }\n\n async delete(id: string | number): Promise<void> {\n assertValidId(\"delete\", id);\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle generic chain — fluent query builder types are too complex to narrow at call site without importing internal Drizzle types\n await (this.db.delete(this.table) as any).where(eq(this.pkColumn, id));\n }\n\n query() {\n return this.db.select().from(this.table);\n }\n\n /** @internal exposed for tests */\n get _primaryKeyName(): string {\n return this.pkName;\n }\n}\n\n/**\n * Non-DI factory for {@link Repository}. The `Repository` constructor is\n * already DI-free (`new Repository(db, table)`); this factory makes the non-DI\n * path explicit and discoverable, so consumers do NOT need `@theokit/di`,\n * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`\n * requires a bound DataSource. Works with any drizzle `db` (incl. better-sqlite3,\n * whose query builders are awaitable).\n *\n * @public\n */\nexport function createRepository<T extends Table>(db: unknown, table: T): Repository<T> {\n return new Repository(db, table);\n}\n","import type { Table } from \"drizzle-orm\";\n\n/** Any Drizzle table. The alias exists so this package's signatures name the domain concept\n * rather than repeating a dependency's type everywhere a table is accepted. */\nexport type AnyTable = Table;\n\n/**\n * The SQL dialect a data source speaks.\n *\n * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`\n * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level\n * to set, and accepting one there would drop it silently.\n */\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\n\n/**\n * What {@link OrmModule.forRoot} needs to build a data source.\n *\n * `db` is the Drizzle handle you already built — this package never opens a connection of its own,\n * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names\n * this source when an application has more than one; omit it and it is `\"default\"`.\n */\nexport interface OrmRootOptions<\n TSchema extends Record<string, AnyTable> = Record<string, AnyTable>,\n> {\n schema: TSchema;\n dialect: Dialect;\n db: unknown;\n dataSourceName?: string;\n}\n\n/**\n * A configured database handle plus the schema and dialect it belongs to.\n *\n * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle\n * handle — running a query no repository covers, or binding it for `@Transactional`.\n */\nexport interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {\n readonly name: string;\n readonly dialect: Dialect;\n readonly schema: TSchema;\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle db handle has driver-specific shape (BetterSQLite3Database vs PgDatabase vs MySqlDatabase); narrow types come at use-site via Repository<T> generic\n readonly db: any;\n}\n\n/**\n * Container token for the default {@link DataSource}.\n *\n * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own\n * token, so this one resolves the source registered without a `dataSourceName`.\n */\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\n\n/**\n * Who is acting, for the duration of one async chain.\n *\n * Repositories copy these into agent-aware columns on insert and update when the table declares\n * them, so a row records which agent and which run produced it without the call sites passing ids\n * down. Established with {@link withAgentContext}; every field is optional because a partial\n * context is more useful than none.\n */\nexport interface AgentContext {\n agentId?: string;\n runId?: string;\n conversationId?: string;\n}\n","import type { Provider } from \"@theokit/di\";\nimport { OrmConfigurationError } from \"./errors.js\";\nimport { createDataSource } from \"./internal/data-source.js\";\nimport { Repository } from \"./repository.js\";\nimport { getRepositoryToken } from \"./tokens.js\";\nimport {\n type AnyTable,\n type DataSource,\n ORM_DATA_SOURCE_TOKEN,\n type OrmRootOptions,\n} from \"./types.js\";\n\nconst registeredDataSources = new Set<string>();\n\nfunction dataSourceTokenFor(name: string): string {\n return name === \"default\" ? ORM_DATA_SOURCE_TOKEN : `${ORM_DATA_SOURCE_TOKEN}:${name}`;\n}\n\nfunction entityArrayOrThrow(entities: unknown): readonly unknown[] {\n if (!Array.isArray(entities)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature: entities must be an array of Drizzle tables. Got ${typeof entities}`,\n );\n }\n if (entities.length === 0) {\n throw new OrmConfigurationError(\n \"OrmModule.forFeature: entities array is empty. Provide at least one Drizzle table.\",\n );\n }\n return entities;\n}\n\n/**\n * Provider builders that put a data source and its repositories into a container.\n *\n * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The\n * split is what lets a feature module declare the tables it needs without repeating the connection\n * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —\n * otherwise the failure would surface as a missing token at the first query, far from its cause.\n */\nexport const OrmModule = {\n forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[] {\n if (opts === null || typeof opts !== \"object\") {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: options is required. Pass { schema, dialect, db }.\",\n );\n }\n if (opts.db === undefined || opts.db === null) {\n throw new OrmConfigurationError(\n \"OrmModule.forRoot: opts.db is required. Pass the Drizzle db instance (e.g. drizzle(client, { schema })).\",\n );\n }\n if (![\"sqlite\", \"pg\", \"mysql\"].includes(opts.dialect)) {\n throw new OrmConfigurationError(\n `OrmModule.forRoot: opts.dialect must be one of \"sqlite\" | \"pg\" | \"mysql\". Got \"${opts.dialect}\".`,\n );\n }\n const name = opts.dataSourceName ?? \"default\";\n const dataSource = createDataSource(opts);\n const token = dataSourceTokenFor(name);\n\n registeredDataSources.add(name);\n\n return [\n {\n provide: token,\n useValue: dataSource,\n },\n ];\n },\n\n forFeature(entities: readonly unknown[], dataSourceName: string = \"default\"): Provider[] {\n const ents = entityArrayOrThrow(entities);\n\n if (!registeredDataSources.has(dataSourceName)) {\n throw new OrmConfigurationError(\n `OrmModule.forFeature called${\n dataSourceName === \"default\" ? \"\" : ` for dataSource=\"${dataSourceName}\"`\n } before OrmModule.forRoot. Call OrmModule.forRoot(opts) first in your Container providers array.`,\n );\n }\n\n const dsToken = dataSourceTokenFor(dataSourceName);\n\n return ents.map((entity) => ({\n provide: getRepositoryToken(entity, dataSourceName),\n inject: [dsToken],\n useFactory: (ds: DataSource) => new Repository(ds.db, entity as AnyTable),\n }));\n },\n\n /** @internal — testing escape hatch to reset module-level state */\n _resetForTesting(): void {\n registeredDataSources.clear();\n },\n};\n","import { OrmConfigurationError } from \"./errors.js\";\nimport { withTxContext } from \"./internal/tx-context.js\";\nimport type { DataSource } from \"./types.js\";\n\nconst DATA_SOURCE_KEY = Symbol.for(\"Theo:orm:dataSource\");\n\n/**\n * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.\n *\n * `@Transactional` is a method decorator: it runs at class-definition time and has no\n * container to ask, so the DataSource has to be put on the instance before the method is\n * called. Nothing does that for you — not `OrmModule`, not the container.\n *\n * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which\n * runs after construction with every dependency already in place:\n *\n * @example\n * ```ts\n * @Injectable()\n * class TransferService {\n * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}\n *\n * @PostConstruct\n * bindTransactions() {\n * bindDataSourceToInstance(this, this.ds);\n * }\n *\n * @Transactional()\n * async transfer() { ... }\n * }\n * ```\n *\n * Without the container, call it directly on the instance before invoking the method.\n */\nexport function bindDataSourceToInstance(instance: object, ds: DataSource): void {\n (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY] = ds;\n}\n\nfunction readDataSourceFromInstance(instance: object): DataSource | undefined {\n const v = (instance as Record<symbol, unknown>)[DATA_SOURCE_KEY];\n return (v as DataSource | undefined) ?? undefined;\n}\n\n/** Options for {@link Transactional}. */\nexport interface TransactionalOptions {\n /**\n * Isolation level for the transaction, passed straight to the driver.\n *\n * Rejected on `sqlite`, which has no per-transaction isolation level to set — see\n * the note in {@link Transactional}.\n */\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\n\n/**\n * Dialects that accept an isolation level on `db.transaction(cb, config)`.\n *\n * SQLite is deliberately absent. Its transactions take a `behavior` (deferred, immediate,\n * exclusive), not an isolation level, so a level passed there would be dropped on the\n * floor — and a silently ignored isolation level is the kind of thing that looks fine in\n * review and corrupts data under load.\n */\nconst DIALECTS_WITH_ISOLATION_LEVEL: ReadonlySet<DataSource[\"dialect\"]> = new Set([\"pg\", \"mysql\"]);\n\n/**\n * `@Transactional(options?)` — run a method inside a database transaction.\n *\n * The wrapped method executes within `db.transaction(...)`, and the transaction handle is\n * published on the async context, so every `Repository` call made during the method, at\n * any depth of `await`, runs on the transaction. The method's resolved value is returned;\n * anything it throws rolls the transaction back.\n *\n * The instance must carry a DataSource before the method runs — see\n * {@link bindDataSourceToInstance}, which is the only thing that puts one there.\n *\n * The driver must run transactions asynchronously. Drizzle's synchronous SQLite drivers\n * (better-sqlite3, bun:sqlite, sql.js, expo-sqlite) are refused with\n * {@link OrmConfigurationError} before the method body runs: a transaction on one synchronous\n * connection cannot stay open across an `await`, and the method would otherwise run, and\n * write, outside any transaction. libSQL and D1 are asynchronous and supported.\n */\nexport function Transactional(opts: TransactionalOptions = {}): MethodDecorator {\n return function transactionalDecorator(\n _target: object,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const original = descriptor.value;\n if (typeof original !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional on ${String(propertyKey)}: target is not a method.`,\n );\n }\n\n descriptor.value = async function transactionalWrapper(\n this: object,\n ...args: unknown[]\n ): Promise<unknown> {\n const transaction = resolveTransactionFn(this, propertyKey, opts);\n\n const run = (tx: unknown): Promise<unknown> =>\n withTxContext(tx, () => original.apply(this, args));\n\n // Only pass a config when one was asked for: drivers differ on what an empty\n // config object means, and the no-options case must stay byte-identical to before.\n return opts.isolationLevel === undefined\n ? transaction(run)\n : transaction(run, { isolationLevel: opts.isolationLevel });\n };\n\n return descriptor;\n };\n}\n\ntype TransactionFn = (cb: (tx: unknown) => Promise<unknown>, config?: unknown) => Promise<unknown>;\n\n/**\n * Everything that has to be true before a transaction can start, checked in one place so\n * the wrapper above stays readable: an instance carries a DataSource, the dialect can\n * honour the requested isolation level, and the driver exposes `transaction()`.\n */\nfunction resolveTransactionFn(\n instance: object,\n propertyKey: string | symbol,\n opts: TransactionalOptions,\n): TransactionFn {\n const where = `@Transactional ${String(propertyKey)}`;\n\n const ds = readDataSourceFromInstance(instance);\n if (!ds) {\n throw new OrmConfigurationError(\n `${where}: no DataSource bound to instance. ` +\n `Call bindDataSourceToInstance(this, dataSource) before invoking the method — ` +\n `from a @PostConstruct hook when the class is container-managed, or directly ` +\n `after construction when it is not.`,\n );\n }\n\n if (opts.isolationLevel !== undefined && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {\n throw new OrmConfigurationError(\n `${where}: isolationLevel \"${opts.isolationLevel}\" is not supported on ${ds.dialect}. ` +\n `Remove the option, or use a dialect that has isolation levels (pg, mysql).`,\n );\n }\n\n const db = ds.db as { transaction?: TransactionFn; resultKind?: unknown };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `${where}: DataSource.db does not expose .transaction(). ` +\n `Ensure you passed a Drizzle db instance.`,\n );\n }\n\n // Checked before the method runs, because afterwards is too late: a synchronous driver throws\n // \"Transaction function cannot return a promise\" only once the callback has returned, by which\n // point the method has started and keeps running, and writing, with no transaction around it.\n if (db.resultKind === \"sync\") {\n throw new OrmConfigurationError(\n `${where}: the ${ds.dialect} driver behind DataSource \"${ds.name}\" runs transactions ` +\n `synchronously (better-sqlite3, bun:sqlite, sql.js, expo-sqlite), and a synchronous ` +\n `transaction cannot stay open across an await. Use an asynchronous driver, or call ` +\n `db.transaction((tx) => { ... }) directly with synchronous statements inside.`,\n );\n }\n\n return db.transaction.bind(db);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/schema-export.ts"],"names":["OrmError","Error","name","OrmSchemaExportError","tableNameOf","table","sym","Symbol","for","inner","_","lower","s","toLowerCase","isInteger","dataType","columnType","test","matchEnum","meta","Array","isArray","enumValues","length","type","enum","matchUuid","_m","_dt","ct","format","matchNumeric","out","scale","multipleOf","matchBigint","matchDate","dt","matchBlob","contentEncoding","matchBoolean","matchJson","matchInteger","matchFloat","matchString","maxLength","COLUMN_MATCHERS","mapColumnToJsonSchema","colName","col","tableName","matcher","result","exportSchema","columns","getTableColumns","properties","required","Object","entries","prop","hasDefault","default","undefined","notNull","push","$schema","title","additionalProperties","exportSchemas","schema"],"mappings":";;;;;;;;AAOO,IAAMA,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC,CAAA;AAgCO,IAAMC,oBAAAA,GAAN,cAAmCH,QAAAA,CAAAA;EAzC1C;;;EA0CoBE,IAAAA,GAAO,sBAAA;AAC3B,CAAA;;;ACYA,SAASE,YAAYC,KAAAA,EAAc;AACjC,EAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQ,OAAOA,KAAAA,KAAU,UAAU,OAAO,WAAA;AACxD,EAAA,MAAMC,GAAAA,GAAOD,KAAAA,iBAAkCE,MAAAA,CAAOC,G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ACT;AAPgBqC,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA","file":"schema-export.cjs","sourcesContent":["/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle\n * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import type { Column, Table } from \"drizzle-orm\";\nimport { getTableColumns } from \"drizzle-orm\";\nimport { OrmSchemaExportError } from \"./errors.js\";\n\n/**\n * A JSON Schema draft-07 object describing one table.\n *\n * This is the contract a non-TypeScript consumer reads. `additionalProperties` is fixed to `false`\n * so a generator in another language produces a closed model rather than one that silently accepts\n * columns this table does not have.\n */\nexport type JsonSchema7 = {\n $schema?: string;\n title?: string;\n type: \"object\";\n properties: Record<string, JsonSchema7Property>;\n required: string[];\n additionalProperties: false;\n};\n\n/**\n * One column, as JSON Schema draft-07 sees it.\n *\n * `x-check` is the one field outside the standard: it carries the SQL check constraint verbatim,\n * because draft-07 has no vocabulary for it and dropping it would let a generated model accept\n * values the database will reject.\n */\nexport type JsonSchema7Property = {\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\" | \"object\" | \"array\" | \"null\";\n format?: string;\n maxLength?: number;\n multipleOf?: number;\n default?: unknown;\n enum?: ReadonlyArray<string | number>;\n contentEncoding?: string;\n \"x-check\"?: string;\n description?: string;\n};\n\ninterface ColumnInternal {\n dataType?: string;\n columnType?: string;\n notNull?: boolean;\n hasDefault?: boolean;\n default?: unknown;\n defaultFn?: () => unknown;\n enumValues?: ReadonlyArray<string>;\n length?: number;\n precision?: number;\n scale?: number;\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n}\n\nfunction tableNameOf(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction lower(s: string | undefined): string {\n return (s ?? \"\").toLowerCase();\n}\n\nfunction isInteger(dataType: string, columnType: string): boolean {\n if (dataType === \"number\" && /int/.test(columnType)) return true;\n if (dataType === \"integer\") return true;\n return false;\n}\n\ntype ColumnMatcher = (meta: ColumnInternal, dt: string, ct: string) => JsonSchema7Property | null;\n\nconst matchEnum: ColumnMatcher = (meta) =>\n Array.isArray(meta.enumValues) && meta.enumValues.length > 0\n ? { type: \"string\", enum: [...meta.enumValues] }\n : null;\n\nconst matchUuid: ColumnMatcher = (_m, _dt, ct) =>\n /uuid/.test(ct) ? { type: \"string\", format: \"uuid\" } : null;\n\nconst matchNumeric: ColumnMatcher = (meta, _dt, ct) => {\n if (!/numeric|decimal/.test(ct)) return null;\n const out: JsonSchema7Property = { type: \"string\", format: \"decimal\" };\n if (typeof meta.scale === \"number\" && meta.scale >= 0) {\n out.multipleOf = 10 ** -meta.scale;\n }\n return out;\n};\n\nconst matchBigint: ColumnMatcher = (_m, _dt, ct) =>\n /bigint/.test(ct) ? { type: \"string\", format: \"int64\" } : null;\n\nconst matchDate: ColumnMatcher = (_m, dt, ct) =>\n dt === \"date\" || /timestamp|date/.test(ct) ? { type: \"string\", format: \"date-time\" } : null;\n\nconst matchBlob: ColumnMatcher = (_m, _dt, ct) =>\n /blob|bytea|binary/.test(ct) ? { type: \"string\", contentEncoding: \"base64\" } : null;\n\nconst matchBoolean: ColumnMatcher = (_m, dt, ct) =>\n dt === \"boolean\" || /boolean|bool/.test(ct) ? { type: \"boolean\" } : null;\n\nconst matchJson: ColumnMatcher = (_m, dt, ct) =>\n dt === \"json\" || /json/.test(ct) ? { type: \"object\" } : null;\n\nconst matchInteger: ColumnMatcher = (_m, dt, ct) =>\n isInteger(dt, ct) ? { type: \"integer\" } : null;\n\nconst matchFloat: ColumnMatcher = (_m, dt, ct) =>\n dt === \"number\" || /real|double|float/.test(ct) ? { type: \"number\" } : null;\n\nconst matchString: ColumnMatcher = (meta, dt, ct) => {\n if (!(dt === \"string\" || /text|varchar|char/.test(ct))) return null;\n const out: JsonSchema7Property = { type: \"string\" };\n if (typeof meta.length === \"number\" && meta.length > 0) out.maxLength = meta.length;\n return out;\n};\n\nconst COLUMN_MATCHERS: readonly ColumnMatcher[] = [\n matchEnum,\n matchUuid,\n matchNumeric,\n matchBigint,\n matchDate,\n matchBlob,\n matchBoolean,\n matchJson,\n matchInteger,\n matchFloat,\n matchString,\n];\n\nfunction mapColumnToJsonSchema(\n colName: string,\n col: Column,\n tableName: string,\n): JsonSchema7Property {\n const meta = col as unknown as ColumnInternal;\n const dt = lower(meta.dataType);\n const ct = lower(meta.columnType);\n\n for (const matcher of COLUMN_MATCHERS) {\n const result = matcher(meta, dt, ct);\n if (result !== null) return result;\n }\n\n throw new OrmSchemaExportError(\n `Cannot export column \"${colName}\" of table \"${tableName}\": unknown type (dataType=\"${meta.dataType}\", columnType=\"${meta.columnType}\"). Add to mapColumnToJsonSchema or use the \"_excludeFromExport: true\" annotation.`,\n );\n}\n\n/**\n * Emit the JSON Schema draft-07 description of one Drizzle table.\n *\n * A column is `required` when it is `NOT NULL` and has no default — the two together are what\n * decide whether a caller must supply a value, and treating `NOT NULL` alone as required would\n * demand values the database would have filled in.\n *\n * @throws {OrmSchemaExportError} when a column's type has no mapping. Emitting a partial schema\n * would be worse than failing: a consumer in another language would generate a model missing a\n * field and discover it at the first insert.\n */\nexport function exportSchema(table: Table): JsonSchema7 {\n const tableName = tableNameOf(table);\n const columns = getTableColumns(table) as Record<string, Column>;\n\n const properties: Record<string, JsonSchema7Property> = {};\n const required: string[] = [];\n\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as ColumnInternal;\n const prop = mapColumnToJsonSchema(colName, col, tableName);\n\n if (meta.hasDefault === true) {\n if (meta.default !== undefined) {\n prop.default = meta.default;\n }\n }\n\n if (meta.notNull === true && meta.hasDefault !== true) {\n required.push(colName);\n }\n\n properties[colName] = prop;\n }\n\n return {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n title: tableName,\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n };\n}\n\n/**\n * Emit one schema per table, keyed by the table's name in the database rather than by the key it\n * has in the Drizzle schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`, and a consumer generating models needs the name the\n * database answers to.\n *\n * @throws {OrmSchemaExportError} from the first table that has an unmappable column.\n */\nexport function exportSchemas(schema: Record<string, Table>): Record<string, JsonSchema7> {\n const out: Record<string, JsonSchema7> = {};\n for (const [, table] of Object.entries(schema)) {\n const name = tableNameOf(table);\n out[name] = exportSchema(table);\n }\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/schema-export.ts"],"names":["OrmError","Error","name","OrmSchemaExportError","tableNameOf","table","sym","Symbol","for","inner","_","lower","s","toLowerCase","isInteger","dataType","columnType","test","matchEnum","meta","Array","isArray","enumValues","length","type","enum","matchUuid","_m","_dt","ct","format","matchNumeric","out","scale","multipleOf","matchBigint","matchDate","dt","matchBlob","contentEncoding","matchBoolean","matchJson","matchInteger","matchFloat","matchString","maxLength","COLUMN_MATCHERS","mapColumnToJsonSchema","colName","col","tableName","matcher","result","exportSchema","columns","getTableColumns","properties","required","Object","entries","prop","hasDefault","default","undefined","notNull","push","$schema","title","additionalProperties","exportSchemas","schema"],"mappings":";;;;;;;;AAOO,IAAMA,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC,CAAA;AAiCO,IAAMC,oBAAAA,GAAN,cAAmCH,QAAAA,CAAAA;EA1C1C;;;EA2CoBE,IAAAA,GAAO,sBAAA;AAC3B,CAAA;;;ACWA,SAASE,YAAYC,KAAAA,EAAc;AACjC,EAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQ,OAAOA,KAAAA,KAAU,UAAU,OAAO,WAAA;AACxD,EAAA,MAAMC,GAAAA,GAAOD,KAAAA,iBAAkCE,MAAAA,CAAOC,GAAAA,CAAI,cAAA,CAAA,CAAA;AAC1D,EAAA,IAAI,OAAOF,GAAAA,KAAQ,QAAA,EAAU,OAAOA,GAAAA;AACpC,EAAA,MAAMG,QAASJ,KAAAA,CAAoCK,CAAAA;AACnD,EAAA,OAAOD,OAAOP,IAAAA,IAAQ,WAAA;AACxB;AANSE,MAAAA,CAAAA,WAAAA,EAAAA,aAAAA,CAAAA;AAQT,SAASO,MAAMC,CAAAA,EAAqB;AAClC,EAAA,OAAA,CAAQA,CAAAA,IAAK,IAAIC,WAAAA,EAAW;AAC9B;AAFSF,MAAAA,CAAAA,KAAAA,EAAAA,OAAAA,CAAAA;AAIT,SAASG,SAAAA,CAAUC,UAAkBC,UAAAA,EAAkB;AACrD,EAAA,IAAID,aAAa,QAAA,IAAY,KAAA,CAAME,IAAAA,CAAKD,UAAAA,GAAa,OAAO,IAAA;AAC5D,EAAA,IAAID,QAAAA,KAAa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ChB,IAAA;AAEAQ,IAAAA,UAAAA,CAAWR,OAAAA,CAAAA,GAAWY,IAAAA;AACxB,EAAA;AAEA,EAAA,OAAO;IACLM,OAAAA,EAAS,yCAAA;IACTC,KAAAA,EAAOjB,SAAAA;IACP1B,IAAAA,EAAM,QAAA;AACNgC,IAAAA,UAAAA;AACAC,IAAAA,QAAAA;IACAW,oBAAAA,EAAsB;AACxB,GAAA;AACF;AAhCgBf,MAAAA,CAAAA,YAAAA,EAAAA,cAAAA,CAAAA;AA0CT,SAASgB,cAAcC,MAAAA,EAA6B;AACzD,EAAA,MAAMtC,MAAmC,EAAC;AAC1C,EAAA,KAAA,MAAW,GAAG3B,KAAAA,KAAUqD,MAAAA,CAAOC,OAAAA,CAAQW,MAAAA,CAAAA,EAAS;AAC9C,IAAA,MAAMpE,IAAAA,GAAOE,YAAYC,KAAAA,CAAAA;AACzB2B,IAAAA,GAAAA,CAAI9B,IAAAA,CAAAA,GAAQmD,YAAAA,CAAahD,KAAAA,CAAAA;AAC3B,EAAA;AACA,EAAA,OAAO2B,GAAAA;AACT;AAPgBqC,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA","file":"schema-export.cjs","sourcesContent":["/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, when the handle\n * passed as `db` does not expose `transaction()`, or when that handle is a synchronous SQLite\n * driver whose transactions cannot span an `await`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import type { Column, Table } from \"drizzle-orm\";\nimport { getTableColumns } from \"drizzle-orm\";\nimport { OrmSchemaExportError } from \"./errors.js\";\n\n/**\n * A JSON Schema draft-07 object describing one table.\n *\n * This is the contract a non-TypeScript consumer reads. `additionalProperties` is fixed to `false`\n * so a generator in another language produces a closed model rather than one that silently accepts\n * columns this table does not have.\n */\nexport type JsonSchema7 = {\n $schema?: string;\n title?: string;\n type: \"object\";\n properties: Record<string, JsonSchema7Property>;\n required: string[];\n additionalProperties: false;\n};\n\n/**\n * One column, as JSON Schema draft-07 sees it.\n *\n * `x-check` is the one field outside the standard: it carries the SQL check constraint verbatim,\n * because draft-07 has no vocabulary for it and dropping it would let a generated model accept\n * values the database will reject.\n */\nexport type JsonSchema7Property = {\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\" | \"object\" | \"array\" | \"null\";\n format?: string;\n maxLength?: number;\n multipleOf?: number;\n default?: unknown;\n enum?: ReadonlyArray<string | number>;\n contentEncoding?: string;\n \"x-check\"?: string;\n description?: string;\n};\n\ninterface ColumnInternal {\n dataType?: string;\n columnType?: string;\n notNull?: boolean;\n hasDefault?: boolean;\n default?: unknown;\n defaultFn?: () => unknown;\n enumValues?: ReadonlyArray<string>;\n length?: number;\n precision?: number;\n scale?: number;\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n}\n\nfunction tableNameOf(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction lower(s: string | undefined): string {\n return (s ?? \"\").toLowerCase();\n}\n\nfunction isInteger(dataType: string, columnType: string): boolean {\n if (dataType === \"number\" && /int/.test(columnType)) return true;\n if (dataType === \"integer\") return true;\n return false;\n}\n\ntype ColumnMatcher = (meta: ColumnInternal, dt: string, ct: string) => JsonSchema7Property | null;\n\nconst matchEnum: ColumnMatcher = (meta) =>\n Array.isArray(meta.enumValues) && meta.enumValues.length > 0\n ? { type: \"string\", enum: [...meta.enumValues] }\n : null;\n\nconst matchUuid: ColumnMatcher = (_m, _dt, ct) =>\n /uuid/.test(ct) ? { type: \"string\", format: \"uuid\" } : null;\n\nconst matchNumeric: ColumnMatcher = (meta, _dt, ct) => {\n if (!/numeric|decimal/.test(ct)) return null;\n const out: JsonSchema7Property = { type: \"string\", format: \"decimal\" };\n if (typeof meta.scale === \"number\" && meta.scale >= 0) {\n out.multipleOf = 10 ** -meta.scale;\n }\n return out;\n};\n\nconst matchBigint: ColumnMatcher = (_m, _dt, ct) =>\n /bigint/.test(ct) ? { type: \"string\", format: \"int64\" } : null;\n\nconst matchDate: ColumnMatcher = (_m, dt, ct) =>\n dt === \"date\" || /timestamp|date/.test(ct) ? { type: \"string\", format: \"date-time\" } : null;\n\nconst matchBlob: ColumnMatcher = (_m, _dt, ct) =>\n /blob|bytea|binary/.test(ct) ? { type: \"string\", contentEncoding: \"base64\" } : null;\n\nconst matchBoolean: ColumnMatcher = (_m, dt, ct) =>\n dt === \"boolean\" || /boolean|bool/.test(ct) ? { type: \"boolean\" } : null;\n\nconst matchJson: ColumnMatcher = (_m, dt, ct) =>\n dt === \"json\" || /json/.test(ct) ? { type: \"object\" } : null;\n\nconst matchInteger: ColumnMatcher = (_m, dt, ct) =>\n isInteger(dt, ct) ? { type: \"integer\" } : null;\n\nconst matchFloat: ColumnMatcher = (_m, dt, ct) =>\n dt === \"number\" || /real|double|float/.test(ct) ? { type: \"number\" } : null;\n\nconst matchString: ColumnMatcher = (meta, dt, ct) => {\n if (!(dt === \"string\" || /text|varchar|char/.test(ct))) return null;\n const out: JsonSchema7Property = { type: \"string\" };\n if (typeof meta.length === \"number\" && meta.length > 0) out.maxLength = meta.length;\n return out;\n};\n\nconst COLUMN_MATCHERS: readonly ColumnMatcher[] = [\n matchEnum,\n matchUuid,\n matchNumeric,\n matchBigint,\n matchDate,\n matchBlob,\n matchBoolean,\n matchJson,\n matchInteger,\n matchFloat,\n matchString,\n];\n\nfunction mapColumnToJsonSchema(\n colName: string,\n col: Column,\n tableName: string,\n): JsonSchema7Property {\n const meta = col as unknown as ColumnInternal;\n const dt = lower(meta.dataType);\n const ct = lower(meta.columnType);\n\n for (const matcher of COLUMN_MATCHERS) {\n const result = matcher(meta, dt, ct);\n if (result !== null) return result;\n }\n\n throw new OrmSchemaExportError(\n `Cannot export column \"${colName}\" of table \"${tableName}\": unknown type (dataType=\"${meta.dataType}\", columnType=\"${meta.columnType}\"). Add to mapColumnToJsonSchema or use the \"_excludeFromExport: true\" annotation.`,\n );\n}\n\n/**\n * Emit the JSON Schema draft-07 description of one Drizzle table.\n *\n * A column is `required` when it is `NOT NULL` and has no default — the two together are what\n * decide whether a caller must supply a value, and treating `NOT NULL` alone as required would\n * demand values the database would have filled in.\n *\n * @throws {OrmSchemaExportError} when a column's type has no mapping. Emitting a partial schema\n * would be worse than failing: a consumer in another language would generate a model missing a\n * field and discover it at the first insert.\n */\nexport function exportSchema(table: Table): JsonSchema7 {\n const tableName = tableNameOf(table);\n const columns = getTableColumns(table) as Record<string, Column>;\n\n const properties: Record<string, JsonSchema7Property> = {};\n const required: string[] = [];\n\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as ColumnInternal;\n const prop = mapColumnToJsonSchema(colName, col, tableName);\n\n if (meta.hasDefault === true) {\n if (meta.default !== undefined) {\n prop.default = meta.default;\n }\n }\n\n if (meta.notNull === true && meta.hasDefault !== true) {\n required.push(colName);\n }\n\n properties[colName] = prop;\n }\n\n return {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n title: tableName,\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n };\n}\n\n/**\n * Emit one schema per table, keyed by the table's name in the database rather than by the key it\n * has in the Drizzle schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`, and a consumer generating models needs the name the\n * database answers to.\n *\n * @throws {OrmSchemaExportError} from the first table that has an unmappable column.\n */\nexport function exportSchemas(schema: Record<string, Table>): Record<string, JsonSchema7> {\n const out: Record<string, JsonSchema7> = {};\n for (const [, table] of Object.entries(schema)) {\n const name = tableNameOf(table);\n out[name] = exportSchema(table);\n }\n return out;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/schema-export.ts"],"names":["OrmError","Error","name","OrmSchemaExportError","tableNameOf","table","sym","Symbol","for","inner","_","lower","s","toLowerCase","isInteger","dataType","columnType","test","matchEnum","meta","Array","isArray","enumValues","length","type","enum","matchUuid","_m","_dt","ct","format","matchNumeric","out","scale","multipleOf","matchBigint","matchDate","dt","matchBlob","contentEncoding","matchBoolean","matchJson","matchInteger","matchFloat","matchString","maxLength","COLUMN_MATCHERS","mapColumnToJsonSchema","colName","col","tableName","matcher","result","exportSchema","columns","getTableColumns","properties","required","Object","entries","prop","hasDefault","default","undefined","notNull","push","$schema","title","additionalProperties","exportSchemas","schema"],"mappings":";;;;;;AAOO,IAAMA,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC,CAAA;AAgCO,IAAMC,oBAAAA,GAAN,cAAmCH,QAAAA,CAAAA;EAzC1C;;;EA0CoBE,IAAAA,GAAO,sBAAA;AAC3B,CAAA;;;ACYA,SAASE,YAAYC,KAAAA,EAAc;AACj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,YAAYC,KAAAA,CAAAA;AACzB2B,IAAAA,GAAAA,CAAI9B,IAAAA,CAAAA,GAAQmD,YAAAA,CAAahD,KAAAA,CAAAA;AAC3B,EAAA;AACA,EAAA,OAAO2B,GAAAA;AACT;AAPgBqC,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA","file":"schema-export.js","sourcesContent":["/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, or when the handle\n * passed as `db` does not expose `transaction()`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import type { Column, Table } from \"drizzle-orm\";\nimport { getTableColumns } from \"drizzle-orm\";\nimport { OrmSchemaExportError } from \"./errors.js\";\n\n/**\n * A JSON Schema draft-07 object describing one table.\n *\n * This is the contract a non-TypeScript consumer reads. `additionalProperties` is fixed to `false`\n * so a generator in another language produces a closed model rather than one that silently accepts\n * columns this table does not have.\n */\nexport type JsonSchema7 = {\n $schema?: string;\n title?: string;\n type: \"object\";\n properties: Record<string, JsonSchema7Property>;\n required: string[];\n additionalProperties: false;\n};\n\n/**\n * One column, as JSON Schema draft-07 sees it.\n *\n * `x-check` is the one field outside the standard: it carries the SQL check constraint verbatim,\n * because draft-07 has no vocabulary for it and dropping it would let a generated model accept\n * values the database will reject.\n */\nexport type JsonSchema7Property = {\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\" | \"object\" | \"array\" | \"null\";\n format?: string;\n maxLength?: number;\n multipleOf?: number;\n default?: unknown;\n enum?: ReadonlyArray<string | number>;\n contentEncoding?: string;\n \"x-check\"?: string;\n description?: string;\n};\n\ninterface ColumnInternal {\n dataType?: string;\n columnType?: string;\n notNull?: boolean;\n hasDefault?: boolean;\n default?: unknown;\n defaultFn?: () => unknown;\n enumValues?: ReadonlyArray<string>;\n length?: number;\n precision?: number;\n scale?: number;\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n}\n\nfunction tableNameOf(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction lower(s: string | undefined): string {\n return (s ?? \"\").toLowerCase();\n}\n\nfunction isInteger(dataType: string, columnType: string): boolean {\n if (dataType === \"number\" && /int/.test(columnType)) return true;\n if (dataType === \"integer\") return true;\n return false;\n}\n\ntype ColumnMatcher = (meta: ColumnInternal, dt: string, ct: string) => JsonSchema7Property | null;\n\nconst matchEnum: ColumnMatcher = (meta) =>\n Array.isArray(meta.enumValues) && meta.enumValues.length > 0\n ? { type: \"string\", enum: [...meta.enumValues] }\n : null;\n\nconst matchUuid: ColumnMatcher = (_m, _dt, ct) =>\n /uuid/.test(ct) ? { type: \"string\", format: \"uuid\" } : null;\n\nconst matchNumeric: ColumnMatcher = (meta, _dt, ct) => {\n if (!/numeric|decimal/.test(ct)) return null;\n const out: JsonSchema7Property = { type: \"string\", format: \"decimal\" };\n if (typeof meta.scale === \"number\" && meta.scale >= 0) {\n out.multipleOf = 10 ** -meta.scale;\n }\n return out;\n};\n\nconst matchBigint: ColumnMatcher = (_m, _dt, ct) =>\n /bigint/.test(ct) ? { type: \"string\", format: \"int64\" } : null;\n\nconst matchDate: ColumnMatcher = (_m, dt, ct) =>\n dt === \"date\" || /timestamp|date/.test(ct) ? { type: \"string\", format: \"date-time\" } : null;\n\nconst matchBlob: ColumnMatcher = (_m, _dt, ct) =>\n /blob|bytea|binary/.test(ct) ? { type: \"string\", contentEncoding: \"base64\" } : null;\n\nconst matchBoolean: ColumnMatcher = (_m, dt, ct) =>\n dt === \"boolean\" || /boolean|bool/.test(ct) ? { type: \"boolean\" } : null;\n\nconst matchJson: ColumnMatcher = (_m, dt, ct) =>\n dt === \"json\" || /json/.test(ct) ? { type: \"object\" } : null;\n\nconst matchInteger: ColumnMatcher = (_m, dt, ct) =>\n isInteger(dt, ct) ? { type: \"integer\" } : null;\n\nconst matchFloat: ColumnMatcher = (_m, dt, ct) =>\n dt === \"number\" || /real|double|float/.test(ct) ? { type: \"number\" } : null;\n\nconst matchString: ColumnMatcher = (meta, dt, ct) => {\n if (!(dt === \"string\" || /text|varchar|char/.test(ct))) return null;\n const out: JsonSchema7Property = { type: \"string\" };\n if (typeof meta.length === \"number\" && meta.length > 0) out.maxLength = meta.length;\n return out;\n};\n\nconst COLUMN_MATCHERS: readonly ColumnMatcher[] = [\n matchEnum,\n matchUuid,\n matchNumeric,\n matchBigint,\n matchDate,\n matchBlob,\n matchBoolean,\n matchJson,\n matchInteger,\n matchFloat,\n matchString,\n];\n\nfunction mapColumnToJsonSchema(\n colName: string,\n col: Column,\n tableName: string,\n): JsonSchema7Property {\n const meta = col as unknown as ColumnInternal;\n const dt = lower(meta.dataType);\n const ct = lower(meta.columnType);\n\n for (const matcher of COLUMN_MATCHERS) {\n const result = matcher(meta, dt, ct);\n if (result !== null) return result;\n }\n\n throw new OrmSchemaExportError(\n `Cannot export column \"${colName}\" of table \"${tableName}\": unknown type (dataType=\"${meta.dataType}\", columnType=\"${meta.columnType}\"). Add to mapColumnToJsonSchema or use the \"_excludeFromExport: true\" annotation.`,\n );\n}\n\n/**\n * Emit the JSON Schema draft-07 description of one Drizzle table.\n *\n * A column is `required` when it is `NOT NULL` and has no default — the two together are what\n * decide whether a caller must supply a value, and treating `NOT NULL` alone as required would\n * demand values the database would have filled in.\n *\n * @throws {OrmSchemaExportError} when a column's type has no mapping. Emitting a partial schema\n * would be worse than failing: a consumer in another language would generate a model missing a\n * field and discover it at the first insert.\n */\nexport function exportSchema(table: Table): JsonSchema7 {\n const tableName = tableNameOf(table);\n const columns = getTableColumns(table) as Record<string, Column>;\n\n const properties: Record<string, JsonSchema7Property> = {};\n const required: string[] = [];\n\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as ColumnInternal;\n const prop = mapColumnToJsonSchema(colName, col, tableName);\n\n if (meta.hasDefault === true) {\n if (meta.default !== undefined) {\n prop.default = meta.default;\n }\n }\n\n if (meta.notNull === true && meta.hasDefault !== true) {\n required.push(colName);\n }\n\n properties[colName] = prop;\n }\n\n return {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n title: tableName,\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n };\n}\n\n/**\n * Emit one schema per table, keyed by the table's name in the database rather than by the key it\n * has in the Drizzle schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`, and a consumer generating models needs the name the\n * database answers to.\n *\n * @throws {OrmSchemaExportError} from the first table that has an unmappable column.\n */\nexport function exportSchemas(schema: Record<string, Table>): Record<string, JsonSchema7> {\n const out: Record<string, JsonSchema7> = {};\n for (const [, table] of Object.entries(schema)) {\n const name = tableNameOf(table);\n out[name] = exportSchema(table);\n }\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/schema-export.ts"],"names":["OrmError","Error","name","OrmSchemaExportError","tableNameOf","table","sym","Symbol","for","inner","_","lower","s","toLowerCase","isInteger","dataType","columnType","test","matchEnum","meta","Array","isArray","enumValues","length","type","enum","matchUuid","_m","_dt","ct","format","matchNumeric","out","scale","multipleOf","matchBigint","matchDate","dt","matchBlob","contentEncoding","matchBoolean","matchJson","matchInteger","matchFloat","matchString","maxLength","COLUMN_MATCHERS","mapColumnToJsonSchema","colName","col","tableName","matcher","result","exportSchema","columns","getTableColumns","properties","required","Object","entries","prop","hasDefault","default","undefined","notNull","push","$schema","title","additionalProperties","exportSchemas","schema"],"mappings":";;;;;;AAOO,IAAMA,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAP9B;;;EAQoBC,IAAAA,GAAe,UAAA;AACnC,CAAA;AAiCO,IAAMC,oBAAAA,GAAN,cAAmCH,QAAAA,CAAAA;EA1C1C;;;EA2CoBE,IAAAA,GAAO,sBAAA;AAC3B,CAAA;;;ACWA,SAASE,YAAYC,KAAAA,EAAc;AACjC,EAAA,IAAIA,KAAAA,KAAU,IAAA,IAAQ,OAAOA,KAAAA,KAAU,UAAU,OAAO,WAAA;AACxD,EAAA,MAAMC,GAAAA,GAAOD,KAAAA,iBAAkCE,MAAAA,CAAOC,GAAAA,CAAI,cAAA,CAAA,CAAA;AAC1D,EAAA,IAAI,OAAOF,GAAAA,KAAQ,QAAA,EAAU,OAAOA,GAAAA;AACpC,EAAA,MAAMG,QAASJ,KAAAA,CAAoCK,CAAAA;AACnD,EAAA,OAAOD,OAAOP,IAAAA,IAAQ,WAAA;AACxB;AANSE,MAAAA,CAAAA,WAAAA,EAAAA,aAAAA,CAAAA;AAQT,SAASO,MAAMC,CAAAA,EAAqB;AAClC,EAAA,OAAA,CAAQA,CAAAA,IAAK,IAAIC,WAAAA,EAAW;AAC9B;AAFSF,MAAAA,CAAAA,KAAAA,EAAAA,OAAAA,CAAAA;AAIT,SAASG,SAAAA,CAAUC,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IAAI3C,IAAAA,CAAK6C,OAAAA,KAAY,IAAA,IAAQ7C,IAAAA,CAAK0C,eAAe,IAAA,EAAM;AACrDJ,MAAAA,QAAAA,CAASQ,KAAKjB,OAAAA,CAAAA;AAChB,IAAA;AAEAQ,IAAAA,UAAAA,CAAWR,OAAAA,CAAAA,GAAWY,IAAAA;AACxB,EAAA;AAEA,EAAA,OAAO;IACLM,OAAAA,EAAS,yCAAA;IACTC,KAAAA,EAAOjB,SAAAA;IACP1B,IAAAA,EAAM,QAAA;AACNgC,IAAAA,UAAAA;AACAC,IAAAA,QAAAA;IACAW,oBAAAA,EAAsB;AACxB,GAAA;AACF;AAhCgBf,MAAAA,CAAAA,YAAAA,EAAAA,cAAAA,CAAAA;AA0CT,SAASgB,cAAcC,MAAAA,EAA6B;AACzD,EAAA,MAAMtC,MAAmC,EAAC;AAC1C,EAAA,KAAA,MAAW,GAAG3B,KAAAA,KAAUqD,MAAAA,CAAOC,OAAAA,CAAQW,MAAAA,CAAAA,EAAS;AAC9C,IAAA,MAAMpE,IAAAA,GAAOE,YAAYC,KAAAA,CAAAA;AACzB2B,IAAAA,GAAAA,CAAI9B,IAAAA,CAAAA,GAAQmD,YAAAA,CAAahD,KAAAA,CAAAA;AAC3B,EAAA;AACA,EAAA,OAAO2B,GAAAA;AACT;AAPgBqC,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA","file":"schema-export.js","sourcesContent":["/**\n * Base class for every error this package raises.\n *\n * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a\n * subclass when the response differs: a configuration fault needs a deploy, a validation fault\n * needs a different call.\n */\nexport class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\n/**\n * The wiring is wrong, and no input will make the call succeed.\n *\n * Raised when an entity has no primary key, when `forFeature` runs before `forRoot` for its data\n * source, when `@Transactional` finds no DataSource bound to the instance, when the handle\n * passed as `db` does not expose `transaction()`, or when that handle is a synchronous SQLite\n * driver whose transactions cannot span an `await`. Every case is a mistake in setup rather than in\n * the data, so it fails at the earliest point that can see it rather than at the first query.\n */\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\n/**\n * A caller-supplied value was rejected at the boundary.\n *\n * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty\n * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched\n * nothing usable is indistinguishable from one that matched everything until the rows are gone.\n */\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\n\n/**\n * A table could not be expressed as JSON Schema.\n *\n * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than\n * skipping the column: a consumer generating a model in another language would get one missing a\n * field and find out at the first insert.\n */\nexport class OrmSchemaExportError extends OrmError {\n override readonly name = \"OrmSchemaExportError\";\n}\n","import type { Column, Table } from \"drizzle-orm\";\nimport { getTableColumns } from \"drizzle-orm\";\nimport { OrmSchemaExportError } from \"./errors.js\";\n\n/**\n * A JSON Schema draft-07 object describing one table.\n *\n * This is the contract a non-TypeScript consumer reads. `additionalProperties` is fixed to `false`\n * so a generator in another language produces a closed model rather than one that silently accepts\n * columns this table does not have.\n */\nexport type JsonSchema7 = {\n $schema?: string;\n title?: string;\n type: \"object\";\n properties: Record<string, JsonSchema7Property>;\n required: string[];\n additionalProperties: false;\n};\n\n/**\n * One column, as JSON Schema draft-07 sees it.\n *\n * `x-check` is the one field outside the standard: it carries the SQL check constraint verbatim,\n * because draft-07 has no vocabulary for it and dropping it would let a generated model accept\n * values the database will reject.\n */\nexport type JsonSchema7Property = {\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\" | \"object\" | \"array\" | \"null\";\n format?: string;\n maxLength?: number;\n multipleOf?: number;\n default?: unknown;\n enum?: ReadonlyArray<string | number>;\n contentEncoding?: string;\n \"x-check\"?: string;\n description?: string;\n};\n\ninterface ColumnInternal {\n dataType?: string;\n columnType?: string;\n notNull?: boolean;\n hasDefault?: boolean;\n default?: unknown;\n defaultFn?: () => unknown;\n enumValues?: ReadonlyArray<string>;\n length?: number;\n precision?: number;\n scale?: number;\n primary?: boolean;\n isPrimaryKey?: boolean;\n primaryKey?: boolean;\n}\n\nfunction tableNameOf(table: unknown): string {\n if (table === null || typeof table !== \"object\") return \"<unknown>\";\n const sym = (table as Record<symbol, unknown>)[Symbol.for(\"drizzle:Name\")];\n if (typeof sym === \"string\") return sym;\n const inner = (table as { _?: { name?: string } })._;\n return inner?.name ?? \"<unknown>\";\n}\n\nfunction lower(s: string | undefined): string {\n return (s ?? \"\").toLowerCase();\n}\n\nfunction isInteger(dataType: string, columnType: string): boolean {\n if (dataType === \"number\" && /int/.test(columnType)) return true;\n if (dataType === \"integer\") return true;\n return false;\n}\n\ntype ColumnMatcher = (meta: ColumnInternal, dt: string, ct: string) => JsonSchema7Property | null;\n\nconst matchEnum: ColumnMatcher = (meta) =>\n Array.isArray(meta.enumValues) && meta.enumValues.length > 0\n ? { type: \"string\", enum: [...meta.enumValues] }\n : null;\n\nconst matchUuid: ColumnMatcher = (_m, _dt, ct) =>\n /uuid/.test(ct) ? { type: \"string\", format: \"uuid\" } : null;\n\nconst matchNumeric: ColumnMatcher = (meta, _dt, ct) => {\n if (!/numeric|decimal/.test(ct)) return null;\n const out: JsonSchema7Property = { type: \"string\", format: \"decimal\" };\n if (typeof meta.scale === \"number\" && meta.scale >= 0) {\n out.multipleOf = 10 ** -meta.scale;\n }\n return out;\n};\n\nconst matchBigint: ColumnMatcher = (_m, _dt, ct) =>\n /bigint/.test(ct) ? { type: \"string\", format: \"int64\" } : null;\n\nconst matchDate: ColumnMatcher = (_m, dt, ct) =>\n dt === \"date\" || /timestamp|date/.test(ct) ? { type: \"string\", format: \"date-time\" } : null;\n\nconst matchBlob: ColumnMatcher = (_m, _dt, ct) =>\n /blob|bytea|binary/.test(ct) ? { type: \"string\", contentEncoding: \"base64\" } : null;\n\nconst matchBoolean: ColumnMatcher = (_m, dt, ct) =>\n dt === \"boolean\" || /boolean|bool/.test(ct) ? { type: \"boolean\" } : null;\n\nconst matchJson: ColumnMatcher = (_m, dt, ct) =>\n dt === \"json\" || /json/.test(ct) ? { type: \"object\" } : null;\n\nconst matchInteger: ColumnMatcher = (_m, dt, ct) =>\n isInteger(dt, ct) ? { type: \"integer\" } : null;\n\nconst matchFloat: ColumnMatcher = (_m, dt, ct) =>\n dt === \"number\" || /real|double|float/.test(ct) ? { type: \"number\" } : null;\n\nconst matchString: ColumnMatcher = (meta, dt, ct) => {\n if (!(dt === \"string\" || /text|varchar|char/.test(ct))) return null;\n const out: JsonSchema7Property = { type: \"string\" };\n if (typeof meta.length === \"number\" && meta.length > 0) out.maxLength = meta.length;\n return out;\n};\n\nconst COLUMN_MATCHERS: readonly ColumnMatcher[] = [\n matchEnum,\n matchUuid,\n matchNumeric,\n matchBigint,\n matchDate,\n matchBlob,\n matchBoolean,\n matchJson,\n matchInteger,\n matchFloat,\n matchString,\n];\n\nfunction mapColumnToJsonSchema(\n colName: string,\n col: Column,\n tableName: string,\n): JsonSchema7Property {\n const meta = col as unknown as ColumnInternal;\n const dt = lower(meta.dataType);\n const ct = lower(meta.columnType);\n\n for (const matcher of COLUMN_MATCHERS) {\n const result = matcher(meta, dt, ct);\n if (result !== null) return result;\n }\n\n throw new OrmSchemaExportError(\n `Cannot export column \"${colName}\" of table \"${tableName}\": unknown type (dataType=\"${meta.dataType}\", columnType=\"${meta.columnType}\"). Add to mapColumnToJsonSchema or use the \"_excludeFromExport: true\" annotation.`,\n );\n}\n\n/**\n * Emit the JSON Schema draft-07 description of one Drizzle table.\n *\n * A column is `required` when it is `NOT NULL` and has no default — the two together are what\n * decide whether a caller must supply a value, and treating `NOT NULL` alone as required would\n * demand values the database would have filled in.\n *\n * @throws {OrmSchemaExportError} when a column's type has no mapping. Emitting a partial schema\n * would be worse than failing: a consumer in another language would generate a model missing a\n * field and discover it at the first insert.\n */\nexport function exportSchema(table: Table): JsonSchema7 {\n const tableName = tableNameOf(table);\n const columns = getTableColumns(table) as Record<string, Column>;\n\n const properties: Record<string, JsonSchema7Property> = {};\n const required: string[] = [];\n\n for (const [colName, col] of Object.entries(columns)) {\n const meta = col as unknown as ColumnInternal;\n const prop = mapColumnToJsonSchema(colName, col, tableName);\n\n if (meta.hasDefault === true) {\n if (meta.default !== undefined) {\n prop.default = meta.default;\n }\n }\n\n if (meta.notNull === true && meta.hasDefault !== true) {\n required.push(colName);\n }\n\n properties[colName] = prop;\n }\n\n return {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n title: tableName,\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n };\n}\n\n/**\n * Emit one schema per table, keyed by the table's name in the database rather than by the key it\n * has in the Drizzle schema object — the two differ whenever a table is declared as\n * `users: sqliteTable(\"app_users\", ...)`, and a consumer generating models needs the name the\n * database answers to.\n *\n * @throws {OrmSchemaExportError} from the first table that has an unmappable column.\n */\nexport function exportSchemas(schema: Record<string, Table>): Record<string, JsonSchema7> {\n const out: Record<string, JsonSchema7> = {};\n for (const [, table] of Object.entries(schema)) {\n const name = tableNameOf(table);\n out[name] = exportSchema(table);\n }\n return out;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/orm",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Repository pattern + @InjectRepository decorator + agent-aware columns + @Transactional + schema export polyglot over drizzle-orm, consuming @theokit/di for inversion of control. NestJS TypeORM-equivalent DX for the theokit ecosystem.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheokit/theokit-di#readme",
@@ -38,7 +38,8 @@
38
38
  "types": "./dist/schema-export.d.cts",
39
39
  "default": "./dist/schema-export.cjs"
40
40
  }
41
- }
41
+ },
42
+ "./package.json": "./package.json"
42
43
  },
43
44
  "files": [
44
45
  "dist",
@@ -58,7 +59,7 @@
58
59
  "Theo"
59
60
  ],
60
61
  "peerDependencies": {
61
- "@theokit/di": "^0.1.0 || ^0.2.0",
62
+ "@theokit/di": "^0.2.0",
62
63
  "drizzle-orm": ">=0.36.0",
63
64
  "reflect-metadata": "^0.2.0"
64
65
  },
@@ -68,6 +69,7 @@
68
69
  }
69
70
  },
70
71
  "devDependencies": {
72
+ "@electric-sql/pglite": "^0.5.10",
71
73
  "@stryker-mutator/core": "^9.6.1",
72
74
  "@stryker-mutator/vitest-runner": "^9.6.1",
73
75
  "@swc/core": "^1.15.40",
@@ -81,7 +83,7 @@
81
83
  "typescript": "^5.8.0",
82
84
  "unplugin-swc": "^1.5.9",
83
85
  "vitest": "^4.1.8",
84
- "@theokit/di": "0.2.0"
86
+ "@theokit/di": "0.2.1"
85
87
  },
86
88
  "publishConfig": {
87
89
  "access": "public",