@theokit/orm 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,45 +1,148 @@
1
1
  import { Table, InferSelectModel, SQL, InferInsertModel } from 'drizzle-orm';
2
2
  import { Provider } from '@theokit/di';
3
3
 
4
+ /** Any Drizzle table. The alias exists so this package's signatures name the domain concept
5
+ * rather than repeating a dependency's type everywhere a table is accepted. */
4
6
  type AnyTable = Table;
7
+ /**
8
+ * The SQL dialect a data source speaks.
9
+ *
10
+ * It is carried rather than inferred because behaviour genuinely differs by dialect: `@Transactional`
11
+ * refuses an `isolationLevel` on `sqlite`, which has transaction *behaviours* and no isolation level
12
+ * to set, and accepting one there would drop it silently.
13
+ */
5
14
  type Dialect = "sqlite" | "pg" | "mysql";
15
+ /**
16
+ * What {@link OrmModule.forRoot} needs to build a data source.
17
+ *
18
+ * `db` is the Drizzle handle you already built — this package never opens a connection of its own,
19
+ * so pooling, credentials and migrations stay where you configured them. `dataSourceName` names
20
+ * this source when an application has more than one; omit it and it is `"default"`.
21
+ */
6
22
  interface OrmRootOptions<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {
7
23
  schema: TSchema;
8
24
  dialect: Dialect;
9
25
  db: unknown;
10
26
  dataSourceName?: string;
11
27
  }
28
+ /**
29
+ * A configured database handle plus the schema and dialect it belongs to.
30
+ *
31
+ * Resolve it from the container with {@link ORM_DATA_SOURCE_TOKEN} when you need the raw Drizzle
32
+ * handle — running a query no repository covers, or binding it for `@Transactional`.
33
+ */
12
34
  interface DataSource<TSchema extends Record<string, AnyTable> = Record<string, AnyTable>> {
13
35
  readonly name: string;
14
36
  readonly dialect: Dialect;
15
37
  readonly schema: TSchema;
16
38
  readonly db: any;
17
39
  }
40
+ /**
41
+ * Container token for the default {@link DataSource}.
42
+ *
43
+ * Inject it with `@Inject(ORM_DATA_SOURCE_TOKEN)`. A named data source is registered under its own
44
+ * token, so this one resolves the source registered without a `dataSourceName`.
45
+ */
18
46
  declare const ORM_DATA_SOURCE_TOKEN = "ORM_DATA_SOURCE";
47
+ /**
48
+ * Who is acting, for the duration of one async chain.
49
+ *
50
+ * Repositories copy these into agent-aware columns on insert and update when the table declares
51
+ * them, so a row records which agent and which run produced it without the call sites passing ids
52
+ * down. Established with {@link withAgentContext}; every field is optional because a partial
53
+ * context is more useful than none.
54
+ */
19
55
  interface AgentContext {
20
56
  agentId?: string;
21
57
  runId?: string;
22
58
  conversationId?: string;
23
59
  }
24
60
 
61
+ /**
62
+ * Run `fn` with an agent context attached, so repositories can stamp agent-aware columns without
63
+ * the caller threading the ids through every function in between.
64
+ *
65
+ * The context follows the async chain rather than the call stack, so it survives every `await`
66
+ * inside `fn`. It does NOT survive an escape from that chain: a bare `setTimeout` or `setImmediate`
67
+ * inside `fn` starts a new chain and sees no context. Wrap the whole unit of work, not a fragment
68
+ * of it.
69
+ *
70
+ * @returns whatever `fn` returns, always as a Promise, so a synchronous and an asynchronous `fn`
71
+ * are called the same way.
72
+ */
25
73
  declare function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R>;
74
+ /**
75
+ * The agent context of the current async chain, or `undefined` outside {@link withAgentContext}.
76
+ *
77
+ * `undefined` is a normal answer, not an error: a repository writing agent-aware columns leaves
78
+ * them unset rather than refusing the write, because plain application code has no agent to name.
79
+ */
26
80
  declare function getAgentContext(): AgentContext | undefined;
27
81
 
82
+ /**
83
+ * Base class for every error this package raises.
84
+ *
85
+ * Catch this to handle anything from `@theokit/orm` without naming each subclass, and catch a
86
+ * subclass when the response differs: a configuration fault needs a deploy, a validation fault
87
+ * needs a different call.
88
+ */
28
89
  declare class OrmError extends Error {
29
90
  readonly name: string;
30
91
  }
92
+ /**
93
+ * The wiring is wrong, and no input will make the call succeed.
94
+ *
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
98
+ * the data, so it fails at the earliest point that can see it rather than at the first query.
99
+ */
31
100
  declare class OrmConfigurationError extends OrmError {
32
101
  readonly name = "OrmConfigurationError";
33
102
  }
103
+ /**
104
+ * A caller-supplied value was rejected at the boundary.
105
+ *
106
+ * The id guards are the reason this exists: `findById`, `update` and `delete` refuse a null, empty
107
+ * or non-scalar id rather than passing it to Drizzle, because a `DELETE` whose `WHERE` matched
108
+ * nothing usable is indistinguishable from one that matched everything until the rows are gone.
109
+ */
34
110
  declare class OrmValidationError extends OrmError {
35
111
  readonly name = "OrmValidationError";
36
112
  }
113
+ /**
114
+ * A table could not be expressed as JSON Schema.
115
+ *
116
+ * Raised by {@link exportSchema} for a column whose type has no mapping. It fails rather than
117
+ * skipping the column: a consumer generating a model in another language would get one missing a
118
+ * field and find out at the first insert.
119
+ */
37
120
  declare class OrmSchemaExportError extends OrmError {
38
121
  readonly name = "OrmSchemaExportError";
39
122
  }
40
123
 
124
+ /**
125
+ * Inject the {@link Repository} for one table.
126
+ *
127
+ * Shorthand for `@Inject(getRepositoryToken(entity, dataSourceName))` — the repository must have
128
+ * been registered by {@link OrmModule.forFeature} for the same data source, or resolution fails
129
+ * with `TokenNotFoundError` naming the token.
130
+ *
131
+ * @param entity a Drizzle table object
132
+ * @param dataSourceName the data source this table belongs to; omit for the default one
133
+ * @throws {OrmConfigurationError} at decoration time when `entity` is not a Drizzle table — the
134
+ * token is derived from the table's name, so an unnameable entity cannot produce one.
135
+ */
41
136
  declare function InjectRepository(entity: unknown, dataSourceName?: string): ParameterDecorator;
42
137
 
138
+ /**
139
+ * Provider builders that put a data source and its repositories into a container.
140
+ *
141
+ * Two calls, in this order: `forRoot` once per database, `forFeature` once per group of tables. The
142
+ * split is what lets a feature module declare the tables it needs without repeating the connection
143
+ * settings, and `forFeature` refuses outright when `forRoot` has not run for its data source —
144
+ * otherwise the failure would surface as a missing token at the first query, far from its cause.
145
+ */
43
146
  declare const OrmModule: {
44
147
  forRoot<TSchema extends Record<string, AnyTable>>(opts: OrmRootOptions<TSchema>): Provider[];
45
148
  forFeature(entities: readonly unknown[], dataSourceName?: string): Provider[];
@@ -47,6 +150,22 @@ declare const OrmModule: {
47
150
  _resetForTesting(): void;
48
151
  };
49
152
 
153
+ /**
154
+ * CRUD over one Drizzle table, with the six methods most application code needs.
155
+ *
156
+ * Resolve one per table with {@link InjectRepository}, or build one directly with
157
+ * {@link createRepository} when you want no container at all. Anything the six methods do not cover
158
+ * is what `query()` is for: it hands back the Drizzle builder, so an arbitrary query stays possible
159
+ * without this class growing a second query language.
160
+ *
161
+ * Two guards are deliberate. The constructor refuses a table with no primary key, because every
162
+ * other method addresses rows by it. And `findById`, `update` and `delete` refuse an id that is
163
+ * null, empty or not a string or number — a `DELETE` whose `WHERE` never matched anything usable
164
+ * looks exactly like one that matched every row, and only afterwards.
165
+ *
166
+ * When an agent context is active (see {@link withAgentContext}) and the table declares the
167
+ * matching columns, `insert` and `update` fill them in.
168
+ */
50
169
  declare class Repository<T extends Table> {
51
170
  private readonly defaultDb;
52
171
  private readonly table;
@@ -63,7 +182,7 @@ declare class Repository<T extends Table> {
63
182
  query(): unknown;
64
183
  }
65
184
  /**
66
- * M7-7 — non-DI factory for {@link Repository}. The `Repository` constructor is
185
+ * Non-DI factory for {@link Repository}. The `Repository` constructor is
67
186
  * already DI-free (`new Repository(db, table)`); this factory makes the non-DI
68
187
  * path explicit and discoverable, so consumers do NOT need `@theokit/di`,
69
188
  * decorators, or `reflect-metadata` for plain CRUD — only `@Transactional`
@@ -74,11 +193,69 @@ declare class Repository<T extends Table> {
74
193
  */
75
194
  declare function createRepository<T extends Table>(db: unknown, table: T): Repository<T>;
76
195
 
196
+ /**
197
+ * The container token under which one table's {@link Repository} is registered.
198
+ *
199
+ * `REPO:<table>` for the default data source and `REPO:<source>:<table>` for a named one, mirroring
200
+ * the NestJS TypeORM convention. The name comes from the table as the DATABASE knows it, not from
201
+ * the key it has in your schema object — the two differ whenever a table is declared as
202
+ * `users: sqliteTable("app_users", ...)`.
203
+ *
204
+ * @throws {OrmConfigurationError} when `entity` is null, undefined, or carries no resolvable
205
+ * Drizzle name. Deriving a token from an unnameable entity would register the repository under a
206
+ * token nothing could ask for.
207
+ */
77
208
  declare function getRepositoryToken(entity: unknown, dataSourceName?: string): string;
78
209
 
210
+ /**
211
+ * Attach a {@link DataSource} to an instance so its `@Transactional` methods can find one.
212
+ *
213
+ * `@Transactional` is a method decorator: it runs at class-definition time and has no
214
+ * container to ask, so the DataSource has to be put on the instance before the method is
215
+ * called. Nothing does that for you — not `OrmModule`, not the container.
216
+ *
217
+ * With the container, inject the DataSource and bind it in a `@PostConstruct` hook, which
218
+ * runs after construction with every dependency already in place:
219
+ *
220
+ * @example
221
+ * ```ts
222
+ * @Injectable()
223
+ * class TransferService {
224
+ * constructor(@Inject(ORM_DATA_SOURCE_TOKEN) private readonly ds: DataSource) {}
225
+ *
226
+ * @PostConstruct
227
+ * bindTransactions() {
228
+ * bindDataSourceToInstance(this, this.ds);
229
+ * }
230
+ *
231
+ * @Transactional()
232
+ * async transfer() { ... }
233
+ * }
234
+ * ```
235
+ *
236
+ * Without the container, call it directly on the instance before invoking the method.
237
+ */
238
+ declare function bindDataSourceToInstance(instance: object, ds: DataSource): void;
239
+ /** Options for {@link Transactional}. */
79
240
  interface TransactionalOptions {
241
+ /**
242
+ * Isolation level for the transaction, passed straight to the driver.
243
+ *
244
+ * Rejected on `sqlite`, which has no per-transaction isolation level to set — see
245
+ * the note in {@link Transactional}.
246
+ */
80
247
  isolationLevel?: "read uncommitted" | "read committed" | "repeatable read" | "serializable";
81
248
  }
82
- declare function Transactional(_opts?: TransactionalOptions): MethodDecorator;
249
+ /**
250
+ * `@Transactional(options?)` — run a method inside a database transaction.
251
+ *
252
+ * 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.
255
+ *
256
+ * The instance must carry a DataSource before the method runs — see
257
+ * {@link bindDataSourceToInstance}, which is the only thing that puts one there.
258
+ */
259
+ declare function Transactional(opts?: TransactionalOptions): MethodDecorator;
83
260
 
84
- export { type AgentContext, type AnyTable, type DataSource, type Dialect, InjectRepository, ORM_DATA_SOURCE_TOKEN, OrmConfigurationError, OrmError, OrmModule, type OrmRootOptions, OrmSchemaExportError, OrmValidationError, Repository, Transactional, createRepository, getAgentContext, getRepositoryToken, withAgentContext };
261
+ export { type AgentContext, type AnyTable, type DataSource, type Dialect, InjectRepository, ORM_DATA_SOURCE_TOKEN, OrmConfigurationError, OrmError, OrmModule, type OrmRootOptions, OrmSchemaExportError, OrmValidationError, Repository, Transactional, type TransactionalOptions, bindDataSourceToInstance, createRepository, getAgentContext, getRepositoryToken, withAgentContext };
package/dist/index.js CHANGED
@@ -312,35 +312,53 @@ var OrmModule = {
312
312
 
313
313
  // src/transactional.ts
314
314
  var DATA_SOURCE_KEY = /* @__PURE__ */ Symbol.for("Theo:orm:dataSource");
315
+ function bindDataSourceToInstance(instance, ds) {
316
+ instance[DATA_SOURCE_KEY] = ds;
317
+ }
318
+ __name(bindDataSourceToInstance, "bindDataSourceToInstance");
315
319
  function readDataSourceFromInstance(instance) {
316
320
  const v = instance[DATA_SOURCE_KEY];
317
321
  return v ?? void 0;
318
322
  }
319
323
  __name(readDataSourceFromInstance, "readDataSourceFromInstance");
320
- function Transactional(_opts = {}) {
324
+ var DIALECTS_WITH_ISOLATION_LEVEL = /* @__PURE__ */ new Set([
325
+ "pg",
326
+ "mysql"
327
+ ]);
328
+ function Transactional(opts = {}) {
321
329
  return /* @__PURE__ */ __name(function transactionalDecorator(_target, propertyKey, descriptor) {
322
330
  const original = descriptor.value;
323
331
  if (typeof original !== "function") {
324
332
  throw new OrmConfigurationError(`@Transactional on ${String(propertyKey)}: target is not a method.`);
325
333
  }
326
334
  descriptor.value = /* @__PURE__ */ __name(async function transactionalWrapper(...args) {
327
- const ds = readDataSourceFromInstance(this);
328
- if (!ds) {
329
- throw new OrmConfigurationError(`@Transactional ${String(propertyKey)}: no DataSource bound to instance. The class must be DI-managed via Container.resolve OR bindDataSourceToInstance(instance, ds) must be called before invoking the method.`);
330
- }
331
- const db = ds.db;
332
- if (typeof db.transaction !== "function") {
333
- throw new OrmConfigurationError(`@Transactional ${String(propertyKey)}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`);
334
- }
335
- return db.transaction(async (tx) => {
336
- return withTxContext(tx, () => original.apply(this, args));
335
+ const transaction = resolveTransactionFn(this, propertyKey, opts);
336
+ const run = /* @__PURE__ */ __name((tx) => withTxContext(tx, () => original.apply(this, args)), "run");
337
+ return opts.isolationLevel === void 0 ? transaction(run) : transaction(run, {
338
+ isolationLevel: opts.isolationLevel
337
339
  });
338
340
  }, "transactionalWrapper");
339
341
  return descriptor;
340
342
  }, "transactionalDecorator");
341
343
  }
342
344
  __name(Transactional, "Transactional");
345
+ function resolveTransactionFn(instance, propertyKey, opts) {
346
+ const where = `@Transactional ${String(propertyKey)}`;
347
+ const ds = readDataSourceFromInstance(instance);
348
+ if (!ds) {
349
+ throw new OrmConfigurationError(`${where}: no DataSource bound to instance. Call bindDataSourceToInstance(this, dataSource) before invoking the method \u2014 from a @PostConstruct hook when the class is container-managed, or directly after construction when it is not.`);
350
+ }
351
+ if (opts.isolationLevel !== void 0 && !DIALECTS_WITH_ISOLATION_LEVEL.has(ds.dialect)) {
352
+ throw new OrmConfigurationError(`${where}: isolationLevel "${opts.isolationLevel}" is not supported on ${ds.dialect}. Remove the option, or use a dialect that has isolation levels (pg, mysql).`);
353
+ }
354
+ const db = ds.db;
355
+ if (typeof db.transaction !== "function") {
356
+ throw new OrmConfigurationError(`${where}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`);
357
+ }
358
+ return db.transaction.bind(db);
359
+ }
360
+ __name(resolveTransactionFn, "resolveTransactionFn");
343
361
 
344
- export { InjectRepository, ORM_DATA_SOURCE_TOKEN, OrmConfigurationError, OrmError, OrmModule, OrmSchemaExportError, OrmValidationError, Repository, Transactional, createRepository, getAgentContext, getRepositoryToken, withAgentContext };
362
+ export { InjectRepository, ORM_DATA_SOURCE_TOKEN, OrmConfigurationError, OrmError, OrmModule, OrmSchemaExportError, OrmValidationError, Repository, Transactional, bindDataSourceToInstance, createRepository, getAgentContext, getRepositoryToken, withAgentContext };
345
363
  //# sourceMappingURL=index.js.map
346
364
  //# sourceMappingURL=index.js.map
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","readDataSourceFromInstance","instance","v","Transactional","_opts","transactionalDecorator","_target","propertyKey","descriptor","original","value","String","transactionalWrapper","args","transaction","apply"],"mappings":";;;;;;AAGA,IAAMA,GAAAA,GAAM,IAAIC,iBAAAA,EAAAA;AAET,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;AAIT,SAASM,eAAAA,GAAAA;AACd,EAAA,OAAOR,IAAIS,QAAAA,EAAQ;AACrB;AAFgBD,MAAAA,CAAAA,eAAAA,EAAAA,iBAAAA,CAAAA;;;ACTT,IAAME,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAA9B;;;EACoBC,IAAAA,GAAe,UAAA;AACnC;AAEO,IAAMC,qBAAAA,GAAN,cAAoCH,QAAAA,CAAAA;EAJ3C;;;EAKoBE,IAAAA,GAAO,uBAAA;AAC3B;AAEO,IAAME,kBAAAA,GAAN,cAAiCJ,QAAAA,CAAAA;EARxC;;;EASoBE,IAAAA,GAAO,oBAAA;AAC3B;AAEO,IAAMG,oBAAAA,GAAN,cAAmCL,QAAAA,CAAAA;EAZ1C;;;EAaoBE,IAAAA,GAAO,sBAAA;AAC3B;;;ACZA,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,MAAMG,UAAAA,GA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EAAAA,GAAKI,2BAA2B,IAAI,CAAA;AAC1C,MAAA,IAAI,CAACJ,EAAAA,EAAI;AACP,QAAA,MAAM,IAAIhH,qBAAAA,CACR,CAAA,eAAA,EAAkB+H,MAAAA,CAAOJ,WAAAA,CAAAA,CAAAA,0KAAAA,CAAwL,CAAA;AAErN,MAAA;AAEA,MAAA,MAAMnG,KAAKwF,EAAAA,CAAGxF,EAAAA;AAGd,MAAA,IAAI,OAAOA,EAAAA,CAAG0G,WAAAA,KAAgB,UAAA,EAAY;AACxC,QAAA,MAAM,IAAIlI,qBAAAA,CACR,CAAA,eAAA,EAAkB+H,MAAAA,CAAOJ,WAAAA,CAAAA,CAAAA,wFAAAA,CAAsG,CAAA;AAEnI,MAAA;AAEA,MAAA,OAAOnG,EAAAA,CAAG0G,WAAAA,CAAY,OAAO/E,EAAAA,KAAAA;AAC3B,QAAA,OAAOD,cAAcC,EAAAA,EAAI,MAAM0E,SAASM,KAAAA,CAAM,IAAA,EAAMF,IAAAA,CAAAA,CAAAA;MACtD,CAAA,CAAA;IACF,CAAA,EAvBmB,sBAAA,CAAA;AAyBnB,IAAA,OAAOL,UAAAA;EACT,CAAA,EAtCO,wBAAA,CAAA;AAuCT;AAxCgBL,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA","file":"index.js","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentContext } from \"./types.js\";\n\nconst als = new AsyncLocalStorage<AgentContext>();\n\nexport function withAgentContext<R>(ctx: AgentContext, fn: () => R | Promise<R>): Promise<R> {\n return Promise.resolve(als.run(ctx, fn));\n}\n\nexport function getAgentContext(): AgentContext | undefined {\n return als.getStore();\n}\n","export class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\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\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\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\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 * M7-7 — 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\nexport type AnyTable = Table;\n\nexport type Dialect = \"sqlite\" | \"pg\" | \"mysql\";\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\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\nexport const ORM_DATA_SOURCE_TOKEN = \"ORM_DATA_SOURCE\";\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\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 * Internal: any class containing @Transactional methods must have its\n * DataSource injected via this protocol so the decorator can find it.\n * The OrmModule arranges this automatically when classes are DI-managed.\n *\n * Direct (non-DI) instantiation requires manually calling\n * `bindDataSourceToInstance(instance, ds)` 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\ninterface TransactionalOptions {\n isolationLevel?: \"read uncommitted\" | \"read committed\" | \"repeatable read\" | \"serializable\";\n}\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 ds = readDataSourceFromInstance(this);\n if (!ds) {\n throw new OrmConfigurationError(\n `@Transactional ${String(propertyKey)}: no DataSource bound to instance. The class must be DI-managed via Container.resolve OR bindDataSourceToInstance(instance, ds) must be called before invoking the method.`,\n );\n }\n\n const db = ds.db as {\n transaction?: (cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;\n };\n if (typeof db.transaction !== \"function\") {\n throw new OrmConfigurationError(\n `@Transactional ${String(propertyKey)}: DataSource.db does not expose .transaction(). Ensure you passed a Drizzle db instance.`,\n );\n }\n\n return db.transaction(async (tx: unknown) => {\n return withTxContext(tx, () => original.apply(this, args));\n });\n };\n\n return descriptor;\n };\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","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,MAAA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AAAA,CAAAA;AAEvC,EAAA,MAAMZ,EAAAA,GAAKM,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 +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":";;;;;;;;AAAO,IAAMA,QAAAA,GAAN,cAAuBC,KAAAA,CAAAA;EAA9B;;;EACoBC,IAAAA,GAAe,UAAA;AACnC,CAAA;AAUO,IAAMC,oBAAAA,GAAN,cAAmCH,QAAAA,CAAAA;EAZ1C;;;EAaoBE,IAAAA,GAAO,sBAAA;AAC3B,CAAA;;;AC2BA,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,C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3C,IAAAA,CAAK2C,OAAAA;AACtB,MAAA;AACF,IAAA;AAEA,IAAA,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;AAkCT,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":["export class OrmError extends Error {\n override readonly name: string = \"OrmError\";\n}\n\nexport class OrmConfigurationError extends OrmError {\n override readonly name = \"OrmConfigurationError\";\n}\n\nexport class OrmValidationError extends OrmError {\n override readonly name = \"OrmValidationError\";\n}\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\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\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\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\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;AAgCO,IAAMC,oBAAAA,GAAN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A,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, 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"]}