@orkestrel/relation 0.0.5 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/src/core/index.cjs +62 -15
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +17 -15
- package/dist/src/core/index.d.ts +17 -15
- package/dist/src/core/index.js +62 -15
- package/dist/src/core/index.js.map +1 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
A typed **relation manager** over [`@orkestrel/database`](https://github.com/orkestrel/database)
|
|
4
4
|
tables — name a table's relations once, then `load` / `find` records with their
|
|
5
|
-
related rows already attached. Loading is **batched** —
|
|
6
|
-
across the whole record set,
|
|
7
|
-
|
|
5
|
+
related rows already attached. Loading is **batched** — a direct relation uses
|
|
6
|
+
one query across the whole record set, while a `through` relation uses two
|
|
7
|
+
(junction then target); either count stays constant as the parent count grows.
|
|
8
|
+
Five relation kinds
|
|
8
9
|
(`belongs` / `many` / `one` / `through` / `morph`) cover the FK shapes; nested
|
|
9
10
|
includes recurse through the registry; `link` / `unlink` / `links` manage a
|
|
10
11
|
many-to-many junction without hand-writing join rows. Environment-agnostic —
|
package/dist/src/core/index.cjs
CHANGED
|
@@ -250,11 +250,11 @@ function hasMorph(key, tag, label, model) {
|
|
|
250
250
|
* @remarks
|
|
251
251
|
* The model's own table is fully typed (`table`); related tables are reached by
|
|
252
252
|
* runtime name through the database at the broad `Row` type. Loading is batched:
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
* includes recurse through the registry `lookup`, so
|
|
256
|
-
*
|
|
257
|
-
* is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
253
|
+
* a direct relation uses one query for the whole record set, while a `through`
|
|
254
|
+
* relation uses two (junction then target); both counts remain constant regardless
|
|
255
|
+
* of parent count. Nested includes recurse through the registry `lookup`, so each
|
|
256
|
+
* nested level is batched again. Columns are read with `Reflect.get` (the base row's
|
|
257
|
+
* type is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
258
258
|
*
|
|
259
259
|
* @remarks
|
|
260
260
|
* - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
|
|
@@ -313,11 +313,13 @@ var Model = class {
|
|
|
313
313
|
}
|
|
314
314
|
async find(include, options) {
|
|
315
315
|
const query = this.#table.query();
|
|
316
|
-
if (options?.sort !== void 0)
|
|
317
|
-
|
|
316
|
+
if (options?.sort !== void 0) query.order({
|
|
317
|
+
column: options.sort,
|
|
318
|
+
direction: options.direction ?? "ascending"
|
|
319
|
+
});
|
|
318
320
|
if (options?.offset !== void 0) query.offset(options.offset);
|
|
319
321
|
if (options?.limit !== void 0) query.limit(options.limit);
|
|
320
|
-
const records = await query.
|
|
322
|
+
const records = await query.collect();
|
|
321
323
|
const props = await this.#populate(records, include, this.#resolved, this.#table.primary);
|
|
322
324
|
return records.map((record, index) => Object.assign({}, record, props[index]));
|
|
323
325
|
}
|
|
@@ -332,7 +334,17 @@ var Model = class {
|
|
|
332
334
|
async unlink(key, relation, target) {
|
|
333
335
|
const resolved = this.#through(relation);
|
|
334
336
|
const junction = this.#database.table(resolved.through ?? "");
|
|
335
|
-
const rows = await junction.query().
|
|
337
|
+
const rows = await junction.query().condition({
|
|
338
|
+
column: resolved.source ?? "",
|
|
339
|
+
operator: "equals",
|
|
340
|
+
values: [key],
|
|
341
|
+
connector: "and"
|
|
342
|
+
}).condition({
|
|
343
|
+
column: resolved.target ?? "",
|
|
344
|
+
operator: "equals",
|
|
345
|
+
values: [target],
|
|
346
|
+
connector: "and"
|
|
347
|
+
}).collect();
|
|
336
348
|
for (const row of rows) {
|
|
337
349
|
const id = (0, _orkestrel_database.extractKey)(row, junction.primary);
|
|
338
350
|
if (id !== void 0) await junction.remove(id);
|
|
@@ -341,7 +353,12 @@ var Model = class {
|
|
|
341
353
|
}
|
|
342
354
|
async links(key, relation) {
|
|
343
355
|
const resolved = this.#through(relation);
|
|
344
|
-
const rows = await this.#database.table(resolved.through ?? "").query().
|
|
356
|
+
const rows = await this.#database.table(resolved.through ?? "").query().condition({
|
|
357
|
+
column: resolved.source ?? "",
|
|
358
|
+
operator: "equals",
|
|
359
|
+
values: [key],
|
|
360
|
+
connector: "and"
|
|
361
|
+
}).collect();
|
|
345
362
|
const target = resolved.target ?? "";
|
|
346
363
|
const keys = [];
|
|
347
364
|
for (const row of rows) {
|
|
@@ -401,7 +418,12 @@ var Model = class {
|
|
|
401
418
|
const keys = [...new Set(records.map((record) => this.#field(record, column)).filter(_orkestrel_contract.isDefined))];
|
|
402
419
|
if (keys.length === 0) return records.map(() => void 0);
|
|
403
420
|
const related = this.#database.table(resolved.model);
|
|
404
|
-
const rows = await related.query().
|
|
421
|
+
const rows = await related.query().condition({
|
|
422
|
+
column: related.primary,
|
|
423
|
+
operator: "any",
|
|
424
|
+
values: keys,
|
|
425
|
+
connector: "and"
|
|
426
|
+
}).collect();
|
|
405
427
|
const index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary);
|
|
406
428
|
return records.map((record) => {
|
|
407
429
|
const fk = this.#field(record, column);
|
|
@@ -412,7 +434,12 @@ var Model = class {
|
|
|
412
434
|
const foreign = resolved.key ?? "";
|
|
413
435
|
const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
|
|
414
436
|
if (keys.length === 0) return records.map(() => []);
|
|
415
|
-
const rows = await this.#database.table(resolved.model).query().
|
|
437
|
+
const rows = await this.#database.table(resolved.model).query().condition({
|
|
438
|
+
column: foreign,
|
|
439
|
+
operator: "any",
|
|
440
|
+
values: keys,
|
|
441
|
+
connector: "and"
|
|
442
|
+
}).collect();
|
|
416
443
|
const groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign);
|
|
417
444
|
return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
|
|
418
445
|
}
|
|
@@ -424,7 +451,12 @@ var Model = class {
|
|
|
424
451
|
const target = resolved.target ?? "";
|
|
425
452
|
const parents = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
|
|
426
453
|
if (parents.length === 0) return records.map(() => []);
|
|
427
|
-
const junctions = await this.#database.table(resolved.through ?? "").query().
|
|
454
|
+
const junctions = await this.#database.table(resolved.through ?? "").query().condition({
|
|
455
|
+
column: source,
|
|
456
|
+
operator: "any",
|
|
457
|
+
values: parents,
|
|
458
|
+
connector: "and"
|
|
459
|
+
}).collect();
|
|
428
460
|
const targetsBySource = /* @__PURE__ */ new Map();
|
|
429
461
|
for (const junction of junctions) {
|
|
430
462
|
const value = this.#field(junction, target);
|
|
@@ -437,7 +469,12 @@ var Model = class {
|
|
|
437
469
|
const targets = [...new Set([...targetsBySource.values()].flat())];
|
|
438
470
|
if (targets.length === 0) return records.map(() => []);
|
|
439
471
|
const related = this.#database.table(resolved.model);
|
|
440
|
-
const rows = await related.query().
|
|
472
|
+
const rows = await related.query().condition({
|
|
473
|
+
column: related.primary,
|
|
474
|
+
operator: "any",
|
|
475
|
+
values: targets,
|
|
476
|
+
connector: "and"
|
|
477
|
+
}).collect();
|
|
441
478
|
const index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary);
|
|
442
479
|
return records.map((record) => {
|
|
443
480
|
const out = [];
|
|
@@ -452,7 +489,17 @@ var Model = class {
|
|
|
452
489
|
const foreign = resolved.key ?? "";
|
|
453
490
|
const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
|
|
454
491
|
if (keys.length === 0) return records.map(() => []);
|
|
455
|
-
const rows = await this.#database.table(resolved.model).query().
|
|
492
|
+
const rows = await this.#database.table(resolved.model).query().condition({
|
|
493
|
+
column: foreign,
|
|
494
|
+
operator: "any",
|
|
495
|
+
values: keys,
|
|
496
|
+
connector: "and"
|
|
497
|
+
}).condition({
|
|
498
|
+
column: resolved.tag ?? "",
|
|
499
|
+
operator: "equals",
|
|
500
|
+
values: [resolved.label ?? ""],
|
|
501
|
+
connector: "and"
|
|
502
|
+
}).collect();
|
|
456
503
|
const groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign);
|
|
457
504
|
return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
|
|
458
505
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#name","#table","#resolved","#relations","#lookup","#database","#emitter","#populate","#through","#load","#attached","#loadBelongs","#loadMany","#loadOne","#loadThrough","#loadMorph","#field","#index","#nest","#group","#database","#broad","#relations","#resolved","#vend","#context"],"sources":["../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\n\n// AGENTS §12: invalid relation definitions and misuse `throw` a `RelationError`\n// carrying a machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * An error thrown by the relations layer.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * reference to a relation a model does not define (`UNKNOWN_RELATION`), and\n * `link` / `unlink` / `links` on a relation that is not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is a {@link RelationError}\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn value instanceof RelationError\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport { isArray, isDefined, isRecord, isString } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders below set an\n// explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Descriptor guard\n\n/**\n * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a plain record\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\treturn isRecord(value)\n}\n\n// === Resolution\n\n/**\n * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a\n * `many` (FK column on the related table); a {@link RelationDescriptor} uses its\n * explicit `relationship`, or infers it from the fields present. The target model\n * defaults to the relation name. Throws `INVALID` when the relationship cannot be\n * resolved or a required field is missing.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tlet relationship: Relationship\n\tif (value.relationship !== undefined) {\n\t\trelationship = value.relationship\n\t} else if (isDefined(value.through)) {\n\t\trelationship = 'through'\n\t} else if (isDefined(value.tag)) {\n\t\trelationship = 'morph'\n\t} else if (isDefined(value.column)) {\n\t\trelationship = 'belongs'\n\t} else if (isDefined(value.key)) {\n\t\trelationship = 'one'\n\t} else {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\tconst resolved = new Map<string, ResolvedRelation>()\n\tfor (const [name, value] of Object.entries(relations)) {\n\t\tresolved.set(name, resolveRelation(name, value))\n\t}\n\treturn resolved\n}\n\n// === Builders\n\n/**\n * Build a `belongs` relation — a foreign key on THIS table points at the related row.\n *\n * @param column - The FK column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `many` relation — a foreign key on the RELATED table points back here.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction FK column pointing at THIS model\n * @param target - The junction FK column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.\n *\n * @param key - The FK column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying THIS model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type { DatabaseInterface, Key, Row, TableInterface } from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tRelationProps,\n\tResolvedRelation,\n} from './types.js'\nimport { extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isDefined } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n/**\n * A model — a typed table paired with relation-aware loading.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * for each relation, one query fetches the related rows for the whole record set\n * (`where(col).any(keys)`), grouped in memory and attached — no N+1. Nested\n * includes recurse through the registry `lookup`, so loaded relations carry their\n * own loaded relations. Columns are read with `Reflect.get` (the base row's type\n * is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * AFTER the load resolves / the junction op completes; the emitter isolates a listener\n * throw and routes it to its `error` handler (the `error` option), so a buggy observer can\n * never corrupt the batched eager-load (no N+1 in the events either — one `load` per\n * relation, not per record).\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include): Promise<Loaded<T> | undefined>\n\tload(keys: readonly Key[], include: Include): Promise<readonly (Loaded<T> | undefined)[]>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t): Promise<(Loaded<T> | undefined) | readonly (Loaded<T> | undefined)[]> {\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(present, include, this.#resolved, this.#table.primary)\n\t\t\tlet next = 0\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, props[next++]),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate([base], include, this.#resolved, this.#table.primary)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<readonly Loaded<T>[]> {\n\t\tconst query = this.#table.query()\n\t\tif (options?.sort !== undefined) {\n\t\t\tif (options.direction === 'descending') query.descending(options.sort)\n\t\t\telse query.ascending(options.sort)\n\t\t}\n\t\tif (options?.offset !== undefined) query.offset(options.offset)\n\t\tif (options?.limit !== undefined) query.limit(options.limit)\n\t\tconst records = await query.all()\n\t\tconst props = await this.#populate(records, include, this.#resolved, this.#table.primary)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tawait this.#database.table(resolved.through ?? '').set({\n\t\t\t[resolved.source ?? '']: key,\n\t\t\t[resolved.target ?? '']: target,\n\t\t})\n\t\t// Observe the inserted junction row — AFTER the driver write, so a swallowed listener\n\t\t// throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.where(resolved.source ?? '')\n\t\t\t.equals(key)\n\t\t\t.and(resolved.target ?? '')\n\t\t\t.equals(target)\n\t\t\t.all()\n\t\tfor (const row of rows) {\n\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\tif (id !== undefined) await junction.remove(id)\n\t\t}\n\t\t// Observe the removed junction — AFTER every matching row was deleted.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string): Promise<readonly Key[]> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.where(resolved.source ?? '')\n\t\t\t.equals(key)\n\t\t\t.all()\n\t\tconst target = resolved.target ?? ''\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Read a column off any record (the base row's type is closed — no index access).\n\t#field(record: unknown, column: string): unknown {\n\t\tif (typeof record !== 'object' || record === null) return undefined\n\t\treturn Reflect.get(record, column)\n\t}\n\n\t// Resolve a `through` relation by name, or throw a descriptive error.\n\t#through(relation: string): ResolvedRelation {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t): Promise<RelationProps[]> {\n\t\tconst props: RelationProps[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — AFTER it resolved + was attached, ONCE per\n\t\t\t// relation (not per record — the batched load has no N+1, nor do its events),\n\t\t\t// carrying the relation name + the total related rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, this.#attached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// The total related rows a relation's values attached across the record set — an\n\t// array-valued relation (`many` / `through` / `morph`) sums its lengths, a single-\n\t// valued one (`belongs` / `one`) counts each present row. The `load` event's `count`.\n\t#attached(values: readonly (Row | readonly Row[] | undefined)[]): number {\n\t\tlet total = 0\n\t\tfor (const value of values) {\n\t\t\tif (isArray(value)) total += value.length\n\t\t\telse if (value !== undefined) total += 1\n\t\t}\n\t\treturn total\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | readonly Row[] | undefined)[]> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst column = resolved.column ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, column)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.query().where(related.primary).any(keys).all()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = this.#field(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).query().where(foreign).any(keys).all()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst source = resolved.source ?? ''\n\t\tconst target = resolved.target ?? ''\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database\n\t\t\t.table(resolved.through ?? '')\n\t\t\t.query()\n\t\t\t.where(source)\n\t\t\t.any(parents)\n\t\t\t.all()\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = this.#field(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(this.#field(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.query().where(related.primary).any(targets).all()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database\n\t\t\t.table(resolved.model)\n\t\t\t.query()\n\t\t\t.where(foreign)\n\t\t\t.any(keys)\n\t\t\t.and(resolved.tag ?? '')\n\t\t\t.equals(resolved.label ?? '')\n\t\t\t.all()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t): Promise<readonly Row[]> {\n\t\tif (typeof sub === 'boolean' || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n\n\t// Index rows by the string form of a column (for one-to-one key lookups).\n\t#index(rows: readonly Row[], column: string): Map<string, Row> {\n\t\tconst map = new Map<string, Row>()\n\t\tfor (const row of rows) map.set(String(this.#field(row, column)), row)\n\t\treturn map\n\t}\n\n\t// Group rows by the string form of a column (for one-to-many lookups).\n\t#group(rows: readonly Row[], column: string): Map<string, Row[]> {\n\t\tconst map = new Map<string, Row[]>()\n\t\tfor (const row of rows) {\n\t\t\tconst key = String(this.#field(row, column))\n\t\t\tconst group = map.get(key)\n\t\t\tif (group !== undefined) group.push(row)\n\t\t\telse map.set(key, [row])\n\t\t}\n\t\treturn map\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TablesShape } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * The relation registry — resolves a {@link RelationsShape} once at construction\n * and vends a typed {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Relation targets are validated lazily — a relation to a missing\n * table fails when that relation is first loaded.\n */\nexport class RelationManager<\n\tT extends TablesShape = TablesShape,\n> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map !== undefined) this.#resolved.set(name, resolveRelationMap(map))\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tmodels(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TablesShape } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Create a relation manager over a database and its relation definitions.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example\n * ```ts\n * import { createRelationManager, belongsTo, hasMany } from '@src/core'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TablesShape>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;AAQA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,iBAAiB;AACzB;;;;;;;;;ACfA,SAAgB,qBAAqB,OAA6C;CACjF,QAAA,GAAA,oBAAA,SAAA,CAAgB,KAAK;AACtB;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAgB,MAAc,OAAmC;CAChF,KAAA,GAAA,oBAAA,SAAA,CAAa,KAAK,GACjB,OAAO;EAAE,cAAc;EAAW;EAAM,OAAO;EAAM,QAAQ;CAAM;CAEpE,KAAA,GAAA,oBAAA,QAAA,CAAY,KAAK,GAAG;EACnB,MAAM,MAAM,MAAM;EAClB,IAAI,EAAA,GAAA,oBAAA,SAAA,CAAU,GAAG,GAChB,MAAM,IAAI,cACT,WACA,aAAa,KAAK,yCAClB,EACC,UAAU,KACX,CACD;EAED,O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ACpB,OAAO,IAAI,MAAM,MAAM,OAAO,UAAU,YAAY,UAAU,KAAKE,SAAS,KAAK,GAAG,KAAKJ,MAAM;CAChG;CAGA,SAAS,OAA4C;EACpD,MAAM,WAAW,KAAKE,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAKF,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7CA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#name","#table","#resolved","#relations","#lookup","#database","#emitter","#populate","#through","#load","#attached","#loadBelongs","#loadMany","#loadOne","#loadThrough","#loadMorph","#field","#index","#nest","#group","#database","#broad","#relations","#resolved","#vend","#context"],"sources":["../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\n\n// AGENTS §12: invalid relation definitions and misuse `throw` a `RelationError`\n// carrying a machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * An error thrown by the relations layer.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * reference to a relation a model does not define (`UNKNOWN_RELATION`), and\n * `link` / `unlink` / `links` on a relation that is not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is a {@link RelationError}\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn value instanceof RelationError\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport { isArray, isDefined, isRecord, isString } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders below set an\n// explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Descriptor guard\n\n/**\n * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a plain record\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\treturn isRecord(value)\n}\n\n// === Resolution\n\n/**\n * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a\n * `many` (FK column on the related table); a {@link RelationDescriptor} uses its\n * explicit `relationship`, or infers it from the fields present. The target model\n * defaults to the relation name. Throws `INVALID` when the relationship cannot be\n * resolved or a required field is missing.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tlet relationship: Relationship\n\tif (value.relationship !== undefined) {\n\t\trelationship = value.relationship\n\t} else if (isDefined(value.through)) {\n\t\trelationship = 'through'\n\t} else if (isDefined(value.tag)) {\n\t\trelationship = 'morph'\n\t} else if (isDefined(value.column)) {\n\t\trelationship = 'belongs'\n\t} else if (isDefined(value.key)) {\n\t\trelationship = 'one'\n\t} else {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\tconst resolved = new Map<string, ResolvedRelation>()\n\tfor (const [name, value] of Object.entries(relations)) {\n\t\tresolved.set(name, resolveRelation(name, value))\n\t}\n\treturn resolved\n}\n\n// === Builders\n\n/**\n * Build a `belongs` relation — a foreign key on THIS table points at the related row.\n *\n * @param column - The FK column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `many` relation — a foreign key on the RELATED table points back here.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction FK column pointing at THIS model\n * @param target - The junction FK column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.\n *\n * @param key - The FK column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying THIS model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type { DatabaseInterface, Key, Row, TableInterface } from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tRelationProps,\n\tResolvedRelation,\n} from './types.js'\nimport { extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isDefined } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n/**\n * A model — a typed table paired with relation-aware loading.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * a direct relation uses one query for the whole record set, while a `through`\n * relation uses two (junction then target); both counts remain constant regardless\n * of parent count. Nested includes recurse through the registry `lookup`, so each\n * nested level is batched again. Columns are read with `Reflect.get` (the base row's\n * type is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * AFTER the load resolves / the junction op completes; the emitter isolates a listener\n * throw and routes it to its `error` handler (the `error` option), so a buggy observer can\n * never corrupt the batched eager-load (no N+1 in the events either — one `load` per\n * relation, not per record).\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include): Promise<Loaded<T> | undefined>\n\tload(keys: readonly Key[], include: Include): Promise<readonly (Loaded<T> | undefined)[]>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t): Promise<(Loaded<T> | undefined) | readonly (Loaded<T> | undefined)[]> {\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(present, include, this.#resolved, this.#table.primary)\n\t\t\tlet next = 0\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, props[next++]),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate([base], include, this.#resolved, this.#table.primary)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<readonly Loaded<T>[]> {\n\t\tconst query = this.#table.query()\n\t\tif (options?.sort !== undefined) {\n\t\t\tquery.order({\n\t\t\t\tcolumn: options.sort,\n\t\t\t\tdirection: options.direction ?? 'ascending',\n\t\t\t})\n\t\t}\n\t\tif (options?.offset !== undefined) query.offset(options.offset)\n\t\tif (options?.limit !== undefined) query.limit(options.limit)\n\t\tconst records = await query.collect()\n\t\tconst props = await this.#populate(records, include, this.#resolved, this.#table.primary)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tawait this.#database.table(resolved.through ?? '').set({\n\t\t\t[resolved.source ?? '']: key,\n\t\t\t[resolved.target ?? '']: target,\n\t\t})\n\t\t// Observe the inserted junction row — AFTER the driver write, so a swallowed listener\n\t\t// throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.source ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [key],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.target ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [target],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tfor (const row of rows) {\n\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\tif (id !== undefined) await junction.remove(id)\n\t\t}\n\t\t// Observe the removed junction — AFTER every matching row was deleted.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string): Promise<readonly Key[]> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.source ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [key],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst target = resolved.target ?? ''\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Read a column off any record (the base row's type is closed — no index access).\n\t#field(record: unknown, column: string): unknown {\n\t\tif (typeof record !== 'object' || record === null) return undefined\n\t\treturn Reflect.get(record, column)\n\t}\n\n\t// Resolve a `through` relation by name, or throw a descriptive error.\n\t#through(relation: string): ResolvedRelation {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t): Promise<RelationProps[]> {\n\t\tconst props: RelationProps[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — AFTER it resolved + was attached, ONCE per\n\t\t\t// relation (not per record — the batched load has no N+1, nor do its events),\n\t\t\t// carrying the relation name + the total related rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, this.#attached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// The total related rows a relation's values attached across the record set — an\n\t// array-valued relation (`many` / `through` / `morph`) sums its lengths, a single-\n\t// valued one (`belongs` / `one`) counts each present row. The `load` event's `count`.\n\t#attached(values: readonly (Row | readonly Row[] | undefined)[]): number {\n\t\tlet total = 0\n\t\tfor (const value of values) {\n\t\t\tif (isArray(value)) total += value.length\n\t\t\telse if (value !== undefined) total += 1\n\t\t}\n\t\treturn total\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | readonly Row[] | undefined)[]> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst column = resolved.column ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, column)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: related.primary,\n\t\t\t\toperator: 'any',\n\t\t\t\tvalues: keys,\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = this.#field(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database\n\t\t\t.table(resolved.model)\n\t\t\t.query()\n\t\t\t.condition({ column: foreign, operator: 'any', values: keys, connector: 'and' })\n\t\t\t.collect()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst source = resolved.source ?? ''\n\t\tconst target = resolved.target ?? ''\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database\n\t\t\t.table(resolved.through ?? '')\n\t\t\t.query()\n\t\t\t.condition({ column: source, operator: 'any', values: parents, connector: 'and' })\n\t\t\t.collect()\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = this.#field(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(this.#field(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: related.primary,\n\t\t\t\toperator: 'any',\n\t\t\t\tvalues: targets,\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database\n\t\t\t.table(resolved.model)\n\t\t\t.query()\n\t\t\t.condition({ column: foreign, operator: 'any', values: keys, connector: 'and' })\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.tag ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [resolved.label ?? ''],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t): Promise<readonly Row[]> {\n\t\tif (typeof sub === 'boolean' || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n\n\t// Index rows by the string form of a column (for one-to-one key lookups).\n\t#index(rows: readonly Row[], column: string): Map<string, Row> {\n\t\tconst map = new Map<string, Row>()\n\t\tfor (const row of rows) map.set(String(this.#field(row, column)), row)\n\t\treturn map\n\t}\n\n\t// Group rows by the string form of a column (for one-to-many lookups).\n\t#group(rows: readonly Row[], column: string): Map<string, Row[]> {\n\t\tconst map = new Map<string, Row[]>()\n\t\tfor (const row of rows) {\n\t\t\tconst key = String(this.#field(row, column))\n\t\t\tconst group = map.get(key)\n\t\t\tif (group !== undefined) group.push(row)\n\t\t\telse map.set(key, [row])\n\t\t}\n\t\treturn map\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TableMap } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * The relation registry — resolves a {@link RelationsShape} once at construction\n * and vends a typed {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Relation targets are validated lazily — a relation to a missing\n * table fails when that relation is first loaded.\n */\nexport class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map !== undefined) this.#resolved.set(name, resolveRelationMap(map))\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tmodels(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TableMap } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Create a relation manager over a database and its relation definitions.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example\n * ```ts\n * import { createRelationManager, belongsTo, hasMany } from '@src/core'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TableMap>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;AAQA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,iBAAiB;AACzB;;;;;;;;;ACfA,SAAgB,qBAAqB,OAA6C;CACjF,QAAA,GAAO,oBAAA,SAAA,CAAS,KAAK;AACtB;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAgB,MAAc,OAAmC;CAChF,KAAA,GAAI,oBAAA,SAAA,CAAS,KAAK,GACjB,OAAO;EAAE,cAAc;EAAW;EAAM,OAAO;EAAM,QAAQ;CAAM;CAEpE,KAAA,GAAI,oBAAA,QAAA,CAAQ,KAAK,GAAG;EACnB,MAAM,MAAM,MAAM;EAClB,IAAI,EAAA,GAAC,oBAAA,SAAA,CAAS,GAAG,GAChB,MAAM,IAAI,cACT,WACA,aAAa,KAAK,yCAClB,EACC,UAAU,KACX,CACD;EAED,OAAO;GAAE,cAAc;GAAQ;GAAM,OAAO;GAAM;EAAI;CACvD;CACA,IAAI,CAAC,qBAAqB,KAAK,GAC9B,MAAM,IAAI,cAAc,WAAW,aAAa,KAAK,wCAAwC,EAC5F,UAAU,KACX,CAAC;CAGF,MAAM,QAAQ,MAAM,SAAS;CAE7B,IAAI;CACJ,IAAI,MAAM,iBAAiB,KAAA,GAC1B,eAAe,MAAM;MACf,KAAA,GAAI,oBAAA,UAAA,CAAU,MAAM,OAAO,GACjC,eAAe;MACT,KAAA,GAAI,oBAAA,UAAA,CAAU,MAAM,GAAG,GAC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E,SAAS,KAAK,GAAG,KAAKJ,MAAM;CAChG;CAGA,SAAS,OAA4C;EACpD,MAAM,WAAW,KAAKE,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAKF,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC3CA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { DatabaseInterface } from '@orkestrel/database';
|
|
2
|
-
import { Direction } from '@orkestrel/database';
|
|
3
2
|
import { EmitterErrorHandler } from '@orkestrel/emitter';
|
|
4
3
|
import { EmitterHooks } from '@orkestrel/emitter';
|
|
5
4
|
import { EmitterInterface } from '@orkestrel/emitter';
|
|
6
5
|
import { Key } from '@orkestrel/database';
|
|
6
|
+
import { OrderDirection } from '@orkestrel/database';
|
|
7
7
|
import { Row } from '@orkestrel/database';
|
|
8
8
|
import { RowOf } from '@orkestrel/database';
|
|
9
9
|
import { TableInterface } from '@orkestrel/database';
|
|
10
|
-
import {
|
|
10
|
+
import { TableMap } from '@orkestrel/database';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Build a `belongs` relation — a foreign key on THIS table points at the related row.
|
|
@@ -49,14 +49,15 @@ export declare function belongsTo(column: string, model?: string): RelationDescr
|
|
|
49
49
|
* const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
|
|
50
50
|
* ```
|
|
51
51
|
*/
|
|
52
|
-
export declare function createRelationManager<T extends
|
|
52
|
+
export declare function createRelationManager<T extends TableMap>(options: RelationManagerOptions<T>): RelationManagerInterface<T>;
|
|
53
53
|
|
|
54
54
|
/** Pagination and ordering for `find`. */
|
|
55
55
|
export declare interface FindOptions {
|
|
56
56
|
readonly limit?: number;
|
|
57
57
|
readonly offset?: number;
|
|
58
58
|
readonly sort?: string;
|
|
59
|
-
|
|
59
|
+
/** The sort direction; defaults to `ascending` when {@link sort} is present. */
|
|
60
|
+
readonly direction?: OrderDirection;
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
/**
|
|
@@ -158,11 +159,11 @@ export declare type Loaded<T> = T & Readonly<RelationProps>;
|
|
|
158
159
|
* @remarks
|
|
159
160
|
* The model's own table is fully typed (`table`); related tables are reached by
|
|
160
161
|
* runtime name through the database at the broad `Row` type. Loading is batched:
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
* includes recurse through the registry `lookup`, so
|
|
164
|
-
*
|
|
165
|
-
* is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
162
|
+
* a direct relation uses one query for the whole record set, while a `through`
|
|
163
|
+
* relation uses two (junction then target); both counts remain constant regardless
|
|
164
|
+
* of parent count. Nested includes recurse through the registry `lookup`, so each
|
|
165
|
+
* nested level is batched again. Columns are read with `Reflect.get` (the base row's
|
|
166
|
+
* type is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
166
167
|
*
|
|
167
168
|
* @remarks
|
|
168
169
|
* - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
|
|
@@ -229,8 +230,9 @@ export declare type ModelEventMap<TKey extends Key = Key> = {
|
|
|
229
230
|
* Table operations are reached through `table` (a fully typed
|
|
230
231
|
* {@link TableInterface}); relation loading and through management are on the
|
|
231
232
|
* model itself. `load` fetches one record with its relations populated; `find`
|
|
232
|
-
* fetches many; both batch-load (one query per relation
|
|
233
|
-
* size). `link` / `unlink` / `links` manage a
|
|
233
|
+
* fetches many; both batch-load (one query per direct relation or two per
|
|
234
|
+
* `through`, regardless of result size). `link` / `unlink` / `links` manage a
|
|
235
|
+
* `through` relation's junction rows.
|
|
234
236
|
* Exposes a typed {@link emitter} (AGENTS §13) carrying the eager-load + junction
|
|
235
237
|
* moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
|
|
236
238
|
* observation-only (a swallowed listener throw can never corrupt the batched load).
|
|
@@ -323,7 +325,7 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
|
|
|
323
325
|
* while loading). Relation targets are validated lazily — a relation to a missing
|
|
324
326
|
* table fails when that relation is first loaded.
|
|
325
327
|
*/
|
|
326
|
-
export declare class RelationManager<T extends
|
|
328
|
+
export declare class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {
|
|
327
329
|
#private;
|
|
328
330
|
constructor(options: RelationManagerOptions<T>);
|
|
329
331
|
get count(): number;
|
|
@@ -340,7 +342,7 @@ export declare class RelationManager<T extends TablesShape = TablesShape> implem
|
|
|
340
342
|
* at construction. `model(name)` returns the model for a declared table, typed by
|
|
341
343
|
* that table's row. Follows the manager accessor pattern (`model` / `models`).
|
|
342
344
|
*/
|
|
343
|
-
export declare interface RelationManagerInterface<T extends
|
|
345
|
+
export declare interface RelationManagerInterface<T extends TableMap = TableMap> {
|
|
344
346
|
readonly count: number;
|
|
345
347
|
model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
|
|
346
348
|
models(): readonly string[];
|
|
@@ -348,7 +350,7 @@ export declare interface RelationManagerInterface<T extends TablesShape = Tables
|
|
|
348
350
|
}
|
|
349
351
|
|
|
350
352
|
/** Options for `createRelationManager`. */
|
|
351
|
-
export declare interface RelationManagerOptions<T extends
|
|
353
|
+
export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
|
|
352
354
|
/**
|
|
353
355
|
* The database to build the registry over.
|
|
354
356
|
*
|
|
@@ -395,7 +397,7 @@ export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'mor
|
|
|
395
397
|
* Keys are constrained to the database's declared table names, so relations can
|
|
396
398
|
* only be defined for tables that exist. A table may be omitted (no relations).
|
|
397
399
|
*/
|
|
398
|
-
export declare type RelationsShape<T extends
|
|
400
|
+
export declare type RelationsShape<T extends TableMap = TableMap> = {
|
|
399
401
|
readonly [K in keyof T]?: RelationMap;
|
|
400
402
|
};
|
|
401
403
|
|
package/dist/src/core/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { DatabaseInterface } from '@orkestrel/database';
|
|
2
|
-
import { Direction } from '@orkestrel/database';
|
|
3
2
|
import { EmitterErrorHandler } from '@orkestrel/emitter';
|
|
4
3
|
import { EmitterHooks } from '@orkestrel/emitter';
|
|
5
4
|
import { EmitterInterface } from '@orkestrel/emitter';
|
|
6
5
|
import { Key } from '@orkestrel/database';
|
|
6
|
+
import { OrderDirection } from '@orkestrel/database';
|
|
7
7
|
import { Row } from '@orkestrel/database';
|
|
8
8
|
import { RowOf } from '@orkestrel/database';
|
|
9
9
|
import { TableInterface } from '@orkestrel/database';
|
|
10
|
-
import {
|
|
10
|
+
import { TableMap } from '@orkestrel/database';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Build a `belongs` relation — a foreign key on THIS table points at the related row.
|
|
@@ -49,14 +49,15 @@ export declare function belongsTo(column: string, model?: string): RelationDescr
|
|
|
49
49
|
* const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
|
|
50
50
|
* ```
|
|
51
51
|
*/
|
|
52
|
-
export declare function createRelationManager<T extends
|
|
52
|
+
export declare function createRelationManager<T extends TableMap>(options: RelationManagerOptions<T>): RelationManagerInterface<T>;
|
|
53
53
|
|
|
54
54
|
/** Pagination and ordering for `find`. */
|
|
55
55
|
export declare interface FindOptions {
|
|
56
56
|
readonly limit?: number;
|
|
57
57
|
readonly offset?: number;
|
|
58
58
|
readonly sort?: string;
|
|
59
|
-
|
|
59
|
+
/** The sort direction; defaults to `ascending` when {@link sort} is present. */
|
|
60
|
+
readonly direction?: OrderDirection;
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
/**
|
|
@@ -158,11 +159,11 @@ export declare type Loaded<T> = T & Readonly<RelationProps>;
|
|
|
158
159
|
* @remarks
|
|
159
160
|
* The model's own table is fully typed (`table`); related tables are reached by
|
|
160
161
|
* runtime name through the database at the broad `Row` type. Loading is batched:
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
* includes recurse through the registry `lookup`, so
|
|
164
|
-
*
|
|
165
|
-
* is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
162
|
+
* a direct relation uses one query for the whole record set, while a `through`
|
|
163
|
+
* relation uses two (junction then target); both counts remain constant regardless
|
|
164
|
+
* of parent count. Nested includes recurse through the registry `lookup`, so each
|
|
165
|
+
* nested level is batched again. Columns are read with `Reflect.get` (the base row's
|
|
166
|
+
* type is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
166
167
|
*
|
|
167
168
|
* @remarks
|
|
168
169
|
* - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
|
|
@@ -229,8 +230,9 @@ export declare type ModelEventMap<TKey extends Key = Key> = {
|
|
|
229
230
|
* Table operations are reached through `table` (a fully typed
|
|
230
231
|
* {@link TableInterface}); relation loading and through management are on the
|
|
231
232
|
* model itself. `load` fetches one record with its relations populated; `find`
|
|
232
|
-
* fetches many; both batch-load (one query per relation
|
|
233
|
-
* size). `link` / `unlink` / `links` manage a
|
|
233
|
+
* fetches many; both batch-load (one query per direct relation or two per
|
|
234
|
+
* `through`, regardless of result size). `link` / `unlink` / `links` manage a
|
|
235
|
+
* `through` relation's junction rows.
|
|
234
236
|
* Exposes a typed {@link emitter} (AGENTS §13) carrying the eager-load + junction
|
|
235
237
|
* moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
|
|
236
238
|
* observation-only (a swallowed listener throw can never corrupt the batched load).
|
|
@@ -323,7 +325,7 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
|
|
|
323
325
|
* while loading). Relation targets are validated lazily — a relation to a missing
|
|
324
326
|
* table fails when that relation is first loaded.
|
|
325
327
|
*/
|
|
326
|
-
export declare class RelationManager<T extends
|
|
328
|
+
export declare class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {
|
|
327
329
|
#private;
|
|
328
330
|
constructor(options: RelationManagerOptions<T>);
|
|
329
331
|
get count(): number;
|
|
@@ -340,7 +342,7 @@ export declare class RelationManager<T extends TablesShape = TablesShape> implem
|
|
|
340
342
|
* at construction. `model(name)` returns the model for a declared table, typed by
|
|
341
343
|
* that table's row. Follows the manager accessor pattern (`model` / `models`).
|
|
342
344
|
*/
|
|
343
|
-
export declare interface RelationManagerInterface<T extends
|
|
345
|
+
export declare interface RelationManagerInterface<T extends TableMap = TableMap> {
|
|
344
346
|
readonly count: number;
|
|
345
347
|
model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
|
|
346
348
|
models(): readonly string[];
|
|
@@ -348,7 +350,7 @@ export declare interface RelationManagerInterface<T extends TablesShape = Tables
|
|
|
348
350
|
}
|
|
349
351
|
|
|
350
352
|
/** Options for `createRelationManager`. */
|
|
351
|
-
export declare interface RelationManagerOptions<T extends
|
|
353
|
+
export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
|
|
352
354
|
/**
|
|
353
355
|
* The database to build the registry over.
|
|
354
356
|
*
|
|
@@ -395,7 +397,7 @@ export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'mor
|
|
|
395
397
|
* Keys are constrained to the database's declared table names, so relations can
|
|
396
398
|
* only be defined for tables that exist. A table may be omitted (no relations).
|
|
397
399
|
*/
|
|
398
|
-
export declare type RelationsShape<T extends
|
|
400
|
+
export declare type RelationsShape<T extends TableMap = TableMap> = {
|
|
399
401
|
readonly [K in keyof T]?: RelationMap;
|
|
400
402
|
};
|
|
401
403
|
|
package/dist/src/core/index.js
CHANGED
|
@@ -249,11 +249,11 @@ function hasMorph(key, tag, label, model) {
|
|
|
249
249
|
* @remarks
|
|
250
250
|
* The model's own table is fully typed (`table`); related tables are reached by
|
|
251
251
|
* runtime name through the database at the broad `Row` type. Loading is batched:
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
* includes recurse through the registry `lookup`, so
|
|
255
|
-
*
|
|
256
|
-
* is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
252
|
+
* a direct relation uses one query for the whole record set, while a `through`
|
|
253
|
+
* relation uses two (junction then target); both counts remain constant regardless
|
|
254
|
+
* of parent count. Nested includes recurse through the registry `lookup`, so each
|
|
255
|
+
* nested level is batched again. Columns are read with `Reflect.get` (the base row's
|
|
256
|
+
* type is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
257
257
|
*
|
|
258
258
|
* @remarks
|
|
259
259
|
* - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
|
|
@@ -312,11 +312,13 @@ var Model = class {
|
|
|
312
312
|
}
|
|
313
313
|
async find(include, options) {
|
|
314
314
|
const query = this.#table.query();
|
|
315
|
-
if (options?.sort !== void 0)
|
|
316
|
-
|
|
315
|
+
if (options?.sort !== void 0) query.order({
|
|
316
|
+
column: options.sort,
|
|
317
|
+
direction: options.direction ?? "ascending"
|
|
318
|
+
});
|
|
317
319
|
if (options?.offset !== void 0) query.offset(options.offset);
|
|
318
320
|
if (options?.limit !== void 0) query.limit(options.limit);
|
|
319
|
-
const records = await query.
|
|
321
|
+
const records = await query.collect();
|
|
320
322
|
const props = await this.#populate(records, include, this.#resolved, this.#table.primary);
|
|
321
323
|
return records.map((record, index) => Object.assign({}, record, props[index]));
|
|
322
324
|
}
|
|
@@ -331,7 +333,17 @@ var Model = class {
|
|
|
331
333
|
async unlink(key, relation, target) {
|
|
332
334
|
const resolved = this.#through(relation);
|
|
333
335
|
const junction = this.#database.table(resolved.through ?? "");
|
|
334
|
-
const rows = await junction.query().
|
|
336
|
+
const rows = await junction.query().condition({
|
|
337
|
+
column: resolved.source ?? "",
|
|
338
|
+
operator: "equals",
|
|
339
|
+
values: [key],
|
|
340
|
+
connector: "and"
|
|
341
|
+
}).condition({
|
|
342
|
+
column: resolved.target ?? "",
|
|
343
|
+
operator: "equals",
|
|
344
|
+
values: [target],
|
|
345
|
+
connector: "and"
|
|
346
|
+
}).collect();
|
|
335
347
|
for (const row of rows) {
|
|
336
348
|
const id = extractKey(row, junction.primary);
|
|
337
349
|
if (id !== void 0) await junction.remove(id);
|
|
@@ -340,7 +352,12 @@ var Model = class {
|
|
|
340
352
|
}
|
|
341
353
|
async links(key, relation) {
|
|
342
354
|
const resolved = this.#through(relation);
|
|
343
|
-
const rows = await this.#database.table(resolved.through ?? "").query().
|
|
355
|
+
const rows = await this.#database.table(resolved.through ?? "").query().condition({
|
|
356
|
+
column: resolved.source ?? "",
|
|
357
|
+
operator: "equals",
|
|
358
|
+
values: [key],
|
|
359
|
+
connector: "and"
|
|
360
|
+
}).collect();
|
|
344
361
|
const target = resolved.target ?? "";
|
|
345
362
|
const keys = [];
|
|
346
363
|
for (const row of rows) {
|
|
@@ -400,7 +417,12 @@ var Model = class {
|
|
|
400
417
|
const keys = [...new Set(records.map((record) => this.#field(record, column)).filter(isDefined))];
|
|
401
418
|
if (keys.length === 0) return records.map(() => void 0);
|
|
402
419
|
const related = this.#database.table(resolved.model);
|
|
403
|
-
const rows = await related.query().
|
|
420
|
+
const rows = await related.query().condition({
|
|
421
|
+
column: related.primary,
|
|
422
|
+
operator: "any",
|
|
423
|
+
values: keys,
|
|
424
|
+
connector: "and"
|
|
425
|
+
}).collect();
|
|
404
426
|
const index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary);
|
|
405
427
|
return records.map((record) => {
|
|
406
428
|
const fk = this.#field(record, column);
|
|
@@ -411,7 +433,12 @@ var Model = class {
|
|
|
411
433
|
const foreign = resolved.key ?? "";
|
|
412
434
|
const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
|
|
413
435
|
if (keys.length === 0) return records.map(() => []);
|
|
414
|
-
const rows = await this.#database.table(resolved.model).query().
|
|
436
|
+
const rows = await this.#database.table(resolved.model).query().condition({
|
|
437
|
+
column: foreign,
|
|
438
|
+
operator: "any",
|
|
439
|
+
values: keys,
|
|
440
|
+
connector: "and"
|
|
441
|
+
}).collect();
|
|
415
442
|
const groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign);
|
|
416
443
|
return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
|
|
417
444
|
}
|
|
@@ -423,7 +450,12 @@ var Model = class {
|
|
|
423
450
|
const target = resolved.target ?? "";
|
|
424
451
|
const parents = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
|
|
425
452
|
if (parents.length === 0) return records.map(() => []);
|
|
426
|
-
const junctions = await this.#database.table(resolved.through ?? "").query().
|
|
453
|
+
const junctions = await this.#database.table(resolved.through ?? "").query().condition({
|
|
454
|
+
column: source,
|
|
455
|
+
operator: "any",
|
|
456
|
+
values: parents,
|
|
457
|
+
connector: "and"
|
|
458
|
+
}).collect();
|
|
427
459
|
const targetsBySource = /* @__PURE__ */ new Map();
|
|
428
460
|
for (const junction of junctions) {
|
|
429
461
|
const value = this.#field(junction, target);
|
|
@@ -436,7 +468,12 @@ var Model = class {
|
|
|
436
468
|
const targets = [...new Set([...targetsBySource.values()].flat())];
|
|
437
469
|
if (targets.length === 0) return records.map(() => []);
|
|
438
470
|
const related = this.#database.table(resolved.model);
|
|
439
|
-
const rows = await related.query().
|
|
471
|
+
const rows = await related.query().condition({
|
|
472
|
+
column: related.primary,
|
|
473
|
+
operator: "any",
|
|
474
|
+
values: targets,
|
|
475
|
+
connector: "and"
|
|
476
|
+
}).collect();
|
|
440
477
|
const index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary);
|
|
441
478
|
return records.map((record) => {
|
|
442
479
|
const out = [];
|
|
@@ -451,7 +488,17 @@ var Model = class {
|
|
|
451
488
|
const foreign = resolved.key ?? "";
|
|
452
489
|
const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
|
|
453
490
|
if (keys.length === 0) return records.map(() => []);
|
|
454
|
-
const rows = await this.#database.table(resolved.model).query().
|
|
491
|
+
const rows = await this.#database.table(resolved.model).query().condition({
|
|
492
|
+
column: foreign,
|
|
493
|
+
operator: "any",
|
|
494
|
+
values: keys,
|
|
495
|
+
connector: "and"
|
|
496
|
+
}).condition({
|
|
497
|
+
column: resolved.tag ?? "",
|
|
498
|
+
operator: "equals",
|
|
499
|
+
values: [resolved.label ?? ""],
|
|
500
|
+
connector: "and"
|
|
501
|
+
}).collect();
|
|
455
502
|
const groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign);
|
|
456
503
|
return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
|
|
457
504
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#name","#table","#resolved","#relations","#lookup","#database","#emitter","#populate","#through","#load","#attached","#loadBelongs","#loadMany","#loadOne","#loadThrough","#loadMorph","#field","#index","#nest","#group","#database","#broad","#relations","#resolved","#vend","#context"],"sources":["../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\n\n// AGENTS §12: invalid relation definitions and misuse `throw` a `RelationError`\n// carrying a machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * An error thrown by the relations layer.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * reference to a relation a model does not define (`UNKNOWN_RELATION`), and\n * `link` / `unlink` / `links` on a relation that is not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is a {@link RelationError}\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn value instanceof RelationError\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport { isArray, isDefined, isRecord, isString } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders below set an\n// explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Descriptor guard\n\n/**\n * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a plain record\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\treturn isRecord(value)\n}\n\n// === Resolution\n\n/**\n * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a\n * `many` (FK column on the related table); a {@link RelationDescriptor} uses its\n * explicit `relationship`, or infers it from the fields present. The target model\n * defaults to the relation name. Throws `INVALID` when the relationship cannot be\n * resolved or a required field is missing.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tlet relationship: Relationship\n\tif (value.relationship !== undefined) {\n\t\trelationship = value.relationship\n\t} else if (isDefined(value.through)) {\n\t\trelationship = 'through'\n\t} else if (isDefined(value.tag)) {\n\t\trelationship = 'morph'\n\t} else if (isDefined(value.column)) {\n\t\trelationship = 'belongs'\n\t} else if (isDefined(value.key)) {\n\t\trelationship = 'one'\n\t} else {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\tconst resolved = new Map<string, ResolvedRelation>()\n\tfor (const [name, value] of Object.entries(relations)) {\n\t\tresolved.set(name, resolveRelation(name, value))\n\t}\n\treturn resolved\n}\n\n// === Builders\n\n/**\n * Build a `belongs` relation — a foreign key on THIS table points at the related row.\n *\n * @param column - The FK column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `many` relation — a foreign key on the RELATED table points back here.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction FK column pointing at THIS model\n * @param target - The junction FK column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.\n *\n * @param key - The FK column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying THIS model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type { DatabaseInterface, Key, Row, TableInterface } from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tRelationProps,\n\tResolvedRelation,\n} from './types.js'\nimport { extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isDefined } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n/**\n * A model — a typed table paired with relation-aware loading.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * for each relation, one query fetches the related rows for the whole record set\n * (`where(col).any(keys)`), grouped in memory and attached — no N+1. Nested\n * includes recurse through the registry `lookup`, so loaded relations carry their\n * own loaded relations. Columns are read with `Reflect.get` (the base row's type\n * is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * AFTER the load resolves / the junction op completes; the emitter isolates a listener\n * throw and routes it to its `error` handler (the `error` option), so a buggy observer can\n * never corrupt the batched eager-load (no N+1 in the events either — one `load` per\n * relation, not per record).\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include): Promise<Loaded<T> | undefined>\n\tload(keys: readonly Key[], include: Include): Promise<readonly (Loaded<T> | undefined)[]>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t): Promise<(Loaded<T> | undefined) | readonly (Loaded<T> | undefined)[]> {\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(present, include, this.#resolved, this.#table.primary)\n\t\t\tlet next = 0\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, props[next++]),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate([base], include, this.#resolved, this.#table.primary)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<readonly Loaded<T>[]> {\n\t\tconst query = this.#table.query()\n\t\tif (options?.sort !== undefined) {\n\t\t\tif (options.direction === 'descending') query.descending(options.sort)\n\t\t\telse query.ascending(options.sort)\n\t\t}\n\t\tif (options?.offset !== undefined) query.offset(options.offset)\n\t\tif (options?.limit !== undefined) query.limit(options.limit)\n\t\tconst records = await query.all()\n\t\tconst props = await this.#populate(records, include, this.#resolved, this.#table.primary)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tawait this.#database.table(resolved.through ?? '').set({\n\t\t\t[resolved.source ?? '']: key,\n\t\t\t[resolved.target ?? '']: target,\n\t\t})\n\t\t// Observe the inserted junction row — AFTER the driver write, so a swallowed listener\n\t\t// throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.where(resolved.source ?? '')\n\t\t\t.equals(key)\n\t\t\t.and(resolved.target ?? '')\n\t\t\t.equals(target)\n\t\t\t.all()\n\t\tfor (const row of rows) {\n\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\tif (id !== undefined) await junction.remove(id)\n\t\t}\n\t\t// Observe the removed junction — AFTER every matching row was deleted.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string): Promise<readonly Key[]> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.where(resolved.source ?? '')\n\t\t\t.equals(key)\n\t\t\t.all()\n\t\tconst target = resolved.target ?? ''\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Read a column off any record (the base row's type is closed — no index access).\n\t#field(record: unknown, column: string): unknown {\n\t\tif (typeof record !== 'object' || record === null) return undefined\n\t\treturn Reflect.get(record, column)\n\t}\n\n\t// Resolve a `through` relation by name, or throw a descriptive error.\n\t#through(relation: string): ResolvedRelation {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t): Promise<RelationProps[]> {\n\t\tconst props: RelationProps[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — AFTER it resolved + was attached, ONCE per\n\t\t\t// relation (not per record — the batched load has no N+1, nor do its events),\n\t\t\t// carrying the relation name + the total related rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, this.#attached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// The total related rows a relation's values attached across the record set — an\n\t// array-valued relation (`many` / `through` / `morph`) sums its lengths, a single-\n\t// valued one (`belongs` / `one`) counts each present row. The `load` event's `count`.\n\t#attached(values: readonly (Row | readonly Row[] | undefined)[]): number {\n\t\tlet total = 0\n\t\tfor (const value of values) {\n\t\t\tif (isArray(value)) total += value.length\n\t\t\telse if (value !== undefined) total += 1\n\t\t}\n\t\treturn total\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | readonly Row[] | undefined)[]> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst column = resolved.column ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, column)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.query().where(related.primary).any(keys).all()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = this.#field(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).query().where(foreign).any(keys).all()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst source = resolved.source ?? ''\n\t\tconst target = resolved.target ?? ''\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database\n\t\t\t.table(resolved.through ?? '')\n\t\t\t.query()\n\t\t\t.where(source)\n\t\t\t.any(parents)\n\t\t\t.all()\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = this.#field(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(this.#field(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.query().where(related.primary).any(targets).all()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database\n\t\t\t.table(resolved.model)\n\t\t\t.query()\n\t\t\t.where(foreign)\n\t\t\t.any(keys)\n\t\t\t.and(resolved.tag ?? '')\n\t\t\t.equals(resolved.label ?? '')\n\t\t\t.all()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t): Promise<readonly Row[]> {\n\t\tif (typeof sub === 'boolean' || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n\n\t// Index rows by the string form of a column (for one-to-one key lookups).\n\t#index(rows: readonly Row[], column: string): Map<string, Row> {\n\t\tconst map = new Map<string, Row>()\n\t\tfor (const row of rows) map.set(String(this.#field(row, column)), row)\n\t\treturn map\n\t}\n\n\t// Group rows by the string form of a column (for one-to-many lookups).\n\t#group(rows: readonly Row[], column: string): Map<string, Row[]> {\n\t\tconst map = new Map<string, Row[]>()\n\t\tfor (const row of rows) {\n\t\t\tconst key = String(this.#field(row, column))\n\t\t\tconst group = map.get(key)\n\t\t\tif (group !== undefined) group.push(row)\n\t\t\telse map.set(key, [row])\n\t\t}\n\t\treturn map\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TablesShape } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * The relation registry — resolves a {@link RelationsShape} once at construction\n * and vends a typed {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Relation targets are validated lazily — a relation to a missing\n * table fails when that relation is first loaded.\n */\nexport class RelationManager<\n\tT extends TablesShape = TablesShape,\n> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map !== undefined) this.#resolved.set(name, resolveRelationMap(map))\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tmodels(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TablesShape } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Create a relation manager over a database and its relation definitions.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example\n * ```ts\n * import { createRelationManager, belongsTo, hasMany } from '@src/core'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TablesShape>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;AAQA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,iBAAiB;AACzB;;;;;;;;;ACfA,SAAgB,qBAAqB,OAA6C;CACjF,OAAO,SAAS,KAAK;AACtB;;;;;;;;;;;;;;;AAkBA,SAAgB,gBAAgB,MAAc,OAAmC;CAChF,IAAI,SAAS,KAAK,GACjB,OAAO;EAAE,cAAc;EAAW;EAAM,OAAO;EAAM,QAAQ;CAAM;CAEpE,IAAI,QAAQ,KAAK,GAAG;EACnB,MAAM,MAAM,MAAM;EAClB,IAAI,CAAC,SAAS,GAAG,GAChB,MAAM,IAAI,cACT,WACA,aAAa,KAAK,yCACl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C,OAAO;GAAE;GAAU,SAAS,KAAKF,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7CA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#name","#table","#resolved","#relations","#lookup","#database","#emitter","#populate","#through","#load","#attached","#loadBelongs","#loadMany","#loadOne","#loadThrough","#loadMorph","#field","#index","#nest","#group","#database","#broad","#relations","#resolved","#vend","#context"],"sources":["../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\n\n// AGENTS §12: invalid relation definitions and misuse `throw` a `RelationError`\n// carrying a machine-readable `code`, so a `catch` branches on `error.code`.\n\n/**\n * An error thrown by the relations layer.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * reference to a relation a model does not define (`UNKNOWN_RELATION`), and\n * `link` / `unlink` / `links` on a relation that is not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrow an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is a {@link RelationError}\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn value instanceof RelationError\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport { isArray, isDefined, isRecord, isString } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders below set an\n// explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Descriptor guard\n\n/**\n * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @param value - The value to test\n * @returns `true` when `value` is a plain record\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\treturn isRecord(value)\n}\n\n// === Resolution\n\n/**\n * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a\n * `many` (FK column on the related table); a {@link RelationDescriptor} uses its\n * explicit `relationship`, or infers it from the fields present. The target model\n * defaults to the relation name. Throws `INVALID` when the relationship cannot be\n * resolved or a required field is missing.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tlet relationship: Relationship\n\tif (value.relationship !== undefined) {\n\t\trelationship = value.relationship\n\t} else if (isDefined(value.through)) {\n\t\trelationship = 'through'\n\t} else if (isDefined(value.tag)) {\n\t\trelationship = 'morph'\n\t} else if (isDefined(value.column)) {\n\t\trelationship = 'belongs'\n\t} else if (isDefined(value.key)) {\n\t\trelationship = 'one'\n\t} else {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\tconst resolved = new Map<string, ResolvedRelation>()\n\tfor (const [name, value] of Object.entries(relations)) {\n\t\tresolved.set(name, resolveRelation(name, value))\n\t}\n\treturn resolved\n}\n\n// === Builders\n\n/**\n * Build a `belongs` relation — a foreign key on THIS table points at the related row.\n *\n * @param column - The FK column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `many` relation — a foreign key on the RELATED table points back here.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The FK column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Build a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction FK column pointing at THIS model\n * @param target - The junction FK column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.\n *\n * @param key - The FK column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying THIS model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type { DatabaseInterface, Key, Row, TableInterface } from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tRelationProps,\n\tResolvedRelation,\n} from './types.js'\nimport { extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isDefined } from '@orkestrel/contract'\nimport { RelationError } from './errors.js'\n\n/**\n * A model — a typed table paired with relation-aware loading.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * a direct relation uses one query for the whole record set, while a `through`\n * relation uses two (junction then target); both counts remain constant regardless\n * of parent count. Nested includes recurse through the registry `lookup`, so each\n * nested level is batched again. Columns are read with `Reflect.get` (the base row's\n * type is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * AFTER the load resolves / the junction op completes; the emitter isolates a listener\n * throw and routes it to its `error` handler (the `error` option), so a buggy observer can\n * never corrupt the batched eager-load (no N+1 in the events either — one `load` per\n * relation, not per record).\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The PUSH observation surface (§13) — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include): Promise<Loaded<T> | undefined>\n\tload(keys: readonly Key[], include: Include): Promise<readonly (Loaded<T> | undefined)[]>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t): Promise<(Loaded<T> | undefined) | readonly (Loaded<T> | undefined)[]> {\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(present, include, this.#resolved, this.#table.primary)\n\t\t\tlet next = 0\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, props[next++]),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate([base], include, this.#resolved, this.#table.primary)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<readonly Loaded<T>[]> {\n\t\tconst query = this.#table.query()\n\t\tif (options?.sort !== undefined) {\n\t\t\tquery.order({\n\t\t\t\tcolumn: options.sort,\n\t\t\t\tdirection: options.direction ?? 'ascending',\n\t\t\t})\n\t\t}\n\t\tif (options?.offset !== undefined) query.offset(options.offset)\n\t\tif (options?.limit !== undefined) query.limit(options.limit)\n\t\tconst records = await query.collect()\n\t\tconst props = await this.#populate(records, include, this.#resolved, this.#table.primary)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tawait this.#database.table(resolved.through ?? '').set({\n\t\t\t[resolved.source ?? '']: key,\n\t\t\t[resolved.target ?? '']: target,\n\t\t})\n\t\t// Observe the inserted junction row — AFTER the driver write, so a swallowed listener\n\t\t// throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key): Promise<void> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.source ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [key],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.target ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [target],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tfor (const row of rows) {\n\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\tif (id !== undefined) await junction.remove(id)\n\t\t}\n\t\t// Observe the removed junction — AFTER every matching row was deleted.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string): Promise<readonly Key[]> {\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through ?? '')\n\t\tconst rows = await junction\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.source ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [key],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst target = resolved.target ?? ''\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Read a column off any record (the base row's type is closed — no index access).\n\t#field(record: unknown, column: string): unknown {\n\t\tif (typeof record !== 'object' || record === null) return undefined\n\t\treturn Reflect.get(record, column)\n\t}\n\n\t// Resolve a `through` relation by name, or throw a descriptive error.\n\t#through(relation: string): ResolvedRelation {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t): Promise<RelationProps[]> {\n\t\tconst props: RelationProps[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — AFTER it resolved + was attached, ONCE per\n\t\t\t// relation (not per record — the batched load has no N+1, nor do its events),\n\t\t\t// carrying the relation name + the total related rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, this.#attached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// The total related rows a relation's values attached across the record set — an\n\t// array-valued relation (`many` / `through` / `morph`) sums its lengths, a single-\n\t// valued one (`belongs` / `one`) counts each present row. The `load` event's `count`.\n\t#attached(values: readonly (Row | readonly Row[] | undefined)[]): number {\n\t\tlet total = 0\n\t\tfor (const value of values) {\n\t\t\tif (isArray(value)) total += value.length\n\t\t\telse if (value !== undefined) total += 1\n\t\t}\n\t\treturn total\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | readonly Row[] | undefined)[]> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst column = resolved.column ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, column)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: related.primary,\n\t\t\t\toperator: 'any',\n\t\t\t\tvalues: keys,\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = this.#field(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database\n\t\t\t.table(resolved.model)\n\t\t\t.query()\n\t\t\t.condition({ column: foreign, operator: 'any', values: keys, connector: 'and' })\n\t\t\t.collect()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(Row | undefined)[]> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst source = resolved.source ?? ''\n\t\tconst target = resolved.target ?? ''\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database\n\t\t\t.table(resolved.through ?? '')\n\t\t\t.query()\n\t\t\t.condition({ column: source, operator: 'any', values: parents, connector: 'and' })\n\t\t\t.collect()\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = this.#field(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(this.#field(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related\n\t\t\t.query()\n\t\t\t.condition({\n\t\t\t\tcolumn: related.primary,\n\t\t\t\toperator: 'any',\n\t\t\t\tvalues: targets,\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t): Promise<(readonly Row[])[]> {\n\t\tconst foreign = resolved.key ?? ''\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database\n\t\t\t.table(resolved.model)\n\t\t\t.query()\n\t\t\t.condition({ column: foreign, operator: 'any', values: keys, connector: 'and' })\n\t\t\t.condition({\n\t\t\t\tcolumn: resolved.tag ?? '',\n\t\t\t\toperator: 'equals',\n\t\t\t\tvalues: [resolved.label ?? ''],\n\t\t\t\tconnector: 'and',\n\t\t\t})\n\t\t\t.collect()\n\t\tconst groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign)\n\t\treturn records.map((record) => groups.get(String(this.#field(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t): Promise<readonly Row[]> {\n\t\tif (typeof sub === 'boolean' || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n\n\t// Index rows by the string form of a column (for one-to-one key lookups).\n\t#index(rows: readonly Row[], column: string): Map<string, Row> {\n\t\tconst map = new Map<string, Row>()\n\t\tfor (const row of rows) map.set(String(this.#field(row, column)), row)\n\t\treturn map\n\t}\n\n\t// Group rows by the string form of a column (for one-to-many lookups).\n\t#group(rows: readonly Row[], column: string): Map<string, Row[]> {\n\t\tconst map = new Map<string, Row[]>()\n\t\tfor (const row of rows) {\n\t\t\tconst key = String(this.#field(row, column))\n\t\t\tconst group = map.get(key)\n\t\t\tif (group !== undefined) group.push(row)\n\t\t\telse map.set(key, [row])\n\t\t}\n\t\treturn map\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TableMap } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * The relation registry — resolves a {@link RelationsShape} once at construction\n * and vends a typed {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Relation targets are validated lazily — a relation to a missing\n * table fails when that relation is first loaded.\n */\nexport class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map !== undefined) this.#resolved.set(name, resolveRelationMap(map))\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tmodels(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TableMap } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Create a relation manager over a database and its relation definitions.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example\n * ```ts\n * import { createRelationManager, belongsTo, hasMany } from '@src/core'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TableMap>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;AAaA,IAAa,gBAAb,cAAmC,MA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,QAAQ;EACzB,KAAKC,SAAS,QAAQ;EACtB,KAAKC,aAAa,QAAQ,aAAa,CAAC;EACxC,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAKA,UAAU,GACvD,IAAI,QAAQ,KAAA,GAAW,KAAKC,UAAU,IAAI,MAAM,mBAAmB,GAAG,CAAC;CAEzE;CAEA,IAAI,QAAgB;EACnB,OAAO,KAAKA,UAAU;CACvB;CAEA,MAAkC,MAAsC;EACvE,MAAM,WAAW,KAAKA,UAAU,IAAI,IAAI,qBAAK,IAAI,IAA8B;EAC/E,MAAM,YAAY,KAAKD,WAAW,SAAS,CAAC;EAC5C,OAAO,KAAKE,MAAM,MAAM,KAAKJ,UAAU,MAAM,IAAI,GAAG,UAAU,SAAS;CACxE;CAEA,SAA4B;EAC3B,OAAO,CAAC,GAAG,KAAKG,UAAU,KAAK,CAAC;CACjC;CAEA,IAAI,MAAuB;EAC1B,OAAO,KAAKA,UAAU,IAAI,IAAI;CAC/B;CAIA,MACC,MACA,OACA,UACA,WACoB;EACpB,OAAO,IAAI,MAAM,MAAM,OAAO,UAAU,YAAY,UAAU,KAAKE,SAAS,KAAK,GAAG,KAAKJ,MAAM;CAChG;CAGA,SAAS,OAA4C;EACpD,MAAM,WAAW,KAAKE,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAKF,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC3CA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orkestrel/relation",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "A typed relation manager over database tables — batched eager loading and junction management, environment-agnostic. Part of the @orkestrel line.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"database",
|
|
@@ -64,20 +64,20 @@
|
|
|
64
64
|
"prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run build && npm test"
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
|
-
"@orkestrel/contract": "^0.0.
|
|
68
|
-
"@orkestrel/database": "^0.0.
|
|
69
|
-
"@orkestrel/emitter": "^0.0.
|
|
67
|
+
"@orkestrel/contract": "^0.0.9",
|
|
68
|
+
"@orkestrel/database": "^0.0.7",
|
|
69
|
+
"@orkestrel/emitter": "^0.0.5"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@microsoft/api-extractor": "^7.58.12",
|
|
73
|
-
"@orkestrel/guide": "^0.0.
|
|
74
|
-
"@orkestrel/scaffold": "^0.0.
|
|
73
|
+
"@orkestrel/guide": "^0.0.8",
|
|
74
|
+
"@orkestrel/scaffold": "^0.0.13",
|
|
75
75
|
"@types/node": "^26.1.2",
|
|
76
76
|
"@vitest/browser-playwright": "^4.1.10",
|
|
77
77
|
"oxfmt": "^0.61.0",
|
|
78
78
|
"oxlint": "^1.76.0",
|
|
79
79
|
"typescript": "^6.0.3",
|
|
80
|
-
"vite": "^8.
|
|
80
|
+
"vite": "^8.2.0",
|
|
81
81
|
"vite-plugin-dts": "^5.0.3",
|
|
82
82
|
"vitest": "^4.1.10"
|
|
83
83
|
},
|