@orkestrel/relation 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,20 @@
1
- import { DatabaseInterface } from '@orkestrel/database';
2
- import { EmitterErrorHandler } from '@orkestrel/emitter';
3
- import { EmitterHooks } from '@orkestrel/emitter';
4
- import { EmitterInterface } from '@orkestrel/emitter';
5
- import { Key } from '@orkestrel/database';
6
- import { OperationOptions } from '@orkestrel/database';
7
- import { OrderDirection } from '@orkestrel/database';
8
- import { Row } from '@orkestrel/database';
9
- import { RowOf } from '@orkestrel/database';
10
- import { TableInterface } from '@orkestrel/database';
11
- import { TableMap } from '@orkestrel/database';
12
-
13
- /**
14
- * Build a `belongs` relation — a foreign key on THIS table points at the related row.
15
- *
16
- * @param column - The FK column on this table
1
+ import type { DatabaseInterface } from '@orkestrel/database';
2
+ import type { EmitterErrorHandler } from '@orkestrel/emitter';
3
+ import type { EmitterHooks } from '@orkestrel/emitter';
4
+ import type { EmitterInterface } from '@orkestrel/emitter';
5
+ import type { Key } from '@orkestrel/database';
6
+ import type { OperationOptions } from '@orkestrel/database';
7
+ import type { OrderDirection } from '@orkestrel/database';
8
+ import type { Row } from '@orkestrel/database';
9
+ import type { RowOf } from '@orkestrel/database';
10
+ import type { TableInterface } from '@orkestrel/database';
11
+ import type { TableMap } from '@orkestrel/database';
12
+
13
+ /**
14
+ * Builds a `belongs` relation — a foreign key on the owning table points at the related row
15
+ * (single).
16
+ *
17
+ * @param column - The foreign-key column on this table
17
18
  * @param model - Target table name (defaults to the relation name)
18
19
  * @returns A {@link RelationDescriptor}
19
20
  *
@@ -25,7 +26,25 @@ import { TableMap } from '@orkestrel/database';
25
26
  export declare function belongsTo(column: string, model?: string): RelationDescriptor;
26
27
 
27
28
  /**
28
- * Create a relation manager over a database and its relation definitions.
29
+ * Counts the related rows one relation attached across a record set.
30
+ *
31
+ * @remarks
32
+ * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a
33
+ * single-valued one (`belongs` / `one`) counts each present row. This is the count a
34
+ * `Model` carries on its `load` event.
35
+ *
36
+ * @param values - One relation's loaded value per record
37
+ * @returns The total related rows attached across the set
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3
42
+ * ```
43
+ */
44
+ export declare function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number;
45
+
46
+ /**
47
+ * Creates a {@link RelationManagerInterface} over a database and its relation map.
29
48
  *
30
49
  * @remarks
31
50
  * `relations` maps table names (constrained to the database's tables) to their
@@ -36,46 +55,83 @@ export declare function belongsTo(column: string, model?: string): RelationDescr
36
55
  * @param options - The `database` and an optional `relations` map
37
56
  * @returns A typed {@link RelationManagerInterface}
38
57
  *
39
- * @example
58
+ * @example Defining relations
40
59
  * ```ts
41
- * import { createRelationManager, belongsTo, hasMany } from '@src/core'
60
+ * import {
61
+ * createRelationManager,
62
+ * belongsTo,
63
+ * hasMany,
64
+ * hasOne,
65
+ * hasThrough,
66
+ * hasMorph,
67
+ * } from '@orkestrel/relation'
42
68
  *
43
69
  * const manager = createRelationManager({
44
70
  * database: db,
45
71
  * relations: {
46
- * accounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },
72
+ * accounts: {
73
+ * classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts
74
+ * contacts: hasMany('accountId'), // foreign key on contacts → accounts
75
+ * profile: hasOne('accountId', 'profiles'), // single, foreign key on profiles
76
+ * representatives: hasThrough('accountReps', 'accountId', 'repId', 'representatives'), // through a junction
77
+ * notes: hasMorph('entityId', 'entityType', 'account', 'notes'), // polymorphic
78
+ * },
47
79
  * contacts: { account: belongsTo('accountId', 'accounts') },
48
80
  * },
49
81
  * })
82
+ *
50
83
  * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
51
84
  * ```
52
85
  */
53
86
  export declare function createRelationManager<T extends TableMap>(options: RelationManagerOptions<T>): RelationManagerInterface<T>;
54
87
 
55
- /** Pagination, ordering, and cancellation for `find`. */
88
+ /** Configures pagination, ordering, and cancellation for `find`. */
56
89
  export declare interface FindOptions extends OperationOptions {
57
90
  readonly limit?: number;
58
91
  readonly offset?: number;
59
92
  readonly sort?: string;
60
- /** The sort direction; defaults to `ascending` when {@link sort} is present. */
93
+ /** Holds the sort direction; defaults to `ascending` when {@link sort} is present. */
61
94
  readonly direction?: OrderDirection;
62
95
  }
63
96
 
64
97
  /**
65
- * Build a `many` relation — a foreign key on the RELATED table points back here.
98
+ * Groups rows by the string form of one column, for one-to-many lookups.
99
+ *
100
+ * @remarks
101
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
102
+ * and a string foreign key meet at the same group. Rows keep their input order inside
103
+ * a group, a key no row carries is absent rather than empty, and a row missing the
104
+ * column groups under the string `'undefined'`. This is the projection a `many` load
105
+ * and a `morph` load use to attach every related row per key.
106
+ *
107
+ * @param rows - The rows to group
108
+ * @param column - The column to key on
109
+ * @returns A read-only map from each key's string form to its rows, in input order
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
114
+ * ```
115
+ */
116
+ export declare function groupRows(rows: readonly Row[], column: string): ReadonlyMap<string, readonly Row[]>;
117
+
118
+ /**
119
+ * Builds a `many` relation — a foreign key on the related table points back at the owning row
120
+ * (array).
66
121
  *
67
- * @param key - The FK column on the related table
122
+ * @param key - The foreign-key column on the related table
68
123
  * @param model - Target table name (defaults to the relation name)
69
124
  * @returns A {@link RelationDescriptor}
70
125
  */
71
126
  export declare function hasMany(key: string, model?: string): RelationDescriptor;
72
127
 
73
128
  /**
74
- * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
129
+ * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the
130
+ * related table (array).
75
131
  *
76
- * @param key - The FK column on the related table
132
+ * @param key - The foreign-key column on the related table
77
133
  * @param tag - The discriminator column on the related table
78
- * @param label - The discriminator value identifying THIS model
134
+ * @param label - The discriminator value identifying the owning model
79
135
  * @param model - Target table name (defaults to the relation name)
80
136
  * @returns A {@link RelationDescriptor}
81
137
  *
@@ -87,20 +143,20 @@ export declare function hasMany(key: string, model?: string): RelationDescriptor
87
143
  export declare function hasMorph(key: string, tag: string, label: string, model?: string): RelationDescriptor;
88
144
 
89
145
  /**
90
- * Build a `one` relation — like {@link hasMany}, but a single related row.
146
+ * Builds a `one` relation — like {@link hasMany}, but a single related row.
91
147
  *
92
- * @param key - The FK column on the related table
148
+ * @param key - The foreign-key column on the related table
93
149
  * @param model - Target table name (defaults to the relation name)
94
150
  * @returns A {@link RelationDescriptor}
95
151
  */
96
152
  export declare function hasOne(key: string, model?: string): RelationDescriptor;
97
153
 
98
154
  /**
99
- * Build a `through` relation — a junction table links the two sides (many-to-many).
155
+ * Builds a `through` relation — a junction table links the two sides (many-to-many).
100
156
  *
101
157
  * @param through - The junction table name
102
- * @param source - The junction FK column pointing at THIS model
103
- * @param target - The junction FK column pointing at the related model
158
+ * @param source - The junction foreign-key column pointing at the owning model
159
+ * @param target - The junction foreign-key column pointing at the related model
104
160
  * @param model - Target table name (defaults to the relation name)
105
161
  * @returns A {@link RelationDescriptor}
106
162
  *
@@ -112,7 +168,7 @@ export declare function hasOne(key: string, model?: string): RelationDescriptor;
112
168
  export declare function hasThrough(through: string, source: string, target: string, model?: string): RelationDescriptor;
113
169
 
114
170
  /**
115
- * Which relations to populate when loading — and, recursively, their own.
171
+ * Selects which relations to populate when loading — and, recursively, their own.
116
172
  *
117
173
  * @remarks
118
174
  * `true` loads the relation flat; a nested {@link Include} loads it and its
@@ -128,34 +184,84 @@ export declare interface Include {
128
184
  }
129
185
 
130
186
  /**
131
- * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).
187
+ * Indexes rows by the string form of one column, for keyed lookups.
188
+ *
189
+ * @remarks
190
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
191
+ * and a string foreign key meet at the same entry. A later row with a key an earlier
192
+ * row already holds replaces it, and a row missing the column indexes under the string
193
+ * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
194
+ * attach one related row per key.
195
+ *
196
+ * @param rows - The rows to index
197
+ * @param column - The column to key on
198
+ * @returns A read-only map from each key's string form to its row
199
+ *
200
+ * @example
201
+ * ```ts
202
+ * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
203
+ * ```
204
+ */
205
+ export declare function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row>;
206
+
207
+ /**
208
+ * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
209
+ *
210
+ * @remarks
211
+ * A record satisfies the descriptor when every member it declares carries its declared
212
+ * type: `relationship` is one of the `Relationship` values, and `column`, `key`,
213
+ * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the
214
+ * record omits is unconstrained, a member present with an `undefined` value is refused,
215
+ * and a member the descriptor does not declare is carried without being checked. This
216
+ * is what lets `resolveRelation` read each member after one narrow and report a
217
+ * malformed definition as an `INVALID` `RelationError` instead of resolving a
218
+ * wrong-typed column into an arm that declares it a string.
132
219
  *
133
220
  * @param value - The value to test
134
- * @returns `true` when `value` is a plain record
221
+ * @returns True if `value` is a record whose every declared member holds its declared
222
+ * type; false otherwise
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * isRelationDescriptor(belongsTo('accountId')) // true
227
+ * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
228
+ * ```
135
229
  */
136
230
  export declare function isRelationDescriptor(value: unknown): value is RelationDescriptor;
137
231
 
138
232
  /**
139
- * Narrow an unknown caught value to a {@link RelationError}.
233
+ * Narrows an unknown caught value to a {@link RelationError}.
140
234
  *
141
235
  * @param value - The value to test (typically a `catch` binding)
142
- * @returns `true` when `value` is a {@link RelationError}
236
+ * @returns True if `value` is a {@link RelationError}; false otherwise
143
237
  */
144
238
  export declare function isRelationError(value: unknown): value is RelationError;
145
239
 
146
240
  /**
147
- * A row with its loaded relation properties attached.
241
+ * Represents a row with its loaded relation properties attached.
148
242
  *
149
243
  * @remarks
150
244
  * The base row is fully typed (the table's row type); the relation properties
151
- * ({@link RelationProps}) are broad — narrow them at the use site. Typing each
245
+ * ({@link LoadedMap}) are broad — narrow them at the use site. Typing each
152
246
  * relation property to its target row is a deliberate (documented) deferral, like
153
247
  * the database guide's deferred pieces.
154
248
  */
155
- export declare type Loaded<T> = T & Readonly<RelationProps>;
249
+ export declare type Loaded<T> = T & Readonly<LoadedMap>;
250
+
251
+ /**
252
+ * Holds the relation properties attached to a {@link Loaded} row — each relation
253
+ * name mapped to its loaded related row(s), or `undefined` when a `belongs` /
254
+ * `one` relation misses.
255
+ *
256
+ * @remarks
257
+ * The broad value type (`Row | readonly Row[] | undefined`) is narrowed at the use
258
+ * site. This is the mutable bag a `Model` fills while populating a record set;
259
+ * `Loaded<T>` is a base row intersected with its `Readonly` form.
260
+ */
261
+ export declare type LoadedMap = Record<string, Row | readonly Row[] | undefined>;
156
262
 
157
263
  /**
158
- * A model — a typed table paired with relation-aware loading.
264
+ * Pairs a typed table with relation-aware `load` / `find` and junction management.
159
265
  *
160
266
  * @remarks
161
267
  * The model's own table is fully typed (`table`); related tables are reached by
@@ -167,17 +273,48 @@ export declare type Loaded<T> = T & Readonly<RelationProps>;
167
273
  * type is closed) and relation properties merged with `Object.assign` — no `as`.
168
274
  *
169
275
  * @remarks
170
- * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
276
+ * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
171
277
  * eager-load + junction moments — `load` (a relation resolved: its name + the count of
172
278
  * related rows attached across the whole record set), `link` / `unlink` (a junction row
173
279
  * written) — for fire-and-forget observers. Every event is emitted directly, strictly
174
- * AFTER the load resolves / the junction op completes; the emitter isolates a listener
175
- * throw and routes it to its `error` handler (the `error` option), so a buggy observer can
176
- * never corrupt the batched eager-load (no N+1 in the events either — one `load` per
177
- * relation, not per record).
280
+ * after the load resolves and after the junction operation completes; the emitter
281
+ * isolates a listener throw and routes it to its `error` handler (the `error` option),
282
+ * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events
283
+ * either — one `load` per relation, not per record).
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'
288
+ *
289
+ * const relations = { posts: hasMany('author') }
290
+ * const users = new Model(
291
+ * 'users',
292
+ * database.table('users'),
293
+ * resolveRelationMap(relations),
294
+ * relations,
295
+ * () => undefined,
296
+ * database,
297
+ * )
298
+ * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
299
+ * const ada = await users.load('u1', { posts: true })
300
+ * ```
178
301
  */
179
302
  export declare class Model<T = Row> implements ModelInterface<T> {
180
303
  #private;
304
+ /**
305
+ * Constructs a model over one table and its resolved relations.
306
+ *
307
+ * @param name - The model's table name
308
+ * @param table - The typed table this model's own reads and writes go through
309
+ * @param resolved - The model's relations, resolved by `resolveRelationMap`
310
+ * @param relations - The raw relation map the resolved relations came from
311
+ * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
312
+ * and returns `undefined` for a model the registry does not hold
313
+ * @param database - The broad database used to read related and junction tables by name
314
+ * @param on - Initial {@link ModelEventMap} listeners
315
+ * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
316
+ * swallowed.
317
+ */
181
318
  constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext | undefined, database: DatabaseInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler);
182
319
  get emitter(): EmitterInterface<ModelEventMap>;
183
320
  get name(): string;
@@ -192,39 +329,45 @@ export declare class Model<T = Row> implements ModelInterface<T> {
192
329
  }
193
330
 
194
331
  /**
195
- * The push observation surface of a {@link ModelInterface} (AGENTS §13) — the eager-load
196
- * + junction-management moments a fire-and-forget observer (logging, metrics, a sync
197
- * layer) subscribes to.
198
- *
199
- * @typeParam TKey - The model's primary-key type (a {@link Key}); `link` / `unlink` carry
200
- * the owning key so the map is `ModelEventMap<TKey>`.
332
+ * Declares the push observation surface of a {@link ModelInterface} — the
333
+ * eager-load + junction-management moments a fire-and-forget observer (logging, metrics,
334
+ * a sync layer) subscribes to.
201
335
  *
202
336
  * @remarks
203
- * `load` fires once per relation that an eager-load resolves, carrying the relation NAME +
204
- * the COUNT of related rows attached for the whole record set (it is the batched load
337
+ * `load` fires once per relation that an eager-load resolves, carrying the relation name +
338
+ * the count of related rows attached for the whole record set (it is the batched load
205
339
  * moment, not one event per record — there is no N+1 in the events either). `link` /
206
340
  * `unlink` fire after a junction row is inserted / removed, carrying the owning key + the
207
- * relation name. Listener isolation is the emitter's (AGENTS §13): every event is emitted
341
+ * relation name. Listener isolation is the emitter's: every event is emitted
208
342
  * directly and a listener throw is routed to the emitter's `error` handler (the `error`
209
- * option), never onto this map, and sits AFTER the load resolves / the junction op completes
210
- * — so a throwing observer can never corrupt the eager-load batching or a junction write.
343
+ * option), never onto this map, and sits strictly after the load resolves / the junction op
344
+ * completes — so a throwing observer can never corrupt the eager-load batching or a
345
+ * junction write.
211
346
  * `RelationManager` is event-free by design (a stateless
212
347
  * registry that merely vends models — it has no observable lifecycle of its own); the
213
348
  * per-entity {@link ModelInterface} is where loading and linking happen, so the emitter
214
- * lives there. Subscribe via `model.emitter.on(...)`. Declared as a `type` alias (§4.5 —
215
- * `EventMap` is a `type` kind).
349
+ * lives there. Subscribe through `model.emitter.on(...)`.
216
350
  */
217
- export declare type ModelEventMap<TKey extends Key = Key> = {
218
- /** A relation eager-loaded — the relation name + the count of related rows attached. */
351
+ export declare type ModelEventMap = {
352
+ /**
353
+ * Fires when a relation is eager-loaded — the relation name + the count of related rows
354
+ * attached.
355
+ */
219
356
  readonly load: readonly [name: string, count: number];
220
- /** A junction row was inserted for a `through` relation — the owning key + relation name. */
221
- readonly link: readonly [key: TKey, relation: string];
222
- /** A junction row was removed for a `through` relation — the owning key + relation name. */
223
- readonly unlink: readonly [key: TKey, relation: string];
357
+ /**
358
+ * Fires after a junction row is inserted for a `through` relation — the owning key +
359
+ * relation name.
360
+ */
361
+ readonly link: readonly [key: Key, relation: string];
362
+ /**
363
+ * Fires after a junction row is removed for a `through` relation — the owning key +
364
+ * relation name.
365
+ */
366
+ readonly unlink: readonly [key: Key, relation: string];
224
367
  };
225
368
 
226
369
  /**
227
- * A model — a typed table paired with relation-aware loading and junction
370
+ * Represents a typed table paired with relation-aware loading and junction
228
371
  * management.
229
372
  *
230
373
  * @remarks
@@ -234,7 +377,7 @@ export declare type ModelEventMap<TKey extends Key = Key> = {
234
377
  * fetches many; both batch-load (one query per direct relation or two per
235
378
  * `through`, regardless of result size). `link` / `unlink` / `links` manage a
236
379
  * `through` relation's junction rows.
237
- * Exposes a typed {@link emitter} (AGENTS §13) carrying the eager-load + junction
380
+ * Exposes a typed {@link emitter} carrying the eager-load + junction
238
381
  * moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
239
382
  * observation-only (a swallowed listener throw can never corrupt the batched load).
240
383
  * `link` is idempotent for sequential calls: an existing pair writes nothing and
@@ -246,26 +389,100 @@ export declare interface ModelInterface<T = Row> {
246
389
  readonly name: string;
247
390
  readonly table: TableInterface<T>;
248
391
  readonly relations: RelationMap;
392
+ /**
393
+ * Loads one record by key with the chosen relations populated, or a positional array of
394
+ * records for an array of keys.
395
+ *
396
+ * @remarks
397
+ * A key the table does not hold reads as `undefined`, and an array of keys keeps one slot
398
+ * per key in the order given. Either form batches the relation queries over the whole
399
+ * record set.
400
+ *
401
+ * @param key - The primary key to read
402
+ * @param include - The relations to populate, and recursively their own
403
+ * @param options - The database package's abort option
404
+ * @returns The loaded record, or `undefined` when the key holds none
405
+ */
249
406
  load(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>;
250
407
  load(keys: readonly Key[], include: Include, options?: OperationOptions): Promise<ReadonlyArray<Loaded<T> | undefined>>;
408
+ /**
409
+ * Finds many records, paged and sorted through {@link FindOptions}, with the chosen
410
+ * relations populated.
411
+ *
412
+ * @param include - The relations to populate, and recursively their own
413
+ * @param options - Pagination, ordering, and the abort signal
414
+ * @returns The page's records, each carrying its populated relations
415
+ */
251
416
  find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>>;
417
+ /**
418
+ * Inserts a missing junction row for a `through` relation.
419
+ *
420
+ * @remarks
421
+ * Idempotent for sequential calls: a pair the junction already holds writes nothing and
422
+ * emits nothing. Concurrent calls for one pair may each insert.
423
+ *
424
+ * @param key - The owning record's primary key
425
+ * @param relation - The `through` relation's name
426
+ * @param target - The related record's primary key
427
+ * @param options - The database package's abort option
428
+ * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
429
+ * `UNKNOWN_RELATION` one for a relation the model never declared
430
+ */
252
431
  link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
432
+ /**
433
+ * Removes every matching junction row for a `through` relation inside one transaction.
434
+ *
435
+ * @param key - The owning record's primary key
436
+ * @param relation - The `through` relation's name
437
+ * @param target - The related record's primary key
438
+ * @param options - The database package's abort option
439
+ * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
440
+ * `UNKNOWN_RELATION` one for a relation the model never declared
441
+ */
253
442
  unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
443
+ /**
444
+ * Lists the related keys reachable through a `through` relation.
445
+ *
446
+ * @param key - The owning record's primary key
447
+ * @param relation - The `through` relation's name
448
+ * @param options - The database package's abort option
449
+ * @returns The related keys the junction holds for that record
450
+ * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
451
+ * `UNKNOWN_RELATION` one for a relation the model never declared
452
+ */
254
453
  links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]>;
255
454
  }
256
455
 
257
456
  /**
258
- * A single relation definition.
457
+ * Reads one column off any record, whatever its declared type.
458
+ *
459
+ * @remarks
460
+ * A base row's type is closed, so the column is read with `Reflect.get` rather than
461
+ * index access. Anything that is not an object reads as `undefined`.
462
+ *
463
+ * @param record - The record to read
464
+ * @param column - The column name
465
+ * @returns The column's value, or `undefined` when `record` is not an object
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'
470
+ * ```
471
+ */
472
+ export declare function readColumn(record: unknown, column: string): unknown;
473
+
474
+ /**
475
+ * Represents a single relation definition.
259
476
  *
260
477
  * @remarks
261
- * A `string` is a `belongs` (the FK column on this table); a `readonly string[]`
262
- * is a `many` (the first element is the FK column on the related table); a
263
- * {@link RelationDescriptor} is the object form for everything else.
478
+ * A `string` is a `belongs` (the foreign-key column on this table); a `readonly
479
+ * string[]` is a `many` (the first element is the foreign-key column on the related
480
+ * table); a {@link RelationDescriptor} is the object form for everything else.
264
481
  */
265
482
  export declare type Relation = string | readonly string[] | RelationDescriptor;
266
483
 
267
484
  /**
268
- * A related model's resolved relations and primary-key column, for nested loading.
485
+ * Holds a related model's resolved relations and primary-key column, for nested loading.
269
486
  *
270
487
  * @remarks
271
488
  * The lookup result the relation registry hands a {@link ModelInterface} so it can
@@ -279,7 +496,7 @@ export declare interface RelationContext {
279
496
  }
280
497
 
281
498
  /**
282
- * The object form of a relation.
499
+ * Represents the object form of a relation.
283
500
  *
284
501
  * @remarks
285
502
  * The builder helpers (`belongsTo` / `hasMany` / `hasOne` / `hasThrough` /
@@ -303,7 +520,8 @@ export declare interface RelationDescriptor {
303
520
  }
304
521
 
305
522
  /**
306
- * An error thrown by the relations layer.
523
+ * Represents an error thrown by the relations layer, carrying a machine-readable
524
+ * {@link RelationErrorCode}.
307
525
  *
308
526
  * @remarks
309
527
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
@@ -318,47 +536,103 @@ export declare class RelationError extends Error {
318
536
  constructor(code: RelationErrorCode, message: string, context?: Readonly<Record<string, unknown>>);
319
537
  }
320
538
 
321
- /** A machine-readable {@link RelationError} code. */
539
+ /** Names a machine-readable {@link RelationError} code. */
322
540
  export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_THROUGH';
323
541
 
324
542
  /**
325
- * The relation registry — resolves a {@link RelationsShape} once at construction
326
- * and vends a typed {@link ModelInterface} per declared table.
543
+ * Resolves a {@link RelationsShape} once at construction and vends a typed
544
+ * {@link ModelInterface} per declared table.
327
545
  *
328
546
  * @remarks
329
547
  * Holds the database both at its precise type (to type each model's own table)
330
548
  * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
331
549
  * while loading). Construction validates every target and junction against the
332
550
  * database's declared tables, so invalid definitions fail before an operation runs.
551
+ * The `model` option's `on` and `error` are threaded into every model vended, and
552
+ * each `model(name)` call constructs a handle owning its own emitter, so retain the
553
+ * handle a subscription is taken on.
554
+ *
555
+ * @example
556
+ * ```ts
557
+ * import { RelationManager, hasMany } from '@orkestrel/relation'
558
+ *
559
+ * const manager = new RelationManager({
560
+ * database,
561
+ * relations: { users: { posts: hasMany('author') } },
562
+ * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
563
+ * })
564
+ * const users = manager.model('users')
565
+ * const ada = await users.load('u1', { posts: true })
566
+ * ```
333
567
  */
334
568
  export declare class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {
335
569
  #private;
570
+ /**
571
+ * Constructs a registry over a database and its relation definitions.
572
+ *
573
+ * @param options - The `database`, an optional `relations` map, and the optional
574
+ * `model` emitter settings threaded into every model vended
575
+ * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
576
+ * junction the database does not declare
577
+ */
336
578
  constructor(options: RelationManagerOptions<T>);
337
579
  get count(): number;
338
580
  model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
339
- models(): readonly string[];
581
+ names(): readonly string[];
340
582
  has(name: string): boolean;
341
583
  }
342
584
 
343
585
  /**
344
- * The relation registry — vends a typed {@link ModelInterface} per table.
586
+ * Vends a typed {@link ModelInterface} per table.
345
587
  *
346
588
  * @remarks
347
589
  * Built from a database and a {@link RelationsShape}; relations are resolved once
348
590
  * at construction. `model(name)` returns the model for a declared table, typed by
349
- * that table's row. Follows the manager accessor pattern (`model` / `models`).
591
+ * that table's row. Each call constructs a model, and the returned handle owns its
592
+ * own emitter, so retain the handle a subscription is taken on.
350
593
  */
351
594
  export declare interface RelationManagerInterface<T extends TableMap = TableMap> {
352
595
  readonly count: number;
596
+ /**
597
+ * Returns the typed model for a declared table.
598
+ *
599
+ * @remarks
600
+ * `name` is checked against the database's declared tables, so a typo is a compile error.
601
+ * A declared table with no relation entry yields a relation-less model, still fully usable
602
+ * for typed reads and writes through `table`.
603
+ *
604
+ * @param name - A declared table's name
605
+ * @returns A model typed by that table's row
606
+ */
353
607
  model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
354
- models(): readonly string[];
608
+ /**
609
+ * Lists the names of every model carrying resolved relations.
610
+ *
611
+ * @returns The table names the registry resolved a relation map for
612
+ */
613
+ names(): readonly string[];
614
+ /**
615
+ * Reports whether a model carries resolved relations.
616
+ *
617
+ * @param name - The table name to test
618
+ * @returns True when the registry resolved a relation map for that table; false otherwise
619
+ */
355
620
  has(name: string): boolean;
356
621
  }
357
622
 
358
- /** Options for `createRelationManager`. */
623
+ /**
624
+ * Configures `createRelationManager`.
625
+ *
626
+ * @remarks
627
+ * `model` carries the emitter settings the manager threads into every model it
628
+ * vends: `model.on` seeds each vended handle's initial {@link ModelEventMap}
629
+ * listeners, and `model.error` receives a listener throw as `(error, event)`.
630
+ * Each `model(name)` call constructs a handle with its own emitter, so these
631
+ * settings apply per handle rather than once for the manager.
632
+ */
359
633
  export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
360
634
  /**
361
- * The database to build the registry over.
635
+ * Holds the database to build the registry over.
362
636
  *
363
637
  * @remarks
364
638
  * Intersected with the broad `DatabaseInterface` so the manager gets both the
@@ -367,37 +641,29 @@ export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
367
641
  */
368
642
  readonly database: DatabaseInterface<T> & DatabaseInterface;
369
643
  readonly relations?: RelationsShape<T>;
644
+ readonly model?: {
645
+ readonly on?: EmitterHooks<ModelEventMap>;
646
+ readonly error?: EmitterErrorHandler;
647
+ };
370
648
  }
371
649
 
372
- /** A model's relations, keyed by relation name. */
650
+ /** Holds a model's relations, keyed by relation name. */
373
651
  export declare type RelationMap = Readonly<Record<string, Relation>>;
374
652
 
375
653
  /**
376
- * The relation properties attached to a {@link Loaded} row — each relation name
377
- * mapped to its loaded related row(s), or `undefined` when a `belongs` / `one`
378
- * relation misses.
654
+ * Enumerates the relationships a relation can declare.
379
655
  *
380
656
  * @remarks
381
- * The broad value type (`Row | readonly Row[] | undefined`) is narrowed at the use
382
- * site. This is the mutable bag a `Model` fills while populating a record set;
383
- * `Loaded<T>` is a base row intersected with its `Readonly` form.
384
- */
385
- export declare type RelationProps = Record<string, Row | readonly Row[] | undefined>;
386
-
387
- /**
388
- * The five relation shapes.
389
- *
390
- * @remarks
391
- * `belongs` — a foreign key on THIS table points at the related row (single).
392
- * `many` — a foreign key on the RELATED table points back here (array).
657
+ * `belongs` — a foreign key on the owning table points at the related row (single).
658
+ * `many` — a foreign key on the related table points back here (array).
393
659
  * `one` — like `many`, but a single related row.
394
660
  * `through` — a junction table links the two sides (array, many-to-many).
395
- * `morph` — a foreign key plus a discriminator column on the RELATED table (array, polymorphic).
661
+ * `morph` — a foreign key plus a discriminator column on the related table (array, polymorphic).
396
662
  */
397
663
  export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'morph';
398
664
 
399
665
  /**
400
- * Per-table relation maps — the declarative input to `createRelationManager`.
666
+ * Holds per-table relation maps — the declarative input to `createRelationManager`.
401
667
  *
402
668
  * @remarks
403
669
  * Keys are constrained to the database's declared table names, so relations can
@@ -408,43 +674,117 @@ export declare type RelationsShape<T extends TableMap = TableMap> = {
408
674
  };
409
675
 
410
676
  /**
411
- * A relation resolved at define-time into a flat, ready-to-load form.
677
+ * Represents a `belongs` relation resolved at define-time — the foreign key sits on the owning
678
+ * table.
412
679
  *
413
680
  * @remarks
414
- * The relationship and every column needed to load, link, and unlink are
415
- * precomputed from the raw {@link Relation}, so no inference runs at query time.
681
+ * `column` is that foreign key; the related row is the one whose primary key it holds.
682
+ * `name` is the relation's key in its {@link RelationMap} and `model` the target table.
416
683
  */
417
- export declare interface ResolvedRelation {
418
- readonly relationship: Relationship;
684
+ export declare interface ResolvedBelongs {
685
+ readonly relationship: 'belongs';
419
686
  readonly name: string;
420
687
  readonly model: string;
421
- readonly column?: string;
422
- readonly key?: string;
423
- readonly through?: string;
424
- readonly source?: string;
425
- readonly target?: string;
426
- readonly tag?: string;
427
- readonly label?: string;
688
+ readonly column: string;
689
+ }
690
+
691
+ /**
692
+ * Represents a `many` relation resolved at define-time — the foreign key sits on the related
693
+ * table.
694
+ *
695
+ * @remarks
696
+ * `key` is that foreign key. Every related row holding this record's primary-key value
697
+ * in it is attached, so the loaded property is an array.
698
+ */
699
+ export declare interface ResolvedMany {
700
+ readonly relationship: 'many';
701
+ readonly name: string;
702
+ readonly model: string;
703
+ readonly key: string;
704
+ }
705
+
706
+ /**
707
+ * Represents a `morph` relation resolved at define-time — a polymorphic foreign key and its
708
+ * discriminator.
709
+ *
710
+ * @remarks
711
+ * `key` is the foreign key on the related table, `tag` the discriminator column beside
712
+ * it, and `label` the discriminator value identifying the owning model.
713
+ */
714
+ export declare interface ResolvedMorph {
715
+ readonly relationship: 'morph';
716
+ readonly name: string;
717
+ readonly model: string;
718
+ readonly key: string;
719
+ readonly tag: string;
720
+ readonly label: string;
721
+ }
722
+
723
+ /**
724
+ * Represents a `one` relation resolved at define-time — {@link ResolvedMany}'s foreign key, one
725
+ * row.
726
+ *
727
+ * @remarks
728
+ * `key` is the foreign key on the related table. The first matching row is attached and
729
+ * a miss reads as `undefined`.
730
+ */
731
+ export declare interface ResolvedOne {
732
+ readonly relationship: 'one';
733
+ readonly name: string;
734
+ readonly model: string;
735
+ readonly key: string;
736
+ }
737
+
738
+ /**
739
+ * Represents a relation resolved at define-time into a flat, ready-to-load form.
740
+ *
741
+ * @remarks
742
+ * A union over the arms {@link Relationship} names, discriminated on `relationship`:
743
+ * each arm declares exactly the columns that arm needs to load, link, and unlink, and
744
+ * declares them required. `resolveRelation` precomputes and validates them from the raw
745
+ * {@link Relation}, so no inference and no absence check runs at query time. Narrow on
746
+ * `relationship` before reading an arm's own columns.
747
+ */
748
+ export declare type ResolvedRelation = ResolvedBelongs | ResolvedMany | ResolvedOne | ResolvedThrough | ResolvedMorph;
749
+
750
+ /**
751
+ * Represents a `through` relation resolved at define-time — a junction table links the two
752
+ * sides.
753
+ *
754
+ * @remarks
755
+ * `through` is the junction table, `source` its foreign-key column pointing at the
756
+ * owning model, and `target` its foreign-key column pointing at the related model.
757
+ * These are the columns `link` / `unlink` / `links` write and read.
758
+ */
759
+ export declare interface ResolvedThrough {
760
+ readonly relationship: 'through';
761
+ readonly name: string;
762
+ readonly model: string;
763
+ readonly through: string;
764
+ readonly source: string;
765
+ readonly target: string;
428
766
  }
429
767
 
430
768
  /**
431
- * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
769
+ * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
432
770
  *
433
771
  * @remarks
434
- * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
435
- * `many` (FK column on the related table); a {@link RelationDescriptor} uses its
436
- * explicit `relationship`, or infers it from the fields present. The target model
437
- * defaults to the relation name. Throws `INVALID` when the relationship cannot be
438
- * resolved or a required field is missing.
772
+ * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`
773
+ * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}
774
+ * uses its explicit `relationship`, or infers it from the fields present. The target
775
+ * model defaults to the relation name. Every column the resolved arm declares is
776
+ * validated here, which is what lets each arm declare its columns required.
439
777
  *
440
778
  * @param name - The relation name (its key in the {@link RelationMap})
441
779
  * @param value - The raw relation value
442
- * @returns The resolved relation
780
+ * @returns The resolved relation, on the arm its `relationship` names
781
+ * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a
782
+ * column the resolved arm declares is missing
443
783
  */
444
784
  export declare function resolveRelation(name: string, value: Relation): ResolvedRelation;
445
785
 
446
786
  /**
447
- * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
787
+ * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
448
788
  *
449
789
  * @param relations - The raw relation map
450
790
  * @returns A map keyed by relation name