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