@happyvertical/smrt-core 0.44.0 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/AGENTS.md +8 -8
  2. package/agents/generators.md +34 -0
  3. package/agents/revision-guard.md +66 -0
  4. package/dist/cascade.d.ts +5 -9
  5. package/dist/cascade.d.ts.map +1 -1
  6. package/dist/cascade.js +65 -30
  7. package/dist/cascade.js.map +1 -1
  8. package/dist/embedded-write-queue.d.ts +8 -0
  9. package/dist/embedded-write-queue.d.ts.map +1 -1
  10. package/dist/embedded-write-queue.js +12 -2
  11. package/dist/embedded-write-queue.js.map +1 -1
  12. package/dist/generators/index.d.ts +1 -0
  13. package/dist/generators/index.d.ts.map +1 -1
  14. package/dist/generators/index.js +2 -1
  15. package/dist/generators/preflight-route.d.ts +151 -0
  16. package/dist/generators/preflight-route.d.ts.map +1 -0
  17. package/dist/generators/preflight-route.js +194 -0
  18. package/dist/generators/preflight-route.js.map +1 -0
  19. package/dist/generators/rest.d.ts +12 -0
  20. package/dist/generators/rest.d.ts.map +1 -1
  21. package/dist/generators/rest.js +12 -15
  22. package/dist/generators/rest.js.map +1 -1
  23. package/dist/generators.js +2 -1
  24. package/dist/index.d.ts +2 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +4 -2
  27. package/dist/manifest/static-manifest.d.ts.map +1 -1
  28. package/dist/manifest/static-manifest.js +6 -2
  29. package/dist/manifest/static-manifest.js.map +1 -1
  30. package/dist/manifest/store.js +1 -1
  31. package/dist/manifest/store.js.map +1 -1
  32. package/dist/manifest.json +8 -2
  33. package/dist/object.d.ts +31 -1
  34. package/dist/object.d.ts.map +1 -1
  35. package/dist/object.js +57 -9
  36. package/dist/object.js.map +1 -1
  37. package/dist/revision-guard.d.ts +84 -0
  38. package/dist/revision-guard.d.ts.map +1 -0
  39. package/dist/revision-guard.js +120 -0
  40. package/dist/revision-guard.js.map +1 -0
  41. package/dist/smrt-knowledge.json +16 -7
  42. package/package.json +4 -4
package/AGENTS.md CHANGED
@@ -27,14 +27,14 @@ subsystem you are editing. This file keeps what holds across all of them.
27
27
 
28
28
  - `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided
29
29
  - `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)
30
- - Persisted `save()` calls use the object's loaded `updated_at` revision in the
31
- database `UPDATE`; zero affected rows throws `RUNTIME_REVISION_CONFLICT`
32
- without overwriting the newer row. `save({ expectedUpdatedAt })` supplies an
33
- explicit revision when a caller binds the mutation to an earlier preview or
34
- selection snapshot. Embedded adapters serialize every same-process model
35
- save, delete, and complete `SmrtObject.withTransaction()` callback through
36
- one queue; bound saves re-enter that hold. Custom write paths must use those
37
- public APIs rather than bypassing the CAS ordering contract.
30
+ - Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws
31
+ `RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or
32
+ delete to an earlier snapshot. Remote guarded deletes bind the same predicate
33
+ into the final `DELETE`; embedded adapters compare inside the shared write queue
34
+ before cascading. That queue serializes same-process saves, deletes, and full
35
+ `SmrtObject.withTransaction()` callbacks. Custom writes must preserve this
36
+ public CAS ordering contract. PostgreSQL predicate:
37
+ [agents/revision-guard.md](agents/revision-guard.md).
38
38
  - Native DuckDB UUID columns are hydrated as canonical strings before model
39
39
  initialization, natural-key lookup, and embedded revision claims. Exact
40
40
  natural-key probes retain the interceptor-authorized filter when
@@ -63,6 +63,40 @@ requested path rather than a hardcoded `index.js`.
63
63
  Generated code also has to be valid in an ES module: `arguments` is not a legal
64
64
  binding name there, however convenient it reads.
65
65
 
66
+ ## Browser-plane playbook preflight route (#2590)
67
+
68
+ `GET {basePath}/_preflight?key=<playbook key>` (`src/generators/preflight-route.ts`)
69
+ is an advisory, read-effect, idempotent report of what a caller's playbook would
70
+ be allowed to do — capability *selection*, never authorization. Resolution and
71
+ verdict shaping live in `@happyvertical/smrt-playbooks`, which depends on this
72
+ package, so core takes the evaluator as the `APIConfig.playbookPreflight` seam and
73
+ the dependency stays one-way. Without a provider the route 404s.
74
+
75
+ **`authMiddleware` is never invoked by preflight**, and that is enforced
76
+ structurally rather than by discipline: `PlaybookPreflightRouteOptions` has no
77
+ auth member of any kind, and `rest.ts` passes the boolean `appAuthConfigured`
78
+ instead — so there is no handle in the module to invoke by mistake. A synthetic-
79
+ `Request` dry run is explicitly not an option: the middleware is request-bound,
80
+ returns a `Response` rather than a boolean, and may consult session stores,
81
+ rate-limit, or audit. The app-auth layer therefore reports `unknown`, which is the
82
+ honest answer, and a future `authPredicate` seam can fill it in without changing
83
+ the contract.
84
+
85
+ The static layers preflight predicts against are exported from the same module —
86
+ `isApiActionEnabledForObject`, `isRestActionRoutable`, `isRestRoutePublic`,
87
+ `restFieldReadPermissions`, `restMethodForApiAction`,
88
+ `resolveRegisteredObjectName` — and `APIGenerator`'s own
89
+ `isApiActionEnabled` / `isRoutePublic` now delegate to them, so the route and the
90
+ prediction of the route cannot drift. Exposure and existence are separate
91
+ questions: `include`/`exclude` gate a route, they do not conjure one, so
92
+ `isRestActionRoutable` additionally requires a custom action to be declared in
93
+ `api.routes` — the only map `dispatchCustomCollectionAction` iterates. A custom
94
+ action is predicted against the verb its own route config declares, so a
95
+ `public: 'read'` opt-out neither silently covers a `POST` action nor falsely
96
+ denies a declared `GET` one. Every unresolvable key returns the provider's single uniform
97
+ "unavailable" body with an unconditional 200: unknown and unauthorized keys are
98
+ indistinguishable at the HTTP layer too.
99
+
66
100
  ## Emitted agent surface (#2591)
67
101
 
68
102
  Generated model tools have always been build-time artifacts — virtual module,
@@ -0,0 +1,66 @@
1
+ # Revision compare-and-swap guard (`src/revision-guard.ts`)
2
+
3
+ Every persisted `save()` pins its `UPDATE` to the revision the writer loaded;
4
+ `claimRevision()` does the same without running domain hooks, and
5
+ `delete({ expectedUpdatedAt })` binds the same predicate into its final
6
+ `DELETE`. Zero affected rows raises `RUNTIME_REVISION_CONFLICT` rather than
7
+ overwriting or removing a newer row.
8
+
9
+ ## Why the predicate is not an equality (#2620)
10
+
11
+ The guard used to compare `updated_at` to `loadedRevision.toISOString()`. On
12
+ PostgreSQL a JavaScript `Date` is two lossy conversions away from the stored
13
+ value, so that predicate matched no row at all in two common situations — and
14
+ the object then conflicted on *every* later save, permanently, rather than
15
+ losing a race:
16
+
17
+ - **Precision.** `updated_at` is a microsecond column. Any row last written by
18
+ raw SQL — `updated_at = CURRENT_TIMESTAMP` / `now()`, including SMRT's own
19
+ migration backfills — carries a sub-millisecond tail a `Date` cannot hold.
20
+ - **Process timezone.** Schemas created before the `TIMESTAMPTZ` mapping still
21
+ hold `updated_at` as `timestamp WITHOUT time zone`, and `pg` hydrates that
22
+ type in the process zone, so on a non-UTC host `toISOString()` renders a wall
23
+ clock the row never held. The same columns are written under three different
24
+ conventions — `pg` serializes a bound `Date` in the process zone,
25
+ `claimRevision()` writes a UTC ISO string, and raw `CURRENT_TIMESTAMP` writes
26
+ in the *server* zone — so no single rendering can match every row.
27
+
28
+ ## What the predicate does instead
29
+
30
+ `postgresRevisionCondition()` builds
31
+ `date_trunc('milliseconds', updated_at) IN (…)` over both wall-clock renderings
32
+ of the revision, the process-zone one and the UTC one, each tagged `+00` so a
33
+ `timestamptz` comparison honours it and a `timestamp` comparison discards it —
34
+ the predicate therefore does not depend on the *session* TimeZone either. On a
35
+ UTC process the two renderings coincide and the condition is single-valued.
36
+
37
+ Lost-race semantics are preserved: a concurrent writer advances `updated_at` to
38
+ roughly "now", so it must land on the loaded revision — or, on a non-UTC
39
+ process only, on that revision shifted by the whole UTC offset — to the
40
+ millisecond before it could slip past. Collapsing that second rendering so the
41
+ predicate is single-valued on every process is tracked as #2623.
42
+
43
+ ## Rules
44
+
45
+ - Never rebuild this predicate by hand; call `postgresRevisionCondition()`.
46
+ Every guarded write — `save()`, `claimRevision()`, and the guarded `DELETE` —
47
+ goes through `SmrtObject.revisionPredicate()` so no path is left on the exact
48
+ equality.
49
+ - The condition is PostgreSQL-only. Embedded engines take the process-local
50
+ compare/upsert fallback (`usesEmbeddedRevisionFallback`), and remote LibSQL
51
+ stores ISO text whose exact equality round-trips losslessly.
52
+ - Custom write paths must go through `save()`, `save({ expectedUpdatedAt })`,
53
+ or `claimRevision()` rather than bypassing the CAS ordering contract.
54
+ - The driver-layer half — `pg` hydrating and serializing `timestamp` columns in
55
+ the process zone — is tracked as happyvertical/sdk#1223. The guard
56
+ deliberately assumes neither hydration convention, so a UTC-hydration fix
57
+ there cannot break it.
58
+
59
+ ## Coverage
60
+
61
+ `src/__tests__/issue-2620-revision-guard-precision-postgres.optional.test.ts`
62
+ runs the whole battery — guarded save, `save({ expectedUpdatedAt })`,
63
+ `claimRevision()`, guarded delete, and their still-conflicts counterparts —
64
+ against both `updated_at` column shapes in the registered PostgreSQL suite (`pnpm --filter @happyvertical/smrt-core
65
+ test:postgres`). `src/__tests__/revision-guard.test.ts` covers the rendering
66
+ itself in the default suite.
package/dist/cascade.d.ts CHANGED
@@ -96,15 +96,11 @@ export declare function cascadeReferencesTo(db: DatabaseInterface, registry: Cas
96
96
  /**
97
97
  * Run the cascade and the target row's own deletion atomically.
98
98
  *
99
- * When anything references the class and the adapter exposes `transaction()`,
100
- * the whole sequence runs inside one — including the caller's `deleteSelf`
101
- * statement, so a failure part-way through cannot leave the object deleted with
102
- * its junction rows intact (or vice versa). Adapters without transaction
103
- * support run the same statements sequentially; this is the documented
104
- * degradation, not a silent one.
105
- *
106
- * When nothing references the class there is nothing to keep consistent, and
107
- * the transaction is skipped — see the comment on that branch.
99
+ * When the adapter exposes `transaction()`, the whole sequence runs inside one
100
+ * — including framework-owned row cleanup and the caller's `deleteSelf`
101
+ * statement, so a failure part-way through cannot leave either side orphaned.
102
+ * Adapters without transaction support run the same statements sequentially;
103
+ * this is the documented degradation, not a silent one.
108
104
  *
109
105
  * @param db - Database the object is bound to
110
106
  * @param registry - Registry view used to build cascade plans
@@ -1 +1 @@
1
- {"version":3,"file":"cascade.d.ts","sourceRoot":"","sources":["../src/cascade.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAK5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAKpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAM1D;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,gBAAgB,CAAC;AAsB9C,gFAAgF;AAChF,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,MAAM,EAAE,MAAM,CAAC;IACf,8EAA8E;IAC9E,MAAM,EAAE,cAAc,CAAC;IACvB,4EAA4E;IAC5E,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,mEAAmE;AACnE,MAAM,WAAW,2BAA2B;IAC1C,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,2EAA2E;AAC3E,MAAM,WAAW,WAAW;IAC1B,4EAA4E;IAC5E,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,mEAAmE;IACnE,WAAW,EAAE,2BAA2B,EAAE,CAAC;IAC3C,yEAAyE;IACzE,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,+EAA+E;IAC/E,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;GAMG;AACH,MAAM,MAA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BAAgB,CACnB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAE5E;AASD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,mBAAmB,EAC7B,SAAS,EAAE,MAAM,GAChB,WAAW,CAgIb;AAkZD,8EAA8E;AAC9E,MAAM,WAAW,aAAa;IAC5B,4EAA4E;IAC5E,cAAc,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC5B;;;;OAIG;IACH,oBAAoB,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC3C;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,mBAAmB,EAC7B,MAAM,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,EAAE,CAAA;CAAE,GAC9D,OAAO,CAAC,aAAa,CAAC,CAwBxB;AASD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,iBAAiB,EACrB,QAAQ,EAAE,mBAAmB,EAC7B,MAAM,EAAE;IACN,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,+DAA+D;IAC/D,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;CAC/B,EACD,UAAU,EAAE,CAAC,EAAE,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GACnD,OAAO,CAAC,aAAa,CAAC,CAuDxB"}
package/dist/cascade.js CHANGED
@@ -24,14 +24,11 @@ import { createLogger } from "@happyvertical/logger";
24
24
  * `afterDelete` hooks and interceptors do **not** run, and no change-feed
25
25
  * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.
26
26
  * Only the object `delete()` was called on runs the full lifecycle.
27
- * - When anything needs cascading, everything runs inside a single
28
- * transaction when the adapter exposes one, so a partial cascade cannot
29
- * survive a failure. A class with no typed references AND no registered
30
- * polymorphic association class anywhere in the process skips the
31
- * transaction — see {@link runCascadeDelete}. A `metaType` column can point
27
+ * - Every delete runs inside a single transaction when the adapter exposes
28
+ * one, including cleanup of framework-owned context and embedding rows, so
29
+ * a partial cascade cannot survive a failure. A `metaType` column can point
32
30
  * at any class at runtime, so a polymorphic association class is always
33
- * plausibly relevant; in an app with even one registered, this fast path is
34
- * rare, not the common case.
31
+ * plausibly relevant.
35
32
  *
36
33
  * ## Which references are followed
37
34
  *
@@ -240,6 +237,43 @@ async function tolerateMissingTable(operation, fallback, context) {
240
237
  throw error;
241
238
  }
242
239
  }
240
+ /**
241
+ * System-table cleanup may ignore an absent table for databases created before
242
+ * that subsystem existed, but never a missing column in a table that does
243
+ * exist. The shared `undefined_object` classification intentionally combines
244
+ * both cases, so this security boundary must retain the narrower driver signal.
245
+ */
246
+ function normalizeMissingTableName(value) {
247
+ const unquoted = value.replace(/["'`[\]]/g, "");
248
+ return (unquoted.split(".").at(-1) ?? unquoted).replace(/[^A-Za-z0-9_$-]/g, "").toLowerCase();
249
+ }
250
+ function missingTableNames(messages) {
251
+ const names = [];
252
+ const patterns = [
253
+ /no such table:\s*([^\s,;]+)/giu,
254
+ /(?:relation|table)\s+((?:"[^"]+"(?:\."[^"]+")*)|(?:[A-Za-z0-9_.$-]+))\s+does not exist/giu,
255
+ /table with name\s+((?:"[^"]+")|(?:[A-Za-z0-9_.$-]+))\s+does not exist/giu
256
+ ];
257
+ for (const message of messages) for (const pattern of patterns) for (const match of message.matchAll(pattern)) if (match[1]) names.push(normalizeMissingTableName(match[1]));
258
+ return names;
259
+ }
260
+ function isMissingTableError(error, expectedTable) {
261
+ const classification = classifyDatabaseError(error);
262
+ if (classification.kind !== "undefined_object") return false;
263
+ if (classification.sqlstate === "42703" || classification.driverCode === "42703" || classification.driverCodes.includes("42703")) return false;
264
+ const names = missingTableNames(classification.driverMessages);
265
+ const expected = normalizeMissingTableName(expectedTable);
266
+ return names.length > 0 && names.every((missingTableName) => missingTableName === expected);
267
+ }
268
+ async function tolerateMissingSystemTable(operation, fallback, context) {
269
+ try {
270
+ return await operation();
271
+ } catch (error) {
272
+ if (!isMissingTableError(error, context.table)) throw error;
273
+ logger.warn(`Cascade delete skipped ${context.action} on '${context.table}': table not found in this database.`, { error: error instanceof Error ? error.message : String(error) });
274
+ return fallback;
275
+ }
276
+ }
243
277
  async function selectIds(db, tableName, column, ids) {
244
278
  const found = [];
245
279
  for (const batch of chunkArray(ids, 900)) {
@@ -275,7 +309,8 @@ async function deleteByIds(db, tableName, ids) {
275
309
  * enough.
276
310
  *
277
311
  * A missing system table is not an error — an application database may predate
278
- * the table, and losing derived rows must never fail an otherwise valid delete.
312
+ * the table. Every other cleanup failure propagates so the surrounding delete
313
+ * transaction rolls back rather than orphaning tenant-sensitive recall data.
279
314
  */
280
315
  async function deleteSystemRows(db, ids, classNames) {
281
316
  const ownerIds = ids.filter((id) => typeof id === "string" && id.length > 0 && id !== COLLECTION_OWNER_SENTINEL);
@@ -288,14 +323,13 @@ async function deleteSystemRows(db, ids, classNames) {
288
323
  EMBEDDINGS_TABLE,
289
324
  "object_id",
290
325
  "object_class"
291
- ]]) for (const batch of chunkArray(ownerIds, 900)) try {
292
- await db.delete(table, {
293
- ...idPredicate(idColumn, batch),
294
- ...idPredicate(classColumn, classNames)
295
- });
296
- } catch (error) {
297
- logger.warn(`Failed to clean ${table} rows during cascade delete: ${error instanceof Error ? error.message : String(error)}`);
298
- }
326
+ ]]) for (const batch of chunkArray(ownerIds, 900)) await tolerateMissingSystemTable(() => db.delete(table, {
327
+ ...idPredicate(idColumn, batch),
328
+ ...idPredicate(classColumn, classNames)
329
+ }), void 0, {
330
+ table,
331
+ action: "framework-owned row cleanup"
332
+ });
299
333
  }
300
334
  /**
301
335
  * Resolve every reference pointing at `ids` of `className`, recursively.
@@ -383,15 +417,11 @@ async function cascadeReferencesTo(db, registry, target) {
383
417
  /**
384
418
  * Run the cascade and the target row's own deletion atomically.
385
419
  *
386
- * When anything references the class and the adapter exposes `transaction()`,
387
- * the whole sequence runs inside one — including the caller's `deleteSelf`
388
- * statement, so a failure part-way through cannot leave the object deleted with
389
- * its junction rows intact (or vice versa). Adapters without transaction
390
- * support run the same statements sequentially; this is the documented
391
- * degradation, not a silent one.
392
- *
393
- * When nothing references the class there is nothing to keep consistent, and
394
- * the transaction is skipped — see the comment on that branch.
420
+ * When the adapter exposes `transaction()`, the whole sequence runs inside one
421
+ * — including framework-owned row cleanup and the caller's `deleteSelf`
422
+ * statement, so a failure part-way through cannot leave either side orphaned.
423
+ * Adapters without transaction support run the same statements sequentially;
424
+ * this is the documented degradation, not a silent one.
395
425
  *
396
426
  * @param db - Database the object is bound to
397
427
  * @param registry - Registry view used to build cascade plans
@@ -402,12 +432,17 @@ async function cascadeReferencesTo(db, registry, target) {
402
432
  async function runCascadeDelete(db, registry, target, deleteSelf) {
403
433
  const ids = target.id ? [target.id] : [];
404
434
  if (buildCascadePlan(registry, target.className).isEmpty) {
405
- await deleteSelf(db);
406
- await deleteSystemRows(db, ids, ownerClassCandidates(registry, target.className));
407
- return {
408
- affectedTables: /* @__PURE__ */ new Set(),
409
- affectedTableClasses: /* @__PURE__ */ new Map()
435
+ const runWithoutReferences = async (bound) => {
436
+ await deleteSystemRows(bound, ids, ownerClassCandidates(registry, target.className));
437
+ await deleteSelf(bound);
438
+ return {
439
+ affectedTables: /* @__PURE__ */ new Set(),
440
+ affectedTableClasses: /* @__PURE__ */ new Map()
441
+ };
410
442
  };
443
+ const transaction = db.transaction;
444
+ if (typeof transaction !== "function") return runWithoutReferences(db);
445
+ return transaction.call(db, runWithoutReferences);
411
446
  }
412
447
  const run = async (bound) => {
413
448
  const result = await cascadeReferencesTo(bound, registry, {
@@ -1 +1 @@
1
- {"version":3,"file":"cascade.js","names":[],"sources":["../src/cascade.ts"],"sourcesContent":["/**\n * App-side referential integrity for `SmrtObject.delete()` (#2371).\n *\n * Same-package `@foreignKey` fields now emit database constraints where the\n * engine can enforce the declared policy. Cross-package references and older\n * schemas still rely on this application-side path. Before this module,\n * `delete()` removed the object's own row and nothing else: junction rows,\n * polymorphic association rows, `_smrt_embeddings` and `_smrt_contexts` entries\n * were all left pointing at an id that no longer resolved, and\n * `@foreignKey(..., { onDelete })` was metadata nobody read.\n *\n * This module implements those semantics in the application layer. It mirrors\n * what a DB-level constraint would do, deliberately including the parts that\n * make it *unlike* a model-layer delete:\n *\n * - Cascaded rows are removed with set-based statements. Their `beforeDelete` /\n * `afterDelete` hooks and interceptors do **not** run, and no change-feed\n * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.\n * Only the object `delete()` was called on runs the full lifecycle.\n * - When anything needs cascading, everything runs inside a single\n * transaction when the adapter exposes one, so a partial cascade cannot\n * survive a failure. A class with no typed references AND no registered\n * polymorphic association class anywhere in the process skips the\n * transaction — see {@link runCascadeDelete}. A `metaType` column can point\n * at any class at runtime, so a polymorphic association class is always\n * plausibly relevant; in an app with even one registered, this fast path is\n * rare, not the common case.\n *\n * ## Which references are followed\n *\n * A reference is any `@foreignKey` / `@crossPackageRef` field on a registered\n * class whose target resolves to the deleted object's class (or one of its\n * registered STI ancestors), plus the polymorphic `(metaType, metaId)` pair on\n * {@link SmrtPolymorphicAssociation} subclasses.\n *\n * The action comes from the field's declared `onDelete`. When it is not\n * declared, the default is derived from the referencing class's natural key:\n *\n * | Reference | Default when `onDelete` is absent |\n * |---|---|\n * | Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n * | Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n * | Ordinary same-package reference | `NO ACTION` (deletion is refused while references remain) |\n * | Every `@tenantId()` field | Excluded: tenant scope is not an ownership edge |\n *\n * The natural-key rule is what makes junction rows work without any\n * per-package annotation: a junction declares\n * `@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so\n * `content_id` identifies the row and the row cannot outlive the content it\n * links. An ordinary child (`Order.customerId`) is keyed by `(slug, context)`,\n * so it defaults to immediate `NO ACTION` unless it opts in with\n * `@foreignKey(Customer, { onDelete: 'CASCADE' })`.\n *\n * `@tenantId()` fields are excluded from the natural-key rule even though\n * `@happyvertical/smrt-tenancy` leads a tenant-scoped class's *default*\n * `conflictColumns` with the tenant column (#2360): the tenant column scopes\n * ownership, it does not identify the row the way a junction's foreign key\n * does, and it targets a class (`Tenant`) that is virtually always\n * referenced. Without this exclusion, deleting one `Tenant` row would\n * recursively CASCADE through every tenant-scoped table that has not\n * declared its own `conflictColumns` — the overwhelming majority. The field\n * is detected via the `__tenancy.isTenantIdField` marker `@tenantId()`\n * attaches to its own registration (`FieldMeta.__tenancy`, read structurally\n * so `smrt-core` never depends on `smrt-tenancy`). `@tenantId()` exposes no\n * `onDelete` option today, so this cannot currently be overridden per field.\n *\n * @see https://github.com/happyvertical/smrt/issues/2371\n * @module\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { classifyDatabaseError } from './db-errors.js';\nimport { ConfigurationError, DatabaseError } from './errors.js';\n// Type-only: erased at runtime, so it cannot re-enter the\n// `registry → object → cascade` import cycle.\nimport type { ObjectRegistry } from './registry.js';\nimport {\n normalizeForeignKeyAction,\n resolveForeignKeyDeleteAction,\n} from './schema/foreign-key-policy.js';\nimport type { ForeignKeyAction } from './schema/types.js';\nimport { chunkArray, IN_LIST_CHUNK_SIZE } from './utils/chunk.js';\nimport { toSnakeCase } from './utils/naming.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Referential action applied to rows pointing at a deleted object.\n *\n * Same vocabulary as SQL's `ON DELETE`, enforced by the framework before the\n * engine. `NO ACTION` is preflighted like an immediate restrictive action so\n * application-side and database-side enforcement agree.\n */\nexport type OnDeleteAction = ForeignKeyAction;\n\n/** Table holding framework-managed per-object memory entries. */\nconst CONTEXTS_TABLE = '_smrt_contexts';\n\n/** Table holding framework-managed per-object embedding vectors. */\nconst EMBEDDINGS_TABLE = '_smrt_embeddings';\n\n/**\n * Reserved `_smrt_contexts.owner_id` used by `SmrtCollection.remember()` for\n * collection-scoped memory. A real object id is a UUID and can never equal it,\n * but the guard keeps a malformed id from wiping every sibling's defaults.\n */\nconst COLLECTION_OWNER_SENTINEL = '__collection__';\n\n/**\n * Maximum number of cascade levels followed from the object `delete()` was\n * called on. A cycle between two classes that both declare `onDelete: 'CASCADE'`\n * is broken by the visited set; this bound catches unbounded *chains*.\n */\nconst MAX_CASCADE_DEPTH = 10;\n\n/** One reference that must be resolved before the target row can be removed. */\nexport interface CascadeReference {\n /** Registered name of the class holding the referencing column. */\n className: string;\n /** Table holding the referencing rows. */\n tableName: string;\n /** Field name (camelCase) on the referencing class. */\n fieldName: string;\n /** Column (snake_case) holding the reference. */\n column: string;\n /** Resolved action. `NO ACTION` is preflighted like an immediate RESTRICT. */\n action: OnDeleteAction;\n /** `true` when the action was declared rather than derived from the key. */\n declared: boolean;\n}\n\n/** A polymorphic association table that can point at any class. */\nexport interface CascadePolymorphicReference {\n /** Registered name of the association class. */\n className: string;\n /** Table holding the association rows. */\n tableName: string;\n}\n\n/** Everything that must happen before rows of one class can be deleted. */\nexport interface CascadePlan {\n /** Typed `@foreignKey` / `@crossPackageRef` references, action-resolved. */\n references: CascadeReference[];\n /** Polymorphic association tables that may point at this class. */\n polymorphic: CascadePolymorphicReference[];\n /** `meta_type` values that identify this class in an association row. */\n metaTypes: string[];\n /** `true` when nothing references this class and nothing has to be visited. */\n isEmpty: boolean;\n}\n\n/**\n * Read-only slice of `ObjectRegistry` this module needs.\n *\n * Taking it as a parameter — rather than importing the registry as a value —\n * keeps `cascade.ts` out of the `registry → object → cascade` import cycle,\n * and lets tests drive the planner from a hand-built registry.\n */\nexport type CascadeRegistryView = Pick<\n typeof ObjectRegistry,\n | 'getRelationshipMap'\n | 'getFields'\n | 'getConflictColumns'\n | 'getTableName'\n | 'getSelfReferableNames'\n | 'getClass'\n | 'getSTIBase'\n | 'getDescendants'\n>;\n\n/**\n * Normalize a declared `onDelete` value.\n *\n * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the\n * schema generator has always carried in the manifest. Returns `undefined` for\n * an unset or unrecognized value so the caller can fall back to the default.\n */\nexport function normalizeOnDelete(value: unknown): OnDeleteAction | undefined {\n return normalizeForeignKeyAction(value);\n}\n\nfunction isPolymorphicAssociationClass(fields: Map<string, unknown>): boolean {\n // The three columns `SmrtPolymorphicAssociation` contributes. Requiring all\n // of them keeps an unrelated class that happens to carry a `metaType` from\n // being treated as an association table.\n return fields.has('metaType') && fields.has('metaId') && fields.has('role');\n}\n\n/**\n * Build the cascade plan for one class.\n *\n * The plan is derived entirely from registry metadata, so it is valid for any\n * database the class is used against. It is rebuilt per delete rather than\n * cached: registration is incremental (manifests load lazily, tests register\n * classes between cases) and a stale plan would silently skip a table.\n *\n * @param registry - Registry view (`ObjectRegistry` satisfies it)\n * @param className - Class whose incoming references should be resolved\n */\nexport function buildCascadePlan(\n registry: CascadeRegistryView,\n className: string,\n): CascadePlan {\n // `className` is normally already qualified (delete() passes\n // getResolvedQualifiedName()), but a common same-package `@foreignKey('X')`\n // still stores its target as the bare simple name `X`. That still matches:\n // getSelfReferableNames() walks the full ancestor chain (self included) and\n // adds each ancestor's *simple* name via `getClass(ancestor)?.name`, so the\n // simple form is already in the seed set below, not just the loop's\n // qualified-variant augmentation.\n const targetNames = new Set(registry.getSelfReferableNames(className));\n for (const name of [...targetNames]) {\n const qualified = registry.getClass(name)?.qualifiedName;\n if (qualified) targetNames.add(qualified);\n }\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n\n for (const [sourceClass, relationships] of registry.getRelationshipMap()) {\n const fields = registry.getFields(sourceClass);\n\n if (isPolymorphicAssociationClass(fields)) {\n const tableName = registry.getTableName(sourceClass);\n if (tableName) {\n polymorphic.push({ className: sourceClass, tableName });\n }\n }\n\n if (relationships.length === 0) continue;\n\n let conflictColumns: Set<string> | undefined;\n\n for (const relationship of relationships) {\n if (\n relationship.type !== 'foreignKey' &&\n relationship.type !== 'crossPackageRef'\n ) {\n continue;\n }\n if (!targetNames.has(relationship.targetClass)) continue;\n\n // An explicit app-side-only relationship is archival metadata, not a\n // referential-integrity rule. Its identifier is deliberately allowed to\n // outlive the parent, so delete planning must not block, null, or remove\n // the retained row (#2413).\n if (\n relationship.type === 'foreignKey' &&\n relationship.options?.constraint === false\n ) {\n continue;\n }\n\n const tableName = registry.getTableName(sourceClass);\n if (!tableName) continue;\n\n const column = toSnakeCase(relationship.fieldName);\n if (!conflictColumns) {\n conflictColumns = new Set(registry.getConflictColumns(sourceClass));\n }\n\n // A `@tenantId()` field is a structural scoping marker, not a\n // junction/ownership key — it lands in `conflictColumns` only because\n // #2360 leads every tenant-scoped class's *default* natural key with\n // the tenant column, not because the referencing row is *identified*\n // by its tenant the way a junction row is identified by its parent.\n // Without this guard, deleting a `Tenant` would silently CASCADE\n // through the tenant column of every tenant-scoped class in the\n // schema that has not declared its own `conflictColumns` — the\n // overwhelming majority. `@tenantId()` exposes no `onDelete` today, so\n // an explicit declaration can never widen this back to CASCADE; that\n // is deliberate until tenant-delete cascade is an explicit decision.\n const isTenantIdField =\n relationship.options?.__tenancy?.isTenantIdField === true;\n if (isTenantIdField) continue;\n\n const { action, declared } = resolveForeignKeyDeleteAction({\n declared: relationship.options?.onDelete,\n isConflictColumn: conflictColumns.has(column),\n isTenantIdField: false,\n });\n\n if (\n action === 'SET NULL' &&\n fields.get(relationship.fieldName)?.required\n ) {\n // Fail on the declaration, not later on a NOT NULL violation from the\n // engine — the message there names a column, not the decorator.\n throw ConfigurationError.invalidConfiguration(\n `${sourceClass}.${relationship.fieldName} onDelete: 'SET NULL'`,\n relationship.fieldName,\n \"a nullable field (mark it `nullable: true`, or use 'CASCADE' / 'RESTRICT')\",\n );\n }\n\n references.push({\n className: sourceClass,\n tableName,\n fieldName: relationship.fieldName,\n column,\n action,\n declared,\n });\n }\n }\n\n // Both forms are matched deliberately: an association row written before a\n // class was package-qualified still carries the simple `meta_type`. The\n // qualified form alone is unambiguous; the simple-name fallback can still\n // match a same-simple-name sibling class's row if it also shares a\n // `meta_id` — a real, not just theoretical, risk for a class declaring\n // `idType: 'text'` (non-UUID, not guaranteed globally unique), the same gap\n // `deleteSystemRows()` closed for `_smrt_contexts` / `_smrt_embeddings`\n // (review fix) by adding a class-name filter. Closing it here needs the\n // same STI-and-legacy-name-aware filter this module already builds for\n // `deleteSystemRows()` narrowed further to registry-unambiguous simple\n // names; tracked under #2419 alongside the other same-simple-name\n // collision gaps rather than reworked here.\n const metaTypes: string[] = [];\n const qualified = registry.getClass(className)?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n const simple = registry.getClass(className)?.name ?? className;\n if (!metaTypes.includes(simple)) metaTypes.push(simple);\n\n return {\n references,\n polymorphic,\n metaTypes,\n isEmpty: references.length === 0 && polymorphic.length === 0,\n };\n}\n\n/** Per-delete state shared by every level of the cascade. */\ninterface CascadeContext {\n db: DatabaseInterface;\n registry: CascadeRegistryView;\n /** `table:id` pairs already expanded, so a reference cycle terminates. */\n visited: Set<string>;\n /** Tables touched by the cascade, for read-cache invalidation. */\n affectedTables: Set<string>;\n /**\n * Qualified name of the class that owns each affected table, so the\n * caller can resolve *that* class's own `@smrt({ cache })` config —\n * cross-process cache invalidation is a per-class opt-in, and a table\n * cascaded into belongs to a different class than the one `delete()` was\n * called on.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/** Resolve a registry-recorded class name to its qualified form, when known. */\nfunction toQualifiedClassName(\n registry: CascadeRegistryView,\n className: string,\n): string {\n return registry.getClass(className)?.qualifiedName ?? className;\n}\n\n/**\n * Every value `_smrt_contexts.owner_class` / `_smrt_embeddings.object_class`\n * could plausibly hold for a row belonging to an id of `className` (review\n * fix): both name forms (qualified + simple — older rows predate package\n * qualification) of `className` itself, plus every other member of its STI\n * hierarchy sharing its table. A CASCADE-collected id can belong to any\n * concrete STI subclass of the declaring reference, which stamps its own\n * (more specific) runtime class name at write time, not the reference's.\n *\n * Narrowing by this set — instead of matching by id alone — closes a\n * cross-class collision: two unrelated classes using `idType: 'text'`\n * (non-UUID, not guaranteed globally unique) could otherwise share an id\n * value and have one's `remember()`/embeddings rows deleted by the other's\n * cascade.\n */\nfunction ownerClassCandidates(\n registry: CascadeRegistryView,\n className: string,\n): string[] {\n const stiBase = registry.getSTIBase(className) ?? className;\n const members = new Set<string>([\n className,\n stiBase,\n ...registry.getDescendants(stiBase),\n ]);\n\n const names = new Set<string>();\n for (const member of members) {\n names.add(member);\n const registered = registry.getClass(member);\n if (registered?.qualifiedName) names.add(registered.qualifiedName);\n if (registered?.name) names.add(registered.name);\n }\n return [...names];\n}\n\n/**\n * Build the `where` clause matching `column` against one or more ids.\n *\n * A single id uses equality so the planner can use a plain index; multiple ids\n * use the adapter's `in` operator.\n */\nfunction idPredicate(column: string, ids: string[]): Record<string, unknown> {\n return ids.length === 1 ? { [column]: ids[0] } : { [`${column} in`]: ids };\n}\n\n/**\n * Run a cascade statement against a *referencing* table, tolerating the\n * table (or an expected column) not existing in this database.\n *\n * The cascade plan is built from the in-process registry, which can carry a\n * class from any imported package — including one whose table this specific\n * database was never migrated to include (a partially adopted feature, a\n * package pulled in for its types, or, in a test process, a fixture some\n * other test file registered). A missing referencing table trivially has no\n * rows to act on, so the correct behaviour is identical to the table\n * existing and being empty — this must never abort an otherwise valid\n * delete. Any other failure (a real constraint violation, a lock timeout, a\n * genuine SQL error unrelated to the table's existence) still propagates.\n */\nasync function tolerateMissingTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (classifyDatabaseError(error).kind === 'undefined_object') {\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table or column not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n throw error;\n }\n}\n\nasync function selectIds(\n db: DatabaseInterface,\n tableName: string,\n column: string,\n ids: string[],\n): Promise<string[]> {\n const found: string[] = [];\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n const rows = await tolerateMissingTable(\n () => db.list(tableName, idPredicate(column, batch)),\n [] as Record<string, unknown>[],\n { table: tableName, action: 'CASCADE select' },\n );\n for (const row of rows) {\n const id = row?.id;\n if (typeof id === 'string' && id.length > 0) found.push(id);\n }\n }\n return found;\n}\n\nasync function deleteByIds(\n db: DatabaseInterface,\n tableName: string,\n ids: string[],\n): Promise<void> {\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () => db.delete(tableName, idPredicate('id', batch)),\n undefined,\n { table: tableName, action: 'CASCADE delete' },\n );\n }\n}\n\n/**\n * Remove the framework-managed side rows owned by the given object ids.\n *\n * `_smrt_contexts` and `_smrt_embeddings` are keyed by `(owner_class, owner_id)`\n * and `(object_class, object_id)` respectively. Matched by id *and* class\n * (review fix): id alone would let two unrelated classes using\n * `idType: 'text'` (non-UUID, not guaranteed globally unique) collide on a\n * shared id value and delete each other's memory/embeddings rows. `classNames`\n * is the STI-hierarchy-expanded candidate set from\n * {@link ownerClassCandidates} — the class column stores the *runtime*\n * constructor name, which for an STI hierarchy is a concrete subclass rather\n * than the class the cascade was planned from, so a single exact name is not\n * enough.\n *\n * A missing system table is not an error — an application database may predate\n * the table, and losing derived rows must never fail an otherwise valid delete.\n */\nasync function deleteSystemRows(\n db: DatabaseInterface,\n ids: string[],\n classNames: string[],\n): Promise<void> {\n const ownerIds = ids.filter(\n (id) =>\n typeof id === 'string' &&\n id.length > 0 &&\n id !== COLLECTION_OWNER_SENTINEL,\n );\n if (ownerIds.length === 0 || classNames.length === 0) return;\n\n for (const [table, idColumn, classColumn] of [\n [CONTEXTS_TABLE, 'owner_id', 'owner_class'],\n [EMBEDDINGS_TABLE, 'object_id', 'object_class'],\n ] as const) {\n for (const batch of chunkArray(ownerIds, IN_LIST_CHUNK_SIZE)) {\n try {\n await db.delete(table, {\n ...idPredicate(idColumn, batch),\n ...idPredicate(classColumn, classNames),\n });\n } catch (error) {\n logger.warn(\n `Failed to clean ${table} rows during cascade delete: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n }\n}\n\n/**\n * Resolve every reference pointing at `ids` of `className`, recursively.\n *\n * Does **not** delete the rows identified by `ids` — the caller owns that, so\n * `SmrtObject.delete()` keeps issuing its own final statement and its own\n * lifecycle hooks.\n */\nasync function resolveReferences(\n ctx: CascadeContext,\n className: string,\n tableName: string,\n ids: string[],\n depth: number,\n): Promise<void> {\n const pending = ids.filter((id) => {\n const key = `${tableName}:${id}`;\n if (ctx.visited.has(key)) return false;\n ctx.visited.add(key);\n return true;\n });\n if (pending.length === 0) return;\n\n if (depth > MAX_CASCADE_DEPTH) {\n throw DatabaseError.constraintViolation(\n `cascade delete from ${className} exceeded the maximum depth of ` +\n `${MAX_CASCADE_DEPTH}; check for a chain of onDelete: 'CASCADE' ` +\n 'references that never terminates',\n className,\n );\n }\n\n const plan = buildCascadePlan(ctx.registry, className);\n\n // SQL NO ACTION is immediate on every supported SMRT migration path, so the\n // app-side belt preflights it exactly like RESTRICT before any mutation.\n for (const reference of plan.references) {\n if (reference.action !== 'RESTRICT' && reference.action !== 'NO ACTION') {\n continue;\n }\n let remaining = 0;\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n remaining += await tolerateMissingTable(\n () =>\n ctx.db.count(\n reference.tableName,\n idPredicate(reference.column, batch),\n ),\n 0,\n { table: reference.tableName, action: `${reference.action} check` },\n );\n if (remaining > 0) break;\n }\n if (remaining > 0) {\n throw DatabaseError.constraintViolation(\n `${reference.className}.${reference.fieldName} ` +\n `${reference.declared ? 'declares' : 'resolves to'} onDelete: ` +\n `'${reference.action}' and ${remaining} row(s) still reference this ` +\n `${className}`,\n reference.column,\n );\n }\n }\n\n for (const reference of plan.references) {\n if (reference.action === 'SET NULL') {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () =>\n ctx.db.update(\n reference.tableName,\n idPredicate(reference.column, batch),\n { [reference.column]: null },\n ),\n undefined,\n { table: reference.tableName, action: 'SET NULL' },\n );\n }\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n continue;\n }\n\n if (reference.action !== 'CASCADE') continue;\n\n const childIds = await selectIds(\n ctx.db,\n reference.tableName,\n reference.column,\n pending,\n );\n if (childIds.length === 0) continue;\n\n await resolveReferences(\n ctx,\n reference.className,\n reference.tableName,\n childIds,\n depth + 1,\n );\n await deleteSystemRows(\n ctx.db,\n childIds,\n ownerClassCandidates(ctx.registry, reference.className),\n );\n await deleteByIds(ctx.db, reference.tableName, childIds);\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n }\n\n for (const association of plan.polymorphic) {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n const where: Record<string, unknown> = {\n ...idPredicate('meta_id', batch),\n };\n if (plan.metaTypes.length === 1) {\n where.meta_type = plan.metaTypes[0];\n } else {\n where['meta_type in'] = plan.metaTypes;\n }\n const result = await tolerateMissingTable(\n () => ctx.db.delete(association.tableName, where),\n undefined,\n {\n table: association.tableName,\n action: 'polymorphic association cleanup',\n },\n );\n if ((result?.affected ?? 0) > 0) {\n ctx.affectedTables.add(association.tableName);\n ctx.affectedTableClasses.set(\n association.tableName,\n toQualifiedClassName(ctx.registry, association.className),\n );\n }\n }\n }\n}\n\n/** Outcome of a cascade run, returned so the caller can invalidate caches. */\nexport interface CascadeResult {\n /** Tables whose rows were removed or nulled, excluding the target's own. */\n affectedTables: Set<string>;\n /**\n * Qualified class name that owns each entry in {@link affectedTables},\n * where resolvable — lets the caller check *that* class's own\n * cross-process cache config rather than only its own.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/**\n * Resolve every reference to `ids` of `className` and clean their framework\n * side rows, then hand control back so the caller can delete the rows.\n *\n * Callers are expected to run this on a transaction-bound `db` — see\n * {@link runCascadeDelete}, which owns that decision.\n */\nexport async function cascadeReferencesTo(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: { className: string; tableName: string; ids: string[] },\n): Promise<CascadeResult> {\n const ctx: CascadeContext = {\n db,\n registry,\n visited: new Set(),\n affectedTables: new Set(),\n affectedTableClasses: new Map(),\n };\n await resolveReferences(\n ctx,\n target.className,\n target.tableName,\n target.ids,\n 0,\n );\n await deleteSystemRows(\n db,\n target.ids,\n ownerClassCandidates(registry, target.className),\n );\n return {\n affectedTables: ctx.affectedTables,\n affectedTableClasses: ctx.affectedTableClasses,\n };\n}\n\ntype TransactionCapable = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\n/**\n * Run the cascade and the target row's own deletion atomically.\n *\n * When anything references the class and the adapter exposes `transaction()`,\n * the whole sequence runs inside one — including the caller's `deleteSelf`\n * statement, so a failure part-way through cannot leave the object deleted with\n * its junction rows intact (or vice versa). Adapters without transaction\n * support run the same statements sequentially; this is the documented\n * degradation, not a silent one.\n *\n * When nothing references the class there is nothing to keep consistent, and\n * the transaction is skipped — see the comment on that branch.\n *\n * @param db - Database the object is bound to\n * @param registry - Registry view used to build cascade plans\n * @param target - Class, table and id of the object being deleted\n * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db\n * @returns Tables affected by the cascade, for read-cache invalidation\n */\nexport async function runCascadeDelete(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: {\n className: string;\n tableName: string;\n /** An unsaved object has none; the cascade is then a no-op. */\n id: string | null | undefined;\n },\n deleteSelf: (db: DatabaseInterface) => Promise<void>,\n): Promise<CascadeResult> {\n const ids = target.id ? [target.id] : [];\n\n // Nothing references this class AND no polymorphic association class is\n // registered anywhere in the process. `plan.polymorphic` is unconditionally\n // every registered `SmrtPolymorphicAssociation` subclass — a `metaType`\n // column can point at any class at runtime, so there is no static metadata\n // to scope it by, unlike a typed `@foreignKey`/`@crossPackageRef`. This\n // branch is therefore common for a class with no incoming references in an\n // app with no polymorphic associations at all, but rare — not \"the\n // overwhelmingly common case\" — once even one polymorphic class exists\n // anywhere in the process, since every delete's plan then carries it.\n // Opening a transaction to wrap statements that cannot disagree with each\n // other would cost two extra round trips, and on single-connection adapters\n // it would serialize concurrent deletes behind the transaction queue. Order\n // the two statements instead: the row goes first, so a failure leaves\n // everything as it was, and the derived side rows follow under the\n // best-effort contract they already carry.\n if (buildCascadePlan(registry, target.className).isEmpty) {\n await deleteSelf(db);\n await deleteSystemRows(\n db,\n ids,\n ownerClassCandidates(registry, target.className),\n );\n return { affectedTables: new Set(), affectedTableClasses: new Map() };\n }\n\n const run = async (bound: DatabaseInterface): Promise<CascadeResult> => {\n const result = await cascadeReferencesTo(bound, registry, {\n className: target.className,\n tableName: target.tableName,\n ids,\n });\n await deleteSelf(bound);\n return result;\n };\n\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') {\n return run(db);\n }\n\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, run);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;AAY7C,IAAM,iBAAiB;;AAGvB,IAAM,mBAAmB;;;;;;AAOzB,IAAM,4BAA4B;;;;;;AAOlC,IAAM,oBAAoB;;;;;;;;AAgE1B,SAAgB,kBAAkB,OAA4C;CAC5E,OAAO,0BAA0B,KAAK;AACxC;AAEA,SAAS,8BAA8B,QAAuC;CAI5E,OAAO,OAAO,IAAI,UAAU,KAAK,OAAO,IAAI,QAAQ,KAA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xB,sCAAsB,IAAI,IAAI;CAChC;CACA,MAAM,kBACJ,KACA,OAAO,WACP,OAAO,WACP,OAAO,KACP,CACF;CACA,MAAM,iBACJ,IACA,OAAO,KACP,qBAAqB,UAAU,OAAO,SAAS,CACjD;CACA,OAAO;EACL,gBAAgB,IAAI;EACpB,sBAAsB,IAAI;CAC5B;AACF;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,iBACpB,IACA,UACA,QAMA,YACwB;CACxB,MAAM,MAAM,OAAO,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC;CAiBvC,IAAI,iBAAiB,UAAU,OAAO,SAAS,CAAC,CAAC,SAAS;EACxD,MAAM,WAAW,EAAE;EACnB,MAAM,iBACJ,IACA,KACA,qBAAqB,UAAU,OAAO,SAAS,CACjD;EACA,OAAO;GAAE,gCAAgB,IAAI,IAAI;GAAG,sCAAsB,IAAI,IAAI;EAAE;CACtE;CAEA,MAAM,MAAM,OAAO,UAAqD;EACtE,MAAM,SAAS,MAAM,oBAAoB,OAAO,UAAU;GACxD,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB;EACF,CAAC;EACD,MAAM,WAAW,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAe,GAA0B;CAC/C,IAAI,OAAO,gBAAgB,YACzB,OAAO,IAAI,EAAE;CAGf,OAAO,YAAY,KAIjB,IAAI,GAAG;AACX"}
1
+ {"version":3,"file":"cascade.js","names":[],"sources":["../src/cascade.ts"],"sourcesContent":["/**\n * App-side referential integrity for `SmrtObject.delete()` (#2371).\n *\n * Same-package `@foreignKey` fields now emit database constraints where the\n * engine can enforce the declared policy. Cross-package references and older\n * schemas still rely on this application-side path. Before this module,\n * `delete()` removed the object's own row and nothing else: junction rows,\n * polymorphic association rows, `_smrt_embeddings` and `_smrt_contexts` entries\n * were all left pointing at an id that no longer resolved, and\n * `@foreignKey(..., { onDelete })` was metadata nobody read.\n *\n * This module implements those semantics in the application layer. It mirrors\n * what a DB-level constraint would do, deliberately including the parts that\n * make it *unlike* a model-layer delete:\n *\n * - Cascaded rows are removed with set-based statements. Their `beforeDelete` /\n * `afterDelete` hooks and interceptors do **not** run, and no change-feed\n * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.\n * Only the object `delete()` was called on runs the full lifecycle.\n * - Every delete runs inside a single transaction when the adapter exposes\n * one, including cleanup of framework-owned context and embedding rows, so\n * a partial cascade cannot survive a failure. A `metaType` column can point\n * at any class at runtime, so a polymorphic association class is always\n * plausibly relevant.\n *\n * ## Which references are followed\n *\n * A reference is any `@foreignKey` / `@crossPackageRef` field on a registered\n * class whose target resolves to the deleted object's class (or one of its\n * registered STI ancestors), plus the polymorphic `(metaType, metaId)` pair on\n * {@link SmrtPolymorphicAssociation} subclasses.\n *\n * The action comes from the field's declared `onDelete`. When it is not\n * declared, the default is derived from the referencing class's natural key:\n *\n * | Reference | Default when `onDelete` is absent |\n * |---|---|\n * | Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n * | Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n * | Ordinary same-package reference | `NO ACTION` (deletion is refused while references remain) |\n * | Every `@tenantId()` field | Excluded: tenant scope is not an ownership edge |\n *\n * The natural-key rule is what makes junction rows work without any\n * per-package annotation: a junction declares\n * `@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so\n * `content_id` identifies the row and the row cannot outlive the content it\n * links. An ordinary child (`Order.customerId`) is keyed by `(slug, context)`,\n * so it defaults to immediate `NO ACTION` unless it opts in with\n * `@foreignKey(Customer, { onDelete: 'CASCADE' })`.\n *\n * `@tenantId()` fields are excluded from the natural-key rule even though\n * `@happyvertical/smrt-tenancy` leads a tenant-scoped class's *default*\n * `conflictColumns` with the tenant column (#2360): the tenant column scopes\n * ownership, it does not identify the row the way a junction's foreign key\n * does, and it targets a class (`Tenant`) that is virtually always\n * referenced. Without this exclusion, deleting one `Tenant` row would\n * recursively CASCADE through every tenant-scoped table that has not\n * declared its own `conflictColumns` — the overwhelming majority. The field\n * is detected via the `__tenancy.isTenantIdField` marker `@tenantId()`\n * attaches to its own registration (`FieldMeta.__tenancy`, read structurally\n * so `smrt-core` never depends on `smrt-tenancy`). `@tenantId()` exposes no\n * `onDelete` option today, so this cannot currently be overridden per field.\n *\n * @see https://github.com/happyvertical/smrt/issues/2371\n * @module\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { classifyDatabaseError } from './db-errors.js';\nimport { ConfigurationError, DatabaseError } from './errors.js';\n// Type-only: erased at runtime, so it cannot re-enter the\n// `registry → object → cascade` import cycle.\nimport type { ObjectRegistry } from './registry.js';\nimport {\n normalizeForeignKeyAction,\n resolveForeignKeyDeleteAction,\n} from './schema/foreign-key-policy.js';\nimport type { ForeignKeyAction } from './schema/types.js';\nimport { chunkArray, IN_LIST_CHUNK_SIZE } from './utils/chunk.js';\nimport { toSnakeCase } from './utils/naming.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Referential action applied to rows pointing at a deleted object.\n *\n * Same vocabulary as SQL's `ON DELETE`, enforced by the framework before the\n * engine. `NO ACTION` is preflighted like an immediate restrictive action so\n * application-side and database-side enforcement agree.\n */\nexport type OnDeleteAction = ForeignKeyAction;\n\n/** Table holding framework-managed per-object memory entries. */\nconst CONTEXTS_TABLE = '_smrt_contexts';\n\n/** Table holding framework-managed per-object embedding vectors. */\nconst EMBEDDINGS_TABLE = '_smrt_embeddings';\n\n/**\n * Reserved `_smrt_contexts.owner_id` used by `SmrtCollection.remember()` for\n * collection-scoped memory. A real object id is a UUID and can never equal it,\n * but the guard keeps a malformed id from wiping every sibling's defaults.\n */\nconst COLLECTION_OWNER_SENTINEL = '__collection__';\n\n/**\n * Maximum number of cascade levels followed from the object `delete()` was\n * called on. A cycle between two classes that both declare `onDelete: 'CASCADE'`\n * is broken by the visited set; this bound catches unbounded *chains*.\n */\nconst MAX_CASCADE_DEPTH = 10;\n\n/** One reference that must be resolved before the target row can be removed. */\nexport interface CascadeReference {\n /** Registered name of the class holding the referencing column. */\n className: string;\n /** Table holding the referencing rows. */\n tableName: string;\n /** Field name (camelCase) on the referencing class. */\n fieldName: string;\n /** Column (snake_case) holding the reference. */\n column: string;\n /** Resolved action. `NO ACTION` is preflighted like an immediate RESTRICT. */\n action: OnDeleteAction;\n /** `true` when the action was declared rather than derived from the key. */\n declared: boolean;\n}\n\n/** A polymorphic association table that can point at any class. */\nexport interface CascadePolymorphicReference {\n /** Registered name of the association class. */\n className: string;\n /** Table holding the association rows. */\n tableName: string;\n}\n\n/** Everything that must happen before rows of one class can be deleted. */\nexport interface CascadePlan {\n /** Typed `@foreignKey` / `@crossPackageRef` references, action-resolved. */\n references: CascadeReference[];\n /** Polymorphic association tables that may point at this class. */\n polymorphic: CascadePolymorphicReference[];\n /** `meta_type` values that identify this class in an association row. */\n metaTypes: string[];\n /** `true` when nothing references this class and nothing has to be visited. */\n isEmpty: boolean;\n}\n\n/**\n * Read-only slice of `ObjectRegistry` this module needs.\n *\n * Taking it as a parameter — rather than importing the registry as a value —\n * keeps `cascade.ts` out of the `registry → object → cascade` import cycle,\n * and lets tests drive the planner from a hand-built registry.\n */\nexport type CascadeRegistryView = Pick<\n typeof ObjectRegistry,\n | 'getRelationshipMap'\n | 'getFields'\n | 'getConflictColumns'\n | 'getTableName'\n | 'getSelfReferableNames'\n | 'getClass'\n | 'getSTIBase'\n | 'getDescendants'\n>;\n\n/**\n * Normalize a declared `onDelete` value.\n *\n * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the\n * schema generator has always carried in the manifest. Returns `undefined` for\n * an unset or unrecognized value so the caller can fall back to the default.\n */\nexport function normalizeOnDelete(value: unknown): OnDeleteAction | undefined {\n return normalizeForeignKeyAction(value);\n}\n\nfunction isPolymorphicAssociationClass(fields: Map<string, unknown>): boolean {\n // The three columns `SmrtPolymorphicAssociation` contributes. Requiring all\n // of them keeps an unrelated class that happens to carry a `metaType` from\n // being treated as an association table.\n return fields.has('metaType') && fields.has('metaId') && fields.has('role');\n}\n\n/**\n * Build the cascade plan for one class.\n *\n * The plan is derived entirely from registry metadata, so it is valid for any\n * database the class is used against. It is rebuilt per delete rather than\n * cached: registration is incremental (manifests load lazily, tests register\n * classes between cases) and a stale plan would silently skip a table.\n *\n * @param registry - Registry view (`ObjectRegistry` satisfies it)\n * @param className - Class whose incoming references should be resolved\n */\nexport function buildCascadePlan(\n registry: CascadeRegistryView,\n className: string,\n): CascadePlan {\n // `className` is normally already qualified (delete() passes\n // getResolvedQualifiedName()), but a common same-package `@foreignKey('X')`\n // still stores its target as the bare simple name `X`. That still matches:\n // getSelfReferableNames() walks the full ancestor chain (self included) and\n // adds each ancestor's *simple* name via `getClass(ancestor)?.name`, so the\n // simple form is already in the seed set below, not just the loop's\n // qualified-variant augmentation.\n const targetNames = new Set(registry.getSelfReferableNames(className));\n for (const name of [...targetNames]) {\n const qualified = registry.getClass(name)?.qualifiedName;\n if (qualified) targetNames.add(qualified);\n }\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n\n for (const [sourceClass, relationships] of registry.getRelationshipMap()) {\n const fields = registry.getFields(sourceClass);\n\n if (isPolymorphicAssociationClass(fields)) {\n const tableName = registry.getTableName(sourceClass);\n if (tableName) {\n polymorphic.push({ className: sourceClass, tableName });\n }\n }\n\n if (relationships.length === 0) continue;\n\n let conflictColumns: Set<string> | undefined;\n\n for (const relationship of relationships) {\n if (\n relationship.type !== 'foreignKey' &&\n relationship.type !== 'crossPackageRef'\n ) {\n continue;\n }\n if (!targetNames.has(relationship.targetClass)) continue;\n\n // An explicit app-side-only relationship is archival metadata, not a\n // referential-integrity rule. Its identifier is deliberately allowed to\n // outlive the parent, so delete planning must not block, null, or remove\n // the retained row (#2413).\n if (\n relationship.type === 'foreignKey' &&\n relationship.options?.constraint === false\n ) {\n continue;\n }\n\n const tableName = registry.getTableName(sourceClass);\n if (!tableName) continue;\n\n const column = toSnakeCase(relationship.fieldName);\n if (!conflictColumns) {\n conflictColumns = new Set(registry.getConflictColumns(sourceClass));\n }\n\n // A `@tenantId()` field is a structural scoping marker, not a\n // junction/ownership key — it lands in `conflictColumns` only because\n // #2360 leads every tenant-scoped class's *default* natural key with\n // the tenant column, not because the referencing row is *identified*\n // by its tenant the way a junction row is identified by its parent.\n // Without this guard, deleting a `Tenant` would silently CASCADE\n // through the tenant column of every tenant-scoped class in the\n // schema that has not declared its own `conflictColumns` — the\n // overwhelming majority. `@tenantId()` exposes no `onDelete` today, so\n // an explicit declaration can never widen this back to CASCADE; that\n // is deliberate until tenant-delete cascade is an explicit decision.\n const isTenantIdField =\n relationship.options?.__tenancy?.isTenantIdField === true;\n if (isTenantIdField) continue;\n\n const { action, declared } = resolveForeignKeyDeleteAction({\n declared: relationship.options?.onDelete,\n isConflictColumn: conflictColumns.has(column),\n isTenantIdField: false,\n });\n\n if (\n action === 'SET NULL' &&\n fields.get(relationship.fieldName)?.required\n ) {\n // Fail on the declaration, not later on a NOT NULL violation from the\n // engine — the message there names a column, not the decorator.\n throw ConfigurationError.invalidConfiguration(\n `${sourceClass}.${relationship.fieldName} onDelete: 'SET NULL'`,\n relationship.fieldName,\n \"a nullable field (mark it `nullable: true`, or use 'CASCADE' / 'RESTRICT')\",\n );\n }\n\n references.push({\n className: sourceClass,\n tableName,\n fieldName: relationship.fieldName,\n column,\n action,\n declared,\n });\n }\n }\n\n // Both forms are matched deliberately: an association row written before a\n // class was package-qualified still carries the simple `meta_type`. The\n // qualified form alone is unambiguous; the simple-name fallback can still\n // match a same-simple-name sibling class's row if it also shares a\n // `meta_id` — a real, not just theoretical, risk for a class declaring\n // `idType: 'text'` (non-UUID, not guaranteed globally unique), the same gap\n // `deleteSystemRows()` closed for `_smrt_contexts` / `_smrt_embeddings`\n // (review fix) by adding a class-name filter. Closing it here needs the\n // same STI-and-legacy-name-aware filter this module already builds for\n // `deleteSystemRows()` narrowed further to registry-unambiguous simple\n // names; tracked under #2419 alongside the other same-simple-name\n // collision gaps rather than reworked here.\n const metaTypes: string[] = [];\n const qualified = registry.getClass(className)?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n const simple = registry.getClass(className)?.name ?? className;\n if (!metaTypes.includes(simple)) metaTypes.push(simple);\n\n return {\n references,\n polymorphic,\n metaTypes,\n isEmpty: references.length === 0 && polymorphic.length === 0,\n };\n}\n\n/** Per-delete state shared by every level of the cascade. */\ninterface CascadeContext {\n db: DatabaseInterface;\n registry: CascadeRegistryView;\n /** `table:id` pairs already expanded, so a reference cycle terminates. */\n visited: Set<string>;\n /** Tables touched by the cascade, for read-cache invalidation. */\n affectedTables: Set<string>;\n /**\n * Qualified name of the class that owns each affected table, so the\n * caller can resolve *that* class's own `@smrt({ cache })` config —\n * cross-process cache invalidation is a per-class opt-in, and a table\n * cascaded into belongs to a different class than the one `delete()` was\n * called on.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/** Resolve a registry-recorded class name to its qualified form, when known. */\nfunction toQualifiedClassName(\n registry: CascadeRegistryView,\n className: string,\n): string {\n return registry.getClass(className)?.qualifiedName ?? className;\n}\n\n/**\n * Every value `_smrt_contexts.owner_class` / `_smrt_embeddings.object_class`\n * could plausibly hold for a row belonging to an id of `className` (review\n * fix): both name forms (qualified + simple — older rows predate package\n * qualification) of `className` itself, plus every other member of its STI\n * hierarchy sharing its table. A CASCADE-collected id can belong to any\n * concrete STI subclass of the declaring reference, which stamps its own\n * (more specific) runtime class name at write time, not the reference's.\n *\n * Narrowing by this set — instead of matching by id alone — closes a\n * cross-class collision: two unrelated classes using `idType: 'text'`\n * (non-UUID, not guaranteed globally unique) could otherwise share an id\n * value and have one's `remember()`/embeddings rows deleted by the other's\n * cascade.\n */\nfunction ownerClassCandidates(\n registry: CascadeRegistryView,\n className: string,\n): string[] {\n const stiBase = registry.getSTIBase(className) ?? className;\n const members = new Set<string>([\n className,\n stiBase,\n ...registry.getDescendants(stiBase),\n ]);\n\n const names = new Set<string>();\n for (const member of members) {\n names.add(member);\n const registered = registry.getClass(member);\n if (registered?.qualifiedName) names.add(registered.qualifiedName);\n if (registered?.name) names.add(registered.name);\n }\n return [...names];\n}\n\n/**\n * Build the `where` clause matching `column` against one or more ids.\n *\n * A single id uses equality so the planner can use a plain index; multiple ids\n * use the adapter's `in` operator.\n */\nfunction idPredicate(column: string, ids: string[]): Record<string, unknown> {\n return ids.length === 1 ? { [column]: ids[0] } : { [`${column} in`]: ids };\n}\n\n/**\n * Run a cascade statement against a *referencing* table, tolerating the\n * table (or an expected column) not existing in this database.\n *\n * The cascade plan is built from the in-process registry, which can carry a\n * class from any imported package — including one whose table this specific\n * database was never migrated to include (a partially adopted feature, a\n * package pulled in for its types, or, in a test process, a fixture some\n * other test file registered). A missing referencing table trivially has no\n * rows to act on, so the correct behaviour is identical to the table\n * existing and being empty — this must never abort an otherwise valid\n * delete. Any other failure (a real constraint violation, a lock timeout, a\n * genuine SQL error unrelated to the table's existence) still propagates.\n */\nasync function tolerateMissingTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (classifyDatabaseError(error).kind === 'undefined_object') {\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table or column not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n throw error;\n }\n}\n\n/**\n * System-table cleanup may ignore an absent table for databases created before\n * that subsystem existed, but never a missing column in a table that does\n * exist. The shared `undefined_object` classification intentionally combines\n * both cases, so this security boundary must retain the narrower driver signal.\n */\nfunction normalizeMissingTableName(value: string): string {\n const unquoted = value.replace(/[\"'`[\\]]/g, '');\n return (unquoted.split('.').at(-1) ?? unquoted)\n .replace(/[^A-Za-z0-9_$-]/g, '')\n .toLowerCase();\n}\n\nfunction missingTableNames(messages: readonly string[]): string[] {\n const names: string[] = [];\n const patterns = [\n /no such table:\\s*([^\\s,;]+)/giu,\n /(?:relation|table)\\s+((?:\"[^\"]+\"(?:\\.\"[^\"]+\")*)|(?:[A-Za-z0-9_.$-]+))\\s+does not exist/giu,\n /table with name\\s+((?:\"[^\"]+\")|(?:[A-Za-z0-9_.$-]+))\\s+does not exist/giu,\n ];\n for (const message of messages) {\n for (const pattern of patterns) {\n for (const match of message.matchAll(pattern)) {\n if (match[1]) names.push(normalizeMissingTableName(match[1]));\n }\n }\n }\n return names;\n}\n\nfunction isMissingTableError(error: unknown, expectedTable: string): boolean {\n const classification = classifyDatabaseError(error);\n if (classification.kind !== 'undefined_object') return false;\n if (\n classification.sqlstate === '42703' ||\n classification.driverCode === '42703' ||\n classification.driverCodes.includes('42703')\n ) {\n return false;\n }\n const names = missingTableNames(classification.driverMessages);\n const expected = normalizeMissingTableName(expectedTable);\n return (\n names.length > 0 &&\n names.every((missingTableName) => missingTableName === expected)\n );\n}\n\nasync function tolerateMissingSystemTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (!isMissingTableError(error, context.table)) throw error;\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n}\n\nasync function selectIds(\n db: DatabaseInterface,\n tableName: string,\n column: string,\n ids: string[],\n): Promise<string[]> {\n const found: string[] = [];\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n const rows = await tolerateMissingTable(\n () => db.list(tableName, idPredicate(column, batch)),\n [] as Record<string, unknown>[],\n { table: tableName, action: 'CASCADE select' },\n );\n for (const row of rows) {\n const id = row?.id;\n if (typeof id === 'string' && id.length > 0) found.push(id);\n }\n }\n return found;\n}\n\nasync function deleteByIds(\n db: DatabaseInterface,\n tableName: string,\n ids: string[],\n): Promise<void> {\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () => db.delete(tableName, idPredicate('id', batch)),\n undefined,\n { table: tableName, action: 'CASCADE delete' },\n );\n }\n}\n\n/**\n * Remove the framework-managed side rows owned by the given object ids.\n *\n * `_smrt_contexts` and `_smrt_embeddings` are keyed by `(owner_class, owner_id)`\n * and `(object_class, object_id)` respectively. Matched by id *and* class\n * (review fix): id alone would let two unrelated classes using\n * `idType: 'text'` (non-UUID, not guaranteed globally unique) collide on a\n * shared id value and delete each other's memory/embeddings rows. `classNames`\n * is the STI-hierarchy-expanded candidate set from\n * {@link ownerClassCandidates} — the class column stores the *runtime*\n * constructor name, which for an STI hierarchy is a concrete subclass rather\n * than the class the cascade was planned from, so a single exact name is not\n * enough.\n *\n * A missing system table is not an error — an application database may predate\n * the table. Every other cleanup failure propagates so the surrounding delete\n * transaction rolls back rather than orphaning tenant-sensitive recall data.\n */\nasync function deleteSystemRows(\n db: DatabaseInterface,\n ids: string[],\n classNames: string[],\n): Promise<void> {\n const ownerIds = ids.filter(\n (id) =>\n typeof id === 'string' &&\n id.length > 0 &&\n id !== COLLECTION_OWNER_SENTINEL,\n );\n if (ownerIds.length === 0 || classNames.length === 0) return;\n\n for (const [table, idColumn, classColumn] of [\n [CONTEXTS_TABLE, 'owner_id', 'owner_class'],\n [EMBEDDINGS_TABLE, 'object_id', 'object_class'],\n ] as const) {\n for (const batch of chunkArray(ownerIds, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingSystemTable(\n () =>\n db.delete(table, {\n ...idPredicate(idColumn, batch),\n ...idPredicate(classColumn, classNames),\n }),\n undefined,\n { table, action: 'framework-owned row cleanup' },\n );\n }\n }\n}\n\n/**\n * Resolve every reference pointing at `ids` of `className`, recursively.\n *\n * Does **not** delete the rows identified by `ids` — the caller owns that, so\n * `SmrtObject.delete()` keeps issuing its own final statement and its own\n * lifecycle hooks.\n */\nasync function resolveReferences(\n ctx: CascadeContext,\n className: string,\n tableName: string,\n ids: string[],\n depth: number,\n): Promise<void> {\n const pending = ids.filter((id) => {\n const key = `${tableName}:${id}`;\n if (ctx.visited.has(key)) return false;\n ctx.visited.add(key);\n return true;\n });\n if (pending.length === 0) return;\n\n if (depth > MAX_CASCADE_DEPTH) {\n throw DatabaseError.constraintViolation(\n `cascade delete from ${className} exceeded the maximum depth of ` +\n `${MAX_CASCADE_DEPTH}; check for a chain of onDelete: 'CASCADE' ` +\n 'references that never terminates',\n className,\n );\n }\n\n const plan = buildCascadePlan(ctx.registry, className);\n\n // SQL NO ACTION is immediate on every supported SMRT migration path, so the\n // app-side belt preflights it exactly like RESTRICT before any mutation.\n for (const reference of plan.references) {\n if (reference.action !== 'RESTRICT' && reference.action !== 'NO ACTION') {\n continue;\n }\n let remaining = 0;\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n remaining += await tolerateMissingTable(\n () =>\n ctx.db.count(\n reference.tableName,\n idPredicate(reference.column, batch),\n ),\n 0,\n { table: reference.tableName, action: `${reference.action} check` },\n );\n if (remaining > 0) break;\n }\n if (remaining > 0) {\n throw DatabaseError.constraintViolation(\n `${reference.className}.${reference.fieldName} ` +\n `${reference.declared ? 'declares' : 'resolves to'} onDelete: ` +\n `'${reference.action}' and ${remaining} row(s) still reference this ` +\n `${className}`,\n reference.column,\n );\n }\n }\n\n for (const reference of plan.references) {\n if (reference.action === 'SET NULL') {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () =>\n ctx.db.update(\n reference.tableName,\n idPredicate(reference.column, batch),\n { [reference.column]: null },\n ),\n undefined,\n { table: reference.tableName, action: 'SET NULL' },\n );\n }\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n continue;\n }\n\n if (reference.action !== 'CASCADE') continue;\n\n const childIds = await selectIds(\n ctx.db,\n reference.tableName,\n reference.column,\n pending,\n );\n if (childIds.length === 0) continue;\n\n await resolveReferences(\n ctx,\n reference.className,\n reference.tableName,\n childIds,\n depth + 1,\n );\n await deleteSystemRows(\n ctx.db,\n childIds,\n ownerClassCandidates(ctx.registry, reference.className),\n );\n await deleteByIds(ctx.db, reference.tableName, childIds);\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n }\n\n for (const association of plan.polymorphic) {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n const where: Record<string, unknown> = {\n ...idPredicate('meta_id', batch),\n };\n if (plan.metaTypes.length === 1) {\n where.meta_type = plan.metaTypes[0];\n } else {\n where['meta_type in'] = plan.metaTypes;\n }\n const result = await tolerateMissingTable(\n () => ctx.db.delete(association.tableName, where),\n undefined,\n {\n table: association.tableName,\n action: 'polymorphic association cleanup',\n },\n );\n if ((result?.affected ?? 0) > 0) {\n ctx.affectedTables.add(association.tableName);\n ctx.affectedTableClasses.set(\n association.tableName,\n toQualifiedClassName(ctx.registry, association.className),\n );\n }\n }\n }\n}\n\n/** Outcome of a cascade run, returned so the caller can invalidate caches. */\nexport interface CascadeResult {\n /** Tables whose rows were removed or nulled, excluding the target's own. */\n affectedTables: Set<string>;\n /**\n * Qualified class name that owns each entry in {@link affectedTables},\n * where resolvable — lets the caller check *that* class's own\n * cross-process cache config rather than only its own.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/**\n * Resolve every reference to `ids` of `className` and clean their framework\n * side rows, then hand control back so the caller can delete the rows.\n *\n * Callers are expected to run this on a transaction-bound `db` — see\n * {@link runCascadeDelete}, which owns that decision.\n */\nexport async function cascadeReferencesTo(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: { className: string; tableName: string; ids: string[] },\n): Promise<CascadeResult> {\n const ctx: CascadeContext = {\n db,\n registry,\n visited: new Set(),\n affectedTables: new Set(),\n affectedTableClasses: new Map(),\n };\n await resolveReferences(\n ctx,\n target.className,\n target.tableName,\n target.ids,\n 0,\n );\n await deleteSystemRows(\n db,\n target.ids,\n ownerClassCandidates(registry, target.className),\n );\n return {\n affectedTables: ctx.affectedTables,\n affectedTableClasses: ctx.affectedTableClasses,\n };\n}\n\ntype TransactionCapable = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\n/**\n * Run the cascade and the target row's own deletion atomically.\n *\n * When the adapter exposes `transaction()`, the whole sequence runs inside one\n * — including framework-owned row cleanup and the caller's `deleteSelf`\n * statement, so a failure part-way through cannot leave either side orphaned.\n * Adapters without transaction support run the same statements sequentially;\n * this is the documented degradation, not a silent one.\n *\n * @param db - Database the object is bound to\n * @param registry - Registry view used to build cascade plans\n * @param target - Class, table and id of the object being deleted\n * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db\n * @returns Tables affected by the cascade, for read-cache invalidation\n */\nexport async function runCascadeDelete(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: {\n className: string;\n tableName: string;\n /** An unsaved object has none; the cascade is then a no-op. */\n id: string | null | undefined;\n },\n deleteSelf: (db: DatabaseInterface) => Promise<void>,\n): Promise<CascadeResult> {\n const ids = target.id ? [target.id] : [];\n\n // Nothing references this class AND no polymorphic association class is\n // registered anywhere in the process. `plan.polymorphic` is unconditionally\n // every registered `SmrtPolymorphicAssociation` subclass — a `metaType`\n // column can point at any class at runtime, so there is no static metadata\n // to scope it by, unlike a typed `@foreignKey`/`@crossPackageRef`. This\n // branch is therefore common for a class with no incoming references in an\n // app with no polymorphic associations at all, but rare — not \"the\n // overwhelmingly common case\" — once even one polymorphic class exists\n // anywhere in the process, since every delete's plan then carries it.\n // Framework-owned context and embedding rows still need atomic cleanup even\n // when the registry has no typed or polymorphic references for this class.\n if (buildCascadePlan(registry, target.className).isEmpty) {\n const runWithoutReferences = async (\n bound: DatabaseInterface,\n ): Promise<CascadeResult> => {\n await deleteSystemRows(\n bound,\n ids,\n ownerClassCandidates(registry, target.className),\n );\n await deleteSelf(bound);\n return { affectedTables: new Set(), affectedTableClasses: new Map() };\n };\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') return runWithoutReferences(db);\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, runWithoutReferences);\n }\n\n const run = async (bound: DatabaseInterface): Promise<CascadeResult> => {\n const result = await cascadeReferencesTo(bound, registry, {\n className: target.className,\n tableName: target.tableName,\n ids,\n });\n await deleteSelf(bound);\n return result;\n };\n\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') {\n return run(db);\n }\n\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, run);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkFA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;AAY7C,IAAM,iBAAiB;;AAGvB,IAAM,mBAAmB;;;;;;AAOzB,IAAM,4BAA4B;;;;;;AAOlC,IAAM,oBAAoB;;;;;;;;AAgE1B,SAAgB,kBAAkB,OAA4C;CAC5E,OAAO,0BAA0B,KAAK;AACxC;AAEA,SAAS,8BAA8B,QAAuC;CAI5E,OAAO,OAAO,IAAI,UAAU,KAAK,OAAO,IAAI,QAAQ,KAAK,OAAO,IAAI,MAAM;AAC5E;;;;;;;;;;;;AAaA,SAAgB,iBACd,UACA,WACa;CAQb,MAAM,cAAc,IAAI,IAAI,SAAS,sBAAsB,SAAS,CAAC;CACrE,KAAK,MAAM,QAAQ,CAAC,GAAG,WAAW,GAAG;EACnC,MAAM,YAAY,SAAS,SAAS,IAAI,CAAC,EAAE;EAC3C,IAAI,WAAW,YAAY,IAAI,SAAS;CAC1C;CAEA,MAAM,aAAiC,CAAC;CACxC,MAAM,cAA6C,CAAC;CAEpD,KAAK,MAAM,CAAC,aAAa,kBAAkB,SAAS,mBAAmB,GAAG;EACxE,MAAM,SAAS,SAAS,UAAU,WAAW;EAE7C,IAAI,8BAA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AAO,gBAAgB,YAAY,OAAO,qBAAqB,EAAE;EACrE,OAAO,YAAY,KAIjB,IAAI,oBAAoB;CAC5B;CAEA,MAAM,MAAM,OAAO,UAAqD;EACtE,MAAM,SAAS,MAAM,oBAAoB,OAAO,UAAU;GACxD,WAAW,OAAO;GAClB,WAAW,OAAO;GAClB;EACF,CAAC;EACD,MAAM,WAAW,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAe,GAA0B;CAC/C,IAAI,OAAO,gBAAgB,YACzB,OAAO,IAAI,EAAE;CAGf,OAAO,YAAY,KAIjB,IAAI,GAAG;AACX"}
@@ -9,6 +9,14 @@ interface QueueableDatabase {
9
9
  * handle reintroduces the livelock.
10
10
  */
11
11
  export declare function isEmbeddedDatabase(db: QueueableDatabase): boolean;
12
+ /**
13
+ * Whether `db` is a PostgreSQL handle.
14
+ *
15
+ * The revision compare-and-swap predicate is dialect-specific (#2620): only
16
+ * PostgreSQL needs the millisecond-truncating, timezone-tolerant guard, and
17
+ * only PostgreSQL can evaluate `date_trunc`.
18
+ */
19
+ export declare function isPostgresDatabase(db: QueueableDatabase): boolean;
12
20
  /**
13
21
  * Whether revision compare-and-swap needs the process-local read/upsert path.
14
22
  *
@@ -1 +1 @@
1
- {"version":3,"file":"embedded-write-queue.d.ts","sourceRoot":"","sources":["../src/embedded-write-queue.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AA0C5D,UAAU,iBAAiB;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAEjE;AAED;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAG3E;AAMD;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC,CAwBZ;AAED;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAAC,CAAC,EAClD,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,CAAC,WAAW,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GACxD,OAAO,CAAC,CAAC,CAAC,CAeZ"}
1
+ {"version":3,"file":"embedded-write-queue.d.ts","sourceRoot":"","sources":["../src/embedded-write-queue.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AA0C5D,UAAU,iBAAiB;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAEjE;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAEjE;AAED;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAG3E;AAMD;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC,CAwBZ;AAED;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAAC,CAAC,EAClD,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,CAAC,WAAW,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GACxD,OAAO,CAAC,CAAC,CAAC,CAeZ"}
@@ -45,7 +45,17 @@ var activeQueueKeys = new AsyncLocalStorage();
45
45
  * handle reintroduces the livelock.
46
46
  */
47
47
  function isEmbeddedDatabase(db) {
48
- return !/^postgres(?:ql)?:/iu.test(db?.url ?? "");
48
+ return !isPostgresDatabase(db);
49
+ }
50
+ /**
51
+ * Whether `db` is a PostgreSQL handle.
52
+ *
53
+ * The revision compare-and-swap predicate is dialect-specific (#2620): only
54
+ * PostgreSQL needs the millisecond-truncating, timezone-tolerant guard, and
55
+ * only PostgreSQL can evaluate `date_trunc`.
56
+ */
57
+ function isPostgresDatabase(db) {
58
+ return /^postgres(?:ql)?:/iu.test(db?.url ?? "");
49
59
  }
50
60
  /**
51
61
  * Whether revision compare-and-swap needs the process-local read/upsert path.
@@ -99,6 +109,6 @@ async function withEmbeddedWriteTransaction(db, serialize, operation) {
99
109
  }));
100
110
  }
101
111
  //#endregion
102
- export { isEmbeddedDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction };
112
+ export { isEmbeddedDatabase, isPostgresDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction };
103
113
 
104
114
  //# sourceMappingURL=embedded-write-queue.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"embedded-write-queue.js","names":[],"sources":["../src/embedded-write-queue.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\n/**\n * In-process write serialization for embedded database engines (#2360).\n *\n * File-backed SQLite (libsql) allows one writer at a time and the SDK opens a\n * NEW connection for every null-aware upsert attempt (`transaction(\"write\")`),\n * with no busy timeout on either connection. Any other write on the root\n * connection while such a transaction is open — most commonly the change-feed\n * append that follows every model save — collides as `SQLITE_BUSY`, and under\n * sustained concurrency (a `Promise.all` of creates) the two sides livelock\n * through every retry tier. Before the tenant-led conflict target (#2360) the\n * null-aware path was rare (custom conflict keys with NULL values, #1246);\n * with `tenant_id` leading every tenant-scoped default key, EVERY NULL-tenant\n * (global) create takes it, so the collision became the steady state.\n *\n * The queue makes the process a single writer per embedded database for:\n *\n * - a `save()` whose upsert conflict values contain NULL (the only shape the\n * SDK routes through a second-connection transaction), and\n * - the change-feed append (a root-connection write that follows every save).\n * - every model save and delete, so the embedded revision-CAS compare/upsert\n * fallback cannot race an ordinary save, natural-key create, or delete.\n * - a complete root `SmrtObject.withTransaction()` callback, with writes on\n * its bound handle re-entering the same hold instead of self-deadlocking.\n *\n * Ordinary save/delete holds contain database calls only — never an\n * interceptor or hook. Explicit transaction callbacks are caller-controlled,\n * so their bound model writes re-enter the existing hold. PostgreSQL is never\n * serialized here:\n * its null-aware upsert already arbitrates through advisory locks\n * server-side, and cross-process writers exist that an in-process queue could\n * not order anyway (which is also why this queue is a mitigation for embedded\n * engines' in-process writers, not a cross-process guarantee — embedded\n * engines have no cross-process writers in supported deployments).\n */\n\n/** Queue tail per database identity (URL string, or the handle itself). */\nconst urlQueues = new Map<string, Promise<unknown>>();\nconst handleQueues = new WeakMap<object, Promise<unknown>>();\nconst activeQueueKeys = new AsyncLocalStorage<ReadonlySet<string | object>>();\n\ninterface QueueableDatabase {\n url?: string;\n}\n\n/**\n * Whether `db` is an embedded engine (SQLite/DuckDB/JSON — anything that is\n * not PostgreSQL). Handles without a URL are treated as embedded: serializing\n * them is at worst a throughput cost, while not serializing an embedded\n * handle reintroduces the livelock.\n */\nexport function isEmbeddedDatabase(db: QueueableDatabase): boolean {\n return !/^postgres(?:ql)?:/iu.test(db?.url ?? '');\n}\n\n/**\n * Whether revision compare-and-swap needs the process-local read/upsert path.\n *\n * DuckDB/JSON cannot express the timestamp predicate through the generic\n * update API, and local SQLite has only the process's writers in supported\n * deployments. Remote LibSQL/Turso is different: other processes may write\n * the same database, so it must use one conditional UPDATE at the server.\n */\nexport function usesEmbeddedRevisionFallback(db: QueueableDatabase): boolean {\n const url = db?.url ?? '';\n return isEmbeddedDatabase(db) && !/^(?:https?|libsql):\\/\\//iu.test(url);\n}\n\nfunction queueKey(db: QueueableDatabase): string | object {\n return typeof db?.url === 'string' && db.url.length > 0 ? db.url : db;\n}\n\n/**\n * Run `operation` after every previously queued write on the same database\n * has settled. When `serialize` is false the operation runs immediately.\n */\nexport async function withEmbeddedWriteQueue<T>(\n db: QueueableDatabase,\n serialize: boolean,\n operation: () => Promise<T>,\n): Promise<T> {\n if (!serialize) return operation();\n\n const key = queueKey(db);\n const active = activeQueueKeys.getStore();\n if (active?.has(key)) return operation();\n const previous =\n (typeof key === 'string' ? urlQueues.get(key) : handleQueues.get(key)) ??\n Promise.resolve();\n const run = () =>\n activeQueueKeys.run(new Set([...(active ?? []), key]), operation);\n const next = previous.then(run, run);\n // The stored tail must never reject, or one failed write would poison the\n // queue for every later writer.\n const tail = next.catch(() => undefined);\n if (typeof key === 'string') {\n urlQueues.set(key, tail);\n void tail.finally(() => {\n if (urlQueues.get(key) === tail) urlQueues.delete(key);\n });\n } else {\n handleQueues.set(key, tail);\n }\n return next;\n}\n\n/**\n * Serialize a complete embedded root transaction with ordinary model writes.\n * The transaction handle is registered as a reentrant alias so saves and\n * change-feed appends inside the callback do not queue behind their own root\n * transaction.\n */\nexport async function withEmbeddedWriteTransaction<T>(\n db: DatabaseInterface,\n serialize: boolean,\n operation: (transaction: DatabaseInterface) => Promise<T>,\n): Promise<T> {\n const transaction = db.transaction?.bind(db);\n if (!transaction) {\n throw new Error('Database transaction support is required');\n }\n return withEmbeddedWriteQueue(db, serialize, () =>\n transaction((bound) => {\n if (!serialize) return operation(bound);\n const active = activeQueueKeys.getStore();\n return activeQueueKeys.run(\n new Set([...(active ?? []), queueKey(bound)]),\n () => operation(bound),\n );\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,4BAAY,IAAI,IAA8B;AACpD,IAAM,+BAAe,IAAI,QAAkC;AAC3D,IAAM,kBAAkB,IAAI,kBAAgD;;;;;;;AAY5E,SAAgB,mBAAmB,IAAgC;CACjE,OAAO,CAAC,sBAAsB,KAAK,IAAI,OAAO,EAAE;AAClD;;;;;;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AAI,SAAS,KAAK,CAAC,CAAC,SACtC,UAAU,KAAK,CACvB;CACF,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"embedded-write-queue.js","names":[],"sources":["../src/embedded-write-queue.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\n/**\n * In-process write serialization for embedded database engines (#2360).\n *\n * File-backed SQLite (libsql) allows one writer at a time and the SDK opens a\n * NEW connection for every null-aware upsert attempt (`transaction(\"write\")`),\n * with no busy timeout on either connection. Any other write on the root\n * connection while such a transaction is open — most commonly the change-feed\n * append that follows every model save — collides as `SQLITE_BUSY`, and under\n * sustained concurrency (a `Promise.all` of creates) the two sides livelock\n * through every retry tier. Before the tenant-led conflict target (#2360) the\n * null-aware path was rare (custom conflict keys with NULL values, #1246);\n * with `tenant_id` leading every tenant-scoped default key, EVERY NULL-tenant\n * (global) create takes it, so the collision became the steady state.\n *\n * The queue makes the process a single writer per embedded database for:\n *\n * - a `save()` whose upsert conflict values contain NULL (the only shape the\n * SDK routes through a second-connection transaction), and\n * - the change-feed append (a root-connection write that follows every save).\n * - every model save and delete, so the embedded revision-CAS compare/upsert\n * fallback cannot race an ordinary save, natural-key create, or delete.\n * - a complete root `SmrtObject.withTransaction()` callback, with writes on\n * its bound handle re-entering the same hold instead of self-deadlocking.\n *\n * Ordinary save/delete holds contain database calls only — never an\n * interceptor or hook. Explicit transaction callbacks are caller-controlled,\n * so their bound model writes re-enter the existing hold. PostgreSQL is never\n * serialized here:\n * its null-aware upsert already arbitrates through advisory locks\n * server-side, and cross-process writers exist that an in-process queue could\n * not order anyway (which is also why this queue is a mitigation for embedded\n * engines' in-process writers, not a cross-process guarantee — embedded\n * engines have no cross-process writers in supported deployments).\n */\n\n/** Queue tail per database identity (URL string, or the handle itself). */\nconst urlQueues = new Map<string, Promise<unknown>>();\nconst handleQueues = new WeakMap<object, Promise<unknown>>();\nconst activeQueueKeys = new AsyncLocalStorage<ReadonlySet<string | object>>();\n\ninterface QueueableDatabase {\n url?: string;\n}\n\n/**\n * Whether `db` is an embedded engine (SQLite/DuckDB/JSON — anything that is\n * not PostgreSQL). Handles without a URL are treated as embedded: serializing\n * them is at worst a throughput cost, while not serializing an embedded\n * handle reintroduces the livelock.\n */\nexport function isEmbeddedDatabase(db: QueueableDatabase): boolean {\n return !isPostgresDatabase(db);\n}\n\n/**\n * Whether `db` is a PostgreSQL handle.\n *\n * The revision compare-and-swap predicate is dialect-specific (#2620): only\n * PostgreSQL needs the millisecond-truncating, timezone-tolerant guard, and\n * only PostgreSQL can evaluate `date_trunc`.\n */\nexport function isPostgresDatabase(db: QueueableDatabase): boolean {\n return /^postgres(?:ql)?:/iu.test(db?.url ?? '');\n}\n\n/**\n * Whether revision compare-and-swap needs the process-local read/upsert path.\n *\n * DuckDB/JSON cannot express the timestamp predicate through the generic\n * update API, and local SQLite has only the process's writers in supported\n * deployments. Remote LibSQL/Turso is different: other processes may write\n * the same database, so it must use one conditional UPDATE at the server.\n */\nexport function usesEmbeddedRevisionFallback(db: QueueableDatabase): boolean {\n const url = db?.url ?? '';\n return isEmbeddedDatabase(db) && !/^(?:https?|libsql):\\/\\//iu.test(url);\n}\n\nfunction queueKey(db: QueueableDatabase): string | object {\n return typeof db?.url === 'string' && db.url.length > 0 ? db.url : db;\n}\n\n/**\n * Run `operation` after every previously queued write on the same database\n * has settled. When `serialize` is false the operation runs immediately.\n */\nexport async function withEmbeddedWriteQueue<T>(\n db: QueueableDatabase,\n serialize: boolean,\n operation: () => Promise<T>,\n): Promise<T> {\n if (!serialize) return operation();\n\n const key = queueKey(db);\n const active = activeQueueKeys.getStore();\n if (active?.has(key)) return operation();\n const previous =\n (typeof key === 'string' ? urlQueues.get(key) : handleQueues.get(key)) ??\n Promise.resolve();\n const run = () =>\n activeQueueKeys.run(new Set([...(active ?? []), key]), operation);\n const next = previous.then(run, run);\n // The stored tail must never reject, or one failed write would poison the\n // queue for every later writer.\n const tail = next.catch(() => undefined);\n if (typeof key === 'string') {\n urlQueues.set(key, tail);\n void tail.finally(() => {\n if (urlQueues.get(key) === tail) urlQueues.delete(key);\n });\n } else {\n handleQueues.set(key, tail);\n }\n return next;\n}\n\n/**\n * Serialize a complete embedded root transaction with ordinary model writes.\n * The transaction handle is registered as a reentrant alias so saves and\n * change-feed appends inside the callback do not queue behind their own root\n * transaction.\n */\nexport async function withEmbeddedWriteTransaction<T>(\n db: DatabaseInterface,\n serialize: boolean,\n operation: (transaction: DatabaseInterface) => Promise<T>,\n): Promise<T> {\n const transaction = db.transaction?.bind(db);\n if (!transaction) {\n throw new Error('Database transaction support is required');\n }\n return withEmbeddedWriteQueue(db, serialize, () =>\n transaction((bound) => {\n if (!serialize) return operation(bound);\n const active = activeQueueKeys.getStore();\n return activeQueueKeys.run(\n new Set([...(active ?? []), queueKey(bound)]),\n () => operation(bound),\n );\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,4BAAY,IAAI,IAA8B;AACpD,IAAM,+BAAe,IAAI,QAAkC;AAC3D,IAAM,kBAAkB,IAAI,kBAAgD;;;;;;;AAY5E,SAAgB,mBAAmB,IAAgC;CACjE,OAAO,CAAC,mBAAmB,EAAE;AAC/B;;;;;;;;AASA,SAAgB,mBAAmB,IAAgC;CACjE,OAAO,sBAAsB,KAAK,IAAI,OAAO,EAAE;AACjD;;;;;;;;;AAUA,SAAgB,6BAA6B,IAAgC;CAC3E,MAAM,MAAM,IAAI,OAAO;CACvB,OAAO,mBAAmB,EAAE,KAAK,CAAC,4BAA4B,KAAK,GAAG;AACxE;AAEA,SAAS,SAAS,IAAwC;CACxD,OAAO,OAAO,IAAI,QAAQ,YAAY,GAAG,IAAI,SAAS,IAAI,GAAG,MAAM;AACrE;;;;;AAMA,eAAsB,uBACpB,IACA,WACA,WACY;CACZ,IAAI,CAAC,WAAW,OAAO,UAAU;CAEjC,MAAM,MAAM,SAAS,EAAE;CACvB,MAAM,SAAS,gBAAgB,SAAS;CACxC,IAAI,QAAQ,IAAI,GAAG,GAAG,OAAO,UAAU;CACvC,MAAM,YACH,OAAO,QAAQ,WAAW,UAAU,IAAI,GAAG,IAAI,aAAa,IAAI,GAAG,MACpE,QAAQ,QAAQ;CAClB,MAAM,YACJ,gBAAgB,oBAAI,IAAI,IAAI,CAAC,GAAI,UAAU,CAAC,GAAI,GAAG,CAAC,GAAG,SAAS;CAClE,MAAM,OAAO,SAAS,KAAK,KAAK,GAAG;CAGnC,MAAM,OAAO,KAAK,YAAY,KAAA,CAAS;CACvC,IAAI,OAAO,QAAQ,UAAU;EAC3B,UAAU,IAAI,KAAK,IAAI;EACvB,KAAU,cAAc;GACtB,IAAI,UAAU,IAAI,GAAG,MAAM,MAAM,UAAU,OAAO,GAAG;EACvD,CAAC;CACH,OACE,aAAa,IAAI,KAAK,IAAI;CAE5B,OAAO;AACT;;;;;;;AAQA,eAAsB,6BACpB,IACA,WACA,WACY;CACZ,MAAM,cAAc,GAAG,aAAa,KAAK,EAAE;CAC3C,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,0CAA0C;CAE5D,OAAO,uBAAuB,IAAI,iBAChC,aAAa,UAAU;EACrB,IAAI,CAAC,WAAW,OAAO,UAAU,KAAK;EACtC,MAAM,SAAS,gBAAgB,SAAS;EACxC,OAAO,gBAAgB,oBACrB,IAAI,IAAI,CAAC,GAAI,UAAU,CAAC,GAAI,SAAS,KAAK,CAAC,CAAC,SACtC,UAAU,KAAK,CACvB;CACF,CAAC,CACH;AACF"}
@@ -8,6 +8,7 @@ export { buildCustomActionInputSchema, buildCustomActionInvocationArgs, type Cus
8
8
  export { buildChangeEventStream, type ChangeEventStreamOptions, changeEventSubscribersAtCapacity, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, eventStreamCapacityExceededResponse, normalizeEventsMaxSubscribers, signalVisibleToTenant, tryReserveChangeEventSubscriberSlot, } from './events-route';
9
9
  export type { MCPConfig, MCPContext, MCPRequest, MCPResponse, MCPTool, MCPToolListCacheHint, MCPToolListCacheOptions, } from './mcp';
10
10
  export { MCP_STABLE_CATALOG_TTL_MS, MCPGenerator, resolveMCPToolListCacheHint, sortMCPTools, } from './mcp';
11
+ export { handlePlaybookPreflightRoute, isApiActionEnabledForObject, isRestActionRoutable, isRestRoutePublic, PLAYBOOK_PREFLIGHT_CAPABILITY, PLAYBOOK_PREFLIGHT_ROUTE_SEGMENT, type PlaybookPreflightProvider, type PlaybookPreflightRouteOptions, type PlaybookPreflightRouteRequest, resolveRegisteredObjectName, restFieldReadPermissions, restMethodForApiAction, } from './preflight-route';
11
12
  export type { APIConfig, APIContext, RestServerConfig } from './rest';
12
13
  export { APIGenerator, computeRuntimeWebManifestHash, createRestServer, startRestServer, } from './rest';
13
14
  export type { OpenAPIConfig } from './swagger';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/generators/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAG9D,OAAO,EACL,2BAA2B,EAC3B,eAAe,EACf,uBAAuB,EACvB,uBAAuB,EACvB,2BAA2B,EAC3B,oBAAoB,EACpB,0BAA0B,EAC1B,KAAK,uBAAuB,EAC5B,uBAAuB,EACvB,8BAA8B,EAC9B,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,4BAA4B,EAC5B,+BAA+B,EAC/B,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,8BAA8B,EAC9B,4BAA4B,EAC5B,KAAK,kCAAkC,EACvC,KAAK,4BAA4B,EACjC,2BAA2B,EAC3B,qCAAqC,EACr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