@orkestrel/relation 0.0.22 → 0.0.23

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.
@@ -10,7 +10,9 @@ let _orkestrel_emitter = require("@orkestrel/emitter");
10
10
  * @remarks
11
11
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
12
12
  * relation targeting a table or junction the database does not declare, raised when
13
- * the manager is created (`INVALID`), a reference to a relation a model does not
13
+ * the manager is created (`INVALID`), a junction keyed by its relation's `source` or
14
+ * `target` column (`INVALID`), a row a storage returns that is not a plain record
15
+ * (`INVALID`), a reference to a relation a model does not
14
16
  * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is
15
17
  * not a `through` (`NOT_THROUGH`).
16
18
  */
@@ -28,58 +30,104 @@ var RelationError = class extends Error {
28
30
  /**
29
31
  * Narrows an unknown caught value to a {@link RelationError}.
30
32
  *
33
+ * @remarks
34
+ * Accepts branded instances and subclasses across package copies and module formats.
35
+ * Requires a declared {@link RelationErrorCode} and a `context` that is absent, an object,
36
+ * or a callable object. Refuses look-alikes, transparent proxies, and plain branded objects
37
+ * without requiring an exact `name`.
38
+ *
31
39
  * @param value - The value to test (typically a `catch` binding)
32
- * @returns True if the error carries its own identity brand and declared members; false otherwise
40
+ * @returns True if `value` is a {@link RelationError}; false otherwise
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * try {
45
+ * resolveRelation('ghost', {})
46
+ * } catch (error) {
47
+ * if (isRelationError(error) && error.code === 'INVALID') report(error.message)
48
+ * }
49
+ * ```
33
50
  */
34
51
  function isRelationError(value) {
35
52
  return (0, _orkestrel_contract.holds)(() => {
36
- if (!(value instanceof Error) || _orkestrel_contract.INTRINSICS.prototype(value) === Error.prototype) return false;
37
- if (_orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/relation.RelationError"))?.value !== value) return false;
53
+ const intrinsic = _orkestrel_contract.INTRINSICS.error;
54
+ if (!(0, _orkestrel_contract.isInstance)(value, intrinsic) || _orkestrel_contract.INTRINSICS.prototype(value) === intrinsic.prototype) return false;
55
+ const brand = _orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/relation.RelationError"));
56
+ if (brand === void 0 || brand.value !== value) return false;
38
57
  const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
39
- if (code !== "INVALID" && code !== "UNKNOWN_RELATION" && code !== "NOT_THROUGH") return false;
58
+ if (!(0, _orkestrel_contract.literalOf)("INVALID", "UNKNOWN_RELATION", "NOT_THROUGH")(code)) return false;
40
59
  const context = _orkestrel_contract.INTRINSICS.reflect.read(value, "context");
41
60
  return context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context);
42
61
  });
43
62
  }
63
+ // src/core/shapers.ts
64
+ /**
65
+ * Declares the object form of a relation as a closed contract shape.
66
+ *
67
+ * @remarks
68
+ * Every member is optional: `relationship` is one of the `Relationship` values, and
69
+ * `column`, `key`, `through`, `source`, `target`, `tag`, `label`, and `model` are strings.
70
+ * The object is closed, so an enumerable, string-keyed member the descriptor does not declare
71
+ * refuses it.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { createContract } from '@orkestrel/contract'
76
+ * import { relationDescriptorShape } from '@orkestrel/relation'
77
+ *
78
+ * createContract(relationDescriptorShape).is({ column: 'accountId', comment: 'x' }) // false
79
+ * ```
80
+ */
81
+ var relationDescriptorShape = (0, _orkestrel_contract.objectShape)({
82
+ relationship: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.literalShape)([
83
+ "belongs",
84
+ "many",
85
+ "one",
86
+ "through",
87
+ "morph"
88
+ ])),
89
+ column: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
90
+ key: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
91
+ through: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
92
+ source: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
93
+ target: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
94
+ tag: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
95
+ label: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)()),
96
+ model: (0, _orkestrel_contract.optionalShape)((0, _orkestrel_contract.stringShape)())
97
+ });
98
+ // src/core/contracts.ts
99
+ /**
100
+ * Holds the compiled contract of a relation descriptor, which `resolveRelation` admits through.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * import { relationDescriptorContract } from '@orkestrel/relation'
105
+ *
106
+ * relationDescriptorContract.audit({ column: 'accountId', comment: 'x' }) // [{ reason: 'extra', path: ['comment'] }]
107
+ * ```
108
+ */
109
+ var relationDescriptorContract = (0, _orkestrel_contract.createContract)(relationDescriptorShape);
44
110
  // src/core/validators.ts
45
111
  /**
46
112
  * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
47
113
  *
48
114
  * @remarks
49
- * A record satisfies the descriptor when every member it declares carries its declared
50
- * type: `relationship` is one of the `Relationship` values, and `column`, `key`,
51
- * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the
52
- * record omits is unconstrained, a member present with an `undefined` value is refused,
53
- * and a member the descriptor does not declare is carried without being checked. This
54
- * is what lets `resolveRelation` read each member after one narrow and report a
55
- * malformed definition as an `INVALID` `RelationError` instead of resolving a
56
- * wrong-typed column into an arm that declares it a string.
57
- *
58
- * @param value - The value to test
59
- * @returns True if `value` is a record whose every declared member holds its declared
60
- * type; false otherwise
115
+ * The guard of the compiled `relationDescriptorContract`: a plain record whose every
116
+ * member is optional, with `relationship` one of the `Relationship` values and `column`,
117
+ * `key`, `through`, `source`, `target`, `tag`, `label`, and `model` strings. A member
118
+ * present with an `undefined` value, a member holding another type, and an enumerable,
119
+ * string-keyed member the descriptor does not declare each refuse it. That is what lets
120
+ * `resolveRelation` read each member after one narrow and report a malformed definition
121
+ * as an `INVALID` `RelationError`.
61
122
  *
62
123
  * @example
63
124
  * ```ts
64
125
  * isRelationDescriptor(belongsTo('accountId')) // true
65
126
  * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
127
+ * isRelationDescriptor({ column: 'accountId', comment: 'x' }) // false — `comment` is undeclared
66
128
  * ```
67
129
  */
68
- function isRelationDescriptor(value) {
69
- if (!(0, _orkestrel_contract.isRecord)(value)) return false;
70
- if ("relationship" in value && !(0, _orkestrel_contract.literalOf)("belongs", "many", "one", "through", "morph")(value.relationship)) return false;
71
- for (const member of [
72
- "column",
73
- "key",
74
- "through",
75
- "source",
76
- "target",
77
- "tag",
78
- "label",
79
- "model"
80
- ]) if (member in value && !(0, _orkestrel_contract.isString)(value[member])) return false;
81
- return true;
82
- }
130
+ var isRelationDescriptor = relationDescriptorContract.is;
83
131
  // src/core/helpers.ts
84
132
  /**
85
133
  * Validates a relation table through its bound storage, translating only an undeclared table.
@@ -101,7 +149,7 @@ function validateRelationTable(storage, model, relation, table, junction = false
101
149
  storage.table(table);
102
150
  } catch (error) {
103
151
  if (!(0, _orkestrel_database.isDatabaseError)(error) || error.code !== "NOT_FOUND") throw error;
104
- throw new RelationError("INVALID", `Model '${model}' relation '${relation}' ${junction ? "uses undeclared junction" : "targets undeclared table"} '${table}'`, {
152
+ throw new RelationError("INVALID", junction ? `Relation ${(0, _orkestrel_contract.renderPath)([model, relation])} uses undeclared junction ${(0, _orkestrel_contract.renderPath)([table])}; declare it in the database's tables or correct the relation's through` : `Relation ${(0, _orkestrel_contract.renderPath)([model, relation])} targets undeclared table ${(0, _orkestrel_contract.renderPath)([table])}; declare it in the database's tables or correct the relation's model`, {
105
153
  model,
106
154
  relation,
107
155
  table
@@ -109,20 +157,78 @@ function validateRelationTable(storage, model, relation, table, junction = false
109
157
  }
110
158
  }
111
159
  /**
160
+ * Validates that a `through` relation's junction keys its rows by a column of its own.
161
+ *
162
+ * @remarks
163
+ * `link` writes the pair's `computeLinkKey` into the junction's primary column, so a junction
164
+ * whose primary column is the relation's `source` or `target` column cannot hold that key.
165
+ *
166
+ * @param model - The owning model's name
167
+ * @param resolved - The resolved `through` relation
168
+ * @param primary - The junction table's primary-key column
169
+ * @throws An `INVALID` {@link RelationError} when `primary` is the relation's `source` or
170
+ * `target` column
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * validateRelationJunction('accounts', resolved, 'id') // a junction keyed by `id` passes
175
+ * ```
176
+ */
177
+ function validateRelationJunction(model, resolved, primary) {
178
+ const role = primary === resolved.source ? "source" : primary === resolved.target ? "target" : void 0;
179
+ if (role === void 0) return;
180
+ throw new RelationError("INVALID", `Relation ${(0, _orkestrel_contract.renderPath)([model, resolved.name])} keys its junction ${(0, _orkestrel_contract.renderPath)([resolved.through])} by its ${role} column ${(0, _orkestrel_contract.renderPath)([primary])}; give the junction a separate text primary column, which link fills with computeLinkKey`, {
181
+ model,
182
+ relation: resolved.name,
183
+ table: resolved.through,
184
+ column: primary
185
+ });
186
+ }
187
+ /**
188
+ * Reads one row a storage returned, refusing a value that is not a plain record.
189
+ *
190
+ * @remarks
191
+ * Contract's `isRecord` decides, so a class instance, an array, or a primitive that a custom
192
+ * `DatabaseStorageInterface` returns raises rather than reading as a miss or dropping.
193
+ *
194
+ * @param table - The table the row came from
195
+ * @param row - The row as the storage returned it
196
+ * @returns The row, narrowed to a record
197
+ * @throws An `INVALID` {@link RelationError} naming `table` when `row` is not a plain record
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * readRow('accounts', { id: 'acc1' }) // { id: 'acc1' }
202
+ * ```
203
+ */
204
+ function readRow(table, row) {
205
+ if ((0, _orkestrel_contract.isRecord)(row)) return row;
206
+ throw new RelationError("INVALID", `Table ${(0, _orkestrel_contract.renderPath)([table])} returned a row that is not a plain record; a storage must return plain record rows`, { table });
207
+ }
208
+ /**
112
209
  * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
113
210
  *
114
211
  * @remarks
115
212
  * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`
116
213
  * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}
117
214
  * uses its explicit `relationship`, or infers it from the fields present. The target
118
- * model defaults to the relation name. Every column the resolved arm declares is
119
- * validated here, which is what lets each arm declare its columns required.
215
+ * model defaults to the relation name. A descriptor must pass `relationDescriptorContract`'s
216
+ * strict guard: an undeclared member, enumerable or not, a member holding another type, and
217
+ * a member present as `undefined` each refuse it, and no lossless repair admits it. The
218
+ * refusal carries the contract's audit faults, described against its schema. Every column the resolved arm declares is validated here, which is
219
+ * what lets each arm declare its columns required.
120
220
  *
121
221
  * @param name - The relation name (its key in the {@link RelationMap})
122
222
  * @param value - The raw relation value
123
223
  * @returns The resolved relation, on the arm its `relationship` names
124
- * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a
125
- * column the resolved arm declares is missing
224
+ * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, when the
225
+ * descriptor fails its contract (the faults ride on `context.faults`), or when a column the
226
+ * resolved arm declares is missing
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * resolveRelation('classification', belongsTo('classificationId', 'classifications')).relationship // 'belongs'
231
+ * ```
126
232
  */
127
233
  function resolveRelation(name, value) {
128
234
  if ((0, _orkestrel_contract.isString)(value)) return {
@@ -131,9 +237,10 @@ function resolveRelation(name, value) {
131
237
  model: name,
132
238
  column: value
133
239
  };
240
+ const path = (0, _orkestrel_contract.renderPath)([name]);
134
241
  if ((0, _orkestrel_contract.isArray)(value)) {
135
242
  const key = value[0];
136
- if (!(0, _orkestrel_contract.isString)(key)) throw new RelationError("INVALID", `Relation '${name}': array form needs a string FK column`, { relation: name });
243
+ if (!(0, _orkestrel_contract.isString)(key)) throw new RelationError("INVALID", `Relation ${path}: the array form needs a foreign-key column string first, such as ['accountId']`, { relation: name });
137
244
  return {
138
245
  relationship: "many",
139
246
  name,
@@ -141,14 +248,22 @@ function resolveRelation(name, value) {
141
248
  key
142
249
  };
143
250
  }
144
- if (!isRelationDescriptor(value)) throw new RelationError("INVALID", `Relation '${name}': not a string, array, or descriptor`, { relation: name });
145
- const model = value.model ?? name;
146
- const relationship = value.relationship !== void 0 ? value.relationship : (0, _orkestrel_contract.isDefined)(value.through) ? "through" : (0, _orkestrel_contract.isDefined)(value.tag) ? "morph" : (0, _orkestrel_contract.isDefined)(value.column) ? "belongs" : (0, _orkestrel_contract.isDefined)(value.key) ? "one" : void 0;
147
- if (relationship === void 0) throw new RelationError("INVALID", `Relation '${name}': cannot infer relationship from descriptor`, { relation: name });
251
+ const admitted = (0, _orkestrel_contract.admitValue)(relationDescriptorContract, value);
252
+ if ((0, _orkestrel_contract.isFailure)(admitted)) {
253
+ const faults = admitted.error.faults;
254
+ throw new RelationError("INVALID", `Relation ${path}: expected a column string, a [key] array, or a relation descriptor\n${(0, _orkestrel_contract.describeFaults)(faults, relationDescriptorContract.schema)}`, {
255
+ relation: name,
256
+ faults
257
+ });
258
+ }
259
+ const descriptor = admitted.value;
260
+ const model = descriptor.model ?? name;
261
+ const relationship = descriptor.relationship !== void 0 ? descriptor.relationship : (0, _orkestrel_contract.isDefined)(descriptor.through) ? "through" : (0, _orkestrel_contract.isDefined)(descriptor.tag) ? "morph" : (0, _orkestrel_contract.isDefined)(descriptor.column) ? "belongs" : (0, _orkestrel_contract.isDefined)(descriptor.key) ? "one" : void 0;
262
+ if (relationship === void 0) throw new RelationError("INVALID", `Relation ${path}: cannot infer the relationship; set relationship, or give column (belongs), key (one), through (through), or tag (morph)`, { relation: name });
148
263
  switch (relationship) {
149
264
  case "belongs": {
150
- const column = value.column;
151
- if (column === void 0) throw new RelationError("INVALID", `Relation '${name}': belongs needs 'column'`, { relation: name });
265
+ const column = descriptor.column;
266
+ if (column === void 0) throw new RelationError("INVALID", `Relation ${path}: a belongs relation needs column; build it with belongsTo(column)`, { relation: name });
152
267
  return {
153
268
  relationship,
154
269
  name,
@@ -157,8 +272,8 @@ function resolveRelation(name, value) {
157
272
  };
158
273
  }
159
274
  case "many": {
160
- const key = value.key;
161
- if (key === void 0) throw new RelationError("INVALID", `Relation '${name}': many needs 'key'`, { relation: name });
275
+ const key = descriptor.key;
276
+ if (key === void 0) throw new RelationError("INVALID", `Relation ${path}: a many relation needs key; build it with hasMany(key)`, { relation: name });
162
277
  return {
163
278
  relationship,
164
279
  name,
@@ -167,8 +282,8 @@ function resolveRelation(name, value) {
167
282
  };
168
283
  }
169
284
  case "one": {
170
- const key = value.key;
171
- if (key === void 0) throw new RelationError("INVALID", `Relation '${name}': one needs 'key'`, { relation: name });
285
+ const key = descriptor.key;
286
+ if (key === void 0) throw new RelationError("INVALID", `Relation ${path}: a one relation needs key; build it with hasOne(key)`, { relation: name });
172
287
  return {
173
288
  relationship,
174
289
  name,
@@ -177,8 +292,8 @@ function resolveRelation(name, value) {
177
292
  };
178
293
  }
179
294
  case "through": {
180
- const { through, source, target } = value;
181
- if (through === void 0 || source === void 0 || target === void 0) throw new RelationError("INVALID", `Relation '${name}': through needs 'through', 'source', and 'target'`, { relation: name });
295
+ const { through, source, target } = descriptor;
296
+ if (through === void 0 || source === void 0 || target === void 0) throw new RelationError("INVALID", `Relation ${path}: a through relation needs through, source, and target; build it with hasThrough(through, source, target)`, { relation: name });
182
297
  return {
183
298
  relationship,
184
299
  name,
@@ -189,8 +304,8 @@ function resolveRelation(name, value) {
189
304
  };
190
305
  }
191
306
  case "morph": {
192
- const { key, tag, label } = value;
193
- if (key === void 0 || tag === void 0 || label === void 0) throw new RelationError("INVALID", `Relation '${name}': morph needs 'key', 'tag', and 'label'`, { relation: name });
307
+ const { key, tag, label } = descriptor;
308
+ if (key === void 0 || tag === void 0 || label === void 0) throw new RelationError("INVALID", `Relation ${path}: a morph relation needs key, tag, and label; build it with hasMorph(key, tag, label)`, { relation: name });
194
309
  return {
195
310
  relationship,
196
311
  name,
@@ -212,24 +327,24 @@ function resolveRelationMap(relations) {
212
327
  return new Map(Object.entries(relations).map(([name, value]) => [name, resolveRelation(name, value)]));
213
328
  }
214
329
  /**
215
- * Reads one column off any record, whatever its declared type.
330
+ * Computes the junction row's primary key for one pair of a `through` relation.
216
331
  *
217
332
  * @remarks
218
- * A base row's type is closed, so the column is read with `Reflect.get` rather than
219
- * index access. Anything that is not an object reads as `undefined`.
333
+ * The key is the JSON text of `[key, target]`, so each pair has one key and a string key
334
+ * stays apart from the number it spells. `link` inserts under this key and `unlink` removes
335
+ * it, which is why a junction's primary column must store text.
220
336
  *
221
- * @param record - The record to read
222
- * @param column - The column name
223
- * @returns The column's value, or `undefined` when `record` is not an object
337
+ * @param key - The owning record's primary key
338
+ * @param target - The related record's primary key
339
+ * @returns The pair's junction key
224
340
  *
225
341
  * @example
226
342
  * ```ts
227
- * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'
343
+ * computeLinkKey('acc1', 'rep1') // '["acc1","rep1"]'
228
344
  * ```
229
345
  */
230
- function readColumn(record, column) {
231
- if (!(0, _orkestrel_contract.isObject)(record)) return void 0;
232
- return Reflect.get(record, column);
346
+ function computeLinkKey(key, target) {
347
+ return JSON.stringify([key, target]);
233
348
  }
234
349
  /**
235
350
  * Counts the related rows one relation attached across a record set.
@@ -254,7 +369,7 @@ function countAttached(values) {
254
369
  * Indexes rows by the string form of one column, for keyed lookups.
255
370
  *
256
371
  * @remarks
257
- * The column is read with {@link readColumn} and its value stringified, so a numeric
372
+ * The column is read with `resolveField` and its value stringified, so a numeric
258
373
  * and a string foreign key meet at the same entry. A later row with a key an earlier
259
374
  * row already holds replaces it, and a row missing the column indexes under the string
260
375
  * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
@@ -274,14 +389,14 @@ function countAttached(values) {
274
389
  function indexRows(rows, column, values = rows) {
275
390
  return new Map(Iterator.from(rows).flatMap((row, index) => {
276
391
  const value = values[index];
277
- return value === void 0 ? [] : [[String(readColumn(row, column)), value]];
392
+ return value === void 0 ? [] : [[String((0, _orkestrel_contract.resolveField)(row, column)), value]];
278
393
  }));
279
394
  }
280
395
  /**
281
396
  * Groups rows by the string form of one column, for one-to-many lookups.
282
397
  *
283
398
  * @remarks
284
- * The column is read with {@link readColumn} and its value stringified, so a numeric
399
+ * The column is read with `resolveField` and its value stringified, so a numeric
285
400
  * and a string foreign key meet at the same group. Rows keep their input order inside
286
401
  * a group, a key no row carries is absent rather than empty, and a row missing the
287
402
  * column groups under the string `'undefined'`. This is the projection a `many` load
@@ -299,16 +414,11 @@ function indexRows(rows, column, values = rows) {
299
414
  * ```
300
415
  */
301
416
  function groupRows(rows, column, values = rows) {
302
- const groups = /* @__PURE__ */ new Map();
303
- for (const [index, row] of rows.entries()) {
417
+ const pairs = Iterator.from(rows.entries()).flatMap(([index, row]) => {
304
418
  const value = values[index];
305
- if (value === void 0) continue;
306
- const key = String(readColumn(row, column));
307
- const group = groups.get(key);
308
- if (group !== void 0) group.push(value);
309
- else groups.set(key, [value]);
310
- }
311
- return groups;
419
+ return value === void 0 ? [] : [[String((0, _orkestrel_contract.resolveField)(row, column)), value]];
420
+ });
421
+ return new Map(Iterator.from(Map.groupBy(pairs, ([key]) => key)).map(([key, group]) => [key, group.map(([, value]) => value)]));
312
422
  }
313
423
  /**
314
424
  * Builds a `belongs` relation — a foreign key on the owning table points at the related row
@@ -416,8 +526,10 @@ function hasMorph(key, tag, label, model) {
416
526
  * a direct relation uses one query for the whole record set, while a `through`
417
527
  * relation uses two (junction then target); both counts remain constant regardless
418
528
  * of parent count. Nested includes recurse through the registry `lookup`, so each
419
- * nested level is batched again. Columns are read with `Reflect.get` (the base row's
420
- * type is closed) and relation properties merged with `Object.assign` — no `as`.
529
+ * nested level is batched again. A load by primary key (`belongs`, a `through` target)
530
+ * reads through the table's keyed `get`; a load by foreign key reads through `records`
531
+ * with `any`. Columns are read with `resolveField` and relation properties merged with
532
+ * `Object.assign` — no `as`.
421
533
  *
422
534
  * @remarks
423
535
  * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
@@ -498,95 +610,70 @@ var Model = class {
498
610
  async load(keys, include, options) {
499
611
  (0, _orkestrel_database.checkAbort)(options?.signal);
500
612
  if ((0, _orkestrel_contract.isArray)(keys)) {
501
- const bases = await this.#table.get(keys);
613
+ const bases = (await this.#table.get(keys)).map((base) => base === void 0 ? void 0 : readRow(this.#table.name, base));
502
614
  const present = bases.filter(_orkestrel_contract.isDefined);
503
615
  const attachments = (await this.#populate(present, include, this.#resolved, this.#table.primary, options)).values();
504
616
  return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, attachments.next().value));
505
617
  }
506
- const base = await this.#table.get(keys);
507
- if (base === void 0) return void 0;
618
+ const found = await this.#table.get(keys);
619
+ if (found === void 0) return void 0;
620
+ const base = readRow(this.#table.name, found);
508
621
  const [props] = await this.#populate([base], include, this.#resolved, this.#table.primary, options);
509
622
  return Object.assign({}, base, props);
510
623
  }
511
624
  async find(include, options) {
512
625
  (0, _orkestrel_database.checkAbort)(options?.signal);
513
- const records = await this.#table.records({
626
+ const rows = (await this.#table.records({
514
627
  ...options?.sort !== void 0 ? { order: [{
515
628
  column: options.sort,
516
629
  direction: options.direction ?? "ascending"
517
630
  }] } : {},
518
631
  ...options?.offset !== void 0 ? { offset: options.offset } : {},
519
632
  ...options?.limit !== void 0 ? { limit: options.limit } : {}
520
- }, options);
521
- const props = await this.#populate(records, include, this.#resolved, this.#table.primary, options);
522
- return records.map((record, index) => Object.assign({}, record, props[index]));
633
+ }, options)).map((record) => readRow(this.#table.name, record));
634
+ const props = await this.#populate(rows, include, this.#resolved, this.#table.primary, options);
635
+ return rows.map((row, index) => Object.assign({}, row, props[index]));
523
636
  }
524
637
  async link(key, relation, target, options) {
525
638
  (0, _orkestrel_database.checkAbort)(options?.signal);
526
639
  const resolved = this.#through(relation);
527
640
  const junction = this.#storage.table(resolved.through);
528
- if (await junction.count({ conditions: [{
529
- column: resolved.source,
530
- operator: "equals",
531
- values: [key],
532
- connector: "and"
533
- }, {
534
- column: resolved.target,
535
- operator: "equals",
536
- values: [target],
537
- connector: "and"
538
- }] }, options) > 0) return;
539
- await junction.set({
540
- [resolved.source]: key,
541
- [resolved.target]: target
542
- }, options);
641
+ const id = computeLinkKey(key, target);
642
+ try {
643
+ await junction.add({
644
+ [junction.primary]: id,
645
+ [resolved.source]: key,
646
+ [resolved.target]: target
647
+ }, options);
648
+ } catch (error) {
649
+ if ((0, _orkestrel_database.isDatabaseError)(error) && error.code === "CONFLICT" && await junction.has(id)) return;
650
+ throw error;
651
+ }
543
652
  this.#emitter.emit("link", key, relation);
544
653
  }
545
654
  async unlink(key, relation, target, options) {
546
655
  (0, _orkestrel_database.checkAbort)(options?.signal);
547
656
  const resolved = this.#through(relation);
548
- const junction = this.#storage.table(resolved.through);
549
- const rows = await junction.records({ conditions: [{
550
- column: resolved.source,
551
- operator: "equals",
552
- values: [key],
553
- connector: "and"
554
- }, {
555
- column: resolved.target,
556
- operator: "equals",
557
- values: [target],
558
- connector: "and"
559
- }] }, options);
560
- for (const row of rows) {
561
- const id = (0, _orkestrel_database.extractKey)(row, junction.primary);
562
- if (id !== void 0) await junction.remove(id, options);
563
- }
564
- this.#emitter.emit("unlink", key, relation);
657
+ if (await this.#storage.table(resolved.through).remove(computeLinkKey(key, target), options)) this.#emitter.emit("unlink", key, relation);
565
658
  }
566
659
  async links(key, relation, options) {
567
660
  (0, _orkestrel_database.checkAbort)(options?.signal);
568
661
  const resolved = this.#through(relation);
569
- const rows = await this.#storage.table(resolved.through).records({ conditions: [{
662
+ const junction = this.#storage.table(resolved.through);
663
+ return (await junction.records({ conditions: [{
570
664
  column: resolved.source,
571
665
  operator: "equals",
572
666
  values: [key],
573
667
  connector: "and"
574
- }] }, options);
575
- const target = resolved.target;
576
- const keys = [];
577
- for (const row of rows) {
578
- const value = (0, _orkestrel_database.extractKey)(row, target);
579
- if (value !== void 0) keys.push(value);
580
- }
581
- return keys;
668
+ }] }, options)).map((row) => (0, _orkestrel_database.extractKey)(readRow(junction.name, row), resolved.target)).filter(_orkestrel_contract.isDefined);
582
669
  }
583
670
  #through(relation) {
584
671
  const resolved = this.#resolved.get(relation);
585
- if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model '${this.#name}' has no relation '${relation}'`, {
672
+ if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model ${(0, _orkestrel_contract.renderPath)([this.#name])} has no relation ${(0, _orkestrel_contract.renderPath)([relation])}; declare it in the model's relation map`, {
586
673
  model: this.#name,
587
674
  relation
588
675
  });
589
- if (resolved.relationship !== "through") throw new RelationError("NOT_THROUGH", `Relation '${relation}' on '${this.#name}' is not a through`, {
676
+ if (resolved.relationship !== "through") throw new RelationError("NOT_THROUGH", `Relation ${(0, _orkestrel_contract.renderPath)([this.#name, relation])} is a ${resolved.relationship} relation; link, unlink, and links need a through relation built with hasThrough`, {
590
677
  model: this.#name,
591
678
  relation
592
679
  });
@@ -620,33 +707,28 @@ var Model = class {
620
707
  }
621
708
  async #loadBelongs(records, resolved, sub, options) {
622
709
  const column = resolved.column;
623
- const keys = [...new Set(records.map((record) => readColumn(record, column)).filter(_orkestrel_contract.isDefined))];
710
+ const keys = [...new Set(records.map((record) => (0, _orkestrel_contract.resolveField)(record, column)).filter(_orkestrel_database.isKey))];
624
711
  if (keys.length === 0) return records.map(() => void 0);
625
712
  const related = this.#storage.table(resolved.model);
626
- const rows = await related.records({ conditions: [{
627
- column: related.primary,
628
- operator: "any",
629
- values: keys,
630
- connector: "and"
631
- }] }, options);
713
+ const rows = (await related.get(keys)).filter((row) => row !== void 0).map((row) => readRow(related.name, row));
632
714
  const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
633
715
  return records.map((record) => {
634
- const fk = readColumn(record, column);
635
- return (0, _orkestrel_contract.isDefined)(fk) ? index.get(String(fk)) : void 0;
716
+ const fk = (0, _orkestrel_contract.resolveField)(record, column);
717
+ return (0, _orkestrel_database.isKey)(fk) ? index.get(String(fk)) : void 0;
636
718
  });
637
719
  }
638
720
  async #loadMany(records, resolved, sub, primary, options) {
639
721
  const foreign = resolved.key;
640
- const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
722
+ const keys = [...new Set(records.map((record) => (0, _orkestrel_contract.resolveField)(record, primary)).filter(_orkestrel_contract.isDefined))];
641
723
  if (keys.length === 0) return records.map(() => []);
642
- const rows = await this.#storage.table(resolved.model).records({ conditions: [{
724
+ const rows = (await this.#storage.table(resolved.model).records({ conditions: [{
643
725
  column: foreign,
644
726
  operator: "any",
645
727
  values: keys,
646
728
  connector: "and"
647
- }] }, options);
729
+ }] }, options)).map((row) => readRow(resolved.model, row));
648
730
  const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
649
- return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
731
+ return records.map((record) => groups.get(String((0, _orkestrel_contract.resolveField)(record, primary))) ?? []);
650
732
  }
651
733
  async #loadOne(records, resolved, sub, primary, options) {
652
734
  return (await this.#loadMany(records, resolved, sub, primary, options)).map((group) => group.length > 0 ? group[0] : void 0);
@@ -654,47 +736,28 @@ var Model = class {
654
736
  async #loadThrough(records, resolved, sub, primary, options) {
655
737
  const source = resolved.source;
656
738
  const target = resolved.target;
657
- const parents = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
739
+ const parents = [...new Set(records.map((record) => (0, _orkestrel_contract.resolveField)(record, primary)).filter(_orkestrel_contract.isDefined))];
658
740
  if (parents.length === 0) return records.map(() => []);
659
- const junctions = await this.#storage.table(resolved.through).records({ conditions: [{
741
+ const junctions = (await this.#storage.table(resolved.through).records({ conditions: [{
660
742
  column: source,
661
743
  operator: "any",
662
744
  values: parents,
663
745
  connector: "and"
664
- }] }, options);
665
- const targetsBySource = /* @__PURE__ */ new Map();
666
- for (const junction of junctions) {
667
- const value = readColumn(junction, target);
668
- if (!(0, _orkestrel_contract.isDefined)(value)) continue;
669
- const owner = String(readColumn(junction, source));
670
- const list = targetsBySource.get(owner);
671
- if (list !== void 0) list.push(value);
672
- else targetsBySource.set(owner, [value]);
673
- }
674
- const targets = [...new Set([...targetsBySource.values()].flat())];
746
+ }] }, options)).map((junction) => readRow(resolved.through, junction));
747
+ const targets = [...new Set(junctions.map((junction) => (0, _orkestrel_contract.resolveField)(junction, target)).filter(_orkestrel_database.isKey))];
675
748
  if (targets.length === 0) return records.map(() => []);
749
+ (0, _orkestrel_database.checkAbort)(options?.signal);
676
750
  const related = this.#storage.table(resolved.model);
677
- const rows = await related.records({ conditions: [{
678
- column: related.primary,
679
- operator: "any",
680
- values: targets,
681
- connector: "and"
682
- }] }, options);
751
+ const rows = (await related.get(targets)).filter((row) => row !== void 0).map((row) => readRow(related.name, row));
683
752
  const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
684
- return records.map((record) => {
685
- const out = [];
686
- for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
687
- const row = index.get(String(value));
688
- if (row !== void 0) out.push(row);
689
- }
690
- return out;
691
- });
753
+ const groups = groupRows(junctions, source);
754
+ return records.map((record) => (groups.get(String((0, _orkestrel_contract.resolveField)(record, primary))) ?? []).map((junction) => (0, _orkestrel_contract.resolveField)(junction, target)).filter(_orkestrel_database.isKey).map((value) => index.get(String(value))).filter(_orkestrel_contract.isDefined));
692
755
  }
693
756
  async #loadMorph(records, resolved, sub, primary, options) {
694
757
  const foreign = resolved.key;
695
- const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
758
+ const keys = [...new Set(records.map((record) => (0, _orkestrel_contract.resolveField)(record, primary)).filter(_orkestrel_contract.isDefined))];
696
759
  if (keys.length === 0) return records.map(() => []);
697
- const rows = await this.#storage.table(resolved.model).records({ conditions: [{
760
+ const rows = (await this.#storage.table(resolved.model).records({ conditions: [{
698
761
  column: foreign,
699
762
  operator: "any",
700
763
  values: keys,
@@ -704,9 +767,9 @@ var Model = class {
704
767
  operator: "equals",
705
768
  values: [resolved.label],
706
769
  connector: "and"
707
- }] }, options);
770
+ }] }, options)).map((row) => readRow(resolved.model, row));
708
771
  const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
709
- return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
772
+ return records.map((record) => groups.get(String((0, _orkestrel_contract.resolveField)(record, primary))) ?? []);
710
773
  }
711
774
  async #nest(model, rows, sub, options) {
712
775
  if ((0, _orkestrel_contract.isBoolean)(sub) || rows.length === 0) return rows;
@@ -718,7 +781,7 @@ var Model = class {
718
781
  };
719
782
  // src/core/RelationManager.ts
720
783
  /**
721
- * Resolves a {@link RelationsShape} once at construction and vends a typed
784
+ * Resolves a {@link RelationSchema} once at construction and vends a typed
722
785
  * {@link ModelInterface} per declared table.
723
786
  *
724
787
  * @remarks
@@ -767,7 +830,10 @@ var RelationManager = class {
767
830
  const resolved = resolveRelationMap(map);
768
831
  for (const [relation, entry] of resolved) {
769
832
  validateRelationTable(this.#broad, name, relation, entry.model);
770
- if (entry.relationship === "through") validateRelationTable(this.#broad, name, relation, entry.through, true);
833
+ if (entry.relationship === "through") {
834
+ validateRelationTable(this.#broad, name, relation, entry.through, true);
835
+ validateRelationJunction(name, entry, this.#broad.table(entry.through).primary);
836
+ }
771
837
  }
772
838
  this.#resolved.set(name, resolved);
773
839
  }
@@ -848,6 +914,7 @@ exports.Model = Model;
848
914
  exports.RelationError = RelationError;
849
915
  exports.RelationManager = RelationManager;
850
916
  exports.belongsTo = belongsTo;
917
+ exports.computeLinkKey = computeLinkKey;
851
918
  exports.countAttached = countAttached;
852
919
  exports.createRelationManager = createRelationManager;
853
920
  exports.groupRows = groupRows;
@@ -858,9 +925,12 @@ exports.hasThrough = hasThrough;
858
925
  exports.indexRows = indexRows;
859
926
  exports.isRelationDescriptor = isRelationDescriptor;
860
927
  exports.isRelationError = isRelationError;
861
- exports.readColumn = readColumn;
928
+ exports.readRow = readRow;
929
+ exports.relationDescriptorContract = relationDescriptorContract;
930
+ exports.relationDescriptorShape = relationDescriptorShape;
862
931
  exports.resolveRelation = resolveRelation;
863
932
  exports.resolveRelationMap = resolveRelationMap;
933
+ exports.validateRelationJunction = validateRelationJunction;
864
934
  exports.validateRelationTable = validateRelationTable;
865
935
 
866
936
  //# sourceMappingURL=index.cjs.map