@stonyx/orm 0.3.2-beta.16 → 0.3.2-beta.160

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.
Files changed (66) hide show
  1. package/README.md +1409 -11
  2. package/config/environment.js +99 -12
  3. package/dist/access-verdict.d.ts +85 -0
  4. package/dist/access-verdict.js +284 -0
  5. package/dist/commands.js +34 -0
  6. package/dist/dynamodb/connection.d.ts +31 -0
  7. package/dist/dynamodb/connection.js +28 -0
  8. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  9. package/dist/dynamodb/dynamodb-db.js +596 -0
  10. package/dist/dynamodb/operation-builder.d.ts +76 -0
  11. package/dist/dynamodb/operation-builder.js +116 -0
  12. package/dist/dynamodb/type-map.d.ts +31 -0
  13. package/dist/dynamodb/type-map.js +48 -0
  14. package/dist/hooks.d.ts +15 -1
  15. package/dist/index.d.ts +3 -0
  16. package/dist/index.js +8 -0
  17. package/dist/main.d.ts +116 -0
  18. package/dist/main.js +129 -0
  19. package/dist/manage-record.js +268 -12
  20. package/dist/mysql/connection.d.ts +1 -0
  21. package/dist/mysql/mysql-db.d.ts +8 -0
  22. package/dist/mysql/mysql-db.js +44 -10
  23. package/dist/orm-request.d.ts +274 -3
  24. package/dist/orm-request.js +1259 -65
  25. package/dist/postgres/connection.d.ts +1 -0
  26. package/dist/postgres/connection.js +8 -6
  27. package/dist/postgres/postgres-db.d.ts +8 -0
  28. package/dist/postgres/postgres-db.js +44 -10
  29. package/dist/record.d.ts +16 -0
  30. package/dist/record.js +154 -6
  31. package/dist/relationships.js +1 -1
  32. package/dist/serializer.js +38 -2
  33. package/dist/setup-rest-server.js +51 -5
  34. package/dist/standalone-db.js +17 -5
  35. package/dist/store.d.ts +13 -1
  36. package/dist/store.js +65 -6
  37. package/dist/types/orm-types.d.ts +260 -0
  38. package/dist/utils.d.ts +44 -0
  39. package/dist/utils.js +47 -0
  40. package/package.json +16 -7
  41. package/src/access-verdict.ts +312 -0
  42. package/src/commands.ts +43 -0
  43. package/src/dynamodb/connection.ts +50 -0
  44. package/src/dynamodb/dynamodb-db.ts +811 -0
  45. package/src/dynamodb/operation-builder.ts +202 -0
  46. package/src/dynamodb/type-map.ts +54 -0
  47. package/src/hooks.ts +15 -1
  48. package/src/index.ts +10 -0
  49. package/src/main.ts +133 -0
  50. package/src/manage-record.ts +294 -18
  51. package/src/mysql/connection.ts +1 -0
  52. package/src/mysql/mysql-db.ts +44 -12
  53. package/src/orm-request.ts +1281 -67
  54. package/src/postgres/connection.ts +10 -6
  55. package/src/postgres/postgres-db.ts +44 -12
  56. package/src/record.ts +182 -6
  57. package/src/relationships.ts +1 -1
  58. package/src/serializer.ts +39 -2
  59. package/src/setup-rest-server.ts +59 -6
  60. package/src/standalone-db.ts +17 -6
  61. package/src/store.ts +68 -6
  62. package/src/types/orm-types.ts +268 -1
  63. package/src/types/stonyx-rest-server.d.ts +14 -1
  64. package/src/types/stonyx.d.ts +7 -1
  65. package/src/utils.ts +50 -0
  66. package/config/environment.ts +0 -91
package/dist/store.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import Orm, { relationships } from '@stonyx/orm';
2
- import { TYPES, getHasManyRegistry, getBelongsToRegistry, getPendingRegistry } from './relationships.js';
2
+ import { TYPES, getHasManyRegistry, getBelongsToRegistry, getPendingRegistry, getPendingBelongsToRegistry } from './relationships.js';
3
3
  import ViewResolver from './view-resolver.js';
4
4
  function isStoreRecord(value) {
5
5
  return typeof value === 'object' && value !== null && '__data' in value;
@@ -22,7 +22,7 @@ export default class Store {
22
22
  this.data = new Map();
23
23
  }
24
24
  get(key, id) {
25
- if (!id)
25
+ if (id === undefined)
26
26
  return this.data.get(key);
27
27
  return this.data.get(key)?.get(id);
28
28
  }
@@ -107,13 +107,14 @@ export default class Store {
107
107
  set(key, value) {
108
108
  this.data.set(key, value);
109
109
  }
110
- remove(key, id) {
110
+ remove(key, id, options) {
111
111
  // Guard: read-only views cannot have records removed
112
112
  if (Orm.instance?.isView?.(key)) {
113
113
  throw new Error(`Cannot remove records from read-only view '${key}'`);
114
114
  }
115
- // Auto-persist delete to SQL
116
- if (id && Orm.instance?.sqlDb) {
115
+ // Auto-persist delete to SQL (fire-and-forget) — skipped when the
116
+ // request path handles persist itself to avoid double-delete.
117
+ if (id && Orm.instance?.sqlDb && !options?._skipAutoPersist) {
117
118
  Orm.instance.sqlDb.persist('delete', key, { recordId: id }, {}).catch((err) => {
118
119
  Orm.instance.emitPersistError({
119
120
  operation: 'delete',
@@ -127,6 +128,40 @@ export default class Store {
127
128
  return this.unloadRecord(key, id);
128
129
  this.unloadAllRecords(key);
129
130
  }
131
+ /**
132
+ * Evict a record from the store with full relationship registry cleanup.
133
+ * The caller retains its reference to the returned record, which is the
134
+ * contract memory:false post-persist eviction relies on.
135
+ *
136
+ * @param registryId - The ID used when the record's relationships were
137
+ * registered. For SQL models with pending IDs, this is the original
138
+ * negative pending ID (before the adapter re-keyed to the real DB ID).
139
+ */
140
+ evictRecord(modelName, id, registryId) {
141
+ const modelStore = this.data.get(modelName);
142
+ if (!modelStore)
143
+ return;
144
+ if (typeof id !== 'string' && typeof id !== 'number')
145
+ return;
146
+ const raw = modelStore.get(id);
147
+ if (!raw || !isStoreRecord(raw))
148
+ return;
149
+ const visited = new Set([`${modelName}:${id}`]);
150
+ // Remove from hasMany arrays and nullify belongsTo references using current ID
151
+ // (the adapter updates record.id, so value-based matches need the current ID)
152
+ this._removeFromHasManyArrays(modelName, id, visited);
153
+ this._nullifyBelongsToReferences(modelName, id, visited);
154
+ // Clean up relationship registry entries using the registry key
155
+ // (belongsTo/hasMany registries were keyed by the ID at registration time,
156
+ // which may differ from the current ID if SQL persist re-keyed the record)
157
+ const cleanupId = registryId ?? id;
158
+ this._cleanupRelationshipRegistries(modelName, cleanupId);
159
+ // If registryId differs from id, also clean with current id as safety net
160
+ if (registryId !== undefined && registryId !== id) {
161
+ this._cleanupRelationshipRegistries(modelName, id);
162
+ }
163
+ modelStore.delete(id);
164
+ }
130
165
  unloadRecord(model, id, options = {}) {
131
166
  const modelStore = this.data.get(model);
132
167
  if (!modelStore) {
@@ -149,7 +184,6 @@ export default class Store {
149
184
  this._removeFromHasManyArrays(modelName, recordId, visited);
150
185
  this._nullifyBelongsToReferences(modelName, recordId, visited);
151
186
  this._cleanupRelationshipRegistries(modelName, recordId);
152
- recordToUnload.clean();
153
187
  this.data.get(modelName)?.delete(recordId);
154
188
  }
155
189
  }
@@ -230,6 +264,31 @@ export default class Store {
230
264
  const pendingMap = getPendingRegistry().get(modelName);
231
265
  if (pendingMap)
232
266
  pendingMap.delete(recordId);
267
+ // Clean pendingBelongsTo entries in both directions
268
+ const pendingBelongsToMap = getPendingBelongsToRegistry();
269
+ if (pendingBelongsToMap) {
270
+ // Direction 1: evicted record was the TARGET others were waiting for
271
+ const targetEntries = pendingBelongsToMap.get(modelName);
272
+ if (targetEntries)
273
+ targetEntries.delete(recordId);
274
+ // Direction 2: evicted record was the SOURCE with unresolved forward-references
275
+ for (const [, targetIdMap] of pendingBelongsToMap) {
276
+ for (const [targetId, entries] of targetIdMap) {
277
+ if (!Array.isArray(entries))
278
+ continue;
279
+ const filtered = entries.filter((e) => {
280
+ const entry = e;
281
+ return !(entry.sourceModelName === modelName && entry.relationshipId === recordId);
282
+ });
283
+ if (filtered.length === 0) {
284
+ targetIdMap.delete(targetId);
285
+ }
286
+ else if (filtered.length < entries.length) {
287
+ targetIdMap.set(targetId, filtered);
288
+ }
289
+ }
290
+ }
291
+ }
233
292
  }
234
293
  /**
235
294
  * Extracts hasMany and non-bidirectional belongsTo children from a record
@@ -16,6 +16,7 @@ export interface OrmMysqlConfig {
16
16
  connectionLimit?: number;
17
17
  migrationsDir?: string;
18
18
  migrationsTable?: string;
19
+ autoMigrate?: boolean;
19
20
  [key: string]: unknown;
20
21
  }
21
22
  export interface OrmPostgresConfig {
@@ -27,6 +28,7 @@ export interface OrmPostgresConfig {
27
28
  connectionLimit?: number;
28
29
  migrationsDir?: string;
29
30
  migrationsTable?: string;
31
+ autoMigrate?: boolean;
30
32
  [key: string]: unknown;
31
33
  }
32
34
  export interface OrmPaths {
@@ -42,6 +44,12 @@ export interface OrmRestServerConfig {
42
44
  route: string;
43
45
  metaRoute: boolean;
44
46
  }
47
+ export interface OrmDynamoDBConfig {
48
+ region?: string;
49
+ endpoint?: string;
50
+ tablePrefix?: string;
51
+ [key: string]: unknown;
52
+ }
45
53
  export interface OrmSection {
46
54
  db: OrmDbConfig;
47
55
  paths: OrmPaths;
@@ -49,6 +57,9 @@ export interface OrmSection {
49
57
  mysql?: OrmMysqlConfig;
50
58
  postgres?: OrmPostgresConfig;
51
59
  timescale?: OrmPostgresConfig;
60
+ dynamodb?: OrmDynamoDBConfig;
61
+ logColor?: string;
62
+ logMethod?: string;
52
63
  [key: string]: unknown;
53
64
  }
54
65
  export interface OrmConfig {
@@ -76,9 +87,18 @@ export interface OrmRecord {
76
87
  __pendingSqlId?: boolean;
77
88
  };
78
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
+ */
79
98
  toJSON?(options?: {
80
99
  fields?: Set<string>;
81
100
  baseUrl?: string;
101
+ linkage?: LinkageFilter;
82
102
  }): Record<string, unknown>;
83
103
  [key: string]: unknown;
84
104
  }
@@ -151,3 +171,243 @@ export interface SnapshotEntry {
151
171
  source?: string;
152
172
  viewQuery?: string;
153
173
  }
174
+ /**
175
+ * The shapes a consumer `access()` predicate may return.
176
+ *
177
+ * - `false` (or any falsy value) -- deny, 403.
178
+ * - `true` -- allow, with no per-record filter.
179
+ * - a permission string or array of them, drawn from the same four verbs as
180
+ * {@link AccessContext.operation}. A BARE STRING IS ONE PERMISSION, not a
181
+ * grant of all four.
182
+ * - a `(record) => boolean` predicate -- allow, and filter every record the
183
+ * request touches through it.
184
+ *
185
+ * Anything else fails CLOSED. See `src/orm-request.ts` `auth()`.
186
+ */
187
+ export type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
188
+ /**
189
+ * The closed vocabulary `AccessContext.operation` is drawn from
190
+ * (abofs/stonyx-orm#202).
191
+ *
192
+ * A literal union rather than `string`, so the guarantee the prose makes is the
193
+ * one the compiler enforces: a consumer who writes `operation === 'GET'` or
194
+ * `operation === 'get'` -- the hook vocabulary, see below -- gets a compile
195
+ * error instead of a comparison that never matches. A predicate that stops
196
+ * matching falls through to the permission array, so the misreading is
197
+ * fail-open shaped.
198
+ *
199
+ * In-repo precedent: `PersistErrorDetail.operation` in `src/main.ts`.
200
+ */
201
+ export type AccessOperation = 'read' | 'create' | 'update' | 'delete';
202
+ /**
203
+ * The structural facts about the request being authorised, handed to a consumer
204
+ * `access()` predicate as its SECOND argument (abofs/stonyx-orm#202).
205
+ *
206
+ * These are the facts the framework already holds at authorisation time. Before
207
+ * #202 a consumer had to reconstruct both of them by string-matching a URL, and
208
+ * five independent fail-open variants of that reconstruction were found in one
209
+ * three-line documented example -- each one wrong in the direction that GRANTS
210
+ * access. Read these instead; there is nothing to parse and no variant to miss.
211
+ *
212
+ * `record` is deliberately NOT a member. `auth()` runs after route matching but
213
+ * before any handler executes (`@stonyx/rest-server` `src/request.ts:58-60`),
214
+ * so nothing has been fetched yet -- carrying a record here would force a
215
+ * pre-fetch on every request. It is also unnecessary: the `(record) => boolean`
216
+ * return shape of {@link AccessMethod} already IS the per-record hook, applied
217
+ * by the handlers. Auth-time and record-time are separate decision points.
218
+ */
219
+ export interface AccessContext {
220
+ /**
221
+ * The model this route was mounted for, e.g. `'owner'` or `'phone-number'`.
222
+ *
223
+ * Model names are kebab-case, as declared under `config.orm.paths.model` and
224
+ * keyed in the store -- NOT the pluralised, mount-prefixed route name. It is
225
+ * read from the `OrmRequest` instance and is never derived from the request
226
+ * target, so a mount prefix, a case-varied path, a query string or an
227
+ * absolute-form request-target cannot change it.
228
+ */
229
+ model: string;
230
+ /**
231
+ * The operation being authorised. Exactly one of the four {@link
232
+ * AccessOperation} verbs, or `undefined`. These are exactly the values of
233
+ * `methodAccessMap` in `src/orm-request.ts`, which is also what the
234
+ * permission-array return shape is matched against -- so the two forms cannot
235
+ * disagree.
236
+ *
237
+ * NOT the hook vocabulary. `HookContext.operation` (`src/hooks.ts`) carries
238
+ * `'list' | 'get' | 'create' | 'update' | 'delete'` on an identically-named
239
+ * key of an identically-shaped context object, and the access vocabulary
240
+ * collapses `list` and `get` into `'read'`. For one `GET /animals/1` a hook
241
+ * sees `'get'` and `access()` sees `'read'`. "No second vocabulary" is a
242
+ * statement about the ACCESS path only.
243
+ *
244
+ * `undefined` when the dispatched method has no entry in that map. Express
245
+ * delivers `HEAD` to the `GET` handler, so this is reachable. It is left
246
+ * undefined rather than defaulted on purpose: a fabricated `'read'` would
247
+ * turn an unclassified request into an authorised one.
248
+ *
249
+ * The KEY is required even though the value may be undefined: `auth()` always
250
+ * sets it, and a context that simply omitted it would be indistinguishable
251
+ * from one that classified the request and found nothing.
252
+ */
253
+ operation: AccessOperation | undefined;
254
+ /**
255
+ * The record this route was addressed to, as the store key -- or `null` on a
256
+ * collection route, which is addressed to no record (abofs/stonyx-orm#236).
257
+ *
258
+ * IT IS ALREADY DECODED, AND THAT IS THE WHOLE POINT. Express decodes route
259
+ * PARAMETERS while leaving `request.path` raw, so a consumer comparing
260
+ * `request.path` against a literal compares an undecoded string against a
261
+ * decoded dispatch. `GET /owners/%61rchived` reached such a comparison as
262
+ * `/%61rchived`, walked past a `/archived` deny, and was dispatched as the
263
+ * record `archived` -- 200 with the record in full, and `DELETE` destroyed
264
+ * it, unauthenticated. 255 non-canonical spellings of an 8-character id
265
+ * decode to the same key, so a deny-list of spellings is the wrong shape.
266
+ *
267
+ * SO DO NOT NORMALISE THIS, AND DO NOT NORMALISE ANYTHING ELSE INSTEAD:
268
+ *
269
+ * - Do NOT decode it. Express decodes exactly ONCE, which is what a route
270
+ * parameter means. `GET /owners/%2561rchived` is the legitimate id
271
+ * `%61rchived`, not a second-order spelling of `archived`; a predicate that
272
+ * decoded until stable would deny a record it was never asked about.
273
+ * - Do NOT case-fold it. A record id is a VALUE, not a literal route segment,
274
+ * and express's `case sensitive routing` governs literal segments only.
275
+ * With a distinct owner seeded at `ARCHIVED`, `.toLowerCase()` was measured
276
+ * wrong in BOTH directions at once: `GET /owners/ARCHIVED` 403 (a false
277
+ * deny, on the wrong record) and `GET /owners/%41RCHIVED` 200 (a false
278
+ * allow, on that same record).
279
+ * - Do NOT derive it from `request.path` or the request target. Decoding the
280
+ * whole path decodes THEN splits, while the router splits THEN decodes, so
281
+ * `/owners/archived%2fx` -- a genuinely distinct record whose id is
282
+ * `archived/x` -- was measured over-denied 403.
283
+ *
284
+ * IT IS `getId(request.params)`, BYTE FOR BYTE -- the same single coercion
285
+ * the store lookup uses, exactly as `operation` is the same `methodAccessMap`
286
+ * lookup the permission-array branch uses. The predicate and the dispatch
287
+ * therefore cannot disagree about which record a request addresses. Handing
288
+ * over the raw `request.params.id` instead would reintroduce that divergence
289
+ * on hex-shaped ids: `GET /animals/0x2391` looks up record `9105`.
290
+ *
291
+ * It inherits abofs/stonyx-orm#209 along with that coercion -- on a model
292
+ * declaring `id = attr('string')`, `'9107'` arrives here as the number
293
+ * `9107`. That is consistency WITH THE LOOKUP, which is the property this key
294
+ * exists to buy; it is not a defect to repair here.
295
+ *
296
+ * `null`, not `undefined`, on a collection route -- and the KEY IS ALWAYS
297
+ * PRESENT, the same rule `operation` states above. `auth()` always sets it,
298
+ * so a context arriving WITHOUT the key did not come from `auth()`: it was
299
+ * hand-assembled by a caller resolving the predicate through
300
+ * `Orm.instance.getAccess()`. That absence stays a distinguishable, deniable
301
+ * signal only because the framework never produces it.
302
+ *
303
+ * IT DISAGREES WITH THE HOOK VOCABULARY, AND NOT ONLY ON THE ABSENCE
304
+ * SPELLING. `HookContext.recordId` (`src/hooks.ts`) is an identically-named
305
+ * key on an identically-shaped context object, which is the exact
306
+ * configuration that makes `operation` fail-open shaped -- a hook sees
307
+ * `'get'` where `access()` sees `'read'`. An earlier revision of THIS
308
+ * docblock asserted the opposite ("here they AGREE... they differ in ONE way
309
+ * and it is the absence spelling"). That was measured false, in the fail-open
310
+ * direction, and it is corrected here rather than deleted.
311
+ *
312
+ * MEASURED over the live dispatch, before-hooks registered for all five
313
+ * operations on one model:
314
+ *
315
+ * before:list key ABSENT ('recordId' in context === false)
316
+ * before:get key ABSENT params={"id":"visible1"}
317
+ * before:create key ABSENT
318
+ * before:update key ABSENT params={"id":"visible2"}
319
+ * before:delete recordId="visible3"
320
+ * after:delete recordId="visible3"
321
+ *
322
+ * `_withHooks` assigns `context.recordId` at exactly TWO sites in
323
+ * `src/orm-request.ts`, and BOTH sit inside an `operation === 'delete'`
324
+ * branch. So the two keys differ in COVERAGE, on four of five operations: on
325
+ * a hook context the key is absent for get, list, create and update, while
326
+ * this key is present on every route `auth()` classifies. The absence
327
+ * spelling is the smaller half of the difference, not the whole of it.
328
+ *
329
+ * AND THAT INVERTS THE ARGUMENT ABOVE WHEN IT IS READ ACROSS THE TWO. Here,
330
+ * a missing `recordId` means "did not come from `auth()`" and is deniable.
331
+ * On a hook context it means "this is a get / list / create / update" -- an
332
+ * ordinary request. A consumer who writes the hook-side half of the same
333
+ * rule --
334
+ *
335
+ * beforeHook('update', 'owner', ctx => ctx.recordId === 'archived' ? 403 : undefined)
336
+ *
337
+ * -- gets a deny that NEVER FIRES: measured, `PATCH /owners/visible2` -> 200,
338
+ * with `ctx.recordId === undefined` while the addressed record sits in
339
+ * `ctx.params`. The hook side is abofs/stonyx-orm#242 and is deliberately not
340
+ * repaired here. A predicate must not read `undefined` here as "collection",
341
+ * and nothing in this contract makes it safe to read the two keys as one key.
342
+ *
343
+ * IT NAMES WHICH RECORD OF THE MODEL BEING ASKED ABOUT, NOT WHICH SURFACE,
344
+ * AND THE ANSWER DEPENDS ON WHICH MODEL IS BEING ASKED ABOUT.
345
+ *
346
+ * For the ask about the ROUTE'S OWN model, all three of `GET /owners/gina`,
347
+ * `GET /owners/gina/pets` and `GET /owners/gina/relationships/pets` carry
348
+ * `recordId: 'gina'` -- `auth()` reads it off `request.params`.
349
+ *
350
+ * FOR THE ASK ABOUT A RELATED MODEL, IT IS `null`, AND THAT IS A LIMIT ON
351
+ * WHAT A PREDICATE CAN EXPRESS (abofs/stonyx-orm#232). The two relationship
352
+ * route families resolve the RELATED model's own predicate -- `animal` on
353
+ * `GET /owners/gina/pets`, `owner` on `GET /animals/4/owner` -- and that ask
354
+ * carries `recordId: null` while `request.params` names a record of a
355
+ * DIFFERENT model. So a predicate answering about a related model gets the
356
+ * model name, the operation and the request, and CANNOT branch on which
357
+ * related record it is being asked about.
358
+ *
359
+ * The rule, so it is not re-derived wrong: `recordId` may name a record only
360
+ * where the route addresses exactly one record OF THE MODEL BEING ASKED
361
+ * ABOUT. A `hasMany` related-resource route returns many records of one type
362
+ * and the verdict is resolved ONCE PER TYPE, before any record is examined --
363
+ * seeding it from a record would let the first one decide for all of them.
364
+ *
365
+ * What still works, and what does not, is pinned as behaviour by `#232 AC10`
366
+ * in test/integration/orm-test.ts and stated for consumers in README.md:
367
+ * model-level denies work, request-level denies work, and the per-record
368
+ * FILTER shape works because `access()` may return a function and that
369
+ * function receives the whole record. Branching on identity BEFORE returning
370
+ * does not.
371
+ *
372
+ * `?include=` is a separate surface and is abofs/stonyx-orm#233 / #235.
373
+ */
374
+ recordId: string | number | null;
375
+ }
376
+ /**
377
+ * A consumer `access()` predicate.
378
+ *
379
+ * The second argument is ADDITIVE: JavaScript ignores extra arguments, so every
380
+ * pre-#202 single-argument predicate keeps working untouched. Changing the
381
+ * FIRST argument instead would have been the breaking form, and a predicate
382
+ * that can no longer identify its collection falls through to a full CRUD
383
+ * grant -- so the "safer" breaking change would have converted every unmigrated
384
+ * predicate into a fail-open.
385
+ *
386
+ * `context` is nonetheless REQUIRED in the type, and that costs back-compat
387
+ * nothing. TypeScript already lets a fewer-parameter implementation satisfy a
388
+ * more-parameter signature, so an arity-1 predicate assigns to this type
389
+ * cleanly -- measured under `--strict`. What the `?` bought was the opposite of
390
+ * safety: it silently permitted `getAccess('animal')?.(request)` at the CALL
391
+ * site, i.e. exactly the omission {@link AccessContext} exists to prevent, and
392
+ * that call gets the model-wrong answer. Required, a caller that drops the
393
+ * context gets `TS2554: Expected 2 arguments, but got 1`.
394
+ */
395
+ export type AccessFunction = (request: unknown, context: AccessContext) => AccessMethod;
396
+ /**
397
+ * A resolved, request-scoped linkage decision: may `record` of model `type` be
398
+ * NAMED, by id, inside another model's document (abofs/stonyx-orm#234)?
399
+ *
400
+ * Arity is `(type, record)` and not `(type, id)` because the per-record filter
401
+ * a consumer returns is handed the RECORD -- this repo's own fixture reads
402
+ * `record.owner?.id`, not just `record.id`. The `(type, id)` pair is the CACHE
403
+ * key inside `createLinkageFilter`, not the input.
404
+ *
405
+ * DECLARED HERE, with the rest of the access vocabulary, and imported by every
406
+ * site that names it. It had three structurally-identical hand-written copies
407
+ * (`access-verdict.ts`, `record.ts`, `OrmRecord.toJSON` below) bridged to each
408
+ * other by nothing, so a drift in nullability or a widening of `type` would
409
+ * have landed on one and not the others -- which is the same "second,
410
+ * unreviewed vocabulary" failure `src/access-verdict.ts` exists to prevent, one
411
+ * level up in the type system.
412
+ */
413
+ export type LinkageFilter = (type: string, record: unknown) => boolean;
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";
package/dist/utils.js CHANGED
@@ -15,3 +15,50 @@ export function pluralize(word) {
15
15
  }
16
16
  return basePluralize(word);
17
17
  }
18
+ /**
19
+ * The highest NUMERIC id held by a set of records, or `0` when there is none.
20
+ *
21
+ * ONE COPY, and the duplication it replaces is the reason it lives here. Three
22
+ * near-identical reduces existed at once: `assignRecordId` (server-assigned id
23
+ * selection), `StandaloneDB.create` (src/standalone-db.ts) and the #203 test
24
+ * helper. `docs/improvements.md`'s standing WET Code category prescribes
25
+ * exactly this remedy -- extract into the module that already acts as the
26
+ * shared utility -- and `assignRecordId` already imported `isOrmRecord` from
27
+ * here.
28
+ *
29
+ * NON-NUMBERS ARE SKIPPED RATHER THAN COERCED TO `0`, AND THAT IS STYLISTIC.
30
+ * `StandaloneDB`'s shape mapped them to `0`, which can never beat a seed of
31
+ * `0`. Measured over eleven input classes (`[]`, `1`, `NaN`, `'5'`, `'abc'`,
32
+ * `-3`, `0`, `null`, `undefined`, `Infinity`, and mixed arrays) the two shapes
33
+ * produce IDENTICAL output on every one. In particular `typeof NaN` is
34
+ * `'number'`, so NEITHER shape coerces `NaN` -- both reject it on `NaN > max`,
35
+ * which is `false`. An earlier revision of this code asserted that the skip was
36
+ * what made the `NaN` case work; it is not, the comparison is, and that claim
37
+ * has been removed rather than left standing.
38
+ *
39
+ * WHAT IS LOAD-BEARING is that this is not `Math.max(...ids)`. `Math.max`
40
+ * returns `NaN` if any operand is `NaN`, and a record CAN be held under the key
41
+ * `NaN` -- so the obvious fix assigns `NaN`, lands on that slot and overwrites
42
+ * it, which is abofs/stonyx-orm#203 in a new disguise. Pinned by
43
+ * test/unit/assign-record-id-test.ts AC2; before that file existed the whole
44
+ * suite scored 951/0 under exactly that fix.
45
+ */
46
+ export function maxNumericId(records) {
47
+ return records.reduce((max, record) => {
48
+ const { id } = record;
49
+ return typeof id === 'number' && id > max ? id : max;
50
+ }, 0);
51
+ }
52
+ /**
53
+ * The message prefix `assignRecordId` throws with when no free id can be
54
+ * derived for a model, and the ONE string `createHandler` matches on to answer
55
+ * `409` instead of letting the rejection reach express's default handler.
56
+ *
57
+ * It lives here rather than in either file because both need it and neither
58
+ * should own a copy: a literal in two places is how the two id coercions in
59
+ * orm-request.ts drifted apart (see `coerceId`). The repo has no error codes
60
+ * and no custom error classes -- 24 bare `throw new Error` sites across `src/`
61
+ * -- so a shared prefix is the narrowest way to make ONE failure distinguishable
62
+ * without inventing an error taxonomy this codebase does not use.
63
+ */
64
+ export const NO_FREE_ID_ERROR = 'Cannot assign record ID: no free id available';
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.3.2-beta.16",
7
+ "version": "0.3.2-beta.160",
8
8
  "description": "",
9
9
  "main": "dist/index.js",
10
10
  "type": "module",
@@ -61,16 +61,25 @@
61
61
  },
62
62
  "homepage": "https://github.com/abofs/stonyx-orm#readme",
63
63
  "dependencies": {
64
- "@stonyx/cron": "0.2.1-beta.45",
65
- "@stonyx/events": "0.1.1-beta.47",
66
- "stonyx": "0.2.3-beta.56"
64
+ "@stonyx/cron": "0.2.1-beta.85",
65
+ "@stonyx/events": "0.1.1-beta.52",
66
+ "@stonyx/utils": "0.2.3-beta.26",
67
+ "stonyx": "0.2.3-beta.77"
67
68
  },
68
69
  "peerDependencies": {
70
+ "@aws-sdk/client-dynamodb": "^3.0.0",
71
+ "@aws-sdk/lib-dynamodb": "^3.0.0",
69
72
  "@stonyx/rest-server": ">=0.2.1-beta.14",
70
73
  "mysql2": "^3.0.0",
71
74
  "pg": "^8.0.0"
72
75
  },
73
76
  "peerDependenciesMeta": {
77
+ "@aws-sdk/client-dynamodb": {
78
+ "optional": true
79
+ },
80
+ "@aws-sdk/lib-dynamodb": {
81
+ "optional": true
82
+ },
74
83
  "mysql2": {
75
84
  "optional": true
76
85
  },
@@ -82,8 +91,7 @@
82
91
  }
83
92
  },
84
93
  "devDependencies": {
85
- "@stonyx/rest-server": "0.2.1-beta.45",
86
- "@stonyx/utils": "0.2.3-beta.23",
94
+ "@stonyx/rest-server": "0.2.1-beta.84",
87
95
  "@types/node": "^25.6.0",
88
96
  "mysql2": "^3.20.0",
89
97
  "pg": "^8.20.0",
@@ -95,6 +103,7 @@
95
103
  "scripts": {
96
104
  "build": "tsc",
97
105
  "build:test": "tsc -p tsconfig.test.json",
98
- "test": "pnpm build && NODE_ENV=test node --import tsx/esm --import ./test/setup.ts node_modules/qunit/bin/qunit.js 'test/**/*-test.ts'"
106
+ "test": "pnpm build && NODE_ENV=test node --import tsx/esm --import ./test/setup.ts node_modules/qunit/bin/qunit.js 'test/**/*-test.ts'",
107
+ "test:dynamodb": "pnpm build && node --import tsx/esm --import ./test/integration/dynamodb/setup.ts node_modules/qunit/bin/qunit.js 'test/integration/dynamodb/**/*-test.ts'"
99
108
  }
100
109
  }