@orkestrel/relation 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,438 @@
1
+ import { DatabaseInterface } from '@orkestrel/database';
2
+ import { Direction } from '@orkestrel/database';
3
+ import { EmitterErrorHandler } from '@orkestrel/emitter';
4
+ import { EmitterHooks } from '@orkestrel/emitter';
5
+ import { EmitterInterface } from '@orkestrel/emitter';
6
+ import { Key } from '@orkestrel/database';
7
+ import { Row } from '@orkestrel/database';
8
+ import { RowOf } from '@orkestrel/database';
9
+ import { TableInterface } from '@orkestrel/database';
10
+ import { TablesShape } from '@orkestrel/database';
11
+
12
+ /**
13
+ * Build a `belongs` relation — a foreign key on THIS table points at the related row.
14
+ *
15
+ * @param column - The FK column on this table
16
+ * @param model - Target table name (defaults to the relation name)
17
+ * @returns A {@link RelationDescriptor}
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * { classification: belongsTo('classificationId', 'classifications') }
22
+ * ```
23
+ */
24
+ export declare function belongsTo(column: string, model?: string): RelationDescriptor;
25
+
26
+ /**
27
+ * Create a relation manager over a database and its relation definitions.
28
+ *
29
+ * @remarks
30
+ * `relations` maps table names (constrained to the database's tables) to their
31
+ * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /
32
+ * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a
33
+ * table — its own table is fully typed, related rows load at the `Row` type.
34
+ *
35
+ * @param options - The `database` and an optional `relations` map
36
+ * @returns A typed {@link RelationManagerInterface}
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * import { createRelationManager, belongsTo, hasMany } from '@src/core'
41
+ *
42
+ * const manager = createRelationManager({
43
+ * database: db,
44
+ * relations: {
45
+ * accounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },
46
+ * contacts: { account: belongsTo('accountId', 'accounts') },
47
+ * },
48
+ * })
49
+ * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
50
+ * ```
51
+ */
52
+ export declare function createRelationManager<T extends TablesShape>(options: RelationManagerOptions<T>): RelationManagerInterface<T>;
53
+
54
+ /** Pagination and ordering for `find`. */
55
+ export declare interface FindOptions {
56
+ readonly limit?: number;
57
+ readonly offset?: number;
58
+ readonly sort?: string;
59
+ readonly direction?: Direction;
60
+ }
61
+
62
+ /**
63
+ * Build a `many` relation — a foreign key on the RELATED table points back here.
64
+ *
65
+ * @param key - The FK column on the related table
66
+ * @param model - Target table name (defaults to the relation name)
67
+ * @returns A {@link RelationDescriptor}
68
+ */
69
+ export declare function hasMany(key: string, model?: string): RelationDescriptor;
70
+
71
+ /**
72
+ * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
73
+ *
74
+ * @param key - The FK column on the related table
75
+ * @param tag - The discriminator column on the related table
76
+ * @param label - The discriminator value identifying THIS model
77
+ * @param model - Target table name (defaults to the relation name)
78
+ * @returns A {@link RelationDescriptor}
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }
83
+ * ```
84
+ */
85
+ export declare function hasMorph(key: string, tag: string, label: string, model?: string): RelationDescriptor;
86
+
87
+ /**
88
+ * Build a `one` relation — like {@link hasMany}, but a single related row.
89
+ *
90
+ * @param key - The FK column on the related table
91
+ * @param model - Target table name (defaults to the relation name)
92
+ * @returns A {@link RelationDescriptor}
93
+ */
94
+ export declare function hasOne(key: string, model?: string): RelationDescriptor;
95
+
96
+ /**
97
+ * Build a `through` relation — a junction table links the two sides (many-to-many).
98
+ *
99
+ * @param through - The junction table name
100
+ * @param source - The junction FK column pointing at THIS model
101
+ * @param target - The junction FK column pointing at the related model
102
+ * @param model - Target table name (defaults to the relation name)
103
+ * @returns A {@link RelationDescriptor}
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }
108
+ * ```
109
+ */
110
+ export declare function hasThrough(through: string, source: string, target: string, model?: string): RelationDescriptor;
111
+
112
+ /**
113
+ * Which relations to populate when loading — and, recursively, their own.
114
+ *
115
+ * @remarks
116
+ * `true` loads the relation flat; a nested {@link Include} loads it and its
117
+ * sub-relations. `false` (or omission) skips it.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * const include: Include = { contacts: true, submissions: { policy: true } }
122
+ * ```
123
+ */
124
+ export declare interface Include {
125
+ readonly [relation: string]: boolean | Include;
126
+ }
127
+
128
+ /**
129
+ * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).
130
+ *
131
+ * @param value - The value to test
132
+ * @returns `true` when `value` is a plain record
133
+ */
134
+ export declare function isRelationDescriptor(value: unknown): value is RelationDescriptor;
135
+
136
+ /**
137
+ * Narrow an unknown caught value to a {@link RelationError}.
138
+ *
139
+ * @param value - The value to test (typically a `catch` binding)
140
+ * @returns `true` when `value` is a {@link RelationError}
141
+ */
142
+ export declare function isRelationError(value: unknown): value is RelationError;
143
+
144
+ /**
145
+ * A row with its loaded relation properties attached.
146
+ *
147
+ * @remarks
148
+ * The base row is fully typed (the table's row type); the relation properties
149
+ * ({@link RelationProps}) are broad — narrow them at the use site. Typing each
150
+ * relation property to its target row is a deliberate (documented) deferral, like
151
+ * the database guide's deferred pieces.
152
+ */
153
+ export declare type Loaded<T> = T & Readonly<RelationProps>;
154
+
155
+ /**
156
+ * A model — a typed table paired with relation-aware loading.
157
+ *
158
+ * @remarks
159
+ * The model's own table is fully typed (`table`); related tables are reached by
160
+ * runtime name through the database at the broad `Row` type. Loading is batched:
161
+ * for each relation, one query fetches the related rows for the whole record set
162
+ * (`where(col).any(keys)`), grouped in memory and attached — no N+1. Nested
163
+ * includes recurse through the registry `lookup`, so loaded relations carry their
164
+ * own loaded relations. Columns are read with `Reflect.get` (the base row's type
165
+ * is closed) and relation properties merged with `Object.assign` — no `as`.
166
+ *
167
+ * @remarks
168
+ * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
169
+ * eager-load + junction moments — `load` (a relation resolved: its name + the count of
170
+ * related rows attached across the whole record set), `link` / `unlink` (a junction row
171
+ * written) — for fire-and-forget observers. Every event is emitted directly, strictly
172
+ * AFTER the load resolves / the junction op completes; the emitter isolates a listener
173
+ * throw and routes it to its `error` handler (the `error` option), so a buggy observer can
174
+ * never corrupt the batched eager-load (no N+1 in the events either — one `load` per
175
+ * relation, not per record).
176
+ */
177
+ export declare class Model<T extends object = Row> implements ModelInterface<T> {
178
+ #private;
179
+ constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext | undefined, database: DatabaseInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler);
180
+ get emitter(): EmitterInterface<ModelEventMap>;
181
+ get name(): string;
182
+ get table(): TableInterface<T>;
183
+ get relations(): RelationMap;
184
+ load(key: Key, include: Include): Promise<Loaded<T> | undefined>;
185
+ load(keys: readonly Key[], include: Include): Promise<readonly (Loaded<T> | undefined)[]>;
186
+ find(include: Include, options?: FindOptions): Promise<readonly Loaded<T>[]>;
187
+ link(key: Key, relation: string, target: Key): Promise<void>;
188
+ unlink(key: Key, relation: string, target: Key): Promise<void>;
189
+ links(key: Key, relation: string): Promise<readonly Key[]>;
190
+ }
191
+
192
+ /**
193
+ * The push observation surface of a {@link ModelInterface} (AGENTS §13) — the eager-load
194
+ * + junction-management moments a fire-and-forget observer (logging, metrics, a sync
195
+ * layer) subscribes to.
196
+ *
197
+ * @typeParam TKey - The model's primary-key type (a {@link Key}); `link` / `unlink` carry
198
+ * the owning key so the map is `ModelEventMap<TKey>`.
199
+ *
200
+ * @remarks
201
+ * `load` fires once per relation that an eager-load resolves, carrying the relation NAME +
202
+ * the COUNT of related rows attached for the whole record set (it is the batched load
203
+ * moment, not one event per record — there is no N+1 in the events either). `link` /
204
+ * `unlink` fire after a junction row is inserted / removed, carrying the owning key + the
205
+ * relation name. Listener isolation is the emitter's (AGENTS §13): every event is emitted
206
+ * directly and a listener throw is routed to the emitter's `error` handler (the `error`
207
+ * option), never onto this map, and sits AFTER the load resolves / the junction op completes
208
+ * — so a throwing observer can never corrupt the eager-load batching or a junction write.
209
+ * `RelationManager` is event-free by design (a stateless
210
+ * registry that merely vends models — it has no observable lifecycle of its own); the
211
+ * per-entity {@link ModelInterface} is where loading and linking happen, so the emitter
212
+ * lives there. Subscribe via `model.emitter.on(...)`. Declared as a `type` alias (§4.5 —
213
+ * `EventMap` is a `type` kind).
214
+ */
215
+ export declare type ModelEventMap<TKey extends Key = Key> = {
216
+ /** A relation eager-loaded — the relation name + the count of related rows attached. */
217
+ readonly load: readonly [name: string, count: number];
218
+ /** A junction row was inserted for a `through` relation — the owning key + relation name. */
219
+ readonly link: readonly [key: TKey, relation: string];
220
+ /** A junction row was removed for a `through` relation — the owning key + relation name. */
221
+ readonly unlink: readonly [key: TKey, relation: string];
222
+ };
223
+
224
+ /**
225
+ * A model — a typed table paired with relation-aware loading and junction
226
+ * management.
227
+ *
228
+ * @remarks
229
+ * Table operations are reached through `table` (a fully typed
230
+ * {@link TableInterface}); relation loading and through management are on the
231
+ * model itself. `load` fetches one record with its relations populated; `find`
232
+ * fetches many; both batch-load (one query per relation regardless of result
233
+ * size). `link` / `unlink` / `links` manage a `through` relation's junction rows.
234
+ * Exposes a typed {@link emitter} (AGENTS §13) carrying the eager-load + junction
235
+ * moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
236
+ * observation-only (a swallowed listener throw can never corrupt the batched load).
237
+ */
238
+ export declare interface ModelInterface<T = Row> {
239
+ readonly emitter: EmitterInterface<ModelEventMap>;
240
+ readonly name: string;
241
+ readonly table: TableInterface<T>;
242
+ readonly relations: RelationMap;
243
+ load(key: Key, include: Include): Promise<Loaded<T> | undefined>;
244
+ load(keys: readonly Key[], include: Include): Promise<readonly (Loaded<T> | undefined)[]>;
245
+ find(include: Include, options?: FindOptions): Promise<readonly Loaded<T>[]>;
246
+ link(key: Key, relation: string, target: Key): Promise<void>;
247
+ unlink(key: Key, relation: string, target: Key): Promise<void>;
248
+ links(key: Key, relation: string): Promise<readonly Key[]>;
249
+ }
250
+
251
+ /**
252
+ * A single relation definition.
253
+ *
254
+ * @remarks
255
+ * A `string` is a `belongs` (the FK column on this table); a `readonly string[]`
256
+ * is a `many` (the first element is the FK column on the related table); a
257
+ * {@link RelationDescriptor} is the object form for everything else.
258
+ */
259
+ export declare type Relation = string | readonly string[] | RelationDescriptor;
260
+
261
+ /**
262
+ * A related model's resolved relations and primary-key column, for nested loading.
263
+ *
264
+ * @remarks
265
+ * The lookup result the relation registry hands a {@link ModelInterface} so it can
266
+ * recurse into a related model's own relations. `RelationManager` produces it (one
267
+ * per declared table); `Model` consumes it as its registry lookup's return. Shared
268
+ * here so the producer and consumer stay in lockstep.
269
+ */
270
+ export declare interface RelationContext {
271
+ readonly resolved: ReadonlyMap<string, ResolvedRelation>;
272
+ readonly primary: string;
273
+ }
274
+
275
+ /**
276
+ * The object form of a relation.
277
+ *
278
+ * @remarks
279
+ * The builder helpers (`belongsTo` / `hasMany` / `hasOne` / `hasThrough` /
280
+ * `hasMorph`) set `relationship` explicitly, which removes all ambiguity — `many`
281
+ * and `one` are otherwise indistinguishable by fields alone. When `relationship`
282
+ * is omitted (a hand-written descriptor) it is inferred from the fields present:
283
+ * `column` → `belongs`; `through` + `source` + `target` → `through`; `key` +
284
+ * `tag` + `label` → `morph`; `key` alone → `one`. `model` overrides the target
285
+ * table name (it defaults to the relation name).
286
+ */
287
+ export declare interface RelationDescriptor {
288
+ readonly relationship?: Relationship;
289
+ readonly column?: string;
290
+ readonly key?: string;
291
+ readonly through?: string;
292
+ readonly source?: string;
293
+ readonly target?: string;
294
+ readonly tag?: string;
295
+ readonly label?: string;
296
+ readonly model?: string;
297
+ }
298
+
299
+ /**
300
+ * An error thrown by the relations layer.
301
+ *
302
+ * @remarks
303
+ * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
304
+ * reference to a relation a model does not define (`UNKNOWN_RELATION`), and
305
+ * `link` / `unlink` / `links` on a relation that is not a `through` (`NOT_THROUGH`).
306
+ */
307
+ export declare class RelationError extends Error {
308
+ readonly code: RelationErrorCode;
309
+ readonly context?: Readonly<Record<string, unknown>>;
310
+ constructor(code: RelationErrorCode, message: string, context?: Readonly<Record<string, unknown>>);
311
+ }
312
+
313
+ /** A machine-readable {@link RelationError} code. */
314
+ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_THROUGH';
315
+
316
+ /**
317
+ * The relation registry — resolves a {@link RelationsShape} once at construction
318
+ * and vends a typed {@link ModelInterface} per declared table.
319
+ *
320
+ * @remarks
321
+ * Holds the database both at its precise type (to type each model's own table)
322
+ * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
323
+ * while loading). Relation targets are validated lazily — a relation to a missing
324
+ * table fails when that relation is first loaded.
325
+ */
326
+ export declare class RelationManager<T extends TablesShape = TablesShape> implements RelationManagerInterface<T> {
327
+ #private;
328
+ constructor(options: RelationManagerOptions<T>);
329
+ get count(): number;
330
+ model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
331
+ models(): readonly string[];
332
+ has(name: string): boolean;
333
+ }
334
+
335
+ /**
336
+ * The relation registry — vends a typed {@link ModelInterface} per table.
337
+ *
338
+ * @remarks
339
+ * Built from a database and a {@link RelationsShape}; relations are resolved once
340
+ * at construction. `model(name)` returns the model for a declared table, typed by
341
+ * that table's row. Follows the manager accessor pattern (`model` / `models`).
342
+ */
343
+ export declare interface RelationManagerInterface<T extends TablesShape = TablesShape> {
344
+ readonly count: number;
345
+ model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
346
+ models(): readonly string[];
347
+ has(name: string): boolean;
348
+ }
349
+
350
+ /** Options for `createRelationManager`. */
351
+ export declare interface RelationManagerOptions<T extends TablesShape = TablesShape> {
352
+ readonly database: DatabaseInterface<T>;
353
+ readonly relations?: RelationsShape<T>;
354
+ }
355
+
356
+ /** A model's relations, keyed by relation name. */
357
+ export declare type RelationMap = Readonly<Record<string, Relation>>;
358
+
359
+ /**
360
+ * The relation properties attached to a {@link Loaded} row — each relation name
361
+ * mapped to its loaded related row(s), or `undefined` when a `belongs` / `one`
362
+ * relation misses.
363
+ *
364
+ * @remarks
365
+ * The broad value type (`Row | readonly Row[] | undefined`) is narrowed at the use
366
+ * site. This is the mutable bag a `Model` fills while populating a record set;
367
+ * `Loaded<T>` is a base row intersected with its `Readonly` form.
368
+ */
369
+ export declare type RelationProps = Record<string, Row | readonly Row[] | undefined>;
370
+
371
+ /**
372
+ * The five relation shapes.
373
+ *
374
+ * @remarks
375
+ * `belongs` — a foreign key on THIS table points at the related row (single).
376
+ * `many` — a foreign key on the RELATED table points back here (array).
377
+ * `one` — like `many`, but a single related row.
378
+ * `through` — a junction table links the two sides (array, many-to-many).
379
+ * `morph` — a foreign key plus a discriminator column on the RELATED table (array, polymorphic).
380
+ */
381
+ export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'morph';
382
+
383
+ /**
384
+ * Per-table relation maps — the declarative input to `createRelationManager`.
385
+ *
386
+ * @remarks
387
+ * Keys are constrained to the database's declared table names, so relations can
388
+ * only be defined for tables that exist. A table may be omitted (no relations).
389
+ */
390
+ export declare type RelationsShape<T extends TablesShape = TablesShape> = {
391
+ readonly [K in keyof T]?: RelationMap;
392
+ };
393
+
394
+ /**
395
+ * A relation resolved at define-time into a flat, ready-to-load form.
396
+ *
397
+ * @remarks
398
+ * The relationship and every column needed to load, link, and unlink are
399
+ * precomputed from the raw {@link Relation}, so no inference runs at query time.
400
+ */
401
+ export declare interface ResolvedRelation {
402
+ readonly relationship: Relationship;
403
+ readonly name: string;
404
+ readonly model: string;
405
+ readonly column?: string;
406
+ readonly key?: string;
407
+ readonly through?: string;
408
+ readonly source?: string;
409
+ readonly target?: string;
410
+ readonly tag?: string;
411
+ readonly label?: string;
412
+ }
413
+
414
+ /**
415
+ * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
416
+ *
417
+ * @remarks
418
+ * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
419
+ * `many` (FK column on the related table); a {@link RelationDescriptor} uses its
420
+ * explicit `relationship`, or infers it from the fields present. The target model
421
+ * defaults to the relation name. Throws `INVALID` when the relationship cannot be
422
+ * resolved or a required field is missing.
423
+ *
424
+ * @param name - The relation name (its key in the {@link RelationMap})
425
+ * @param value - The raw relation value
426
+ * @returns The resolved relation
427
+ */
428
+ export declare function resolveRelation(name: string, value: Relation): ResolvedRelation;
429
+
430
+ /**
431
+ * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
432
+ *
433
+ * @param relations - The raw relation map
434
+ * @returns A map keyed by relation name
435
+ */
436
+ export declare function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation>;
437
+
438
+ export { }