@orkestrel/relation 0.0.10 → 0.0.11

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.
@@ -3,7 +3,7 @@ import { checkAbort, extractKey } from "@orkestrel/database";
3
3
  import { Emitter } from "@orkestrel/emitter";
4
4
  //#region src/core/errors.ts
5
5
  /**
6
- * An error thrown by the relations layer.
6
+ * Represents an error thrown by the relations layer.
7
7
  *
8
8
  * @remarks
9
9
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
@@ -23,38 +23,71 @@ var RelationError = class extends Error {
23
23
  }
24
24
  };
25
25
  /**
26
- * Narrow an unknown caught value to a {@link RelationError}.
26
+ * Narrows an unknown caught value to a {@link RelationError}.
27
27
  *
28
28
  * @param value - The value to test (typically a `catch` binding)
29
- * @returns `true` when `value` is a {@link RelationError}
29
+ * @returns True if `value` is a {@link RelationError}; false otherwise
30
30
  */
31
31
  function isRelationError(value) {
32
32
  return value instanceof RelationError;
33
33
  }
34
34
  //#endregion
35
- //#region src/core/helpers.ts
35
+ //#region src/core/validators.ts
36
36
  /**
37
- * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).
37
+ * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
38
+ *
39
+ * @remarks
40
+ * A record satisfies the descriptor when every member it declares carries its declared
41
+ * type: `relationship` is one of the `Relationship` values, and `column`, `key`,
42
+ * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the
43
+ * record omits is unconstrained, a member present with an `undefined` value is refused,
44
+ * and a member the descriptor does not declare is carried without being checked. This
45
+ * is what lets `resolveRelation` read each member after one narrow and report a
46
+ * malformed definition as an `INVALID` `RelationError` instead of resolving a
47
+ * wrong-typed column into an arm that declares it a string.
38
48
  *
39
49
  * @param value - The value to test
40
- * @returns `true` when `value` is a plain record
50
+ * @returns True if `value` is a record whose every declared member holds its declared
51
+ * type; false otherwise
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * isRelationDescriptor(belongsTo('accountId')) // true
56
+ * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
57
+ * ```
41
58
  */
42
59
  function isRelationDescriptor(value) {
43
- return isRecord(value);
60
+ if (!isRecord(value)) return false;
61
+ if ("relationship" in value && value.relationship !== "belongs" && value.relationship !== "many" && value.relationship !== "one" && value.relationship !== "through" && value.relationship !== "morph") return false;
62
+ for (const member of [
63
+ "column",
64
+ "key",
65
+ "through",
66
+ "source",
67
+ "target",
68
+ "tag",
69
+ "label",
70
+ "model"
71
+ ]) if (member in value && !isString(value[member])) return false;
72
+ return true;
44
73
  }
74
+ //#endregion
75
+ //#region src/core/helpers.ts
45
76
  /**
46
- * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
77
+ * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
47
78
  *
48
79
  * @remarks
49
80
  * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
50
81
  * `many` (FK column on the related table); a {@link RelationDescriptor} uses its
51
82
  * explicit `relationship`, or infers it from the fields present. The target model
52
- * defaults to the relation name. Throws `INVALID` when the relationship cannot be
53
- * resolved or a required field is missing.
83
+ * defaults to the relation name. Every column the resolved arm declares is validated
84
+ * here, which is what lets each arm declare its columns required.
54
85
  *
55
86
  * @param name - The relation name (its key in the {@link RelationMap})
56
87
  * @param value - The raw relation value
57
- * @returns The resolved relation
88
+ * @returns The resolved relation, on the arm its `relationship` names
89
+ * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a
90
+ * column the resolved arm declares is missing
58
91
  */
59
92
  function resolveRelation(name, value) {
60
93
  if (isString(value)) return {
@@ -140,7 +173,7 @@ function resolveRelation(name, value) {
140
173
  }
141
174
  }
142
175
  /**
143
- * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
176
+ * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
144
177
  *
145
178
  * @param relations - The raw relation map
146
179
  * @returns A map keyed by relation name
@@ -151,7 +184,102 @@ function resolveRelationMap(relations) {
151
184
  return resolved;
152
185
  }
153
186
  /**
154
- * Build a `belongs` relation — a foreign key on THIS table points at the related row.
187
+ * Reads one column off any record.
188
+ *
189
+ * @remarks
190
+ * A base row's type is closed, so the column is read with `Reflect.get` rather than
191
+ * index access. Anything that is not an object reads as `undefined`.
192
+ *
193
+ * @param record - The record to read
194
+ * @param column - The column name
195
+ * @returns The column's value, or `undefined` when `record` is not an object
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'
200
+ * ```
201
+ */
202
+ function readColumn(record, column) {
203
+ if (typeof record !== "object" || record === null) return void 0;
204
+ return Reflect.get(record, column);
205
+ }
206
+ /**
207
+ * Counts the related rows one relation attached across a record set.
208
+ *
209
+ * @remarks
210
+ * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a
211
+ * single-valued one (`belongs` / `one`) counts each present row. This is the count a
212
+ * `Model` carries on its `load` event.
213
+ *
214
+ * @param values - One relation's loaded value per record
215
+ * @returns The total related rows attached across the set
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3
220
+ * ```
221
+ */
222
+ function countAttached(values) {
223
+ let total = 0;
224
+ for (const value of values) if (isArray(value)) total += value.length;
225
+ else if (value !== void 0) total += 1;
226
+ return total;
227
+ }
228
+ /**
229
+ * Indexes rows by the string form of one column, for keyed lookups.
230
+ *
231
+ * @remarks
232
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
233
+ * and a string foreign key meet at the same entry. A later row with a key an earlier
234
+ * row already holds replaces it, and a row missing the column indexes under the string
235
+ * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
236
+ * attach one related row per key.
237
+ *
238
+ * @param rows - The rows to index
239
+ * @param column - The column to key on
240
+ * @returns A read-only map from each key's string form to its row
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
245
+ * ```
246
+ */
247
+ function indexRows(rows, column) {
248
+ const index = /* @__PURE__ */ new Map();
249
+ for (const row of rows) index.set(String(readColumn(row, column)), row);
250
+ return index;
251
+ }
252
+ /**
253
+ * Groups rows by the string form of one column, for one-to-many lookups.
254
+ *
255
+ * @remarks
256
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
257
+ * and a string foreign key meet at the same group. Rows keep their input order inside
258
+ * a group, a key no row carries is absent rather than empty, and a row missing the
259
+ * column groups under the string `'undefined'`. This is the projection a `many` load
260
+ * and a `morph` load use to attach every related row per key.
261
+ *
262
+ * @param rows - The rows to group
263
+ * @param column - The column to key on
264
+ * @returns A read-only map from each key's string form to its rows, in input order
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
269
+ * ```
270
+ */
271
+ function groupRows(rows, column) {
272
+ const groups = /* @__PURE__ */ new Map();
273
+ for (const row of rows) {
274
+ const key = String(readColumn(row, column));
275
+ const group = groups.get(key);
276
+ if (group !== void 0) group.push(row);
277
+ else groups.set(key, [row]);
278
+ }
279
+ return groups;
280
+ }
281
+ /**
282
+ * Builds a `belongs` relation — a foreign key on THIS table points at the related row.
155
283
  *
156
284
  * @param column - The FK column on this table
157
285
  * @param model - Target table name (defaults to the relation name)
@@ -170,7 +298,7 @@ function belongsTo(column, model) {
170
298
  };
171
299
  }
172
300
  /**
173
- * Build a `many` relation — a foreign key on the RELATED table points back here.
301
+ * Builds a `many` relation — a foreign key on the RELATED table points back here.
174
302
  *
175
303
  * @param key - The FK column on the related table
176
304
  * @param model - Target table name (defaults to the relation name)
@@ -184,7 +312,7 @@ function hasMany(key, model) {
184
312
  };
185
313
  }
186
314
  /**
187
- * Build a `one` relation — like {@link hasMany}, but a single related row.
315
+ * Builds a `one` relation — like {@link hasMany}, but a single related row.
188
316
  *
189
317
  * @param key - The FK column on the related table
190
318
  * @param model - Target table name (defaults to the relation name)
@@ -198,7 +326,7 @@ function hasOne(key, model) {
198
326
  };
199
327
  }
200
328
  /**
201
- * Build a `through` relation — a junction table links the two sides (many-to-many).
329
+ * Builds a `through` relation — a junction table links the two sides (many-to-many).
202
330
  *
203
331
  * @param through - The junction table name
204
332
  * @param source - The junction FK column pointing at THIS model
@@ -221,7 +349,7 @@ function hasThrough(through, source, target, model) {
221
349
  };
222
350
  }
223
351
  /**
224
- * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
352
+ * Builds a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
225
353
  *
226
354
  * @param key - The FK column on the related table
227
355
  * @param tag - The discriminator column on the related table
@@ -246,7 +374,7 @@ function hasMorph(key, tag, label, model) {
246
374
  //#endregion
247
375
  //#region src/core/Model.ts
248
376
  /**
249
- * A model — a typed table paired with relation-aware loading.
377
+ * Pairs a typed table with relation-aware loading.
250
378
  *
251
379
  * @remarks
252
380
  * The model's own table is fully typed (`table`); related tables are reached by
@@ -258,7 +386,7 @@ function hasMorph(key, tag, label, model) {
258
386
  * type is closed) and relation properties merged with `Object.assign` — no `as`.
259
387
  *
260
388
  * @remarks
261
- * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
389
+ * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
262
390
  * eager-load + junction moments — `load` (a relation resolved: its name + the count of
263
391
  * related rows attached across the whole record set), `link` / `unlink` (a junction row
264
392
  * written) — for fire-and-forget observers. Every event is emitted directly, strictly
@@ -266,6 +394,23 @@ function hasMorph(key, tag, label, model) {
266
394
  * throw and routes it to its `error` handler (the `error` option), so a buggy observer can
267
395
  * never corrupt the batched eager-load (no N+1 in the events either — one `load` per
268
396
  * relation, not per record).
397
+ *
398
+ * @example
399
+ * ```ts
400
+ * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'
401
+ *
402
+ * const relations = { posts: hasMany('author') }
403
+ * const users = new Model(
404
+ * 'users',
405
+ * database.table('users'),
406
+ * resolveRelationMap(relations),
407
+ * relations,
408
+ * () => undefined,
409
+ * database,
410
+ * )
411
+ * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
412
+ * const ada = await users.load('u1', { posts: true })
413
+ * ```
269
414
  */
270
415
  var Model = class {
271
416
  #name;
@@ -275,6 +420,20 @@ var Model = class {
275
420
  #lookup;
276
421
  #database;
277
422
  #emitter;
423
+ /**
424
+ * Constructs a model over one table and its resolved relations.
425
+ *
426
+ * @param name - The model's table name
427
+ * @param table - The typed table this model's own reads and writes go through
428
+ * @param resolved - The model's relations, resolved by `resolveRelationMap`
429
+ * @param relations - The raw relation map the resolved relations came from
430
+ * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
431
+ * and returns `undefined` for a model the registry does not hold
432
+ * @param database - The broad database used to read related and junction tables by name
433
+ * @param on - Initial {@link ModelEventMap} listeners
434
+ * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
435
+ * swallowed.
436
+ */
278
437
  constructor(name, table, resolved, relations, lookup, database, on, error) {
279
438
  this.#name = name;
280
439
  this.#table = table;
@@ -329,43 +488,41 @@ var Model = class {
329
488
  async link(key, relation, target, options) {
330
489
  checkAbort(options?.signal);
331
490
  const resolved = this.#through(relation);
332
- const source = resolved.source ?? "";
333
- const column = resolved.target ?? "";
334
- const junction = this.#database.table(resolved.through ?? "");
491
+ const junction = this.#database.table(resolved.through);
335
492
  if (await junction.count({ conditions: [{
336
- column: source,
493
+ column: resolved.source,
337
494
  operator: "equals",
338
495
  values: [key],
339
496
  connector: "and"
340
497
  }, {
341
- column,
498
+ column: resolved.target,
342
499
  operator: "equals",
343
500
  values: [target],
344
501
  connector: "and"
345
502
  }] }, options) > 0) return;
346
503
  await junction.set({
347
- [source]: key,
348
- [column]: target
504
+ [resolved.source]: key,
505
+ [resolved.target]: target
349
506
  }, options);
350
507
  this.#emitter.emit("link", key, relation);
351
508
  }
352
509
  async unlink(key, relation, target, options) {
353
510
  checkAbort(options?.signal);
354
511
  const resolved = this.#through(relation);
355
- const junction = this.#database.table(resolved.through ?? "");
512
+ const junction = this.#database.table(resolved.through);
356
513
  const rows = await junction.records({ conditions: [{
357
- column: resolved.source ?? "",
514
+ column: resolved.source,
358
515
  operator: "equals",
359
516
  values: [key],
360
517
  connector: "and"
361
518
  }, {
362
- column: resolved.target ?? "",
519
+ column: resolved.target,
363
520
  operator: "equals",
364
521
  values: [target],
365
522
  connector: "and"
366
523
  }] }, options);
367
524
  await this.#database.transaction(async (transaction) => {
368
- const scoped = transaction.table(resolved.through ?? "");
525
+ const scoped = transaction.table(resolved.through);
369
526
  for (const row of rows) {
370
527
  const id = extractKey(row, junction.primary);
371
528
  if (id !== void 0) await scoped.remove(id, options);
@@ -376,13 +533,13 @@ var Model = class {
376
533
  async links(key, relation, options) {
377
534
  checkAbort(options?.signal);
378
535
  const resolved = this.#through(relation);
379
- const rows = await this.#database.table(resolved.through ?? "").records({ conditions: [{
380
- column: resolved.source ?? "",
536
+ const rows = await this.#database.table(resolved.through).records({ conditions: [{
537
+ column: resolved.source,
381
538
  operator: "equals",
382
539
  values: [key],
383
540
  connector: "and"
384
541
  }] }, options);
385
- const target = resolved.target ?? "";
542
+ const target = resolved.target;
386
543
  const keys = [];
387
544
  for (const row of rows) {
388
545
  const value = extractKey(row, target);
@@ -390,10 +547,6 @@ var Model = class {
390
547
  }
391
548
  return keys;
392
549
  }
393
- #field(record, column) {
394
- if (typeof record !== "object" || record === null) return void 0;
395
- return Reflect.get(record, column);
396
- }
397
550
  #through(relation) {
398
551
  const resolved = this.#resolved.get(relation);
399
552
  if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model '${this.#name}' has no relation '${relation}'`, {
@@ -419,16 +572,10 @@ var Model = class {
419
572
  const target = props[index];
420
573
  if (target !== void 0) target[resolved.name] = value;
421
574
  });
422
- this.#emitter.emit("load", resolved.name, this.#attached(values));
575
+ this.#emitter.emit("load", resolved.name, countAttached(values));
423
576
  }
424
577
  return props;
425
578
  }
426
- #attached(values) {
427
- let total = 0;
428
- for (const value of values) if (isArray(value)) total += value.length;
429
- else if (value !== void 0) total += 1;
430
- return total;
431
- }
432
579
  async #load(records, resolved, sub, primary, options) {
433
580
  switch (resolved.relationship) {
434
581
  case "belongs": return this.#loadBelongs(records, resolved, sub, options);
@@ -439,8 +586,8 @@ var Model = class {
439
586
  }
440
587
  }
441
588
  async #loadBelongs(records, resolved, sub, options) {
442
- const column = resolved.column ?? "";
443
- const keys = [...new Set(records.map((record) => this.#field(record, column)).filter(isDefined))];
589
+ const column = resolved.column;
590
+ const keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))];
444
591
  if (keys.length === 0) return records.map(() => void 0);
445
592
  const related = this.#database.table(resolved.model);
446
593
  const rows = await related.records({ conditions: [{
@@ -449,15 +596,15 @@ var Model = class {
449
596
  values: keys,
450
597
  connector: "and"
451
598
  }] }, options);
452
- const index = this.#index(await this.#nest(resolved.model, rows, sub, options), related.primary);
599
+ const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
453
600
  return records.map((record) => {
454
- const fk = this.#field(record, column);
601
+ const fk = readColumn(record, column);
455
602
  return isDefined(fk) ? index.get(String(fk)) : void 0;
456
603
  });
457
604
  }
458
605
  async #loadMany(records, resolved, sub, primary, options) {
459
- const foreign = resolved.key ?? "";
460
- const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
606
+ const foreign = resolved.key;
607
+ const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
461
608
  if (keys.length === 0) return records.map(() => []);
462
609
  const rows = await this.#database.table(resolved.model).records({ conditions: [{
463
610
  column: foreign,
@@ -465,18 +612,18 @@ var Model = class {
465
612
  values: keys,
466
613
  connector: "and"
467
614
  }] }, options);
468
- const groups = this.#group(await this.#nest(resolved.model, rows, sub, options), foreign);
469
- return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
615
+ const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
616
+ return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
470
617
  }
471
618
  async #loadOne(records, resolved, sub, primary, options) {
472
619
  return (await this.#loadMany(records, resolved, sub, primary, options)).map((group) => group.length > 0 ? group[0] : void 0);
473
620
  }
474
621
  async #loadThrough(records, resolved, sub, primary, options) {
475
- const source = resolved.source ?? "";
476
- const target = resolved.target ?? "";
477
- const parents = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
622
+ const source = resolved.source;
623
+ const target = resolved.target;
624
+ const parents = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
478
625
  if (parents.length === 0) return records.map(() => []);
479
- const junctions = await this.#database.table(resolved.through ?? "").records({ conditions: [{
626
+ const junctions = await this.#database.table(resolved.through).records({ conditions: [{
480
627
  column: source,
481
628
  operator: "any",
482
629
  values: parents,
@@ -484,9 +631,9 @@ var Model = class {
484
631
  }] }, options);
485
632
  const targetsBySource = /* @__PURE__ */ new Map();
486
633
  for (const junction of junctions) {
487
- const value = this.#field(junction, target);
634
+ const value = readColumn(junction, target);
488
635
  if (!isDefined(value)) continue;
489
- const owner = String(this.#field(junction, source));
636
+ const owner = String(readColumn(junction, source));
490
637
  const list = targetsBySource.get(owner);
491
638
  if (list !== void 0) list.push(value);
492
639
  else targetsBySource.set(owner, [value]);
@@ -500,10 +647,10 @@ var Model = class {
500
647
  values: targets,
501
648
  connector: "and"
502
649
  }] }, options);
503
- const index = this.#index(await this.#nest(resolved.model, rows, sub, options), related.primary);
650
+ const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
504
651
  return records.map((record) => {
505
652
  const out = [];
506
- for (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {
653
+ for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
507
654
  const row = index.get(String(value));
508
655
  if (row !== void 0) out.push(row);
509
656
  }
@@ -511,8 +658,8 @@ var Model = class {
511
658
  });
512
659
  }
513
660
  async #loadMorph(records, resolved, sub, primary, options) {
514
- const foreign = resolved.key ?? "";
515
- const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
661
+ const foreign = resolved.key;
662
+ const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
516
663
  if (keys.length === 0) return records.map(() => []);
517
664
  const rows = await this.#database.table(resolved.model).records({ conditions: [{
518
665
  column: foreign,
@@ -520,13 +667,13 @@ var Model = class {
520
667
  values: keys,
521
668
  connector: "and"
522
669
  }, {
523
- column: resolved.tag ?? "",
670
+ column: resolved.tag,
524
671
  operator: "equals",
525
- values: [resolved.label ?? ""],
672
+ values: [resolved.label],
526
673
  connector: "and"
527
674
  }] }, options);
528
- const groups = this.#group(await this.#nest(resolved.model, rows, sub, options), foreign);
529
- return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
675
+ const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
676
+ return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
530
677
  }
531
678
  async #nest(model, rows, sub, options) {
532
679
  if (typeof sub === "boolean" || rows.length === 0) return rows;
@@ -535,43 +682,54 @@ var Model = class {
535
682
  const props = await this.#populate(rows, sub, context.resolved, context.primary, options);
536
683
  return rows.map((row, index) => Object.assign({}, row, props[index]));
537
684
  }
538
- #index(rows, column) {
539
- const map = /* @__PURE__ */ new Map();
540
- for (const row of rows) map.set(String(this.#field(row, column)), row);
541
- return map;
542
- }
543
- #group(rows, column) {
544
- const map = /* @__PURE__ */ new Map();
545
- for (const row of rows) {
546
- const key = String(this.#field(row, column));
547
- const group = map.get(key);
548
- if (group !== void 0) group.push(row);
549
- else map.set(key, [row]);
550
- }
551
- return map;
552
- }
553
685
  };
554
686
  //#endregion
555
687
  //#region src/core/RelationManager.ts
556
688
  /**
557
- * The relation registry — resolves a {@link RelationsShape} once at construction
558
- * and vends a typed {@link ModelInterface} per declared table.
689
+ * Resolves a {@link RelationsShape} once at construction and vends a typed
690
+ * {@link ModelInterface} per declared table.
559
691
  *
560
692
  * @remarks
561
693
  * Holds the database both at its precise type (to type each model's own table)
562
694
  * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
563
695
  * while loading). Construction validates every target and junction against the
564
696
  * database's declared tables, so invalid definitions fail before an operation runs.
697
+ * The `model` option's `on` and `error` are threaded into every model vended, and
698
+ * each `model(name)` call constructs a handle owning its own emitter, so retain the
699
+ * handle a subscription is taken on.
700
+ *
701
+ * @example
702
+ * ```ts
703
+ * import { RelationManager, hasMany } from '@orkestrel/relation'
704
+ *
705
+ * const manager = new RelationManager({
706
+ * database,
707
+ * relations: { users: { posts: hasMany('author') } },
708
+ * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
709
+ * })
710
+ * const users = manager.model('users')
711
+ * const ada = await users.load('u1', { posts: true })
712
+ * ```
565
713
  */
566
714
  var RelationManager = class {
567
715
  #database;
568
716
  #broad;
569
717
  #relations;
718
+ #model;
570
719
  #resolved = /* @__PURE__ */ new Map();
720
+ /**
721
+ * Constructs a registry over a database and its relation definitions.
722
+ *
723
+ * @param options - The `database`, an optional `relations` map, and the optional
724
+ * `model` emitter settings threaded into every model vended
725
+ * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
726
+ * junction the database does not declare
727
+ */
571
728
  constructor(options) {
572
729
  this.#database = options.database;
573
730
  this.#broad = options.database;
574
731
  this.#relations = options.relations ?? {};
732
+ this.#model = options.model;
575
733
  const declared = new Set(Object.keys(this.#broad.export()));
576
734
  for (const [name, map] of Object.entries(this.#relations)) {
577
735
  if (map === void 0) continue;
@@ -582,7 +740,7 @@ var RelationManager = class {
582
740
  relation,
583
741
  table: entry.model
584
742
  });
585
- if (entry.relationship === "through" && entry.through !== void 0 && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
743
+ if (entry.relationship === "through" && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
586
744
  model: name,
587
745
  relation,
588
746
  table: entry.through
@@ -599,14 +757,14 @@ var RelationManager = class {
599
757
  const relations = this.#relations[name] ?? {};
600
758
  return this.#vend(name, this.#database.table(name), resolved, relations);
601
759
  }
602
- models() {
760
+ names() {
603
761
  return [...this.#resolved.keys()];
604
762
  }
605
763
  has(name) {
606
764
  return this.#resolved.has(name);
607
765
  }
608
766
  #vend(name, table, resolved, relations) {
609
- return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad);
767
+ return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad, this.#model?.on, this.#model?.error);
610
768
  }
611
769
  #context(model) {
612
770
  const resolved = this.#resolved.get(model);
@@ -620,7 +778,7 @@ var RelationManager = class {
620
778
  //#endregion
621
779
  //#region src/core/factories.ts
622
780
  /**
623
- * Create a relation manager over a database and its relation definitions.
781
+ * Creates a relation manager over a database and its relation definitions.
624
782
  *
625
783
  * @remarks
626
784
  * `relations` maps table names (constrained to the database's tables) to their
@@ -649,6 +807,6 @@ function createRelationManager(options) {
649
807
  return new RelationManager(options);
650
808
  }
651
809
  //#endregion
652
- export { Model, RelationError, RelationManager, belongsTo, createRelationManager, hasMany, hasMorph, hasOne, hasThrough, isRelationDescriptor, isRelationError, resolveRelation, resolveRelationMap };
810
+ export { Model, RelationError, RelationManager, belongsTo, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError, readColumn, resolveRelation, resolveRelationMap };
653
811
 
654
812
  //# sourceMappingURL=index.js.map