@lacecms/application 0.1.0-alpha.4 → 0.1.0-alpha.6
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.
- package/dist/accounts.d.ts +301 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +342 -0
- package/dist/accounts.js.map +1 -0
- package/dist/configuration-evolution.d.ts +151 -0
- package/dist/configuration-evolution.d.ts.map +1 -0
- package/dist/configuration-evolution.js +568 -0
- package/dist/configuration-evolution.js.map +1 -0
- package/dist/configuration-fields.d.ts +30 -0
- package/dist/configuration-fields.d.ts.map +1 -0
- package/dist/configuration-fields.js +170 -0
- package/dist/configuration-fields.js.map +1 -0
- package/dist/configuration-migration.d.ts +130 -0
- package/dist/configuration-migration.d.ts.map +1 -0
- package/dist/configuration-migration.js +255 -0
- package/dist/configuration-migration.js.map +1 -0
- package/dist/configuration-sync.d.ts +192 -12
- package/dist/configuration-sync.d.ts.map +1 -1
- package/dist/configuration-sync.js +815 -39
- package/dist/configuration-sync.js.map +1 -1
- package/dist/content-use-cases.d.ts +53 -3
- package/dist/content-use-cases.d.ts.map +1 -1
- package/dist/content-use-cases.js +190 -19
- package/dist/content-use-cases.js.map +1 -1
- package/dist/email.d.ts +80 -0
- package/dist/email.d.ts.map +1 -0
- package/dist/email.js +134 -0
- package/dist/email.js.map +1 -0
- package/dist/index.d.ts +139 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +46 -1
- package/dist/index.js.map +1 -1
- package/dist/media-use-cases.d.ts +68 -1
- package/dist/media-use-cases.d.ts.map +1 -1
- package/dist/media-use-cases.js +151 -1
- package/dist/media-use-cases.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
import { validateModelFields } from "@lacecms/content";
|
|
2
|
-
import { DomainError, actorId, contentEntryId, contentModelKey, contentSnapshotId, createContentEntry, } from "@lacecms/domain";
|
|
1
|
+
import { canonicalizeJson, schemaFieldAt, parseSchemaPath, validateModelFields, } from "@lacecms/content";
|
|
2
|
+
import { DomainError, actorId, contentEntryId, contentModelKey, contentSnapshotId, createContentEntry, isSingletonKind, } from "@lacecms/domain";
|
|
3
|
+
import { CONFIGURATION_SYNC_SCAN_PAGE_SIZE, changeNeedsEvidence, createSnapshotEvidenceAccumulator, diffContentModelStructures, validateStructureHints, } from "./configuration-evolution.js";
|
|
4
|
+
import { CONFIGURATION_SYNC_MIGRATION_PAGE_SIZE, createMigrationEvidenceAccumulator, planEntryMigration, } from "./configuration-migration.js";
|
|
5
|
+
export * from "./configuration-evolution.js";
|
|
6
|
+
export * from "./configuration-migration.js";
|
|
3
7
|
export const contentSyncActor = Object.freeze({
|
|
4
8
|
id: actorId("system:content-sync"),
|
|
5
9
|
role: "admin",
|
|
@@ -21,16 +25,38 @@ function copyStoredModel(model) {
|
|
|
21
25
|
kind: model.kind,
|
|
22
26
|
projectionHash: model.projectionHash,
|
|
23
27
|
publishedSnapshotCount: model.publishedSnapshotCount,
|
|
28
|
+
...(model.snapshotFingerprint === undefined
|
|
29
|
+
? {}
|
|
30
|
+
: { snapshotFingerprint: model.snapshotFingerprint }),
|
|
31
|
+
...(model.structure === undefined ? {} : { structure: model.structure }),
|
|
24
32
|
structureHash: model.structureHash,
|
|
25
33
|
version: model.version,
|
|
26
34
|
});
|
|
27
35
|
}
|
|
28
|
-
|
|
36
|
+
/** JSON-safe stored state for reports; the baseline itself is reduced to its presence. */
|
|
37
|
+
function reportedStoredModel(model) {
|
|
38
|
+
const { structure, ...rest } = model;
|
|
39
|
+
return { ...rest, hasBaseline: structure !== undefined };
|
|
40
|
+
}
|
|
41
|
+
function diagnostic(code, modelKey, message, details = {}) {
|
|
42
|
+
const values = typeof details === "string" ? { relatedModelKey: details } : details;
|
|
29
43
|
return Object.freeze({
|
|
44
|
+
...(values.affectedCount === undefined ? {} : { affectedCount: values.affectedCount }),
|
|
45
|
+
...(values.blockType === undefined ? {} : { blockType: values.blockType }),
|
|
46
|
+
...(values.changeClass === undefined ? {} : { changeClass: values.changeClass }),
|
|
30
47
|
code,
|
|
48
|
+
...(values.fieldKey === undefined
|
|
49
|
+
? {}
|
|
50
|
+
: {
|
|
51
|
+
fieldKey: values.fieldKey,
|
|
52
|
+
...(values.fieldKey.startsWith("/") ? { schemaPath: values.fieldKey } : {}),
|
|
53
|
+
}),
|
|
31
54
|
message,
|
|
32
55
|
modelKey: contentModelKey(modelKey),
|
|
33
|
-
...(relatedModelKey === undefined
|
|
56
|
+
...(values.relatedModelKey === undefined
|
|
57
|
+
? {}
|
|
58
|
+
: { relatedModelKey: contentModelKey(values.relatedModelKey) }),
|
|
59
|
+
...(values.snapshots === undefined ? {} : { snapshots: Object.freeze([...values.snapshots]) }),
|
|
34
60
|
});
|
|
35
61
|
}
|
|
36
62
|
function compareByKey(left, right) {
|
|
@@ -39,7 +65,9 @@ function compareByKey(left, right) {
|
|
|
39
65
|
function compareDiagnostics(left, right) {
|
|
40
66
|
return (left.modelKey.localeCompare(right.modelKey) ||
|
|
41
67
|
left.code.localeCompare(right.code) ||
|
|
42
|
-
(left.relatedModelKey ?? "").localeCompare(right.relatedModelKey ?? "")
|
|
68
|
+
(left.relatedModelKey ?? "").localeCompare(right.relatedModelKey ?? "") ||
|
|
69
|
+
(left.fieldKey ?? "").localeCompare(right.fieldKey ?? "") ||
|
|
70
|
+
(left.blockType ?? "").localeCompare(right.blockType ?? ""));
|
|
43
71
|
}
|
|
44
72
|
function hasSnapshots(model) {
|
|
45
73
|
return model.draftSnapshotCount > 0 || model.publishedSnapshotCount > 0;
|
|
@@ -52,10 +80,363 @@ function snapshotDescription(model) {
|
|
|
52
80
|
states.push(`published=${model.publishedSnapshotCount}`);
|
|
53
81
|
return states.join(", ");
|
|
54
82
|
}
|
|
55
|
-
function
|
|
56
|
-
return
|
|
83
|
+
function countsDescription(counts) {
|
|
84
|
+
return `draft=${counts.draft}, published=${counts.published}`;
|
|
85
|
+
}
|
|
86
|
+
function total(counts) {
|
|
87
|
+
return counts === undefined ? 0 : counts.draft + counts.published;
|
|
88
|
+
}
|
|
89
|
+
/** Draft and published counts of holder evidence, without the named snapshots. */
|
|
90
|
+
function holderCounts(holders) {
|
|
91
|
+
return holders === undefined
|
|
92
|
+
? undefined
|
|
93
|
+
: Object.freeze({ draft: holders.draft, published: holders.published });
|
|
94
|
+
}
|
|
95
|
+
function incompatible(model, stored, evolution) {
|
|
96
|
+
return Object.freeze({
|
|
97
|
+
action: "incompatible-change",
|
|
98
|
+
...(evolution === undefined ? {} : { evolution }),
|
|
99
|
+
model,
|
|
100
|
+
stored,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
function undecidedChange(change) {
|
|
104
|
+
return Object.freeze({
|
|
105
|
+
class: change.class,
|
|
106
|
+
...(change.from === undefined ? {} : { from: change.from }),
|
|
107
|
+
...(change.hinted === undefined ? {} : { hinted: change.hinted }),
|
|
108
|
+
kind: change.kind,
|
|
109
|
+
...(change.properties === undefined ? {} : { properties: change.properties }),
|
|
110
|
+
scope: change.scope,
|
|
111
|
+
target: change.target,
|
|
112
|
+
...(change.scope === "field" && change.target.startsWith("/")
|
|
113
|
+
? { schemaPath: change.target }
|
|
114
|
+
: {}),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Decides every structural change of a populated model from its stored
|
|
119
|
+
* evidence, records refusals as diagnostics, and lists the planned backfills.
|
|
120
|
+
*/
|
|
121
|
+
function decideEvolution(current, stored, changes, context) {
|
|
122
|
+
const modelKey = current.key;
|
|
123
|
+
const populated = hasSnapshots(stored);
|
|
124
|
+
const storedCounts = Object.freeze({
|
|
125
|
+
draft: stored.draftSnapshotCount,
|
|
126
|
+
published: stored.publishedSnapshotCount,
|
|
127
|
+
});
|
|
128
|
+
if (!populated) {
|
|
129
|
+
return {
|
|
130
|
+
evolution: Object.freeze({
|
|
131
|
+
backfills: Object.freeze([]),
|
|
132
|
+
changes: Object.freeze(changes.map(undecidedChange)),
|
|
133
|
+
snapshots: storedCounts,
|
|
134
|
+
}),
|
|
135
|
+
refused: false,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
let evidence;
|
|
139
|
+
if (changes.some(changeNeedsEvidence)) {
|
|
140
|
+
const fingerprint = stored.snapshotFingerprint ?? "";
|
|
141
|
+
const migrations = changes
|
|
142
|
+
.filter((change) => versionedBlockChange(change))
|
|
143
|
+
.map((change) => Object.freeze({ type: change.target, version: change.version.to }));
|
|
144
|
+
context.scanRequests.push(Object.freeze({
|
|
145
|
+
changes,
|
|
146
|
+
blockFields: Object.fromEntries((current.structure?.blockDefinitions ?? []).map((block) => [
|
|
147
|
+
block.type,
|
|
148
|
+
block.fields,
|
|
149
|
+
])),
|
|
150
|
+
storedFields: stored.structure?.fields,
|
|
151
|
+
fields: current.fields,
|
|
152
|
+
fingerprint,
|
|
153
|
+
...(migrations.length === 0 ? {} : { migrations: Object.freeze(migrations) }),
|
|
154
|
+
modelKey: stored.key,
|
|
155
|
+
}));
|
|
156
|
+
const candidate = context.evidence?.[stored.key];
|
|
157
|
+
if (candidate === undefined || candidate.fingerprint !== fingerprint) {
|
|
158
|
+
context.diagnostics.push(diagnostic("SNAPSHOT_EVIDENCE_STALE", modelKey, `Model ${modelKey} needs a fresh scan of its stored snapshots; rerun synchronization.`));
|
|
159
|
+
return {
|
|
160
|
+
evolution: Object.freeze({
|
|
161
|
+
backfills: Object.freeze([]),
|
|
162
|
+
changes: Object.freeze(changes.map(undecidedChange)),
|
|
163
|
+
snapshots: storedCounts,
|
|
164
|
+
}),
|
|
165
|
+
refused: true,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
evidence = candidate;
|
|
169
|
+
}
|
|
170
|
+
let refused = false;
|
|
171
|
+
const refuse = (code, message, details) => {
|
|
172
|
+
refused = true;
|
|
173
|
+
context.diagnostics.push(diagnostic(code, modelKey, message, details));
|
|
174
|
+
};
|
|
175
|
+
const decided = [];
|
|
176
|
+
const backfills = [];
|
|
177
|
+
const renames = [];
|
|
178
|
+
const fieldRemovals = [];
|
|
179
|
+
const blockRemovals = [];
|
|
180
|
+
const blockMigrations = [];
|
|
181
|
+
let seoRemoval = false;
|
|
182
|
+
for (const change of changes) {
|
|
183
|
+
const fieldKey = change.scope === "field" ? change.target : undefined;
|
|
184
|
+
const blockType = change.scope === "block" ? change.target : undefined;
|
|
185
|
+
let affected;
|
|
186
|
+
let backfill;
|
|
187
|
+
let violations;
|
|
188
|
+
let migration;
|
|
189
|
+
if (change.kind === "field-type-changed") {
|
|
190
|
+
refuse("FIELD_TYPE_CHANGED", `Model ${modelKey} changes the type of field ${change.target} while snapshots exist (${snapshotDescription(stored)}).`, { changeClass: change.class, fieldKey });
|
|
191
|
+
}
|
|
192
|
+
else if (change.class === "breaking" && change.kind === "route-changed") {
|
|
193
|
+
if (stored.publishedSnapshotCount > 0) {
|
|
194
|
+
refuse("ROUTE_CHANGE_HAS_PUBLISHED", `Model ${modelKey} changes its ${change.target} while ${stored.publishedSnapshotCount} entries are published.`, { affectedCount: stored.publishedSnapshotCount, changeClass: change.class });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
else if (change.class === "breaking") {
|
|
198
|
+
refuse("FIELD_CHANGE_UNSUPPORTED", `Model ${modelKey} changes ${change.scope} ${change.target}${change.properties === undefined ? "" : ` (${change.properties.join(", ")})`} in a way synchronization cannot apply while snapshots exist.`, { changeClass: change.class, ...(fieldKey === undefined ? {} : { fieldKey }) });
|
|
199
|
+
}
|
|
200
|
+
else if (change.kind === "field-renamed") {
|
|
201
|
+
const occupied = evidence?.fieldHolders[change.target];
|
|
202
|
+
affected = holderCounts(evidence?.fieldHolders[change.from ?? ""]);
|
|
203
|
+
if (occupied !== undefined && total(occupied) > 0) {
|
|
204
|
+
refuse("FIELD_RENAME_TARGET_HAS_DATA", `Model ${modelKey} renames field ${change.from} to ${change.target}, but ${total(occupied)} snapshots already hold ${change.target} (${countsDescription(occupied)}).`, {
|
|
205
|
+
affectedCount: total(occupied),
|
|
206
|
+
changeClass: change.class,
|
|
207
|
+
fieldKey,
|
|
208
|
+
snapshots: occupied.snapshots,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
else if (total(affected) > 0) {
|
|
212
|
+
renames.push(Object.freeze({ from: change.from, to: change.target }));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
else if (change.kind === "field-removed") {
|
|
216
|
+
const holders = evidence?.fieldHolders[change.target];
|
|
217
|
+
affected = holderCounts(holders);
|
|
218
|
+
if (holders !== undefined && total(holders) > 0) {
|
|
219
|
+
if (change.hinted === true) {
|
|
220
|
+
fieldRemovals.push(change.target);
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
refuse("FIELD_REMOVAL_HAS_DATA", `Model ${modelKey} removes field ${change.target}, which holds data in ${total(holders)} snapshots (${countsDescription(holders)}). Declare removedFields: ["${change.target}"] to prune it, or renamedFrom: "${change.target}" on the field that replaces it.`, {
|
|
224
|
+
affectedCount: total(holders),
|
|
225
|
+
changeClass: change.class,
|
|
226
|
+
fieldKey,
|
|
227
|
+
snapshots: holders.snapshots,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
else if (change.kind === "seo-disabled") {
|
|
233
|
+
const holders = evidence?.seoHolders;
|
|
234
|
+
affected = holderCounts(holders);
|
|
235
|
+
if (holders !== undefined && total(holders) > 0) {
|
|
236
|
+
if (change.hinted === true) {
|
|
237
|
+
seoRemoval = true;
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
refuse("SEO_REMOVAL_HAS_DATA", `Model ${modelKey} disables seo while ${total(holders)} snapshots hold SEO values (${countsDescription(holders)}). Declare removedSeo: true to prune them.`, {
|
|
241
|
+
affectedCount: total(holders),
|
|
242
|
+
changeClass: change.class,
|
|
243
|
+
snapshots: holders.snapshots,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
else if (change.kind === "block-type-removed") {
|
|
249
|
+
const holders = evidence?.blockHolders[change.target];
|
|
250
|
+
affected = holderCounts(holders);
|
|
251
|
+
if (holders !== undefined && total(holders) > 0) {
|
|
252
|
+
if (change.hinted === true) {
|
|
253
|
+
blockRemovals.push(change.target);
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
refuse("BLOCK_TYPE_REMOVAL_HAS_BLOCKS", `Model ${modelKey} disallows block type ${change.target}, which ${total(holders)} snapshots use (${countsDescription(holders)}). Declare removedBlocks: ["${change.target}"] to drop those blocks.`, {
|
|
257
|
+
affectedCount: total(holders),
|
|
258
|
+
blockType,
|
|
259
|
+
changeClass: change.class,
|
|
260
|
+
snapshots: holders.snapshots,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
else if (change.kind === "block-definition-changed") {
|
|
266
|
+
const holders = evidence?.blockHolders[change.target];
|
|
267
|
+
affected = holderCounts(holders);
|
|
268
|
+
if (!versionedBlockChange(change)) {
|
|
269
|
+
if (holders !== undefined && total(holders) > 0) {
|
|
270
|
+
refuse("BLOCK_DEFINITION_CHANGE_HAS_BLOCKS", `Block type ${change.target} changes its definition without a version increase while ${total(holders)} snapshots of model ${modelKey} hold such blocks (${countsDescription(holders)}). Increase the block version and declare migrations.`, {
|
|
271
|
+
affectedCount: total(holders),
|
|
272
|
+
blockType,
|
|
273
|
+
changeClass: change.class,
|
|
274
|
+
snapshots: holders.snapshots,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
const facts = evidence?.migrations?.[change.target];
|
|
280
|
+
const decision = facts === undefined
|
|
281
|
+
? { planned: false, refusals: [] }
|
|
282
|
+
: decideBlockMigration(modelKey, change.target, facts);
|
|
283
|
+
for (const refusal of decision.refusals) {
|
|
284
|
+
refuse(refusal.code, refusal.message, {
|
|
285
|
+
affectedCount: refusal.findings.count,
|
|
286
|
+
blockType,
|
|
287
|
+
changeClass: change.class,
|
|
288
|
+
snapshots: refusal.findings.snapshots,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
if (decision.planned && facts !== undefined) {
|
|
292
|
+
migration = Object.freeze({ from: facts.fromVersions, to: facts.toVersion });
|
|
293
|
+
blockMigrations.push(Object.freeze({
|
|
294
|
+
blockType: change.target,
|
|
295
|
+
blocks: facts.blocks,
|
|
296
|
+
draft: facts.snapshots.draft,
|
|
297
|
+
fromVersions: facts.fromVersions,
|
|
298
|
+
published: facts.snapshots.published,
|
|
299
|
+
toVersion: facts.toVersion,
|
|
300
|
+
}));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else if (change.class === "validated") {
|
|
305
|
+
const findings = evidence?.violations[change.target];
|
|
306
|
+
violations = findings?.count ?? 0;
|
|
307
|
+
if (findings !== undefined && findings.count > 0) {
|
|
308
|
+
refuse("CONSTRAINT_VIOLATED", `Model ${modelKey} tightens field ${change.target} (${(change.properties ?? []).join(", ")}), but ${findings.count} stored snapshots do not satisfy it.`, {
|
|
309
|
+
affectedCount: findings.count,
|
|
310
|
+
changeClass: change.class,
|
|
311
|
+
fieldKey,
|
|
312
|
+
snapshots: findings.snapshots,
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (change.backfill === true) {
|
|
317
|
+
backfill = evidence?.backfills[change.target] ?? Object.freeze({ draft: 0, published: 0 });
|
|
318
|
+
if (total(backfill) > 0) {
|
|
319
|
+
const invalidDefault = evidence?.violations[change.target];
|
|
320
|
+
if (change.class !== "validated" &&
|
|
321
|
+
invalidDefault !== undefined &&
|
|
322
|
+
invalidDefault.count > 0)
|
|
323
|
+
refuse("CONSTRAINT_VIOLATED", `Model ${modelKey} default for ${change.target} is invalid for stored snapshots.`, {
|
|
324
|
+
affectedCount: invalidDefault.count,
|
|
325
|
+
changeClass: change.class,
|
|
326
|
+
fieldKey,
|
|
327
|
+
snapshots: invalidDefault.snapshots,
|
|
328
|
+
});
|
|
329
|
+
if (current.fields[change.target]?.type === "media" ||
|
|
330
|
+
(evidence?.mediaBackfills?.[change.target]?.count ?? 0) > 0) {
|
|
331
|
+
refuse("MEDIA_DEFAULT_BACKFILL_UNSUPPORTED", `Model ${modelKey} declares a default for media field ${change.target}, which cannot be backfilled into ${total(backfill)} snapshots; remove the default or add the field without one.`, {
|
|
332
|
+
affectedCount: total(backfill),
|
|
333
|
+
changeClass: change.class,
|
|
334
|
+
fieldKey,
|
|
335
|
+
...(evidence?.mediaBackfills?.[change.target] === undefined ||
|
|
336
|
+
(current.fields[change.target]?.type === "media" && !change.target.startsWith("/"))
|
|
337
|
+
? {}
|
|
338
|
+
: { snapshots: evidence.mediaBackfills[change.target].snapshots }),
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
backfills.push(change.target);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
decided.push(Object.freeze({
|
|
347
|
+
...(affected === undefined ? {} : { affected }),
|
|
348
|
+
...(backfill === undefined ? {} : { backfill }),
|
|
349
|
+
class: change.class,
|
|
350
|
+
...(change.from === undefined ? {} : { from: change.from }),
|
|
351
|
+
...(change.hinted === undefined ? {} : { hinted: change.hinted }),
|
|
352
|
+
kind: change.kind,
|
|
353
|
+
...(migration === undefined ? {} : { migration }),
|
|
354
|
+
...(change.properties === undefined ? {} : { properties: change.properties }),
|
|
355
|
+
scope: change.scope,
|
|
356
|
+
target: change.target,
|
|
357
|
+
...(change.scope === "field" && change.target.startsWith("/")
|
|
358
|
+
? { schemaPath: change.target }
|
|
359
|
+
: {}),
|
|
360
|
+
...(violations === undefined ? {} : { violations }),
|
|
361
|
+
}));
|
|
362
|
+
}
|
|
363
|
+
if (evidence !== undefined && evidence.oversized.count > 0) {
|
|
364
|
+
refuse("BACKFILL_EXCEEDS_LIMIT", `Model ${modelKey} field rewrites would push ${evidence.oversized.count} snapshots above the content size, list-element or media-reference limit.`, {
|
|
365
|
+
affectedCount: evidence.oversized.count,
|
|
366
|
+
snapshots: evidence.oversized.snapshots,
|
|
367
|
+
fieldKey: changes.find((change) => change.scope === "field" && change.target.startsWith("/"))?.target,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return {
|
|
371
|
+
evolution: Object.freeze({
|
|
372
|
+
backfills: Object.freeze(backfills.sort()),
|
|
373
|
+
...([
|
|
374
|
+
...Object.values(current.fields),
|
|
375
|
+
...Object.values((stored.structure?.fields ?? {})),
|
|
376
|
+
].some((field) => field.type === "group" || field.type === "list")
|
|
377
|
+
? { recursiveFields: true }
|
|
378
|
+
: {}),
|
|
379
|
+
...(blockRemovals.length === 0 ? {} : { blockRemovals: Object.freeze(blockRemovals.sort()) }),
|
|
380
|
+
changes: Object.freeze(decided),
|
|
381
|
+
...(fieldRemovals.length === 0 ? {} : { fieldRemovals: Object.freeze(fieldRemovals.sort()) }),
|
|
382
|
+
...(blockMigrations.length === 0
|
|
383
|
+
? {}
|
|
384
|
+
: {
|
|
385
|
+
migrations: Object.freeze(blockMigrations.sort((left, right) => left.blockType.localeCompare(right.blockType))),
|
|
386
|
+
}),
|
|
387
|
+
...(renames.length === 0
|
|
388
|
+
? {}
|
|
389
|
+
: {
|
|
390
|
+
renames: Object.freeze(renames.sort((left, right) => left.to.localeCompare(right.to))),
|
|
391
|
+
}),
|
|
392
|
+
...(seoRemoval ? { seoRemoval: true } : {}),
|
|
393
|
+
snapshots: evidence?.snapshots ?? storedCounts,
|
|
394
|
+
}),
|
|
395
|
+
refused,
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
/** Whether a block definition change also changes the block version. */
|
|
399
|
+
function versionedBlockChange(change) {
|
|
400
|
+
return (change.kind === "block-definition-changed" &&
|
|
401
|
+
change.version !== undefined &&
|
|
402
|
+
change.version.from !== change.version.to);
|
|
57
403
|
}
|
|
58
|
-
|
|
404
|
+
/** Refuses a block migration on any finding; otherwise plans it when blocks are stale. */
|
|
405
|
+
function decideBlockMigration(modelKey, blockType, facts) {
|
|
406
|
+
const to = facts.toVersion;
|
|
407
|
+
const groups = [
|
|
408
|
+
[
|
|
409
|
+
"missing",
|
|
410
|
+
"BLOCK_MIGRATION_MISSING",
|
|
411
|
+
`Block type ${blockType} of model ${modelKey} has ${facts.missing.count} stored blocks without a migration path to version ${to}; declare migrations for every version after the oldest stored one.`,
|
|
412
|
+
],
|
|
413
|
+
[
|
|
414
|
+
"ahead",
|
|
415
|
+
"BLOCK_VERSION_AHEAD",
|
|
416
|
+
`Block type ${blockType} of model ${modelKey} has ${facts.ahead.count} stored blocks newer than the configured version ${to}.`,
|
|
417
|
+
],
|
|
418
|
+
[
|
|
419
|
+
"failed",
|
|
420
|
+
"BLOCK_MIGRATION_FAILED",
|
|
421
|
+
`Block type ${blockType} migration to version ${to} failed for ${facts.failed.count} stored blocks of model ${modelKey}.`,
|
|
422
|
+
],
|
|
423
|
+
[
|
|
424
|
+
"invalid",
|
|
425
|
+
"BLOCK_MIGRATION_INVALID",
|
|
426
|
+
`Block type ${blockType} migration to version ${to} produced ${facts.invalid.count} invalid blocks in model ${modelKey}.`,
|
|
427
|
+
],
|
|
428
|
+
];
|
|
429
|
+
const refusals = [];
|
|
430
|
+
for (const [key, code, message] of groups) {
|
|
431
|
+
const findings = facts[key];
|
|
432
|
+
if (findings.count > 0)
|
|
433
|
+
refusals.push({ code, findings, message });
|
|
434
|
+
}
|
|
435
|
+
return { planned: refusals.length === 0 && facts.blocks > 0, refusals };
|
|
436
|
+
}
|
|
437
|
+
function classifyMatchedModel(current, stored, context) {
|
|
438
|
+
const { diagnostics } = context;
|
|
439
|
+
const model = copyModel(current);
|
|
59
440
|
if (model.kind !== stored.kind) {
|
|
60
441
|
diagnostics.push(diagnostic("MODEL_KIND_CHANGED", model.key, `Model ${model.key} changes kind from ${stored.kind} to ${model.kind}.`));
|
|
61
442
|
return incompatible(model, stored);
|
|
@@ -64,21 +445,58 @@ function classifyMatchedModel(model, stored, diagnostics) {
|
|
|
64
445
|
diagnostics.push(diagnostic("VERSION_REGRESSION", model.key, `Model ${model.key} regresses version from ${stored.version} to ${model.version}.`));
|
|
65
446
|
return incompatible(model, stored);
|
|
66
447
|
}
|
|
67
|
-
const
|
|
448
|
+
const hasBaseline = stored.structure !== undefined;
|
|
449
|
+
const legacyMatch = !hasBaseline &&
|
|
450
|
+
current.legacyStructureHash !== undefined &&
|
|
451
|
+
current.legacyStructureHash === stored.structureHash;
|
|
452
|
+
const structureChanged = model.structureHash !== stored.structureHash && !legacyMatch;
|
|
68
453
|
if (structureChanged && model.version === stored.version) {
|
|
69
454
|
diagnostics.push(diagnostic("STRUCTURE_CHANGE_NEEDS_VERSION_BUMP", model.key, `Model ${model.key} changes structure without increasing version ${model.version}.`));
|
|
70
455
|
return incompatible(model, stored);
|
|
71
456
|
}
|
|
72
|
-
|
|
73
|
-
|
|
457
|
+
let evolution;
|
|
458
|
+
if (structureChanged && hasBaseline && current.structure !== undefined) {
|
|
459
|
+
const hints = {
|
|
460
|
+
...(current.removedBlocks === undefined ? {} : { removedBlocks: current.removedBlocks }),
|
|
461
|
+
...(current.removedFields === undefined ? {} : { removedFields: current.removedFields }),
|
|
462
|
+
...(current.renamedFields === undefined ? {} : { renamedFields: current.renamedFields }),
|
|
463
|
+
...(current.kind !== "global" && current.removedSeo === true ? { removedSeo: true } : {}),
|
|
464
|
+
};
|
|
465
|
+
const issues = validateStructureHints(stored.structure, hints);
|
|
466
|
+
for (const issue of issues) {
|
|
467
|
+
diagnostics.push(issue.kind === "target-exists"
|
|
468
|
+
? diagnostic("FIELD_RENAME_TARGET_EXISTS", model.key, `Model ${model.key} renames field ${issue.from} to ${issue.target}, but the stored structure already has both fields.`, { fieldKey: issue.target })
|
|
469
|
+
: diagnostic("FIELD_RENAME_SOURCE_MISSING", model.key, `Model ${model.key} renames field ${issue.from} to ${issue.target}, but the stored structure has neither field.`, { fieldKey: issue.target }));
|
|
470
|
+
}
|
|
471
|
+
if (issues.length > 0)
|
|
472
|
+
return incompatible(model, stored);
|
|
473
|
+
const decided = decideEvolution(current, stored, diffContentModelStructures(stored.structure, current.structure, hints), context);
|
|
474
|
+
if (decided.refused)
|
|
475
|
+
return incompatible(model, stored, decided.evolution);
|
|
476
|
+
evolution = decided.evolution;
|
|
477
|
+
}
|
|
478
|
+
else if (structureChanged && hasSnapshots(stored)) {
|
|
479
|
+
if (current.structure === undefined) {
|
|
480
|
+
diagnostics.push(diagnostic("STRUCTURE_CHANGE_HAS_SNAPSHOTS", model.key, `Model ${model.key} changes structure while snapshots exist (${snapshotDescription(stored)}).`));
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
diagnostics.push(diagnostic("STRUCTURE_BASELINE_MISSING", model.key, `Model ${model.key} changes structure while snapshots exist (${snapshotDescription(stored)}) and no structure baseline is stored. Restore the previous definition, run content sync once to record a baseline, then apply the change.`));
|
|
484
|
+
}
|
|
74
485
|
return incompatible(model, stored);
|
|
75
486
|
}
|
|
76
487
|
if (structureChanged || model.version > stored.version) {
|
|
77
|
-
return Object.freeze({
|
|
488
|
+
return Object.freeze({
|
|
489
|
+
action: "version-update",
|
|
490
|
+
...(evolution === undefined ? {} : { evolution }),
|
|
491
|
+
model,
|
|
492
|
+
});
|
|
78
493
|
}
|
|
79
494
|
if (model.projectionHash !== stored.projectionHash) {
|
|
80
495
|
return Object.freeze({ action: "label-update", model });
|
|
81
496
|
}
|
|
497
|
+
if ((!hasBaseline || legacyMatch) && current.structure !== undefined) {
|
|
498
|
+
return Object.freeze({ action: "record-baseline", model });
|
|
499
|
+
}
|
|
82
500
|
return undefined;
|
|
83
501
|
}
|
|
84
502
|
function modelForStoredState(stored) {
|
|
@@ -93,9 +511,8 @@ function modelForStoredState(stored) {
|
|
|
93
511
|
function operationKey(operation) {
|
|
94
512
|
return operation.model.key;
|
|
95
513
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const diagnostics = [];
|
|
514
|
+
function planWithContext(input, context) {
|
|
515
|
+
const { diagnostics } = context;
|
|
99
516
|
const operations = [];
|
|
100
517
|
const currentModels = [...input.models].sort(compareByKey);
|
|
101
518
|
const storedModels = [...input.storedModels].map(copyStoredModel).sort(compareByKey);
|
|
@@ -126,7 +543,7 @@ export function planConfigurationSynchronization(input) {
|
|
|
126
543
|
const stored = storedByKey.get(model.key);
|
|
127
544
|
if (stored !== undefined && !duplicateStoredKeys.has(model.key)) {
|
|
128
545
|
consumedStoredKeys.add(stored.key);
|
|
129
|
-
const operation = classifyMatchedModel(
|
|
546
|
+
const operation = classifyMatchedModel(current, stored, context);
|
|
130
547
|
if (operation !== undefined)
|
|
131
548
|
operations.push(operation);
|
|
132
549
|
continue;
|
|
@@ -151,12 +568,18 @@ export function planConfigurationSynchronization(input) {
|
|
|
151
568
|
operations.push(incompatible(model, former));
|
|
152
569
|
continue;
|
|
153
570
|
}
|
|
154
|
-
const transition = classifyMatchedModel(
|
|
571
|
+
const transition = classifyMatchedModel(current, former, context);
|
|
155
572
|
if (transition?.action === "incompatible-change") {
|
|
156
573
|
operations.push(transition);
|
|
157
574
|
continue;
|
|
158
575
|
}
|
|
159
|
-
|
|
576
|
+
const evolution = transition?.action === "version-update" ? transition.evolution : undefined;
|
|
577
|
+
operations.push(Object.freeze({
|
|
578
|
+
action: "rename",
|
|
579
|
+
...(evolution === undefined ? {} : { evolution }),
|
|
580
|
+
model,
|
|
581
|
+
renamedFrom: former.key,
|
|
582
|
+
}));
|
|
160
583
|
}
|
|
161
584
|
for (const stored of storedModels) {
|
|
162
585
|
if (consumedStoredKeys.has(stored.key) || duplicateStoredKeys.has(stored.key))
|
|
@@ -181,11 +604,89 @@ export function planConfigurationSynchronization(input) {
|
|
|
181
604
|
requiresApply: isValid && frozenOperations.length > 0,
|
|
182
605
|
});
|
|
183
606
|
}
|
|
607
|
+
/** Plans configuration identity reconciliation without reading or mutating a runtime adapter. */
|
|
608
|
+
export function planConfigurationSynchronization(input) {
|
|
609
|
+
return planWithContext(input, { diagnostics: [], evidence: input.evidence, scanRequests: [] });
|
|
610
|
+
}
|
|
611
|
+
/** Lists the populated models whose structural changes must be decided from stored snapshots. */
|
|
612
|
+
export function planConfigurationSyncScans(input) {
|
|
613
|
+
const context = { diagnostics: [], evidence: undefined, scanRequests: [] };
|
|
614
|
+
planWithContext(input, context);
|
|
615
|
+
return Object.freeze([...context.scanRequests].sort((left, right) => left.modelKey.localeCompare(right.modelKey)));
|
|
616
|
+
}
|
|
617
|
+
/** Field defaults an applied operation writes into snapshots lacking the field. */
|
|
618
|
+
export function configurationSyncBackfills(operation, model) {
|
|
619
|
+
if (operation.action !== "version-update" && operation.action !== "rename")
|
|
620
|
+
return [];
|
|
621
|
+
return (operation.evolution?.backfills ?? []).map((fieldKey) => {
|
|
622
|
+
const definition = schemaFieldAt(model.fields, parseSchemaPath(fieldKey));
|
|
623
|
+
if (definition?.defaultValue === undefined) {
|
|
624
|
+
throw new DomainError("CONTENT_INVALID_STATE", `Backfill field ${fieldKey} has no configured default.`);
|
|
625
|
+
}
|
|
626
|
+
return Object.freeze({
|
|
627
|
+
fieldKey,
|
|
628
|
+
json: canonicalizeJson(definition.defaultValue),
|
|
629
|
+
});
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Ordered content writes of an applied operation: field renames, field
|
|
634
|
+
* removals, block-type removals, SEO removal, then default backfills.
|
|
635
|
+
*/
|
|
636
|
+
export function configurationSyncContentWrites(operation, model) {
|
|
637
|
+
if (operation.action !== "version-update" && operation.action !== "rename")
|
|
638
|
+
return [];
|
|
639
|
+
const evolution = operation.evolution;
|
|
640
|
+
if (evolution === undefined)
|
|
641
|
+
return [];
|
|
642
|
+
return Object.freeze([
|
|
643
|
+
...(evolution.recursiveFields ? [] : (evolution.renames ?? [])).map((rename) => Object.freeze({ action: "rename-field", from: rename.from, to: rename.to })),
|
|
644
|
+
...(evolution.recursiveFields ? [] : (evolution.fieldRemovals ?? [])).map((fieldKey) => Object.freeze({ action: "remove-field", fieldKey })),
|
|
645
|
+
...(evolution.blockRemovals ?? []).map((blockType) => Object.freeze({ action: "remove-block-type", blockType })),
|
|
646
|
+
...(evolution.seoRemoval === true ? [Object.freeze({ action: "remove-seo" })] : []),
|
|
647
|
+
...(evolution.recursiveFields ? [] : configurationSyncBackfills(operation, model)).map((backfill) => Object.freeze({ action: "backfill-field", ...backfill })),
|
|
648
|
+
]);
|
|
649
|
+
}
|
|
650
|
+
/** Canonical baseline JSON an applied model write stores, or null without a structure. */
|
|
651
|
+
export function configurationSyncBaseline(model) {
|
|
652
|
+
return model.structure === undefined
|
|
653
|
+
? { hash: null, json: null }
|
|
654
|
+
: { hash: model.structureHash, json: canonicalizeJson(model.structure) };
|
|
655
|
+
}
|
|
656
|
+
/** Whether applying a plan changes public projections or published content. */
|
|
657
|
+
export function configurationSyncAdvancesPublicState(plan) {
|
|
658
|
+
return plan.operations.some((operation) => operation.action !== "record-baseline");
|
|
659
|
+
}
|
|
184
660
|
export function checkConfigurationSynchronization(plan) {
|
|
185
661
|
return Object.freeze({ exitCode: plan.isValid && !plan.requiresApply ? 0 : 1, plan });
|
|
186
662
|
}
|
|
663
|
+
function reportedOperation(operation) {
|
|
664
|
+
if (operation.action !== "incompatible-change" && operation.action !== "blocked-removal") {
|
|
665
|
+
return operation;
|
|
666
|
+
}
|
|
667
|
+
return { ...operation, stored: reportedStoredModel(operation.stored) };
|
|
668
|
+
}
|
|
187
669
|
export function renderConfigurationSyncPlanJson(plan) {
|
|
188
|
-
return JSON.stringify(plan);
|
|
670
|
+
return JSON.stringify({ ...plan, operations: plan.operations.map(reportedOperation) });
|
|
671
|
+
}
|
|
672
|
+
function changeLine(change) {
|
|
673
|
+
const details = [];
|
|
674
|
+
if (change.from !== undefined)
|
|
675
|
+
details.push(`from ${change.from}`);
|
|
676
|
+
if (change.hinted === true)
|
|
677
|
+
details.push("hinted");
|
|
678
|
+
if (change.migration !== undefined)
|
|
679
|
+
details.push(`version ${change.migration.from.join(",")} -> ${change.migration.to}`);
|
|
680
|
+
if (change.properties !== undefined)
|
|
681
|
+
details.push(change.properties.join(", "));
|
|
682
|
+
if (change.affected !== undefined)
|
|
683
|
+
details.push(`affected: ${countsDescription(change.affected)}`);
|
|
684
|
+
if (change.violations !== undefined)
|
|
685
|
+
details.push(`violations: ${change.violations}`);
|
|
686
|
+
if (change.backfill !== undefined)
|
|
687
|
+
details.push(`backfill: ${countsDescription(change.backfill)}`);
|
|
688
|
+
const suffix = details.length === 0 ? "" : ` (${details.join("; ")})`;
|
|
689
|
+
return ` ${change.class} ${change.kind} ${change.scope} ${change.target}${suffix}`;
|
|
189
690
|
}
|
|
190
691
|
export function renderConfigurationSyncPlanText(plan) {
|
|
191
692
|
const lines = [
|
|
@@ -198,6 +699,35 @@ export function renderConfigurationSyncPlanText(plan) {
|
|
|
198
699
|
for (const operation of plan.operations) {
|
|
199
700
|
const rename = operation.action === "rename" ? ` from ${operation.renamedFrom}` : "";
|
|
200
701
|
lines.push(`- ${operation.action} ${operation.model.key}${rename}`);
|
|
702
|
+
const evolution = operation.action === "version-update" ||
|
|
703
|
+
operation.action === "rename" ||
|
|
704
|
+
operation.action === "incompatible-change"
|
|
705
|
+
? operation.evolution
|
|
706
|
+
: undefined;
|
|
707
|
+
if (evolution === undefined)
|
|
708
|
+
continue;
|
|
709
|
+
lines.push(` snapshots: ${countsDescription(evolution.snapshots)}`);
|
|
710
|
+
for (const change of evolution.changes)
|
|
711
|
+
lines.push(changeLine(change));
|
|
712
|
+
if (evolution.renames !== undefined) {
|
|
713
|
+
const renames = evolution.renames.map((rename) => `${rename.from} -> ${rename.to}`);
|
|
714
|
+
lines.push(` planned renames: ${renames.join(", ")}`);
|
|
715
|
+
}
|
|
716
|
+
if (evolution.fieldRemovals !== undefined) {
|
|
717
|
+
lines.push(` planned field removals: ${evolution.fieldRemovals.join(", ")}`);
|
|
718
|
+
}
|
|
719
|
+
if (evolution.blockRemovals !== undefined) {
|
|
720
|
+
lines.push(` planned block removals: ${evolution.blockRemovals.join(", ")}`);
|
|
721
|
+
}
|
|
722
|
+
if (evolution.seoRemoval === true)
|
|
723
|
+
lines.push(" planned SEO removal: all snapshots");
|
|
724
|
+
if (evolution.migrations !== undefined) {
|
|
725
|
+
const migrations = evolution.migrations.map((migration) => `${migration.blockType} ${migration.fromVersions.join(",")} -> ${migration.toVersion} (draft=${migration.draft}, published=${migration.published}, blocks=${migration.blocks})`);
|
|
726
|
+
lines.push(` planned block migrations: ${migrations.join(", ")}`);
|
|
727
|
+
}
|
|
728
|
+
if (evolution.backfills.length > 0) {
|
|
729
|
+
lines.push(` planned backfills: ${evolution.backfills.join(", ")}`);
|
|
730
|
+
}
|
|
201
731
|
}
|
|
202
732
|
lines.push("Diagnostics:");
|
|
203
733
|
if (plan.diagnostics.length === 0)
|
|
@@ -205,6 +735,19 @@ export function renderConfigurationSyncPlanText(plan) {
|
|
|
205
735
|
for (const value of plan.diagnostics) {
|
|
206
736
|
const related = value.relatedModelKey === undefined ? "" : ` (${value.relatedModelKey})`;
|
|
207
737
|
lines.push(`- [${value.code}] ${value.modelKey}${related}: ${value.message}`);
|
|
738
|
+
for (const snapshot of value.snapshots ?? []) {
|
|
739
|
+
const block = snapshot.blockKey === undefined
|
|
740
|
+
? ""
|
|
741
|
+
: ` block ${snapshot.blockKey}${snapshot.schemaVersion === undefined ? "" : ` v${snapshot.schemaVersion}`}`;
|
|
742
|
+
const at = snapshot.path === undefined || snapshot.path === "" ? "" : ` at ${snapshot.path}`;
|
|
743
|
+
const cause = snapshot.reason === undefined ? "" : `: ${snapshot.reason}`;
|
|
744
|
+
lines.push(` ${snapshot.state} ${snapshot.entryId} "${snapshot.title}"${block}${at}${cause}`);
|
|
745
|
+
}
|
|
746
|
+
if (value.snapshots !== undefined &&
|
|
747
|
+
value.affectedCount !== undefined &&
|
|
748
|
+
value.affectedCount > value.snapshots.length) {
|
|
749
|
+
lines.push(` … and ${value.affectedCount - value.snapshots.length} more`);
|
|
750
|
+
}
|
|
208
751
|
}
|
|
209
752
|
return lines.join("\n");
|
|
210
753
|
}
|
|
@@ -215,24 +758,138 @@ export function reportConfigurationSynchronization(plan) {
|
|
|
215
758
|
text: renderConfigurationSyncPlanText(plan),
|
|
216
759
|
});
|
|
217
760
|
}
|
|
218
|
-
|
|
761
|
+
function registryError(message) {
|
|
762
|
+
throw new DomainError("CONTENT_INVALID_STATE", message);
|
|
763
|
+
}
|
|
764
|
+
/** Executable definitions of the migrated block types, checked against their configured versions. */
|
|
765
|
+
function migrationDefinitions(blocks, targets) {
|
|
766
|
+
if (blocks === undefined) {
|
|
767
|
+
registryError("The block registry is required to migrate stored blocks.");
|
|
768
|
+
}
|
|
769
|
+
const definitions = new Map();
|
|
770
|
+
for (const target of targets) {
|
|
771
|
+
const definition = blocks.get(target.type);
|
|
772
|
+
if (definition?.version !== target.version) {
|
|
773
|
+
registryError(`The block registry does not define block type ${target.type} at version ${target.version}.`);
|
|
774
|
+
}
|
|
775
|
+
definitions.set(target.type, definition);
|
|
776
|
+
}
|
|
777
|
+
return definitions;
|
|
778
|
+
}
|
|
779
|
+
/** Scans one model's snapshots, and its stale blocks when migrations apply, through the read port. */
|
|
780
|
+
async function scanModel(state, request, blocks) {
|
|
781
|
+
const accumulator = createSnapshotEvidenceAccumulator(request);
|
|
782
|
+
let after;
|
|
783
|
+
do {
|
|
784
|
+
const page = await state.readConfigurationSyncSnapshots({
|
|
785
|
+
...(after === undefined ? {} : { after }),
|
|
786
|
+
limit: CONFIGURATION_SYNC_SCAN_PAGE_SIZE,
|
|
787
|
+
modelKey: contentModelKey(request.modelKey),
|
|
788
|
+
});
|
|
789
|
+
accumulator.add(page.items.map((snapshot) => {
|
|
790
|
+
if (request.migrations === undefined || blocks === undefined)
|
|
791
|
+
return snapshot;
|
|
792
|
+
const definitions = migrationDefinitions(blocks, request.migrations);
|
|
793
|
+
const migrationSnapshot = {
|
|
794
|
+
blocks: snapshot.blocks.map((block, position) => ({
|
|
795
|
+
...block,
|
|
796
|
+
position,
|
|
797
|
+
data: block.data ?? {},
|
|
798
|
+
hidden: block.hidden ?? false,
|
|
799
|
+
})),
|
|
800
|
+
fields: snapshot.fields,
|
|
801
|
+
references: snapshot.references ?? [],
|
|
802
|
+
revision: snapshot.revision,
|
|
803
|
+
snapshotId: snapshot.snapshotId,
|
|
804
|
+
state: snapshot.state,
|
|
805
|
+
title: snapshot.title,
|
|
806
|
+
};
|
|
807
|
+
const planned = planEntryMigration({ entryId: snapshot.entryId, [snapshot.state]: migrationSnapshot }, definitions, contentSyncActor.id, {
|
|
808
|
+
fields: request.storedFields ?? request.fields,
|
|
809
|
+
blocks: new Map(blocks.blocks.map((block) => [block.type, block])),
|
|
810
|
+
});
|
|
811
|
+
const rewrite = planned.unit?.snapshots[0];
|
|
812
|
+
if (rewrite === undefined)
|
|
813
|
+
return snapshot;
|
|
814
|
+
const rewritten = new Map(rewrite.blocks.map((block) => [block.key, block.data]));
|
|
815
|
+
return {
|
|
816
|
+
...snapshot,
|
|
817
|
+
blocks: snapshot.blocks.map((block) => ({
|
|
818
|
+
...block,
|
|
819
|
+
data: rewritten.get(block.key) ?? block.data ?? {},
|
|
820
|
+
})),
|
|
821
|
+
references: [
|
|
822
|
+
...(snapshot.references ?? []).filter((reference) => !rewritten.has(reference.sourceKey)),
|
|
823
|
+
...rewrite.references,
|
|
824
|
+
],
|
|
825
|
+
};
|
|
826
|
+
}));
|
|
827
|
+
after = page.next;
|
|
828
|
+
} while (after !== undefined);
|
|
829
|
+
const evidence = accumulator.result();
|
|
830
|
+
if (request.migrations === undefined)
|
|
831
|
+
return evidence;
|
|
832
|
+
const migrations = createMigrationEvidenceAccumulator(migrationDefinitions(blocks, request.migrations), contentSyncActor.id, {
|
|
833
|
+
fields: request.storedFields ?? request.fields,
|
|
834
|
+
blocks: new Map(blocks.blocks.map((block) => [block.type, block])),
|
|
835
|
+
});
|
|
836
|
+
do {
|
|
837
|
+
const page = await state.readConfigurationSyncMigrationEntries({
|
|
838
|
+
...(after === undefined ? {} : { after }),
|
|
839
|
+
limit: CONFIGURATION_SYNC_MIGRATION_PAGE_SIZE,
|
|
840
|
+
modelKey: contentModelKey(request.modelKey),
|
|
841
|
+
targets: request.migrations,
|
|
842
|
+
});
|
|
843
|
+
migrations.add(page.items);
|
|
844
|
+
after = page.next;
|
|
845
|
+
} while (after !== undefined);
|
|
846
|
+
return Object.freeze({ ...evidence, migrations: migrations.result() });
|
|
847
|
+
}
|
|
848
|
+
function assertRegistryCoversModels(models, blocks) {
|
|
849
|
+
for (const model of models) {
|
|
850
|
+
for (const type of model.blocks) {
|
|
851
|
+
if (blocks.get(type) === undefined) {
|
|
852
|
+
registryError(`Model ${model.key} allows block type ${type}, which the registry lacks.`);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Reads persistence once, scans data-dependent models, executes needed block
|
|
859
|
+
* migrations in memory, and produces the non-mutating decision.
|
|
860
|
+
*/
|
|
219
861
|
export async function prepareConfigurationSynchronization(input) {
|
|
862
|
+
if (input.blocks !== undefined)
|
|
863
|
+
assertRegistryCoversModels(input.models, input.blocks);
|
|
220
864
|
const storedModels = Object.freeze((await input.state.readConfigurationSyncState()).map(copyStoredModel).sort(compareByKey));
|
|
221
|
-
const
|
|
222
|
-
|
|
865
|
+
const evidence = {};
|
|
866
|
+
for (const request of planConfigurationSyncScans({ models: input.models, storedModels })) {
|
|
867
|
+
evidence[request.modelKey] = await scanModel(input.state, request, input.blocks);
|
|
868
|
+
}
|
|
869
|
+
const frozenEvidence = Object.freeze(evidence);
|
|
870
|
+
const plan = planConfigurationSynchronization({
|
|
871
|
+
evidence: frozenEvidence,
|
|
872
|
+
models: input.models,
|
|
873
|
+
storedModels,
|
|
874
|
+
});
|
|
875
|
+
return Object.freeze({
|
|
876
|
+
evidence: frozenEvidence,
|
|
877
|
+
plan,
|
|
878
|
+
report: reportConfigurationSynchronization(plan),
|
|
879
|
+
storedModels,
|
|
880
|
+
});
|
|
223
881
|
}
|
|
224
|
-
/** Creates the one incomplete draft that a newly synchronized page must own. */
|
|
225
|
-
export function
|
|
226
|
-
if (input.model.kind
|
|
227
|
-
throw new DomainError("CONTENT_INVALID_STATE", "Only page models receive synchronized entries.");
|
|
882
|
+
/** Creates the one incomplete draft that a newly synchronized page or global must own. */
|
|
883
|
+
export function createConfigurationSyncSingletonEntry(input) {
|
|
884
|
+
if (input.model.kind === "collection") {
|
|
885
|
+
throw new DomainError("CONTENT_INVALID_STATE", "Only page and global models receive synchronized entries.");
|
|
228
886
|
}
|
|
229
887
|
const entryId = contentEntryId(input.entryId);
|
|
230
888
|
const snapshotId = contentSnapshotId(input.snapshotId);
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
kind: "page",
|
|
234
|
-
|
|
235
|
-
});
|
|
889
|
+
const key = contentModelKey(input.model.key);
|
|
890
|
+
const model = Object.freeze(input.model.kind === "page"
|
|
891
|
+
? { key, kind: "page", path: input.model.path }
|
|
892
|
+
: { key, kind: "global" });
|
|
236
893
|
const entry = createContentEntry({
|
|
237
894
|
id: entryId,
|
|
238
895
|
model,
|
|
@@ -251,21 +908,139 @@ export function createConfigurationSyncPageEntry(input) {
|
|
|
251
908
|
});
|
|
252
909
|
return Object.freeze({ entry, modelKey: model.key });
|
|
253
910
|
}
|
|
254
|
-
/** Applies a freshly prepared valid plan and allocates identities only for
|
|
911
|
+
/** Applies a freshly prepared valid plan and allocates identities only for singleton creates. */
|
|
912
|
+
/** One operator line describing the stored blocks an apply migrated. */
|
|
913
|
+
export function configurationSyncMigrationSummary(counts) {
|
|
914
|
+
return `Migrated blocks: ${counts.blocks} (drafts=${counts.drafts}, published=${counts.published}).`;
|
|
915
|
+
}
|
|
916
|
+
/** Plan JSON without planned block migrations, which the migration phase consumes. */
|
|
917
|
+
function planJsonWithoutMigrations(plan) {
|
|
918
|
+
return renderConfigurationSyncPlanJson({
|
|
919
|
+
...plan,
|
|
920
|
+
operations: plan.operations.map((operation) => {
|
|
921
|
+
if (!("evolution" in operation) || operation.evolution === undefined)
|
|
922
|
+
return operation;
|
|
923
|
+
const { migrations: _migrations, ...evolution } = operation.evolution;
|
|
924
|
+
return {
|
|
925
|
+
...operation,
|
|
926
|
+
evolution: {
|
|
927
|
+
...evolution,
|
|
928
|
+
changes: evolution.changes.map(({ migration: _migration, ...change }) => change),
|
|
929
|
+
},
|
|
930
|
+
};
|
|
931
|
+
}),
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
/** Stored model keys and targets of every planned block migration. */
|
|
935
|
+
function plannedMigrations(plan) {
|
|
936
|
+
const planned = [];
|
|
937
|
+
for (const operation of plan.operations) {
|
|
938
|
+
if (operation.action !== "version-update" && operation.action !== "rename")
|
|
939
|
+
continue;
|
|
940
|
+
const migrations = operation.evolution?.migrations;
|
|
941
|
+
if (migrations === undefined)
|
|
942
|
+
continue;
|
|
943
|
+
planned.push({
|
|
944
|
+
modelKey: operation.action === "rename" ? operation.renamedFrom : operation.model.key,
|
|
945
|
+
targets: migrations.map((migration) => ({
|
|
946
|
+
type: migration.blockType,
|
|
947
|
+
version: migration.toVersion,
|
|
948
|
+
})),
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
return planned;
|
|
952
|
+
}
|
|
953
|
+
function staleSynchronization(message) {
|
|
954
|
+
throw new DomainError("CONTENT_INVALID_STATE", message);
|
|
955
|
+
}
|
|
956
|
+
/** Rewrites every stale block of the planned migrations in guarded per-entry units. */
|
|
957
|
+
async function migrateStoredBlocks(input, planned) {
|
|
958
|
+
const storedModels = await input.target.readConfigurationSyncState();
|
|
959
|
+
let blocks = 0;
|
|
960
|
+
let drafts = 0;
|
|
961
|
+
let published = 0;
|
|
962
|
+
for (const { modelKey, targets } of planned) {
|
|
963
|
+
const definitions = migrationDefinitions(input.blocks, targets);
|
|
964
|
+
let after;
|
|
965
|
+
do {
|
|
966
|
+
const page = await input.target.readConfigurationSyncMigrationEntries({
|
|
967
|
+
...(after === undefined ? {} : { after }),
|
|
968
|
+
limit: CONFIGURATION_SYNC_MIGRATION_PAGE_SIZE,
|
|
969
|
+
modelKey,
|
|
970
|
+
targets,
|
|
971
|
+
});
|
|
972
|
+
const units = [];
|
|
973
|
+
for (const entry of page.items) {
|
|
974
|
+
const model = input.models.find((model) => model.key === modelKey || model.renamedFrom === modelKey);
|
|
975
|
+
const migration = planEntryMigration(entry, definitions, contentSyncActor.id, {
|
|
976
|
+
fields: storedModels.find((stored) => stored.key === modelKey)?.structure
|
|
977
|
+
?.fields ??
|
|
978
|
+
model?.fields ??
|
|
979
|
+
{},
|
|
980
|
+
blocks: new Map(input.blocks.blocks.map((block) => [block.type, block])),
|
|
981
|
+
});
|
|
982
|
+
if (migration.findings.length > 0) {
|
|
983
|
+
staleSynchronization("Block migration results changed since planning; the synchronization plan is stale.");
|
|
984
|
+
}
|
|
985
|
+
if (migration.unit !== undefined)
|
|
986
|
+
units.push(migration.unit);
|
|
987
|
+
}
|
|
988
|
+
if (units.length > 0) {
|
|
989
|
+
const written = await input.target.applyConfigurationSyncBlockMigrations({
|
|
990
|
+
migratedAt: input.clock.now(),
|
|
991
|
+
modelKey,
|
|
992
|
+
units,
|
|
993
|
+
});
|
|
994
|
+
blocks += written.blocks;
|
|
995
|
+
drafts += written.drafts;
|
|
996
|
+
published += written.published;
|
|
997
|
+
}
|
|
998
|
+
after = page.next;
|
|
999
|
+
} while (after !== undefined);
|
|
1000
|
+
}
|
|
1001
|
+
return Object.freeze({ blocks, drafts, published });
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Applies a reviewed plan. Planned block migrations are first written in
|
|
1005
|
+
* guarded per-entry units; the plan is then prepared again from current state
|
|
1006
|
+
* and must match the reviewed plan apart from its migrations before the final
|
|
1007
|
+
* guarded mutation runs. A stale error leaves committed units in place, and a
|
|
1008
|
+
* rerun completes the remaining work.
|
|
1009
|
+
*/
|
|
255
1010
|
export async function applyPreparedConfigurationSynchronization(input) {
|
|
256
1011
|
if (!input.prepared.plan.isValid) {
|
|
257
1012
|
throw new DomainError("CONTENT_INVALID_STATE", "Configuration synchronization plan is invalid.");
|
|
258
1013
|
}
|
|
1014
|
+
let prepared = input.prepared;
|
|
1015
|
+
let migrated;
|
|
1016
|
+
const planned = plannedMigrations(prepared.plan);
|
|
1017
|
+
if (planned.length > 0) {
|
|
1018
|
+
migrated = await migrateStoredBlocks({ blocks: input.blocks, clock: input.clock, target: input.target, models: input.models }, planned);
|
|
1019
|
+
prepared = await prepareConfigurationSynchronization({
|
|
1020
|
+
...(input.blocks === undefined ? {} : { blocks: input.blocks }),
|
|
1021
|
+
models: input.models,
|
|
1022
|
+
state: input.target,
|
|
1023
|
+
});
|
|
1024
|
+
if (!prepared.plan.isValid ||
|
|
1025
|
+
plannedMigrations(prepared.plan).length > 0 ||
|
|
1026
|
+
planJsonWithoutMigrations(prepared.plan) !== planJsonWithoutMigrations(input.prepared.plan)) {
|
|
1027
|
+
staleSynchronization("Configuration synchronization plan is stale after block migration.");
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
const result = await applyFinalMutation(input, prepared);
|
|
1031
|
+
return migrated === undefined ? result : Object.freeze({ ...result, migrated });
|
|
1032
|
+
}
|
|
1033
|
+
async function applyFinalMutation(input, prepared) {
|
|
259
1034
|
const models = new Map(input.models.map((model) => [model.key, model]));
|
|
260
1035
|
const appliedAt = input.clock.now();
|
|
261
|
-
const
|
|
262
|
-
for (const operation of
|
|
1036
|
+
const singletonEntries = [];
|
|
1037
|
+
for (const operation of prepared.plan.operations) {
|
|
263
1038
|
if (operation.action !== "create")
|
|
264
1039
|
continue;
|
|
265
1040
|
const model = models.get(operation.model.key);
|
|
266
|
-
if (model
|
|
1041
|
+
if (model === undefined || !isSingletonKind(model.kind))
|
|
267
1042
|
continue;
|
|
268
|
-
|
|
1043
|
+
singletonEntries.push(createConfigurationSyncSingletonEntry({
|
|
269
1044
|
appliedAt,
|
|
270
1045
|
entryId: input.ids.next(),
|
|
271
1046
|
model,
|
|
@@ -274,10 +1049,11 @@ export async function applyPreparedConfigurationSynchronization(input) {
|
|
|
274
1049
|
}
|
|
275
1050
|
return input.target.applyConfigurationSynchronization({
|
|
276
1051
|
appliedAt,
|
|
277
|
-
|
|
1052
|
+
evidence: prepared.evidence,
|
|
1053
|
+
expectedStoredModels: prepared.storedModels,
|
|
278
1054
|
models: input.models,
|
|
279
|
-
|
|
280
|
-
plan:
|
|
1055
|
+
singletonEntries,
|
|
1056
|
+
plan: prepared.plan,
|
|
281
1057
|
});
|
|
282
1058
|
}
|
|
283
1059
|
//# sourceMappingURL=configuration-sync.js.map
|