@stonyx/orm 0.3.2-alpha.66 → 0.3.2-alpha.68

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.
@@ -1,7 +1,7 @@
1
1
  import Orm, { store } from '@stonyx/orm';
2
2
  import OrmRecord from './record.js';
3
3
  import { getGlobalRegistry, getPendingRegistry, getPendingBelongsToRegistry, getBelongsToRegistry, getHasManyRegistry } from './relationships.js';
4
- import { isOrmRecord } from './utils.js';
4
+ import { isOrmRecord, maxNumericId, NO_FREE_ID_ERROR } from './utils.js';
5
5
  const defaultOptions = {
6
6
  isDbRecord: false,
7
7
  serialize: true,
@@ -153,17 +153,58 @@ export function updateRecord(record, rawData, userOptions = {}) {
153
153
  }
154
154
  }
155
155
  /**
156
- * gets the next available id based on last record entry.
156
+ * gets the next available id, based on the HIGHEST id present.
157
157
  *
158
158
  * In MySQL mode with numeric IDs, assigns a temporary pending ID.
159
159
  * MySQL's AUTO_INCREMENT provides the real ID after INSERT.
160
+ *
161
+ * ---------------------------------------------------------------------------
162
+ * WAS: `Array.from(storeMap.values()).at(-1).id + 1` — the LAST INSERTED id,
163
+ * not the maximum (abofs/stonyx-orm#203). The store is a Map, so insertion
164
+ * order stops being ascending the moment a record is deleted and recreated, a
165
+ * db.json is written out of order, a directory-mode store is read back in file
166
+ * order, or a caller POSTs a high id and then a low one. After that, every
167
+ * server-assigned id is one that is ALREADY TAKEN — and `createRecord`'s
168
+ * last-entry-wins branch then overwrites that record IN PLACE and answers 200.
169
+ * No error, no 409, and the store's size does not change. That is the whole
170
+ * defect, and it is reachable from a create with NO id at all, which is the
171
+ * most ordinary write a consumer performs.
172
+ *
173
+ * Covered by test/unit/assign-record-id-test.ts. Note for anyone changing this
174
+ * function: before that file existed, the whole suite scored 951/0 both on the
175
+ * defect and on a naive `Math.max` fix that introduced a second one. A green
176
+ * suite is not evidence here; those assertions are.
177
+ * ---------------------------------------------------------------------------
160
178
  */
161
179
  function assignRecordId(modelName, rawData) {
162
- if (rawData.id)
180
+ // PRESENCE, not truthiness. `0` is a legal value for an `attr('number')` id,
181
+ // and `if (rawData.id) return` silently reassigned it, handing the caller back
182
+ // a different record than the one it named (#203).
183
+ //
184
+ // `''` is deliberately NOT honoured here and this is not an oversight: it is
185
+ // the one string that means "no id". `parseInt('')` is `NaN`, a record CAN be
186
+ // held under the key `NaN`, and orm-request.ts's body-id normalisation relies
187
+ // on `''` staying absent — otherwise `POST {"id":""}` answers 409 against a
188
+ // record it never named.
189
+ //
190
+ // WHAT WIDENING THIS TO `!== undefined` ACTUALLY DOES, measured rather than
191
+ // asserted: `{id: ''}` early-returns, `parseInt('')` NaNs it, and the record
192
+ // lands on the store's `NaN` slot and OVERWRITES whatever is there — #203's
193
+ // own defect class. It does NOT turn access-filter-enforcement-test.ts
194
+ // assertion 44 red; an earlier revision of this comment claimed it did, which
195
+ // converted an unknown into a false assurance. AC6's BOUNDARY assertions are
196
+ // what catch it, and they only do so because they seed the `NaN` slot first.
197
+ if (rawData.id || rawData.id === 0)
163
198
  return;
164
199
  // In SQL mode with numeric IDs, defer to database auto-increment.
165
200
  // Use unique negative integers — they survive the number transform (parseInt preserves negatives)
166
201
  // and avoid NaN store-key collisions that string pending IDs caused.
202
+ //
203
+ // This early return is ABOVE the max computation on purpose: a pending
204
+ // negative must never be a candidate for, or be perturbed by, the max path.
205
+ // Pinned directly (AC5.3) rather than by asserting the max is unaffected —
206
+ // that assertion could not have failed, because nothing negative ever reaches
207
+ // the code below.
167
208
  if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
168
209
  rawData.id = -(++pendingIdCounter);
169
210
  rawData.__pendingSqlId = true;
@@ -173,13 +214,197 @@ function assignRecordId(modelName, rawData) {
173
214
  if (!storeMap)
174
215
  throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
175
216
  const modelStore = Array.from(storeMap.values()).filter(isOrmRecord);
176
- const lastRecord = modelStore.at(-1);
177
- rawData.id = lastRecord ? lastRecord.id + 1 : 1;
217
+ // ONE COPY of the max-numeric-id reduce, in src/utils.ts. There were three
218
+ // (here, StandaloneDB.create, and the #203 test helper) and `docs/
219
+ // improvements.md`'s WET Code category prescribes the extraction. What that
220
+ // helper must NOT be is `Math.max(...ids)`; the reason is measured and it is
221
+ // documented at the helper rather than duplicated here. Pinned by AC2.
222
+ const maxId = maxNumericId(modelStore);
223
+ // THE OCCUPANCY CHECK RUNS ON THE LANDING KEY, NOT ON THE RAW CANDIDATE, and
224
+ // the difference is a silent data loss rather than a nicety.
225
+ //
226
+ // `createRecord` looks the record up under `rawData.id` (:50) but WRITES it
227
+ // under `record.id` (:69) — the value after the model's declared id transform
228
+ // has run inside `serialize`. When the transform is not the identity those two
229
+ // differ, so a guard written as `storeMap.has(rawData.id)` checks a key the
230
+ // record will never occupy, misses an occupied slot and overwrites it —
231
+ // measured on an `uppercase`-id model: the guard checks `owner-1`, the record
232
+ // lands under `OWNER-1`, store size unchanged, no error. That is
233
+ // abofs/stonyx-orm#205's lookup-key/landing-key divergence reappearing inside
234
+ // #203's own fix, which is why AC4 exists and why `rawData.id` is set to the
235
+ // LANDING key below.
236
+ //
237
+ // THE SCOPE OF THAT CLAIM, stated rather than implied. Setting `rawData.id` to
238
+ // the landing key makes :50 and :69 agree for every IDEMPOTENT id transform —
239
+ // `number`, `float`, `string`, `passthrough`, `uppercase`, `trim`. It does NOT
240
+ // make them agree for `date` or `timestamp`: `transforms.date` returns a NEW
241
+ // object every call and a `Map` keys by identity, so `storeMap.has(landingKey)`
242
+ // is always `false` there and the occupancy check is vacuous. `dev` is broken
243
+ // for those types too — this is not a regression — but no comment here may
244
+ // claim a property it was not measured to have (#212 § AC5).
245
+ //
246
+ // Resolved ONCE, outside the walk: `getIdType` instantiates the model class,
247
+ // so resolving it per candidate would put a model construction on every
248
+ // iteration of a loop that exists to walk past occupied slots.
249
+ const toStoreKey = storeKeyDeriver(modelName);
250
+ // DOES THIS MODEL FILE ITS RECORDS UNDER STRING KEYS? Decided by RUNNING the
251
+ // model's own id transform once, not by matching a type NAME against a list:
252
+ // `Orm.instance.transforms` (main.ts:70) is a public, MUTABLE instance
253
+ // property, so any enumeration of "the string-ish types" written here would be
254
+ // wrong the moment a consumer registers one.
255
+ const stringKeyed = typeof toStoreKey(maxId + 1) === 'string';
256
+ // THE CANDIDATE FOR A STRING-KEYED MODEL IS NOT A BARE NUMBER, and this is
257
+ // abofs/stonyx-orm#209 — which is REOPENED — not aesthetics.
258
+ //
259
+ // `orm-request.ts`'s `coerceId` (:322) resolves a NUMERIC-LOOKING string to a
260
+ // NUMBER on every id-bearing surface, while a model declaring
261
+ // `id = attr('string')` files under the STRING key. So a server-assigned `'1'`
262
+ // produces a record that is created and then NOT ADDRESSABLE. Measured over
263
+ // the route, owner store `{'1': ...}`:
264
+ //
265
+ // GET /owners/1 -> 404 (the record exists)
266
+ // DELETE /owners/1 -> 404
267
+ // GET /owners/owner-1 -> 200
268
+ //
269
+ // and `_withHooks` (:1185) hands an after-`create` hook
270
+ // `context.record === undefined` for the same reason. `dev` assigned `'bob1'`,
271
+ // which is not numeric-looking, so `dev` has neither problem: a bare-number
272
+ // candidate would move #209 from "a caller supplied a numeric-looking id" onto
273
+ // the DEFAULT path for every server-assigned create on every string-id model.
274
+ // Prefixing with the model name keeps #209's population exactly as narrow as
275
+ // it already was, without touching the one shared coercion or the assertion
276
+ // that pins #209 open. Pinned by AC3.
277
+ const toCandidate = stringKeyed
278
+ ? (value) => `${modelName}-${value}`
279
+ : (value) => value;
280
+ // `maxId + 1` is the id AC1 pins: strictly greater than every numeric key
281
+ // present. IT IS NOT ALWAYS AVAILABLE, and that gap was a live denial of
282
+ // service. Float64 has no integer successor at or above 2^53, so
283
+ // `maxId + 1 === maxId` for every `maxId >= 9007199254740992` and `+ 1` inside
284
+ // the walk is a NO-OP there. One record filed under that key — which an
285
+ // unauthenticated `POST {"id":9007199254740992}` puts there, and which reaches
286
+ // even a filter-protected collection through has-many.ts:65 (#207), a channel
287
+ // GATE 0 does not cover — made the walk unable to advance, so it exhausted its
288
+ // budget and threw on EVERY subsequent server-assigned create, permanently,
289
+ // until that record was deleted. Measured over the route: 200, then 500 for
290
+ // every no-id create. `dev` answers 200.
291
+ //
292
+ // So a store holding one adversarial record must not disable its collection.
293
+ // When "above the max" is not a usable strategy the walk RESTARTS FROM 1: the
294
+ // store holds at most `size` keys, so one of `1 .. size + 1` is always free
295
+ // under an injective id transform. Pinned by AC7.
296
+ const start = maxId + 1;
297
+ let landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, start);
298
+ // THE RESTART, and it is the whole of the ceiling fix. Killing mutation:
299
+ // delete this block -> AC7 goes red (the route answers 409 instead of the
300
+ // created resource).
301
+ if (landingKey === NO_FREE_KEY && start !== 1) {
302
+ landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, 1);
303
+ }
304
+ if (landingKey === NO_FREE_KEY) {
305
+ // Reachable only with a NON-INJECTIVE id transform — see `firstFreeKey`.
306
+ // `createHandler` matches this message and answers 409 rather than letting it
307
+ // reach express's default handler, which serialises a stack trace with
308
+ // absolute install paths outside NODE_ENV=production (the hazard
309
+ // orm-request.ts:553-558 exists to name). Pinned by AC8.
310
+ throw new Error(`${NO_FREE_ID_ERROR} for model "${modelName}"`);
311
+ }
312
+ rawData.id = landingKey;
178
313
  }
179
- function isStringIdModel(modelName) {
180
- const modelClass = Orm.instance.getRecordClasses(modelName).modelClass;
314
+ // Returned instead of a key so that "no key" cannot be confused with a transform
315
+ // that legitimately produced `undefined` or `null`.
316
+ const NO_FREE_KEY = Symbol('no free store key');
317
+ /**
318
+ * The first store key at or above `start` that no record occupies, walking
319
+ * candidate ids upward, or `NO_FREE_KEY` if the walk cannot reach one.
320
+ */
321
+ function firstFreeKey(storeMap, toStoreKey, toCandidate, start) {
322
+ let candidate = start;
323
+ let landingKey = toStoreKey(toCandidate(candidate));
324
+ let attempts = 0;
325
+ while (storeMap.has(landingKey)) {
326
+ // THE BOUND IS EXACTLY TIGHT, not conservative: this walk tries
327
+ // `storeMap.size + 1` DISTINCT candidates against at most `storeMap.size`
328
+ // occupied keys, so under an injective `toStoreKey` it provably cannot fire.
329
+ // Under a non-injective one it provably terminates — and that is a reachable
330
+ // consumer state rather than a hypothesis: `transforms.boolean`
331
+ // (transforms.ts:4) collapses every candidate onto `true`/`false`, and
332
+ // `Orm.instance.transforms` (main.ts:70) is public and MUTABLE, so a consumer
333
+ // can register an arbitrary non-injective transform and name it as an id
334
+ // type. Without this, a no-id create spins forever inside a synchronous store
335
+ // walk and pins a worker, which is worse than either collision policy. Its
336
+ // EXISTENCE and its THRESHOLD are both pinned by AC8: deleting it makes AC8
337
+ // HANG rather than fail, and weakening it to fire on the first collision
338
+ // makes AC8.1 red.
339
+ if (++attempts > storeMap.size)
340
+ return NO_FREE_KEY;
341
+ // NOTE FOR ANYONE ADDING A SECOND EXIT HERE. A `candidate + 1 === candidate`
342
+ // float-saturation check was written, measured, and REMOVED: with the
343
+ // restart-from-1 above in place, deleting the saturation check leaves the
344
+ // whole suite green, because the budget reaches the same `NO_FREE_KEY` one
345
+ // pass later and the restart still answers. An unkillable guard in a change
346
+ // whose deliverable is falsifiable coverage is exactly what this story exists
347
+ // to stop shipping. `+ 1` being a no-op at 2^53 costs `size` extra `Map.has`
348
+ // calls on that one path and changes no outcome.
349
+ candidate += 1;
350
+ landingKey = toStoreKey(toCandidate(candidate));
351
+ }
352
+ return landingKey;
353
+ }
354
+ /**
355
+ * Returns the derivation that maps an id VALUE to the store KEY a record
356
+ * carrying it will actually be filed under — the model's declared id transform,
357
+ * the same one `serialize` runs at createRecord:68 before the `.set` at :69.
358
+ */
359
+ function storeKeyDeriver(modelName) {
360
+ const idType = getIdType(modelName);
361
+ const transform = idType ? Orm.instance?.transforms?.[idType] : undefined;
362
+ // SURVIVOR, RETAINED, with its reachability condition stated rather than left
363
+ // silent — `docs/project-structure.md` § "unkillable code reads as coverage and
364
+ // is not" is the standing rule and it applies outside orm-request.ts too.
365
+ //
366
+ // No mutation in this repo can kill this branch, and that is STRUCTURAL rather
367
+ // than an untested gap: `Model` declares `id = attr('number')` (model.ts:15) so
368
+ // every registered model has an id type; `ModelProperty` refuses a type with no
369
+ // registered transform (model-property.ts:4) so a declared type always
370
+ // resolves; and `getIdType` can therefore only return `undefined` when
371
+ // `getRecordClasses` yields no `modelClass` — in which case `createRecord`
372
+ // throws at :62 a few lines later regardless, so no record is ever filed
373
+ // through this branch.
374
+ //
375
+ // BECOMES REACHABLE if a model can be declared without an `id` property, if a
376
+ // store map can exist for a model with no registered class, or if
377
+ // `createRecord` stops constructing the model class. Kept rather than deleted
378
+ // because the alternative on that path is a `transform is not a function`
379
+ // TypeError, and because identity is exactly what `createRecord` would file
380
+ // under when no transform exists — the two agree, which is the property AC4 is
381
+ // about.
382
+ if (typeof transform !== 'function')
383
+ return value => value;
384
+ return value => {
385
+ try {
386
+ return transform(value);
387
+ }
388
+ catch {
389
+ // `uppercase` and `trim` (transforms.ts:11-12) call a string method on the
390
+ // value directly, so a NUMERIC candidate throws `value?.toUpperCase is not
391
+ // a function`. On `dev` they never saw one — `lastRecord.id + 1` on a
392
+ // string id is a string — so feeding them a number here would regress a
393
+ // legal, registered id type into an uncaught 500. The retry feeds the
394
+ // string form, which is the shape an id actually arrives in off a JSON body
395
+ // or a URL param. A transform that throws on BOTH shapes still propagates.
396
+ // Pinned by AC9.
397
+ return transform(String(value));
398
+ }
399
+ };
400
+ }
401
+ function getIdType(modelName) {
402
+ const modelClass = Orm.instance?.getRecordClasses(modelName).modelClass;
181
403
  if (!modelClass)
182
- return false;
404
+ return undefined;
183
405
  const model = new modelClass(modelName);
184
- return model.id?.type === 'string';
406
+ return model.id?.type;
407
+ }
408
+ function isStringIdModel(modelName) {
409
+ return getIdType(modelName) === 'string';
185
410
  }
@@ -218,7 +218,8 @@ import { getPluralName } from './plural-registry.js';
218
218
  import { getBeforeHooks, getAfterHooks } from './hooks.js';
219
219
  import config from 'stonyx/config';
220
220
  import log from 'stonyx/log';
221
- import { isOrmRecord } from './utils.js';
221
+ import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
222
+ import { interpretAccess, createLinkageFilter } from './access-verdict.js';
222
223
  const methodAccessMap = {
223
224
  GET: 'read',
224
225
  POST: 'create',
@@ -561,7 +562,13 @@ export default class OrmRequest extends Request {
561
562
  if (queryFilterPredicate)
562
563
  recordsToReturn = recordsToReturn.filter(queryFilterPredicate);
563
564
  const baseUrl = getBaseUrl(request);
564
- const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
565
+ // ONE filter per REQUEST, not one per record: it carries the per-type
566
+ // verdict cache and the per-(type, id) decision cache, and both are
567
+ // worthless if it is rebuilt inside the map. Measured on this exact
568
+ // surface with no `include=`: 48 linkage entries collapse to 7 distinct
569
+ // (type, id) pairs.
570
+ const linkage = createLinkageFilter(request);
571
+ const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
565
572
  return buildResponse(data, request.query?.include, recordsToReturn, {
566
573
  links: { self: `${baseUrl}/${pluralizedModel}` },
567
574
  baseUrl
@@ -579,7 +586,13 @@ export default class OrmRequest extends Request {
579
586
  const fieldsMap = parseFields(request.query);
580
587
  const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
581
588
  const baseUrl = getBaseUrl(request);
582
- return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
589
+ const linkage = createLinkageFilter(request);
590
+ // `buildResponse` is deliberately NOT given the linkage filter. It builds
591
+ // `included`, and WHETHER A RESOURCE APPEARS THERE AT ALL is membership,
592
+ // which belongs to abofs/stonyx-orm#233 -- see this file's #234 note and
593
+ // the ownership boundary in that issue. Only the PRIMARY document's
594
+ // linkage is filtered here.
595
+ return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
583
596
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
584
597
  baseUrl
585
598
  });
@@ -711,7 +724,39 @@ export default class OrmRequest extends Request {
711
724
  // is true for a record the request did not create. The map's size is the
712
725
  // only O(1) signal that distinguishes an insert from an overwrite.
713
726
  const slotsBefore = store.get(model)?.size ?? 0;
714
- const created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
727
+ // THE ONE `createRecord` FAILURE THIS ROUTE ANSWERS RATHER THAN
728
+ // PROPAGATES, and it is narrow on purpose.
729
+ //
730
+ // `assignRecordId` throws when it cannot derive a free store key for a
731
+ // server-assigned id. Unguarded that rejection is auto-forwarded -- there
732
+ // is no catch here, none in @stonyx/rest-server's dispatcher
733
+ // (dist/request.js:41-70), and express 5 hands it to its default error
734
+ // handler, which serialises the STACK, with absolute install paths and the
735
+ // internal module graph, to an unauthenticated caller outside
736
+ // NODE_ENV=production. That is the hazard :553-558 already names in this
737
+ // file, and every sibling refusal in this handler returns an integer
738
+ // status instead. So this one returns 409, matching the client-duplicate
739
+ // refusal at :713: the caller asked for a record and the collection has no
740
+ // id to give it.
741
+ //
742
+ // MATCHED ON THE SHARED PREFIX, not on a literal, and NOT by catching
743
+ // everything: `createRecord` also throws for "ORM is not ready", a
744
+ // read-only view and an unregistered model store, and turning any of those
745
+ // into a 409 would report a configuration fault as a conflict. Anything
746
+ // else is re-thrown unchanged.
747
+ let created;
748
+ try {
749
+ created = createRecord(model, recordAttributes, { serialize: false, _skipAutoPersist: true });
750
+ }
751
+ catch (error) {
752
+ if (!(error instanceof Error) || !error.message.startsWith(NO_FREE_ID_ERROR))
753
+ throw error;
754
+ // Not silently. A collection that can no longer assign an id is a
755
+ // configuration fault (a non-injective id transform), and a bare 409
756
+ // with no diagnostic is indistinguishable from an ordinary duplicate.
757
+ log.error?.(`[@stonyx/orm] ${error.message}`);
758
+ return 409; // Conflict
759
+ }
715
760
  const record = isOrmRecord(created) ? created : null;
716
761
  if (!record)
717
762
  return 500;
@@ -735,11 +780,32 @@ export default class OrmRequest extends Request {
735
780
  //
736
781
  // Both conditions are required and neither implies the other:
737
782
  // createdNewSlot -- the store grew, so this request inserted rather
738
- // than overwrote. Guards `assignRecordId` picking an
739
- // id that is already taken (it returns
740
- // last-INSERTED + 1, not max + 1, so a store whose
741
- // insertion order is not ascending collides) -- see
742
- // abofs/stonyx-orm#203.
783
+ // than overwrote. SURVIVOR AS OF #203, AND THAT IS
784
+ // WHAT THIS NOTE IS FOR. It used to be killable:
785
+ // `assignRecordId` returned last-INSERTED + 1, so a
786
+ // server-assigned id could land on an occupied slot,
787
+ // `createRecord` updated in place, and removing this
788
+ // half turned access-filter-enforcement-test.ts
789
+ // assertion 31 red. #203 closed that: the
790
+ // server-assigned path now walks past occupied keys,
791
+ // so no create reaching here can overwrite. Measured
792
+ // -- delete `createdNewSlot &&` below: `dev` gives
793
+ // 55 pass / 1 fail with assertion 31 RED, this tree
794
+ // gives 56 pass / 0 fail, GREEN.
795
+ // KEPT ANYWAY, AND NOT FOR THE OLD REASON. Without
796
+ // it a denied create becomes `store.remove` on a key
797
+ // the caller may have influenced, which :815-820
798
+ // records as having been an unauthenticated deletion
799
+ // primitive across the whole id space. BECOMES
800
+ // KILLABLE AGAIN the moment any caller-supplied id
801
+ // can reach `createRecord` from this handler --
802
+ // which is exactly what has-many.ts:65 and
803
+ // belongs-to.ts:45 already do for ANOTHER model's
804
+ // store (abofs/stonyx-orm#207), and what a third
805
+ // un-stripped id channel would do for this one
806
+ // (#204). Do not delete it on the strength of #203
807
+ // being closed; that is the reasoning :862-867 warns
808
+ // about, one level up.
743
809
  // identity -- the slot still holds the object we just created,
744
810
  // so nothing between createRecord and here replaced
745
811
  // it. Deleting this half SURVIVES the suite, and it
@@ -1113,15 +1179,21 @@ export default class OrmRequest extends Request {
1113
1179
  return 404;
1114
1180
  const relatedData = record.__relationships[relationshipName];
1115
1181
  const baseUrl = getBaseUrl(request);
1182
+ // LINKAGE ONLY. This filter decides which ids the emitted documents may
1183
+ // NAME in their own `relationships.*.data`; it does NOT decide whether
1184
+ // the related records themselves are served -- that is the parent-only
1185
+ // filtering this route has done since #190, and widening it to the
1186
+ // related record is abofs/stonyx-orm#196.
1187
+ const linkage = createLinkageFilter(request);
1116
1188
  let data;
1117
1189
  if (info.isArray) {
1118
1190
  // hasMany - return array
1119
1191
  const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
1120
- data = related.map(r => r.toJSON?.({ baseUrl }));
1192
+ data = related.map(r => r.toJSON?.({ baseUrl, linkage }));
1121
1193
  }
1122
1194
  else {
1123
1195
  // belongsTo - return single or null
1124
- data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
1196
+ data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl, linkage }) : null;
1125
1197
  }
1126
1198
  return {
1127
1199
  links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}/${dasherizedName}` },
@@ -1232,26 +1304,23 @@ export default class OrmRequest extends Request {
1232
1304
  log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
1233
1305
  return 403; // Forbidden
1234
1306
  }
1235
- if (!access)
1236
- return 403;
1237
- if (typeof access === 'function') {
1238
- state.filter = access;
1239
- return undefined;
1240
- }
1241
- if (access === true)
1242
- return undefined;
1243
- // `AccessMethod` declares `string` legal and it fell through every branch
1244
- // above, returning undefined -- i.e. FULL CRUD, no filter. `return 'read'`
1245
- // is the natural reading of a type that lists `string` first, and it
1246
- // granted DELETE. A bare string is one permission, not a grant of all four.
1247
- const permitted = typeof access === 'string' ? [access] : access;
1248
- // Anything that is not a permission array by this point -- an object, a
1249
- // number, a Symbol -- is a consumer mistake, and the only safe reading of a
1250
- // shape the contract does not define is a denial. Fail CLOSED.
1251
- if (!Array.isArray(permitted))
1252
- return 403;
1253
- if (!permitted.includes(methodAccessMap[request.method]))
1307
+ // THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
1308
+ //
1309
+ // It used to be inline here, and it was the only copy, which was fine while
1310
+ // `auth()` was the only thing that had to ask. It is not any more: the
1311
+ // linkage path has to ask model X's predicate about model X's records while
1312
+ // servicing a request routed to model Y, and a second inline copy of these
1313
+ // six branches would be a second authorization vocabulary -- one that can
1314
+ // drift, and that reviewers would have to notice had drifted. The branch
1315
+ // order in `interpretAccess` is this block, moved, not rewritten.
1316
+ const verdict = interpretAccess(access, methodAccessMap[request.method]);
1317
+ if (!verdict.granted)
1254
1318
  return 403;
1319
+ // The function return shape is the per-record hook, and `state` is the
1320
+ // whole transport for it: @stonyx/rest-server memoises one state object per
1321
+ // request and hands the same one to `auth()` and to the handler.
1322
+ if (verdict.filter)
1323
+ state.filter = verdict.filter;
1255
1324
  return undefined;
1256
1325
  }
1257
1326
  }
package/dist/record.d.ts CHANGED
@@ -2,6 +2,18 @@ import type Serializer from './serializer.js';
2
2
  interface ToJSONOptions {
3
3
  fields?: Set<string>;
4
4
  baseUrl?: string;
5
+ /**
6
+ * An ALREADY-RESOLVED linkage decision, supplied by a caller that holds the
7
+ * request (abofs/stonyx-orm#234). Returning `false` for a related record
8
+ * drops that record's `{ type, id }` from `relationships.*.data`.
9
+ *
10
+ * This method APPLIES a verdict; it never RESOLVES one -- see
11
+ * `src/access-verdict.ts` for the two measured reasons it cannot. ABSENT is
12
+ * the default and the default is TODAY'S DOCUMENT, unchanged, because
13
+ * `toJSON` is also the `JSON.stringify` hook and an implicit caller has no
14
+ * syntactic place to pass this (abofs/stonyx-orm#230).
15
+ */
16
+ linkage?: (type: string, record: unknown) => boolean;
5
17
  }
6
18
  interface SerializeOptions {
7
19
  update?: boolean;
package/dist/record.js CHANGED
@@ -65,7 +65,13 @@ export default class Record {
65
65
  toJSON(options = {}) {
66
66
  if (!this.__serialized)
67
67
  throw new Error('Record must be serialized before being converted to JSON');
68
- const { fields, baseUrl } = options;
68
+ // DESTRUCTURED FROM A VALUE THAT IS NOT ALWAYS AN OBJECT. `toJSON` is the
69
+ // ECMAScript serialization hook, so `JSON.stringify({ data: record })`
70
+ // arrives here as `toJSON('data')` -- a STRING in the options slot.
71
+ // Destructuring a string yields `undefined` for every key, which is exactly
72
+ // the no-argument default, so the implicit path keeps working and keeps
73
+ // emitting today's document (abofs/stonyx-orm#230).
74
+ const { fields, baseUrl, linkage } = options;
69
75
  const { __data: data } = this;
70
76
  const modelName = this.__model.__name;
71
77
  const pluralizedModelName = getPluralName(modelName);
@@ -87,9 +93,20 @@ export default class Record {
87
93
  for (const [key, childRecord] of Object.entries(this.__relationships)) {
88
94
  if (fields && !fields.has(key))
89
95
  continue;
96
+ // The linkage decision is applied HERE, alongside the existing
97
+ // `__model` liveness check, and it produces exactly the shapes that
98
+ // check already produces: a dropped hasMany member leaves `data: []`,
99
+ // a dropped belongsTo leaves `data: null`. Both already ship -- a
100
+ // genuinely-empty hasMany emits `data: []` with links, and a cleaned
101
+ // belongsTo emits `data: null` -- so a filtered relationship is
102
+ // BYTE-IDENTICAL to an empty one and there is no new wire shape and no
103
+ // oracle. It never throws: a throw here escapes the enclosing
104
+ // `JSON.stringify` and takes `console.log` and `Orm.db.save()`'s
105
+ // neighbours with it, which is a far worse failure mode than a status.
106
+ const isLinkable = (r) => !linkage || linkage(r.__model.__name, r);
90
107
  const relationshipData = Array.isArray(childRecord)
91
- ? childRecord.filter((r) => r?.__model).map((r) => ({ type: r.__model.__name, id: r.id }))
92
- : (childRecord && childRecord.__model) ? { type: childRecord.__model.__name, id: childRecord.id } : null;
108
+ ? childRecord.filter((r) => r?.__model).filter(isLinkable).map((r) => ({ type: r.__model.__name, id: r.id }))
109
+ : (childRecord && childRecord.__model && isLinkable(childRecord)) ? { type: childRecord.__model.__name, id: childRecord.id } : null;
93
110
  // Dasherize the key for URL paths (e.g., accessLinks -> access-links)
94
111
  const dasherizedKey = camelCaseToKebabCase(key);
95
112
  relationships[dasherizedKey] = { data: relationshipData };
@@ -7,6 +7,10 @@
7
7
  */
8
8
  import fs from 'fs/promises';
9
9
  import path from 'path';
10
+ // `./utils.js` pulls in `@stonyx/utils/string` and nothing else -- no ORM
11
+ // bootstrap, no `@stonyx/orm` index, no side effects -- so the "no framework
12
+ // dependencies" property above still holds.
13
+ import { maxNumericId } from './utils.js';
10
14
  export default class StandaloneDB {
11
15
  mode;
12
16
  dbPath;
@@ -102,11 +106,19 @@ export default class StandaloneDB {
102
106
  async create(collection, data) {
103
107
  const records = await this.readCollection(collection);
104
108
  if (!data.id) {
105
- const maxId = records.reduce((max, r) => {
106
- const rid = typeof r.id === 'number' ? r.id : 0;
107
- return rid > max ? rid : max;
108
- }, 0);
109
- data.id = maxId + 1;
109
+ // SHARED WITH `assignRecordId` (src/manage-record.ts), which is the other
110
+ // place this repo picks a server-assigned id. It was a second copy of the
111
+ // reduce, and nothing here pointed at it — a maintainer editing this
112
+ // method could not discover the other existed. See `maxNumericId` for why
113
+ // it is not `Math.max` (abofs/stonyx-orm#203).
114
+ //
115
+ // THE TWO ARE NOT THE SAME FUNCTION beyond this line, deliberately.
116
+ // `StandaloneDB` has no model, id-type or transform concept, so `maxId + 1`
117
+ // IS its store key; `assignRecordId` has to map the candidate through the
118
+ // model's declared id transform first, and then walk past occupied keys.
119
+ // Transplanting this method's remaining logic into the ORM reproduces
120
+ // #203's landing-key defect exactly — which is what AC4 pins.
121
+ data.id = maxNumericId(records) + 1;
110
122
  }
111
123
  // Check for duplicate id
112
124
  const existing = records.find(r => r.id === data.id);
@@ -87,9 +87,18 @@ export interface OrmRecord {
87
87
  __pendingSqlId?: boolean;
88
88
  };
89
89
  __relationships: Record<string, unknown>;
90
+ /**
91
+ * `linkage` is an ALREADY-RESOLVED decision supplied by a caller that holds
92
+ * the request (abofs/stonyx-orm#234): return `false` for a related record and
93
+ * its `{ type, id }` is dropped from `relationships.*.data`. Omitting it is
94
+ * the default, and the default is the pre-#234 document unchanged -- this
95
+ * method is also the `JSON.stringify` hook, so an implicit caller has no
96
+ * syntactic place to pass it (abofs/stonyx-orm#230).
97
+ */
90
98
  toJSON?(options?: {
91
99
  fields?: Set<string>;
92
100
  baseUrl?: string;
101
+ linkage?: (type: string, record: unknown) => boolean;
93
102
  }): Record<string, unknown>;
94
103
  [key: string]: unknown;
95
104
  }
package/dist/utils.d.ts CHANGED
@@ -5,3 +5,47 @@ export declare function isDbError(error: unknown): error is {
5
5
  };
6
6
  export declare function isOrmRecord(value: unknown): value is OrmRecord;
7
7
  export declare function pluralize(word: string): string;
8
+ /**
9
+ * The highest NUMERIC id held by a set of records, or `0` when there is none.
10
+ *
11
+ * ONE COPY, and the duplication it replaces is the reason it lives here. Three
12
+ * near-identical reduces existed at once: `assignRecordId` (server-assigned id
13
+ * selection), `StandaloneDB.create` (src/standalone-db.ts) and the #203 test
14
+ * helper. `docs/improvements.md`'s standing WET Code category prescribes
15
+ * exactly this remedy -- extract into the module that already acts as the
16
+ * shared utility -- and `assignRecordId` already imported `isOrmRecord` from
17
+ * here.
18
+ *
19
+ * NON-NUMBERS ARE SKIPPED RATHER THAN COERCED TO `0`, AND THAT IS STYLISTIC.
20
+ * `StandaloneDB`'s shape mapped them to `0`, which can never beat a seed of
21
+ * `0`. Measured over eleven input classes (`[]`, `1`, `NaN`, `'5'`, `'abc'`,
22
+ * `-3`, `0`, `null`, `undefined`, `Infinity`, and mixed arrays) the two shapes
23
+ * produce IDENTICAL output on every one. In particular `typeof NaN` is
24
+ * `'number'`, so NEITHER shape coerces `NaN` -- both reject it on `NaN > max`,
25
+ * which is `false`. An earlier revision of this code asserted that the skip was
26
+ * what made the `NaN` case work; it is not, the comparison is, and that claim
27
+ * has been removed rather than left standing.
28
+ *
29
+ * WHAT IS LOAD-BEARING is that this is not `Math.max(...ids)`. `Math.max`
30
+ * returns `NaN` if any operand is `NaN`, and a record CAN be held under the key
31
+ * `NaN` -- so the obvious fix assigns `NaN`, lands on that slot and overwrites
32
+ * it, which is abofs/stonyx-orm#203 in a new disguise. Pinned by
33
+ * test/unit/assign-record-id-test.ts AC2; before that file existed the whole
34
+ * suite scored 951/0 under exactly that fix.
35
+ */
36
+ export declare function maxNumericId(records: {
37
+ id?: unknown;
38
+ }[]): number;
39
+ /**
40
+ * The message prefix `assignRecordId` throws with when no free id can be
41
+ * derived for a model, and the ONE string `createHandler` matches on to answer
42
+ * `409` instead of letting the rejection reach express's default handler.
43
+ *
44
+ * It lives here rather than in either file because both need it and neither
45
+ * should own a copy: a literal in two places is how the two id coercions in
46
+ * orm-request.ts drifted apart (see `coerceId`). The repo has no error codes
47
+ * and no custom error classes -- 24 bare `throw new Error` sites across `src/`
48
+ * -- so a shared prefix is the narrowest way to make ONE failure distinguishable
49
+ * without inventing an error taxonomy this codebase does not use.
50
+ */
51
+ export declare const NO_FREE_ID_ERROR = "Cannot assign record ID: no free id available";