@forge-cms/runtime 0.4.0 → 0.6.0

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 (73) hide show
  1. package/dist/auth-managed.d.ts +19 -0
  2. package/dist/auth-managed.d.ts.map +1 -0
  3. package/dist/auth-managed.js +24 -0
  4. package/dist/auth-managed.js.map +1 -0
  5. package/dist/concurrency.d.ts +8 -0
  6. package/dist/concurrency.d.ts.map +1 -0
  7. package/dist/concurrency.js +15 -0
  8. package/dist/concurrency.js.map +1 -0
  9. package/dist/context.d.ts +5 -0
  10. package/dist/context.d.ts.map +1 -1
  11. package/dist/errors.d.ts +29 -1
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +38 -0
  14. package/dist/errors.js.map +1 -1
  15. package/dist/files.d.ts +15 -1
  16. package/dist/files.d.ts.map +1 -1
  17. package/dist/files.js +55 -14
  18. package/dist/files.js.map +1 -1
  19. package/dist/globals.d.ts +21 -3
  20. package/dist/globals.d.ts.map +1 -1
  21. package/dist/globals.js +240 -31
  22. package/dist/globals.js.map +1 -1
  23. package/dist/handlers.d.ts +16 -9
  24. package/dist/handlers.d.ts.map +1 -1
  25. package/dist/handlers.js +63 -99
  26. package/dist/handlers.js.map +1 -1
  27. package/dist/index.d.ts +6 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +8 -4
  30. package/dist/index.js.map +1 -1
  31. package/dist/localization.d.ts +17 -0
  32. package/dist/localization.d.ts.map +1 -1
  33. package/dist/localization.js +56 -0
  34. package/dist/localization.js.map +1 -1
  35. package/dist/operations.d.ts +89 -0
  36. package/dist/operations.d.ts.map +1 -1
  37. package/dist/operations.js +824 -116
  38. package/dist/operations.js.map +1 -1
  39. package/dist/populate.d.ts +23 -3
  40. package/dist/populate.d.ts.map +1 -1
  41. package/dist/populate.js +40 -8
  42. package/dist/populate.js.map +1 -1
  43. package/dist/read-policy.d.ts +35 -0
  44. package/dist/read-policy.d.ts.map +1 -0
  45. package/dist/read-policy.js +59 -0
  46. package/dist/read-policy.js.map +1 -0
  47. package/dist/relation-integrity.d.ts +90 -11
  48. package/dist/relation-integrity.d.ts.map +1 -1
  49. package/dist/relation-integrity.js +145 -60
  50. package/dist/relation-integrity.js.map +1 -1
  51. package/dist/relation-lifecycle.d.ts +95 -0
  52. package/dist/relation-lifecycle.d.ts.map +1 -0
  53. package/dist/relation-lifecycle.js +424 -0
  54. package/dist/relation-lifecycle.js.map +1 -0
  55. package/dist/runtime.d.ts +26 -2
  56. package/dist/runtime.d.ts.map +1 -1
  57. package/dist/runtime.js +120 -49
  58. package/dist/runtime.js.map +1 -1
  59. package/dist/storage-intents.d.ts +96 -0
  60. package/dist/storage-intents.d.ts.map +1 -0
  61. package/dist/storage-intents.js +217 -0
  62. package/dist/storage-intents.js.map +1 -0
  63. package/dist/system-fields.d.ts +27 -0
  64. package/dist/system-fields.d.ts.map +1 -0
  65. package/dist/system-fields.js +74 -0
  66. package/dist/system-fields.js.map +1 -0
  67. package/dist/typed-api.d.ts +2 -2
  68. package/dist/typed-api.d.ts.map +1 -1
  69. package/dist/versions.d.ts +76 -6
  70. package/dist/versions.d.ts.map +1 -1
  71. package/dist/versions.js +258 -44
  72. package/dist/versions.js.map +1 -1
  73. package/package.json +9 -7
@@ -1,9 +1,38 @@
1
+ import { assertNotAuthManaged, isAuthManagedCollection } from './auth-managed.js';
1
2
  import { InvalidInputError } from './errors.js';
3
+ import { versionsEnabled } from './versions.js';
2
4
  /**
3
- * Relation integrity utilities for handling cascade, restrict, and set-null on delete.
5
+ * The raw-adapter fallback used when a caller invokes `handleCascadeDelete`/`handleSetNullOnDelete`
6
+ * directly, without a `mutator` — a low-level primitive, but still a `@forge-cms/runtime` public export,
7
+ * not the raw `DatabaseAdapter` escape hatch itself. The boundary (spec 061) applies here too: it would
8
+ * otherwise be a second, undocumented generic-write path into a managed collection, reachable without
9
+ * ever going through `operations.ts`. `operations.ts`'s own `deleteDocumentInternal` always supplies a
10
+ * real mutator (backed by its own `deleteDocumentInternal`/`update`, already guarded), so this only
11
+ * changes behavior for a caller using the raw fallback on purpose.
4
12
  */
13
+ function defaultMutator(ctx) {
14
+ return {
15
+ deleteDocument: (args) => {
16
+ assertNotAuthManaged(ctx, args.collection);
17
+ return ctx.adapters.database.delete(args.collection, args.id);
18
+ },
19
+ update: (args) => {
20
+ assertNotAuthManaged(ctx, args.collection);
21
+ // A raw write to a versioned document would commit a change with no version row, silently
22
+ // breaking the version-number serialization every versioned update relies on (spec 062 §3).
23
+ const target = ctx.getCollection(args.collection);
24
+ if (target && versionsEnabled(target)) {
25
+ throw new Error(`Collection '${args.collection}' has versions enabled; pass a mutator backed by the runtime's ` +
26
+ `update() so the change and its version snapshot are written together (spec 062).`);
27
+ }
28
+ return ctx.adapters.database.update(args.collection, args.id, args.data);
29
+ }
30
+ };
31
+ }
5
32
  /**
6
- * Finds all relation fields in a collection that reference a target collection.
33
+ * Finds all relation fields in a collection that reference a target collection. Includes
34
+ * self-relations (`collection === targetCollection`) — spec 058 §5 removed the previous same-collection
35
+ * skip, which silently let a self-relation's `onDelete` go unenforced entirely.
7
36
  */
8
37
  export function findRelationFields(collection, targetCollection) {
9
38
  const relations = [];
@@ -18,114 +47,170 @@ export function findRelationFields(collection, targetCollection) {
18
47
  return relations;
19
48
  }
20
49
  /**
21
- * Finds all documents in a collection that reference a specific document ID.
50
+ * Finds all documents in a collection that reference a specific document ID. The many-relation branch
51
+ * uses the `containsValue` operator (spec 050, every adapter) for a real database-side membership
52
+ * query instead of an unconditional full-table scan filtered in JavaScript (spec 058 §5).
22
53
  */
23
54
  export async function findReferencingDocuments(ctx, collection, fieldName, documentId, many) {
24
55
  if (many) {
25
- // For many relations, we need to check if the ID is in the array
26
- const allDocs = await ctx.adapters.database.findMany({ collection: collection.slug });
27
- return allDocs.filter((doc) => {
28
- const value = doc[fieldName];
29
- return Array.isArray(value) && value.includes(documentId);
30
- });
31
- }
32
- else {
33
- // For single relations, use where clause
34
56
  return ctx.adapters.database.findMany({
35
57
  collection: collection.slug,
36
- where: { [fieldName]: documentId }
58
+ where: { [fieldName]: { containsValue: documentId } }
37
59
  });
38
60
  }
61
+ return ctx.adapters.database.findMany({
62
+ collection: collection.slug,
63
+ where: { [fieldName]: documentId }
64
+ });
39
65
  }
40
66
  /**
41
- * Checks if a document can be deleted based on relation constraints.
42
- * Throws InvalidInputError if deletion is restricted.
67
+ * @deprecated Since spec 064 `runtime.delete()` checks restrictions against the final state of its
68
+ * whole plan, inside one atomic batch; this one-level, read-only pre-check remains for direct callers.
69
+ *
70
+ * Checks if a document can be deleted based on relation constraints. Throws {@link InvalidInputError}
71
+ * — before any mutation happens — if deletion is restricted, or if a `set-null` relation targets a
72
+ * `required: true` field that has live references: a null value can never satisfy a required field, so
73
+ * this is treated the same as `restrict` rather than failing deep inside a partially-completed cascade
74
+ * with a generic validation error (spec 058 §5's required-field-on-set-null guard).
75
+ *
76
+ * The same applies to a `cascade`/`set-null` relation whose dependent collection is managed by the
77
+ * auth adapter (spec 061): the cascade would be a generic write into that collection, which the runtime
78
+ * refuses for everyone, so it is rejected here — before any mutation, with a message about the document
79
+ * being deleted rather than about the managed collection — instead of failing part-way through.
80
+ *
81
+ * There is deliberately no supported way to clear the reference and retry: the auth adapter's own
82
+ * `updateUser` only accepts email/name/role/password, not an arbitrary custom field, so this rejection
83
+ * is not "remove the reference, then delete" advice — see the error message, and spec 061 §7/Non-goals.
84
+ * The only way past it is the documented raw `DatabaseAdapter` escape hatch (outside runtime guarantees).
43
85
  */
44
86
  export async function checkDeleteRestrictions(ctx, targetCollection, documentId) {
45
- // Check all collections for relations to this collection
46
87
  for (const collection of ctx.getCollections()) {
47
- if (collection.slug === targetCollection.slug)
48
- continue;
49
88
  const relations = findRelationFields(collection, targetCollection.slug);
50
89
  for (const { fieldName, options } of relations) {
51
90
  const onDelete = options.onDelete ?? 'restrict';
52
- if (onDelete === 'restrict') {
53
- const referencing = await findReferencingDocuments(ctx, collection, fieldName, documentId, options.many ?? false);
54
- if (referencing.length > 0) {
55
- throw new InvalidInputError(`Cannot delete document '${documentId}' from '${targetCollection.slug}': ` +
56
- `referenced by ${referencing.length} document(s) in '${collection.slug}'`);
57
- }
91
+ const unsafeRequiredSetNull = onDelete === 'set-null' && options.required === true;
92
+ const authManagedDependent = onDelete !== 'restrict' && isAuthManagedCollection(ctx, collection.slug);
93
+ if (onDelete !== 'restrict' && !unsafeRequiredSetNull && !authManagedDependent)
94
+ continue;
95
+ const referencing = await findReferencingDocuments(ctx, collection, fieldName, documentId, options.many ?? false);
96
+ if (referencing.length === 0)
97
+ continue;
98
+ if (authManagedDependent) {
99
+ throw new InvalidInputError(`Cannot delete document '${documentId}' from '${targetCollection.slug}': ` +
100
+ `${referencing.length} document(s) in '${collection.slug}' reference it with ` +
101
+ `onDelete '${onDelete}', but '${collection.slug}' is managed by the configured auth adapter, ` +
102
+ `so a relation cascade cannot change it. Clearing the reference on those document(s) is not ` +
103
+ `possible through generic collection CRUD or the auth adapter's user-management operations; ` +
104
+ `it requires direct database access, which is outside runtime guarantees`);
58
105
  }
106
+ if (unsafeRequiredSetNull) {
107
+ throw new InvalidInputError(`Cannot delete document '${documentId}' from '${targetCollection.slug}': field '${fieldName}' ` +
108
+ `on '${collection.slug}' is required and configured 'onDelete: set-null', which cannot ` +
109
+ `satisfy ${referencing.length} referencing document(s) without violating that requirement`);
110
+ }
111
+ throw new InvalidInputError(`Cannot delete document '${documentId}' from '${targetCollection.slug}': ` +
112
+ `referenced by ${referencing.length} document(s) in '${collection.slug}'`);
59
113
  }
60
114
  }
61
115
  }
62
116
  /**
63
- * Handles cascade delete: deletes all documents that reference the deleted document.
117
+ * @deprecated Not atomic — each dependent delete commits on its own. `runtime.delete()` (spec 064)
118
+ * commits the whole cascade graph in one batch and no longer calls this.
119
+ *
120
+ * Handles cascade delete: deletes all documents that reference the deleted document. With a real
121
+ * mutator supplied, each dependent delete recurses through the full delete pipeline (its own
122
+ * `checkDeleteRestrictions`/cascade/set-null included) — so a cascade chain several levels deep is
123
+ * fully processed, not just one level. Not transactional: if a later step fails (a second-level
124
+ * `restrict`, a hook throwing, a DB error), documents already deleted by earlier steps stay deleted —
125
+ * the current `DatabaseAdapter` contract has no cross-document transaction to roll back with, and this
126
+ * matches the pre-058 code's identical (if previously undocumented) property.
64
127
  */
65
- export async function handleCascadeDelete(ctx, targetCollection, documentId) {
128
+ export async function handleCascadeDelete(ctx, targetCollection, documentId, integrityOptions = {}) {
129
+ const mutator = integrityOptions.mutator ?? defaultMutator(ctx);
130
+ const visited = integrityOptions.visited ?? new Set();
131
+ const user = integrityOptions.user ?? null;
66
132
  for (const collection of ctx.getCollections()) {
67
- if (collection.slug === targetCollection.slug)
68
- continue;
69
133
  const relations = findRelationFields(collection, targetCollection.slug);
70
134
  for (const { fieldName, options } of relations) {
71
135
  const onDelete = options.onDelete ?? 'restrict';
72
- if (onDelete === 'cascade') {
73
- const referencing = await findReferencingDocuments(ctx, collection, fieldName, documentId, options.many ?? false);
74
- // Delete all referencing documents
75
- for (const doc of referencing) {
76
- await ctx.adapters.database.delete(collection.slug, doc.id);
77
- }
136
+ if (onDelete !== 'cascade')
137
+ continue;
138
+ const referencing = await findReferencingDocuments(ctx, collection, fieldName, documentId, options.many ?? false);
139
+ for (const doc of referencing) {
140
+ const key = `${collection.slug}:${doc.id}`;
141
+ // Already deleted (or in progress) via another cascade path, or a reference cycle — do not
142
+ // reprocess or recurse forever.
143
+ if (visited.has(key))
144
+ continue;
145
+ visited.add(key);
146
+ await mutator.deleteDocument({
147
+ collection: collection.slug,
148
+ id: doc.id,
149
+ overrideAccess: true,
150
+ ...(user !== null && { user })
151
+ });
78
152
  }
79
153
  }
80
154
  }
81
155
  }
82
156
  /**
83
- * Handles set-null: sets relation fields to null in all referencing documents.
157
+ * @deprecated Not atomic — each update commits on its own. `runtime.delete()` (spec 064) commits its
158
+ * set-null updates in the same batch as the delete and no longer calls this.
159
+ *
160
+ * Handles set-null: sets relation fields to null (or removes the id from a many-relation array) in
161
+ * all referencing documents. Skips a document already processed elsewhere in this same delete
162
+ * operation (cascade-deleted, or already set-null'd via another field/path) via the shared `visited`
163
+ * set — including the case of a self-relation pointing a document at itself, which would otherwise try
164
+ * to update a row that is itself mid-deletion.
84
165
  */
85
- export async function handleSetNullOnDelete(ctx, targetCollection, documentId) {
166
+ export async function handleSetNullOnDelete(ctx, targetCollection, documentId, integrityOptions = {}) {
167
+ const mutator = integrityOptions.mutator ?? defaultMutator(ctx);
168
+ const visited = integrityOptions.visited ?? new Set();
169
+ const user = integrityOptions.user ?? null;
86
170
  for (const collection of ctx.getCollections()) {
87
- if (collection.slug === targetCollection.slug)
88
- continue;
89
171
  const relations = findRelationFields(collection, targetCollection.slug);
90
172
  for (const { fieldName, options } of relations) {
91
173
  const onDelete = options.onDelete ?? 'restrict';
92
- if (onDelete === 'set-null') {
93
- const referencing = await findReferencingDocuments(ctx, collection, fieldName, documentId, options.many ?? false);
94
- // Update each referencing document
95
- for (const doc of referencing) {
96
- if (options.many) {
97
- // Remove the ID from the array
98
- const currentValue = doc[fieldName];
99
- const newValue = currentValue.filter((id) => id !== documentId);
100
- await ctx.adapters.database.update(collection.slug, doc.id, {
101
- [fieldName]: newValue
102
- });
103
- }
104
- else {
105
- // Set to null
106
- await ctx.adapters.database.update(collection.slug, doc.id, {
107
- [fieldName]: null
108
- });
109
- }
110
- }
174
+ if (onDelete !== 'set-null')
175
+ continue;
176
+ const referencing = await findReferencingDocuments(ctx, collection, fieldName, documentId, options.many ?? false);
177
+ for (const doc of referencing) {
178
+ const key = `${collection.slug}:${doc.id}`;
179
+ if (visited.has(key))
180
+ continue;
181
+ visited.add(key);
182
+ const newValue = options.many
183
+ ? (doc[fieldName] ?? []).filter((id) => id !== documentId)
184
+ : null;
185
+ await mutator.update({
186
+ collection: collection.slug,
187
+ id: doc.id,
188
+ data: { [fieldName]: newValue },
189
+ overrideAccess: true,
190
+ ...(user !== null && { user })
191
+ });
111
192
  }
112
193
  }
113
194
  }
114
195
  }
115
196
  /**
116
- * Finds orphaned documents: documents with relation fields pointing to non-existent documents.
197
+ * Finds orphaned documents: documents whose top-level `relation` or `upload` field points at a document
198
+ * that does not exist. Diagnostic only — nothing is repaired. Since spec 064 a successfully committed
199
+ * supported write or delete cannot create one; orphans found here predate it, or were written through
200
+ * the raw `DatabaseAdapter` or the auth adapter's user lifecycle.
117
201
  */
118
202
  export async function findOrphanedDocuments(ctx, collection) {
119
203
  const orphans = [];
120
204
  const allDocs = await ctx.adapters.database.findMany({ collection: collection.slug });
121
205
  for (const [fieldName, field] of Object.entries(collection.fields)) {
122
- if (field.kind !== 'relation')
206
+ if (field.kind !== 'relation' && field.kind !== 'upload')
123
207
  continue;
124
208
  const options = field.options;
125
209
  const targetCollection = options.collection;
210
+ const many = field.kind === 'relation' && options.many === true;
126
211
  for (const doc of allDocs) {
127
212
  const value = doc[fieldName];
128
- if (options.many && Array.isArray(value)) {
213
+ if (many && Array.isArray(value)) {
129
214
  // Check each ID in the array
130
215
  for (const id of value) {
131
216
  if (typeof id === 'string') {
@@ -1 +1 @@
1
- {"version":3,"file":"relation-integrity.js","sourceRoot":"","sources":["../src/relation-integrity.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;GAEG;AAEH;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAChC,UAAgC,EAChC,gBAAwB;IAExB,MAAM,SAAS,GAAgE,EAAE,CAAC;IAElF,KAAK,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC9B,MAAM,OAAO,GAAG,KAAK,CAAC,OAA+B,CAAC;YACtD,IAAI,OAAO,CAAC,UAAU,KAAK,gBAAgB,EAAE,CAAC;gBAC5C,SAAS,CAAC,IAAI,CAAC,EAAE,SAA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AC;iBAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBACrC,wBAAwB;gBACxB,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAAC;gBAC7E,IAAI,CAAC,MAAM,EAAE,CAAC;oBACZ,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;gBAC/D,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,95 @@
1
+ import type { CollectionDefinition, FieldMap, GlobalDefinition } from '@forge-cms/core';
2
+ import type { AtomicWriteOperation, DatabaseRecord, DatabaseWhere } from '@forge-cms/db';
3
+ import type { OperationContext } from './context.js';
4
+ /**
5
+ * The reference shapes relation integrity cannot enforce (spec 064 §2), found at startup so they are
6
+ * refused instead of silently ignored. Returns one message per problem (empty = supported). Reads the
7
+ * schema only — never persisted data.
8
+ *
9
+ * `isAuthManaged` answers `AuthAdapter.managesCollection` (spec 061); `onDelete: 'cascade' | 'set-null'`
10
+ * onto such a collection could never run, because its documents are only ever deleted by the auth
11
+ * adapter's own user lifecycle.
12
+ */
13
+ export declare function validateRelationSchema(collections: readonly CollectionDefinition[], globals?: readonly GlobalDefinition[], isAuthManaged?: (slug: string) => boolean): string[];
14
+ /**
15
+ * "No row references any of `ids` in `target` any more" — one `assertCount(…, 0)` per referring field of
16
+ * a collection or global. The single definition of the final-state reference guard, shared by a content
17
+ * delete's plan and by the guard an auth adapter commits with its own user delete (spec 065).
18
+ */
19
+ export declare function noReferenceAssertions(ctx: OperationContext, target: string, ids: readonly string[]): AtomicWriteOperation[];
20
+ /** Whether any supported relation/upload field of a collection or global references `target`. */
21
+ export declare function isReferenced(ctx: OperationContext, target: string): boolean;
22
+ /** Target collection → the unique ids a write references there, plus the fields that wrote them. */
23
+ export type WrittenTargets = Map<string, {
24
+ ids: Set<string>;
25
+ fields: Set<string>;
26
+ }>;
27
+ /**
28
+ * The relation targets a write introduces. On update (`existing` given) only values that change count:
29
+ * a single reference different from the stored one, and for `many` only ids not already stored — so a
30
+ * partial update that leaves a (possibly historically orphaned) reference alone validates nothing.
31
+ */
32
+ export declare function collectWrittenTargets(fields: FieldMap, data: Record<string, unknown>, existing?: Record<string, unknown>): WrittenTargets;
33
+ /**
34
+ * The references an update **re-sends unchanged** (spec 064 §4): single values equal to the stored one,
35
+ * and ids of a `many` value already stored. They are not target-checked (a historical orphan must stay
36
+ * saveable), so instead the write only commits while the row **still holds them**. Otherwise a relation
37
+ * delete that cleared them after this update read the row (set-null) would be silently undone, leaving a
38
+ * reference to the deleted document. `undefined` when nothing is re-sent.
39
+ */
40
+ export declare function echoedReferenceGuard(fields: FieldMap, data: Record<string, unknown>, existing: Record<string, unknown>): DatabaseWhere | undefined;
41
+ /**
42
+ * The deterministic answer for a write naming a target that does not exist: one `count` per target
43
+ * collection (an `in` over the unique ids, not a read per id), then a `400` naming the field and the
44
+ * missing ids. This is the only place "missing" is reported as bad input — a target that disappears
45
+ * after this read fails the write's own `assertCount` instead (a `409`, see {@link targetAssertions}).
46
+ */
47
+ export declare function verifyTargetsExist(ctx: OperationContext, targets: WrittenTargets): Promise<void>;
48
+ /**
49
+ * `assertCount`s proving every written target still exists when the write commits: one per target
50
+ * collection, or one per 90 ids of a very large `many` write (each counts against the batch cap).
51
+ */
52
+ export declare function targetAssertions(targets: WrittenTargets): AtomicWriteOperation[];
53
+ export interface PlannedDelete {
54
+ collection: CollectionDefinition;
55
+ /** The document as read while planning; its `updated_at` guards the batch and its `_storageKey` is cleaned up. */
56
+ doc: DatabaseRecord;
57
+ }
58
+ export interface PlannedSetNull {
59
+ collection: CollectionDefinition;
60
+ id: string;
61
+ /** Field → the deleted ids to clear from it (single → `null`, many → removed from the array). */
62
+ removals: Map<string, {
63
+ many: boolean;
64
+ ids: Set<string>;
65
+ }>;
66
+ }
67
+ export interface RelationDeletePlan {
68
+ /** Root first, then dependents in discovery order. */
69
+ deletes: PlannedDelete[];
70
+ setNulls: PlannedSetNull[];
71
+ /** "No surviving row references a deleted document", checked last in the batch (final state). */
72
+ assertions: AtomicWriteOperation[];
73
+ }
74
+ /**
75
+ * Plans a delete's complete relation consequences **with reads only** — nothing is written and no hook
76
+ * runs here. Breadth-first over `collection:id` keys, each scheduled at most once, so self references,
77
+ * cycles and diamonds terminate. Every referencing-row query is bounded (`limit: MAX + 1`): a plan that
78
+ * could not fit in one batch is refused, never truncated or chunked.
79
+ *
80
+ * Restrict and required set-null are judged against the **final** state: a reference only blocks the
81
+ * delete if the document holding it survives (a restrict referrer that is itself cascade-deleted in the
82
+ * same plan does not block). Throws `InvalidInputError` for a blocking restrict, a surviving required
83
+ * set-null, a cascade/set-null into an auth-managed collection (spec 061), or an oversized plan.
84
+ */
85
+ export declare function planRelationDelete(ctx: OperationContext, root: {
86
+ collection: CollectionDefinition;
87
+ doc: DatabaseRecord;
88
+ }): Promise<RelationDeletePlan>;
89
+ /**
90
+ * The set-null patch for `doc` as it is now: single references to a deleted id become `null`, deleted
91
+ * ids are removed from `many` arrays. `null` when the document no longer references any of them (it
92
+ * changed since planning) — then there is nothing to write.
93
+ */
94
+ export declare function setNullPatch(planned: PlannedSetNull, doc: DatabaseRecord): Record<string, unknown> | null;
95
+ //# sourceMappingURL=relation-lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relation-lifecycle.d.ts","sourceRoot":"","sources":["../src/relation-lifecycle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,oBAAoB,EACpB,QAAQ,EACR,gBAAgB,EAGjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM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