@happyvertical/smrt-core 0.54.2 → 0.54.4

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 (207) hide show
  1. package/AGENTS.md +6 -1
  2. package/README.md +8 -0
  3. package/agents/change-feed.md +7 -12
  4. package/agents/generators.md +13 -0
  5. package/agents/object-runtime.md +8 -0
  6. package/agents/schema-paths.md +14 -0
  7. package/dist/__typechecks__/collection-read-plan.d.ts +2 -2
  8. package/dist/__typechecks__/collection-read-plan.d.ts.map +1 -1
  9. package/dist/audit-context.d.ts +4 -0
  10. package/dist/audit-context.d.ts.map +1 -0
  11. package/dist/audit-context.js +16 -0
  12. package/dist/audit-context.js.map +1 -0
  13. package/dist/audit.d.ts +34 -0
  14. package/dist/audit.d.ts.map +1 -0
  15. package/dist/audit.js +63 -0
  16. package/dist/audit.js.map +1 -0
  17. package/dist/browser.d.ts +19 -18
  18. package/dist/browser.d.ts.map +1 -1
  19. package/dist/browser.js +4 -3
  20. package/dist/cascade.d.ts +1 -1
  21. package/dist/cascade.d.ts.map +1 -1
  22. package/dist/cascade.js +10 -7
  23. package/dist/cascade.js.map +1 -1
  24. package/dist/change-feed.js +1 -1
  25. package/dist/child-accessors.d.ts +1 -1
  26. package/dist/child-accessors.d.ts.map +1 -1
  27. package/dist/collection-read-plan.d.ts +3 -3
  28. package/dist/collection-read-plan.d.ts.map +1 -1
  29. package/dist/collection.d.ts +13 -6
  30. package/dist/collection.d.ts.map +1 -1
  31. package/dist/collection.js +59 -4
  32. package/dist/collection.js.map +1 -1
  33. package/dist/data-query.d.ts +1 -1
  34. package/dist/data-query.d.ts.map +1 -1
  35. package/dist/embedded-write-queue.d.ts +2 -0
  36. package/dist/embedded-write-queue.d.ts.map +1 -1
  37. package/dist/embedded-write-queue.js +12 -5
  38. package/dist/embedded-write-queue.js.map +1 -1
  39. package/dist/embeddings/index.d.ts +5 -5
  40. package/dist/embeddings/index.d.ts.map +1 -1
  41. package/dist/embeddings/provider.d.ts +1 -1
  42. package/dist/embeddings/provider.d.ts.map +1 -1
  43. package/dist/embeddings/storage.d.ts +1 -1
  44. package/dist/embeddings/storage.d.ts.map +1 -1
  45. package/dist/generated-collection-access.d.ts +3 -3
  46. package/dist/generated-collection-access.d.ts.map +1 -1
  47. package/dist/generators/changes-route.js +1 -1
  48. package/dist/generators/index.d.ts +12 -12
  49. package/dist/generators/index.d.ts.map +1 -1
  50. package/dist/generators/mcp-runtime-template.d.ts +2 -0
  51. package/dist/generators/mcp-runtime-template.d.ts.map +1 -1
  52. package/dist/generators/mcp-runtime-template.js +18 -16
  53. package/dist/generators/mcp-runtime-template.js.map +1 -1
  54. package/dist/generators/mcp-tool-name.d.ts +6 -0
  55. package/dist/generators/mcp-tool-name.d.ts.map +1 -1
  56. package/dist/generators/mcp-tool-name.js.map +1 -1
  57. package/dist/generators/mcp.d.ts +34 -1
  58. package/dist/generators/mcp.d.ts.map +1 -1
  59. package/dist/generators/mcp.js +148 -110
  60. package/dist/generators/mcp.js.map +1 -1
  61. package/dist/generators/rest.d.ts +4 -4
  62. package/dist/generators/rest.d.ts.map +1 -1
  63. package/dist/generators/rest.js +16 -7
  64. package/dist/generators/rest.js.map +1 -1
  65. package/dist/hierarchical.d.ts +2 -2
  66. package/dist/hierarchical.d.ts.map +1 -1
  67. package/dist/index.d.ts +68 -66
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +9 -7
  70. package/dist/junction.d.ts +31 -12
  71. package/dist/junction.d.ts.map +1 -1
  72. package/dist/junction.js +31 -12
  73. package/dist/junction.js.map +1 -1
  74. package/dist/knowledge.js +1 -1
  75. package/dist/knowledge.js.map +1 -1
  76. package/dist/manifest/index.d.ts +7 -7
  77. package/dist/manifest/index.d.ts.map +1 -1
  78. package/dist/manifest/manifest-loader.d.ts.map +1 -1
  79. package/dist/manifest/manifest-loader.js +1 -1
  80. package/dist/manifest/manifest-loader.js.map +1 -1
  81. package/dist/manifest/static-manifest.d.ts.map +1 -1
  82. package/dist/manifest/static-manifest.js +106 -9
  83. package/dist/manifest/static-manifest.js.map +1 -1
  84. package/dist/manifest/store.d.ts +8 -0
  85. package/dist/manifest/store.d.ts.map +1 -1
  86. package/dist/manifest/store.js +12 -2
  87. package/dist/manifest/store.js.map +1 -1
  88. package/dist/manifest.json +119 -9
  89. package/dist/migrations/differ.d.ts +3 -3
  90. package/dist/migrations/differ.d.ts.map +1 -1
  91. package/dist/migrations/differ.js +8 -4
  92. package/dist/migrations/differ.js.map +1 -1
  93. package/dist/object.d.ts +8 -7
  94. package/dist/object.d.ts.map +1 -1
  95. package/dist/object.js +19 -7
  96. package/dist/object.js.map +1 -1
  97. package/dist/polymorphic-association.d.ts +1 -1
  98. package/dist/polymorphic-association.d.ts.map +1 -1
  99. package/dist/prebuild/index.d.ts +1 -1
  100. package/dist/prebuild/index.d.ts.map +1 -1
  101. package/dist/query-bounds.d.ts +1 -1
  102. package/dist/query-bounds.d.ts.map +1 -1
  103. package/dist/registry/cache-config.d.ts +1 -1
  104. package/dist/registry/cache-config.d.ts.map +1 -1
  105. package/dist/registry/class-registration.d.ts +1 -1
  106. package/dist/registry/class-registration.d.ts.map +1 -1
  107. package/dist/registry/class-registration.js +75 -10
  108. package/dist/registry/class-registration.js.map +1 -1
  109. package/dist/registry/collection-resolution.d.ts +3 -3
  110. package/dist/registry/collection-resolution.d.ts.map +1 -1
  111. package/dist/registry/collection-resolution.js +2 -1
  112. package/dist/registry/collection-resolution.js.map +1 -1
  113. package/dist/registry/collision-policy.d.ts +8 -0
  114. package/dist/registry/collision-policy.d.ts.map +1 -1
  115. package/dist/registry/collision-policy.js +2 -2
  116. package/dist/registry/collision-policy.js.map +1 -1
  117. package/dist/registry/embedding-manager.d.ts +1 -1
  118. package/dist/registry/embedding-manager.d.ts.map +1 -1
  119. package/dist/registry/framework-base-classes.d.ts.map +1 -1
  120. package/dist/registry/framework-base-classes.js +2 -1
  121. package/dist/registry/framework-base-classes.js.map +1 -1
  122. package/dist/registry/index.d.ts +6 -6
  123. package/dist/registry/index.d.ts.map +1 -1
  124. package/dist/registry/inheritance-resolver.d.ts +2 -2
  125. package/dist/registry/inheritance-resolver.d.ts.map +1 -1
  126. package/dist/registry/manifest-field-merge.d.ts +1 -1
  127. package/dist/registry/manifest-field-merge.d.ts.map +1 -1
  128. package/dist/registry/name-resolver.d.ts +1 -1
  129. package/dist/registry/name-resolver.d.ts.map +1 -1
  130. package/dist/registry/qualified-name-aliases.d.ts +1 -1
  131. package/dist/registry/qualified-name-aliases.d.ts.map +1 -1
  132. package/dist/registry/relationship-graph.d.ts +1 -1
  133. package/dist/registry/relationship-graph.d.ts.map +1 -1
  134. package/dist/registry/runtime-overrides.d.ts +1 -1
  135. package/dist/registry/runtime-overrides.d.ts.map +1 -1
  136. package/dist/registry/schema-builder.d.ts.map +1 -1
  137. package/dist/registry/schema-builder.js +33 -4
  138. package/dist/registry/schema-builder.js.map +1 -1
  139. package/dist/registry/shared-state.d.ts +9 -3
  140. package/dist/registry/shared-state.d.ts.map +1 -1
  141. package/dist/registry/shared-state.js +12 -1
  142. package/dist/registry/shared-state.js.map +1 -1
  143. package/dist/registry/types.d.ts +11 -5
  144. package/dist/registry/types.d.ts.map +1 -1
  145. package/dist/registry/validator.d.ts +1 -1
  146. package/dist/registry/validator.d.ts.map +1 -1
  147. package/dist/registry.d.ts +19 -13
  148. package/dist/registry.d.ts.map +1 -1
  149. package/dist/registry.js +25 -3
  150. package/dist/registry.js.map +1 -1
  151. package/dist/relationship-loader.d.ts +1 -1
  152. package/dist/relationship-loader.d.ts.map +1 -1
  153. package/dist/runtime/client.d.ts +1 -1
  154. package/dist/runtime/client.d.ts.map +1 -1
  155. package/dist/runtime/index.d.ts +5 -5
  156. package/dist/runtime/index.d.ts.map +1 -1
  157. package/dist/runtime/server.d.ts +1 -1
  158. package/dist/runtime/server.d.ts.map +1 -1
  159. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  160. package/dist/scanner/manifest-generator.js +5 -1
  161. package/dist/scanner/manifest-generator.js.map +1 -1
  162. package/dist/scanner/types.d.ts +8 -0
  163. package/dist/scanner/types.d.ts.map +1 -1
  164. package/dist/scanner/types.js.map +1 -1
  165. package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
  166. package/dist/schema/ddl/duckdb-strategy.js +1 -0
  167. package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
  168. package/dist/schema/ddl/null-equal-index.d.ts.map +1 -1
  169. package/dist/schema/ddl/null-equal-index.js +4 -2
  170. package/dist/schema/ddl/null-equal-index.js.map +1 -1
  171. package/dist/schema/ddl/types.d.ts +1 -1
  172. package/dist/schema/ddl/types.d.ts.map +1 -1
  173. package/dist/schema/generator.d.ts +3 -0
  174. package/dist/schema/generator.d.ts.map +1 -1
  175. package/dist/schema/generator.js +38 -0
  176. package/dist/schema/generator.js.map +1 -1
  177. package/dist/smrt-knowledge.json +74 -20
  178. package/dist/sync/apply.d.ts +2 -0
  179. package/dist/sync/apply.d.ts.map +1 -1
  180. package/dist/sync/apply.js +7 -3
  181. package/dist/sync/apply.js.map +1 -1
  182. package/dist/utils/scanner-module.d.ts +9 -0
  183. package/dist/utils/scanner-module.d.ts.map +1 -1
  184. package/dist/utils.d.ts +1 -1
  185. package/dist/utils.d.ts.map +1 -1
  186. package/dist/vite-plugin/changes-route.d.ts +1 -1
  187. package/dist/vite-plugin/changes-route.d.ts.map +1 -1
  188. package/dist/vite-plugin/events-route.d.ts +1 -1
  189. package/dist/vite-plugin/events-route.d.ts.map +1 -1
  190. package/dist/vite-plugin/index.d.ts +14 -0
  191. package/dist/vite-plugin/index.d.ts.map +1 -1
  192. package/dist/vite-plugin/index.js +58 -18
  193. package/dist/vite-plugin/index.js.map +1 -1
  194. package/dist/vite-plugin/package-stamp.d.ts +41 -0
  195. package/dist/vite-plugin/package-stamp.d.ts.map +1 -0
  196. package/dist/vite-plugin/package-stamp.js +33 -0
  197. package/dist/vite-plugin/package-stamp.js.map +1 -0
  198. package/dist/vite-plugin/sveltekit-generator.d.ts +1 -1
  199. package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
  200. package/dist/vite-plugin/sveltekit-generator.js +5 -3
  201. package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
  202. package/dist/vite-plugin/sync-apply-route.d.ts +1 -1
  203. package/dist/vite-plugin/sync-apply-route.d.ts.map +1 -1
  204. package/dist/vite-plugin/sync-apply-route.js +10 -0
  205. package/dist/vite-plugin/sync-apply-route.js.map +1 -1
  206. package/dist/vite-plugin.js +2 -2
  207. package/package.json +10 -10
@@ -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 * - 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 // Keep canonical self/ancestor identities from the registry. Never resolve\n // their display aliases again: a shared simple name can select another\n // package. Legacy relationship views without canonical metadata still use\n // the simple aliases already included by getSelfReferableNames().\n const targetNames = new Set(registry.getSelfReferableNames(className));\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n const visitedBuckets = new Set<unknown>();\n\n const relationshipMap = registry.getRelationshipMap();\n for (const [sourceClass, relationships] of relationshipMap) {\n const simpleSource = relationships[0]?.sourceClass;\n if (\n simpleSource &&\n sourceClass !== simpleSource &&\n relationshipMap.get(simpleSource) === relationships\n ) {\n continue;\n }\n if (visitedBuckets.has(relationships)) continue;\n visitedBuckets.add(relationships);\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 const target =\n relationship.targetQualifiedClass === undefined\n ? relationship.targetClass\n : relationship.targetQualifiedClass;\n if (target === null || !targetNames.has(target)) 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 columnName: column,\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 // A class's deprecated qualified names (#3338) still identify it in rows\n // written before it moved package, so deleting it removes those too.\n const metaTypes: string[] = [];\n const registered = registry.getClass(className);\n const qualified = registered?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n for (const alias of registered?.config?.previousQualifiedNames ?? []) {\n if (typeof alias === 'string' && !metaTypes.includes(alias)) {\n metaTypes.push(alias);\n }\n }\n const simple = registered?.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 // A caught missing-table DELETE still aborts PostgreSQL's transaction.\n // Optional/abstract association tables must be checked before mutation.\n if (!(await ctx.db.tableExists(association.tableName))) continue;\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;CAKb,MAAM,cAAc,IAAI,IAAI,SAAS,sBAAsB,SAAS,CAAC;CAErE,MAAM,aAAiC,CAAC;CACxC,MAAM,cAA6C,CAAC;CACpD,MAAM,iCAAiB,IAAI,IAAa;CAExC,MAAM,kBAAkB,SAAS,mBAAmB;CACpD,KAAK,MAAM,CAAC,aAAa,kBAAkB,iBAAiB;EAC1D,MAAM,eAAe,cAAc,EAAE,EAAE;EACvC,IACE,gBACA,gBAAgB,gBAChB,gBAAgB,IAAI,YAAY,MAAM,eAEtC;EAEF,IAAI,eAAe,IAAI,aAAa,GAAG;EACvC,eAAe,IAAI,aAAa;EAChC,MAAM,SAAS,SAAS,UAAU,WAAW;EAE7C,IAAI,8BAA8B,MAAM,GAAG;GACzC,MAAM,YAAY,SAAS,aAAa,WAAW;GACnD,IAAI,WACF,YAAY,KAAK;IAAE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ACJ,OACA,KACA,qBAAqB,UAAU,OAAO,SAAS,CACjD;GACA,MAAM,WAAW,KAAK;GACtB,OAAO;IAAE,gCAAgB,IAAI,IAAI;IAAG,sCAAsB,IAAI,IAAI;GAAE;EACtE;EACA,MAAM,cAAe,GAA0B;EAC/C,IAAI,OAAO,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"}
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 { buildWhere, type DatabaseInterface } from '@happyvertical/sql';\nimport { classifyDatabaseError } from './db-errors.js';\nimport {\n isEmbeddedDatabase,\n isFrameworkTransactionHandle,\n isPostgresDatabase,\n withEmbeddedWriteTransaction,\n} from './embedded-write-queue.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 // Keep canonical self/ancestor identities from the registry. Never resolve\n // their display aliases again: a shared simple name can select another\n // package. Legacy relationship views without canonical metadata still use\n // the simple aliases already included by getSelfReferableNames().\n const targetNames = new Set(registry.getSelfReferableNames(className));\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n const visitedBuckets = new Set<unknown>();\n\n const relationshipMap = registry.getRelationshipMap();\n for (const [sourceClass, relationships] of relationshipMap) {\n const simpleSource = relationships[0]?.sourceClass;\n if (\n simpleSource &&\n sourceClass !== simpleSource &&\n relationshipMap.get(simpleSource) === relationships\n ) {\n continue;\n }\n if (visitedBuckets.has(relationships)) continue;\n visitedBuckets.add(relationships);\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 const target =\n relationship.targetQualifiedClass === undefined\n ? relationship.targetClass\n : relationship.targetQualifiedClass;\n if (target === null || !targetNames.has(target)) 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 columnName: column,\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 // A class's deprecated qualified names (#3338) still identify it in rows\n // written before it moved package, so deleting it removes those too.\n const metaTypes: string[] = [];\n const registered = registry.getClass(className);\n const qualified = registered?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n for (const alias of registered?.config?.previousQualifiedNames ?? []) {\n if (typeof alias === 'string' && !metaTypes.includes(alias)) {\n metaTypes.push(alias);\n }\n }\n const simple = registered?.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 dialect = isPostgresDatabase(db) ? 'postgres' : 'sqlite';\n const where = buildWhere(idPredicate(column, batch), 1, dialect);\n const table = `\"${tableName.replaceAll('\"', '\"\"')}\"`;\n const sql = `SELECT CAST(\"id\" AS VARCHAR) AS \"id\" FROM ${table} ${where.sql}`;\n const rows = await tolerateMissingTable(\n () => db.query(sql, ...where.values).then((result) => result.rows),\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 // A caught missing-table DELETE still aborts PostgreSQL's transaction.\n // Optional/abstract association tables must be checked before mutation.\n if (!(await ctx.db.tableExists(association.tableName))) continue;\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 withEmbeddedWriteTransaction(\n db,\n isEmbeddedDatabase(db),\n runWithoutReferences,\n isFrameworkTransactionHandle(db),\n );\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 withEmbeddedWriteTransaction(\n db,\n isEmbeddedDatabase(db),\n run,\n isFrameworkTransactionHandle(db),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,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;CAKb,MAAM,cAAc,IAAI,IAAI,SAAS,sBAAsB,SAAS,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,GACrB,KACA,6BAA6B,EAAE,CACjC;AACF"}
@@ -1,9 +1,9 @@
1
+ import { isEmbeddedDatabase, withEmbeddedWriteQueue } from "./embedded-write-queue.js";
1
2
  import { getChangeFeedSensitiveTables, isChangeFeedSensitiveTable, isChangeFeedSensitiveWrite } from "./change-feed-sensitivity.js";
2
3
  import { resolveDbCacheKey } from "./collection-cache.js";
3
4
  import { toSafeInteger } from "./utils/safe-integer.js";
4
5
  import { publishChangeSignal } from "./change-signals.js";
5
6
  import { resolveDispatchTenantScope } from "./dispatch/tenant-resolver.js";
6
- import { isEmbeddedDatabase, withEmbeddedWriteQueue } from "./embedded-write-queue.js";
7
7
  import { GlobalInterceptors } from "./interceptors.js";
8
8
  import { detectEngine } from "./schema/ddl/index.js";
9
9
  import { CREATE_SMRT_CHANGES_TABLE, ENSURE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION, ENSURE_POSTGRES_CHANGE_FEED_SCHEMA, FRAMEWORK_OPERATIONAL_TABLES, POSTGRES_CHANGE_FEED_APPEND_BATCH_FUNCTION_IDENTITY, POSTGRES_CHANGE_FEED_APPEND_BATCH_FUNCTION_NAME, POSTGRES_CHANGE_FEED_APPEND_FUNCTION_IDENTITY, POSTGRES_CHANGE_FEED_APPEND_FUNCTION_NAME, POSTGRES_CHANGE_FEED_DRAIN_FUNCTION_IDENTITY, POSTGRES_CHANGE_FEED_DRAIN_FUNCTION_NAME, POSTGRES_CHANGE_FEED_HELPER_MARKER, POSTGRES_CHANGE_FEED_PENDING_TABLE, REPLACE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION, RETIRED_SYSTEM_TABLES } from "./system/schema.js";
@@ -36,7 +36,7 @@
36
36
  * `ObjectRegistry.getInverseRelationshipsForSelf`), so calling the accessor on
37
37
  * an STI subclass instance resolves a `@oneToMany` declared on its base.
38
38
  */
39
- import type { RelationshipMetadata } from './registry/types';
39
+ import type { RelationshipMetadata } from "./registry/types.js";
40
40
  /**
41
41
  * Compute the canonical child-accessor method name for a `@oneToMany` field.
42
42
  *
@@ -1 +1 @@
1
- {"version":3,"file":"child-accessors.d.ts","sourceRoot":"","sources":["../src/child-accessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAE7D;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,4BAA4B,CAC1C,IAAI,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,SAAS,EACzC,aAAa,EAAE,oBAAoB,EAAE,GAAG,SAAS,GAChD,IAAI,CAsCN"}
1
+ {"version":3,"file":"child-accessors.d.ts","sourceRoot":"","sources":["../src/child-accessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAkB,CAAC;AAE7D;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,4BAA4B,CAC1C,IAAI,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,SAAS,EACzC,aAAa,EAAE,oBAAoB,EAAE,GAAG,SAAS,GAChD,IAAI,CAsCN"}
@@ -1,6 +1,6 @@
1
- import type { SmrtClassOptions } from './class';
2
- import type { SmrtListOptions, SmrtSelectedRow, SmrtSelectField } from './collection';
3
- import type { SmrtObject } from './object';
1
+ import type { SmrtClassOptions } from "./class.js";
2
+ import type { SmrtListOptions, SmrtSelectedRow, SmrtSelectField } from "./collection.js";
3
+ import type { SmrtObject } from "./object.js";
4
4
  type DynamicSmrtObject = SmrtObject & Record<string, unknown>;
5
5
  type SmrtHydratedCollectionReadOptions<ModelType extends SmrtObject> = Omit<SmrtListOptions<ModelType>, 'select'> & {
6
6
  select?: undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"collection-read-plan.d.ts","sourceRoot":"","sources":["../src/collection-read-plan.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,KAAK,EAEV,eAAe,EACf,eAAe,EACf,eAAe,EAChB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAG3C,KAAK,iBAAiB,GAAG,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC9D,KAAK,iCAAiC,CAAC,SAAS,SAAS,UAAU,IAAI,IAAI,CACzE,eAAe,CAAC,SAAS,CAAC,EAC1B,QAAQ,CACT,GAAG;IACF,MAAM,CAAC,EAAE,SAAS,CAAC;CACpB,CAAC;AACF,KAAK,kCAAkC,CAAC,SAAS,SAAS,UAAU,IAAI,IAAI,CAC1E,eAAe,CAAC,SAAS,CAAC,EAC1B,QAAQ,GAAG,SAAS,CACrB,GAAG;IACF,MAAM,EAAE,SAAS,eAAe,CAAC,SAAS,CAAC,EAAE,CAAC;IAC9C,OAAO,CAAC,EAAE,KAAK,CAAC;CACjB,CAAC;AACF,KAAK,yBAAyB,CAAC,SAAS,SAAS,UAAU,IACvD,iCAAiC,CAAC,SAAS,CAAC,GAC5C,kCAAkC,CAAC,SAAS,CAAC,CAAC;AAClD,KAAK,sBAAsB,GAAG,yBAAyB,CAAC,iBAAiB,CAAC,CAAC;AAC3E,OAAO,CAAC,MAAM,2BAA2B,EAAE,OAAO,MAAM,CAAC;AAEzD,KAAK,kCAAkC,CACrC,SAAS,SAAS,UAAU,EAC5B,WAAW,SAAS,yBAAyB,CAAC,SAAS,CAAC,GAAG,SAAS,IAEpE,WAAW,SAAS,kCAAkC,CAAC,SAAS,CAAC,GAC7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AE,CAAC;CACnC,GACG,MAAM,SAAS,SAAS,eAAe,CACrC,gCAAgC,CAAC,KAAK,CAAC,CACxC,EAAE,GACD,eAAe,CAAC,gCAAgC,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,EAAE,GAClE,KAAK,GACP,gCAAgC,CAAC,KAAK,CAAC,EAAE,CAAC;AAE9C,gEAAgE;AAChE,MAAM,MAAM,4BAA4B,CAAC,IAAI,SAAS,sBAAsB,IAC1E;KACG,GAAG,IAAI,MAAM,IAAI,GAAG,iCAAiC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;CAClE,CAAC;AAEJ,MAAM,WAAW,gCAAgC;IAC/C;;;;OAIG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,mEAAmE;IACnE,iBAAiB,CAAC,EAAE,gBAAgB,CAAC;CACtC;AAwBD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,yBAAyB,CAC7C,KAAK,CAAC,IAAI,SAAS,sBAAsB,EAEzC,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,gCAAgC,GACxC,OAAO,CAAC,4BAA4B,CAAC,IAAI,CAAC,CAAC,CAsD7C"}
@@ -1,7 +1,8 @@
1
- import type { SmrtClassOptions } from './class';
2
- import { SmrtClass } from './class';
3
- import { type CollectionCacheConfig } from './collection-cache';
4
- import type { SmrtObject } from './object';
1
+ import { type AuditContext, type CollectionAuditOptions } from './audit.js';
2
+ import type { SmrtClassOptions } from "./class.js";
3
+ import { SmrtClass } from "./class.js";
4
+ import { type CollectionCacheConfig } from "./collection-cache.js";
5
+ import type { SmrtObject } from "./object.js";
5
6
  /** Maximum number of independent facet fields accepted by one call. */
6
7
  export declare const MAX_FACET_FIELDS = 20;
7
8
  /** Default number of distinct values returned for each facet field. */
@@ -227,6 +228,8 @@ interface CollectionFieldDefinition {
227
228
  * Configuration options for SmrtCollection
228
229
  */
229
230
  export interface SmrtCollectionOptions extends SmrtClassOptions {
231
+ /** Trusted actor and transaction-bound sink for models declaring audit: true. */
232
+ auditTrail?: CollectionAuditOptions;
230
233
  /**
231
234
  * Page size `list()` applies when the caller passes no `limit` (#2367).
232
235
  *
@@ -815,7 +818,11 @@ export declare class SmrtCollection<ModelType extends SmrtObject> extends SmrtCl
815
818
  *
816
819
  * @see {@link getOrUpsert} to avoid duplicates by finding-or-creating
817
820
  */
818
- create(options: SmrtCreateInput<ModelType>): Promise<ModelType>;
821
+ create(options: SmrtCreateInput<ModelType>, context?: Partial<AuditContext>): Promise<ModelType>;
822
+ /** Owning seam for generated CRUD that already validates fields and permissions. */
823
+ withAuditMutation<T>(instance: ModelType, action: 'created' | 'updated' | 'deleted', mutate: (bound: ModelType) => Promise<T>, context?: Partial<AuditContext>): Promise<T>;
824
+ /** Update registered mutable fields, with revision guards and optional audit. */
825
+ update(id: string, values: Partial<SmrtCreateInput<ModelType>>, context?: Partial<AuditContext>): Promise<ModelType | null>;
819
826
  /** @internal Test creation overrides inside the owning protected boundary. */
820
827
  static hasBaseCreateLifecycle<T extends SmrtObject>(collection: SmrtCollection<T>): boolean;
821
828
  /** Initialize using the same owning path as create(), without persistence. */
@@ -940,7 +947,7 @@ export declare class SmrtCollection<ModelType extends SmrtObject> extends SmrtCl
940
947
  * }
941
948
  * ```
942
949
  */
943
- delete(id: string): Promise<boolean>;
950
+ delete(id: string, context?: Partial<AuditContext>): Promise<boolean>;
944
951
  /**
945
952
  * Returns the number of records matching the given filter conditions.
946
953
  *
@@ -1 +1 @@
1
- {"version":3,"file":"collection.d.ts","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAEL,KAAK,qBAAqB,EAS3B,MAAM,oBAAoB,CAAC;AAiB5B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AA8H3C,uEAAuE;AACvE,eAAO,MAAM,gBAAgB,K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IACU,WAAW,CACtB,MAAM,EAAE,SAAS,GAAG,MAAM,EAC1B,OAAO,GAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,OAAO,CAAC;KAClB,GACL,OAAO,CAAC,KAAK,CAAC,SAAS,GAAG;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAoEtD;;;;;;;;;;;;;;;;;;;;;OAqBG;IACU,sBAAsB,CACjC,SAAS,EAAE,MAAM,EAAE,EACnB,OAAO,GAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,KAAK,CAAC,EAAE,eAAe,CAAC,SAAS,CAAC,CAAC;KAC/B,GACL,OAAO,CAAC,KAAK,CAAC,SAAS,GAAG;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAqItD;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACU,yBAAyB,CACpC,OAAO,GAAE;QACP,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE;YAAE,SAAS,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,KAAK,IAAI,CAAC;KAClE,GACL,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;CA4DnD"}
@@ -13,6 +13,7 @@ import { resolveOneToManyInverse, resolveRelationshipTargetName } from "./relati
13
13
  import { verifyPersistenceTable } from "./schema/table-verifier.js";
14
14
  import { fieldsFromClass, formatDataJs, toCamelCase } from "./utils.js";
15
15
  import { ObjectRegistry } from "./registry.js";
16
+ import { auditSnapshot, isAudited, requireAuditOptions, writeAudit } from "./audit.js";
16
17
  import { createLogger } from "@happyvertical/logger";
17
18
  import { buildWhere } from "@happyvertical/sql";
18
19
  //#region src/collection.ts
@@ -888,7 +889,7 @@ var SmrtCollection = class SmrtCollection extends SmrtClass {
888
889
  * ```
889
890
  */
890
891
  static async create(options = {}) {
891
- const { _className, _deferRuntimeInitialization, _reuseInitializedDb, db, defaultListLimit, persistence, ai, decisions, fs, logging, maxListLimit, metrics, pubsub, sanitization, signals } = options;
892
+ const { _className, _deferRuntimeInitialization, _reuseInitializedDb, db, defaultListLimit, auditTrail, persistence, ai, decisions, fs, logging, maxListLimit, metrics, pubsub, sanitization, signals } = options;
892
893
  const collectionOptions = {
893
894
  _className,
894
895
  _deferRuntimeInitialization,
@@ -898,6 +899,7 @@ var SmrtCollection = class SmrtCollection extends SmrtClass {
898
899
  ai,
899
900
  decisions,
900
901
  defaultListLimit,
902
+ auditTrail,
901
903
  fs,
902
904
  logging,
903
905
  maxListLimit,
@@ -1384,11 +1386,55 @@ var SmrtCollection = class SmrtCollection extends SmrtClass {
1384
1386
  *
1385
1387
  * @see {@link getOrUpsert} to avoid duplicates by finding-or-creating
1386
1388
  */
1387
- async create(options) {
1389
+ async create(options, context) {
1388
1390
  const instance = await this.createUnsaved(options);
1391
+ if (isAudited(instance)) {
1392
+ instance.requireInsertOnSave();
1393
+ await this.withAuditMutation(instance, "created", async (bound) => {
1394
+ await bound.save();
1395
+ }, context);
1396
+ return instance;
1397
+ }
1389
1398
  await instance.save();
1390
1399
  return instance;
1391
1400
  }
1401
+ /** Owning seam for generated CRUD that already validates fields and permissions. */
1402
+ async withAuditMutation(instance, action, mutate, context) {
1403
+ if (!isAudited(instance)) return await mutate(instance);
1404
+ const audit = requireAuditOptions(this.options.auditTrail, context);
1405
+ const adapter = instance.db;
1406
+ if (typeof adapter.inferSchemaFromJSON === "function" || typeof adapter.getTableLoadErrors === "function") throw new Error("Automatic auditing requires transactional persistence; JSON export adapters are unsupported");
1407
+ return await instance.withTransaction(async (bound) => {
1408
+ const before = action === "created" ? {} : auditSnapshot(bound);
1409
+ const result = await mutate(bound);
1410
+ await writeAudit(bound, action, before, action === "deleted" ? {} : auditSnapshot(bound), audit);
1411
+ return result;
1412
+ });
1413
+ }
1414
+ /** Update registered mutable fields, with revision guards and optional audit. */
1415
+ async update(id, values, context) {
1416
+ const instance = await this.get(id, { cache: false });
1417
+ if (!instance) return null;
1418
+ const registered = ObjectRegistry.getClassByConstructor(instance.constructor);
1419
+ const name = registered?.qualifiedName || registered?.name || instance.constructor.name;
1420
+ const fields = await ObjectRegistry.getAllFields(name);
1421
+ for (const key of Object.keys(values)) {
1422
+ const definition = fields.get(key);
1423
+ if (!definition || definition.readonly || definition._meta?.readonly || [
1424
+ "id",
1425
+ "slug",
1426
+ "context",
1427
+ "tenantId",
1428
+ "createdAt",
1429
+ "updatedAt"
1430
+ ].includes(key) || key.startsWith("_")) throw new Error(`Collection update cannot assign field '${key}'`);
1431
+ }
1432
+ await this.withAuditMutation(instance, "updated", async (bound) => {
1433
+ Object.assign(bound, values);
1434
+ await bound.save();
1435
+ }, context);
1436
+ return instance;
1437
+ }
1392
1438
  /** @internal Test creation overrides inside the owning protected boundary. */
1393
1439
  static hasBaseCreateLifecycle(collection) {
1394
1440
  return collection.create === SmrtCollection.prototype.create && collection.createUnsaved === SmrtCollection.prototype.createUnsaved;
@@ -1513,6 +1559,11 @@ var SmrtCollection = class SmrtCollection extends SmrtClass {
1513
1559
  if (existing) {
1514
1560
  const diff = this.getDiffSync(existing, diffData);
1515
1561
  if (diff) {
1562
+ if (isAudited(existing)) {
1563
+ const updated = await this.update(existing.id, diff);
1564
+ if (!updated) throw new Error("Record disappeared before getOrUpsert update");
1565
+ return updated;
1566
+ }
1516
1567
  Object.assign(existing, diff);
1517
1568
  await existing.save();
1518
1569
  }
@@ -1692,11 +1743,15 @@ var SmrtCollection = class SmrtCollection extends SmrtClass {
1692
1743
  * }
1693
1744
  * ```
1694
1745
  */
1695
- async delete(id) {
1746
+ async delete(id, context) {
1696
1747
  await ObjectRegistry.ensureManifestLoaded(this.getResolvedItemClassName());
1697
1748
  const instance = await this.get(id, { cache: false });
1698
1749
  if (!instance) return false;
1699
- await instance.delete();
1750
+ const audited = isAudited(instance);
1751
+ await this.withAuditMutation(instance, "deleted", async (bound) => {
1752
+ if (audited && !bound.updated_at) throw new Error("Audited delete requires a persisted revision");
1753
+ await bound.delete(audited ? { expectedUpdatedAt: bound.updated_at ?? void 0 } : {});
1754
+ }, context);
1700
1755
  return true;
1701
1756
  }
1702
1757
  /**