@lacecms/application 0.1.0-alpha.8 → 0.1.0-rc2

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