@coraltravelcenter/b2c-landing-builder 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import crypto from "node:crypto";
2
2
 
3
- import {findMissingRemoteAssets, planAssetChanges, uploadChangedAssets} from "./assets.mjs";
3
+ import {findMissingRemoteAssets, uploadChangedAssets, remoteAssetReader} from "./assets.mjs";
4
4
  import {BackofficeClient} from "./backoffice-client.mjs";
5
5
  import {readBuildManifest} from "./manifest.mjs";
6
6
  import {
@@ -28,14 +28,6 @@ import {
28
28
  import {localSections, planWidgetChanges, remoteSections, syncWidgets} from "./widgets.mjs";
29
29
  import {createTerminalUi} from "../cli/terminal-ui.mjs";
30
30
 
31
- function paths(items) {
32
- return items.map((item) => item.path);
33
- }
34
-
35
- function logList(log, label, items) {
36
- log(`[dry-run] ${label}: ${items.length ? items.join(", ") : "none"}`);
37
- }
38
-
39
31
  export async function createCmsTerminalUi({terminal, embedded = false, project} = {}) {
40
32
  terminal ||= await createTerminalUi();
41
33
  const list = (prefix, items) => items.map((item) => `${prefix} ${item}`).join("\n");
@@ -73,6 +65,15 @@ function sectionScope(local, remote, base, section) {
73
65
  return [...new Set([...Object.keys(local), ...Object.keys(remote), ...Object.keys(base || {})])];
74
66
  }
75
67
 
68
+ function sectionHistory(state, placement) {
69
+ const cms = state.cms;
70
+ if ((cms?.pageContentId && cms.pageContentId !== placement.pageContentId) ||
71
+ (cms?.layoutAreaId && cms.layoutAreaId !== placement.layoutAreaId)) {
72
+ return {base: null, localBase: null};
73
+ }
74
+ return {base: cms?.sections || null, localBase: cms?.localSections || null};
75
+ }
76
+
76
77
  function visibleWidgetPlan(plan) {
77
78
  return {add: plan.add, update: plan.update, remove: plan.remove, reorder: plan.reorder};
78
79
  }
@@ -84,116 +85,46 @@ function backofficePageUrl(preset, pageContentId) {
84
85
  return String(url);
85
86
  }
86
87
 
87
- export async function planDeployment({
88
- config,
89
- preset,
90
- root = process.cwd(),
91
- token,
92
- client,
93
- update = false,
94
- assetsOnly = false,
95
- relink = false,
96
- pruneAssets = false,
97
- publish = false,
98
- section = null,
99
- strategy = "ask",
100
- prompts,
101
- log = console.log,
88
+ export async function deploymentStatus({
89
+ config, preset, root = process.cwd(), token, getToken, client, section = null, prompts, log = console.log,
102
90
  }) {
103
91
  const manifest = readBuildManifest(root);
104
- const api = client || new BackofficeClient({brand: preset.id, token});
92
+ if (manifest.project !== config.project.name || manifest.site !== preset.id) {
93
+ throw new Error("Build manifest does not match the current project. Run build again.");
94
+ }
95
+ if (section && !manifest.blocks.some((block) => block.path === `${section}.html`)) {
96
+ throw new Error(`Section ${JSON.stringify(section)} not found in the last build. Run build if the source changed.`);
97
+ }
98
+ log("Comparing the last build in @CMS/; source changes since build are not included. Run build to refresh it.");
105
99
  const previous = readDeploymentState(preset.id, manifest.folder, root);
106
100
  const binding = readDeploymentBinding(preset.id, manifest.folder, root);
107
101
  const pending = readPendingDeployment(preset.id, manifest.folder, root);
108
- if (section && !manifest.blocks.some((block) => block.path === `${section}.html`)) {
109
- const available = manifest.blocks.map((block) => block.path.replace(/\.html$/, ""));
110
- throw new Error(`Section ${JSON.stringify(section)} not found. Available sections: ${available.join(", ") || "none"}`);
111
- }
112
- if (pending && pending.scope !== (section || null)) {
113
- const expected = pending.scope ? `deploy --dry-run --section ${pending.scope}` : "deploy --dry-run";
114
- throw new Error(`Incomplete deploy ${pending.deploymentId} has a different scope. Run b2c-landing-vite ${expected}.`);
115
- }
116
- log("[dry-run] checking CDN and CMS state...");
117
- const assets = await planAssetChanges({
118
- manifest,
119
- state: previous,
120
- remoteRoot: new URL(preset.assetsBase).pathname,
121
- listFiles: api.listFiles?.bind(api),
122
- prune: pruneAssets,
123
- });
124
- log(`[dry-run] no CMS data will be changed`);
125
- log(`[dry-run] target: ${preset.assetsBase}/${manifest.assetsPrefix}/`);
126
- logList(log, "assets to upload", paths(assets.upload));
127
- logList(log, "existing assets to skip", paths(assets.skip));
128
- logList(log, "immutable asset conflicts", paths(assets.conflicts));
129
- logList(log, "managed assets to remove", assets.remove);
130
- log(`[dry-run] unchanged assets: ${assets.unchanged}`);
131
- if (assetsOnly) return {assets};
132
- if (assets.conflicts.length) {
133
- log("[dry-run] CMS plan is blocked by immutable asset conflicts");
134
- return {assets, blocked: "immutable-assets"};
135
- }
136
-
137
- let placement;
138
- let pageContent;
139
- let page;
140
102
  if (pending) {
141
- placement = pending.placement;
142
- pageContent = await validateSavedPlacement({client: api, placement});
143
- page = {action: "resume incomplete deploy", pageContentId: placement.pageContentId};
144
- } else if (relink) {
145
- const selected = await selectExistingPagePlacement({client: api, domain: preset.domain, prompts});
146
- placement = selected.placement;
147
- pageContent = selected.pageContent;
148
- const checkout = !update && [1, 4].includes(pageContent.status);
149
- page = {action: checkout ? "relink and create checkout version" : "relink and update selected version", pageContentId: placement.pageContentId};
150
- } else if (binding) {
151
- const selected = await selectBoundPagePlacement({client: api, binding, prompts});
152
- placement = selected.placement;
153
- pageContent = selected.pageContent;
154
- const checkout = !update && [1, 4].includes(pageContent.status);
155
- page = {action: checkout ? "create checkout version" : "update current version", pageContentId: placement.pageContentId};
156
- } else {
157
- const selected = await selectNewPagePlacement({client: api, manifest, prompts});
158
- placement = selected.placement;
159
- pageContent = {pageContents: []};
160
- page = {action: "create page", ...selected.draft};
103
+ log(`Incomplete deploy: ${pending.deploymentId} · ${pending.phase} · scope: ${pending.scope || "all sections"}`);
104
+ if (pending.phase === "preparing-target") log("Target creation result is uncertain; check Backoffice before resuming deploy.");
105
+ } else log("Incomplete deploy: none");
106
+ const pendingPlacement = pending?.placement || pending?.sourcePlacement;
107
+ if (!binding && !pendingPlacement) {
108
+ log("No saved CMS page binding. Run deploy to select or create a page.");
109
+ return {bound: false, pending};
161
110
  }
111
+ const api = client || new BackofficeClient({brand: preset.id, token: token || await getToken?.()});
112
+ const selected = pendingPlacement
113
+ ? {placement: pendingPlacement, pageContent: await validateSavedPlacement({client: api, placement: pendingPlacement})}
114
+ : await selectBoundPagePlacement({client: api, binding, prompts});
115
+ const {placement, pageContent} = selected;
116
+ log(`CMS version: ${placement.pageContentId} · ${versionLabel(pageContent)}`);
162
117
  const local = localSections(manifest, root);
163
118
  const remote = remoteSections(pageContent, placement, manifest.folder);
164
- const base = previous.cms?.sections || null;
165
- const reconciliation = page.action === "create page"
166
- ? null
167
- : resolveSections({
168
- local,
169
- remote,
170
- base,
171
- scope: sectionScope(local, remote, base, section),
172
- strategy: strategy === "ask" ? "merge" : strategy,
173
- });
174
- if (reconciliation?.unsafe.length) {
175
- log(`[dry-run] CMS plan is blocked by unresolved remote changes: ${reconciliation.unsafe.map(({id}) => id).join(", ")}`);
176
- return {assets, page, placement, reconciliation, blocked: "remote-changes"};
177
- }
178
- const widgets = planWidgetChanges({
179
- manifest,
180
- placement,
181
- pageContent,
182
- root,
183
- desiredSections: reconciliation?.sections || local,
184
- sectionIds: section ? [section] : null,
185
- });
186
- log(`[dry-run] page: ${page.action}${page.pageName ? ` “${page.pageName}”` : ""}`);
187
- log(`[dry-run] area: ${placement.layoutAreaId}, insertion position: ${Math.max(0, placement.orderIndex) + 1}`);
188
- logList(log, "widgets to add", widgets.add);
189
- logList(log, "widgets to update", widgets.update);
190
- logList(log, "widgets to remove", widgets.remove);
191
- logList(log, "widgets to reorder", widgets.reorder.map((item) => `${item.title} (${item.from} → ${item.to})`));
192
- if (publish) {
193
- const issues = publicationIssues(pageContent);
194
- log(`[dry-run] publish: ${issues.length ? `blocked (${issues.join(", ")})` : "page after widget sync"}`);
119
+ const {base, localBase} = sectionHistory(previous, placement);
120
+ const reconciliation = resolveSections({local, remote, base, localBase,
121
+ scope: sectionScope(local, remote, base, section)});
122
+ const summary = summarizeChanges(reconciliation.changes);
123
+ for (const [kind, ids] of Object.entries(summary)) {
124
+ log(`${kind}: ${ids.length ? ids.join(", ") : "none"}`);
195
125
  }
196
- return {assets, page, placement, widgets: visibleWidgetPlan(widgets), reconciliation, publish};
126
+ if (reconciliation.unsafe.length) log("Explicit resolution is required during deploy; no CMS changes were made.");
127
+ return {bound: true, pending, placement, summary, reconciliation};
197
128
  }
198
129
 
199
130
  export async function deployAssetsOnly({
@@ -224,6 +155,7 @@ export async function deployAssetsOnly({
224
155
  remoteRoot: new URL(preset.assetsBase).pathname,
225
156
  uploadFile: api.uploadFile.bind(api),
226
157
  listFiles: api.listFiles?.bind(api),
158
+ readRemoteAsset: api.readRemoteAsset?.bind(api) || remoteAssetReader(preset.assetsBase, api.fetchImpl),
227
159
  prune: pruneAssets,
228
160
  deleteFile: api.deleteFile?.bind(api),
229
161
  });
@@ -258,6 +190,9 @@ export async function deployProject({
258
190
  const available = manifest.blocks.map((block) => block.path.replace(/\.html$/, ""));
259
191
  throw new Error(`Section ${JSON.stringify(section)} not found. Available sections: ${available.join(", ") || "none"}`);
260
192
  }
193
+ if (pending?.phase === "preparing-target") {
194
+ throw new Error(`Deploy ${pending.deploymentId} has an uncertain page creation result. Check Backoffice before removing the pending journal; automatic creation was blocked to prevent duplicates.`);
195
+ }
261
196
  if (pending && pending.scope !== (section || null)) {
262
197
  const expected = pending.scope ? `deploy --section ${pending.scope}` : "deploy";
263
198
  throw new Error(
@@ -302,8 +237,15 @@ export async function deployProject({
302
237
  "The pending journal was preserved; review the checkout before running deploy again."
303
238
  );
304
239
  }
305
- selectedPage = {pageContent, placement: pending.placement, binding: pending.binding};
306
- nextBinding = pending.binding;
240
+ const recoveredBinding = pending.binding || {
241
+ ...pending.targetBinding,
242
+ pageId: pending.targetBinding?.pageId || pageContent.pageId ||
243
+ String(pending.placement.pageContentId).match(/^(Pages_\d+)_PageContents_\d+_V_\d+$/)?.[1],
244
+ lastPageContentId: pending.placement.pageContentId,
245
+ };
246
+ if (!recoveredBinding.pageId) throw new Error("Created CMS target is recorded but pageId is unknown; recover the binding from Backoffice before continuing.");
247
+ selectedPage = {pageContent, placement: pending.placement, binding: recoveredBinding};
248
+ nextBinding = recoveredBinding;
307
249
  ui.info(
308
250
  `Resuming incomplete deploy ${pending.deploymentId} on ${pending.placement.pageContentId}; ` +
309
251
  `${pending.completed.length} operation${pending.completed.length === 1 ? " was" : "s were"} completed previously`
@@ -338,14 +280,15 @@ export async function deployProject({
338
280
  }
339
281
 
340
282
  let reconciliation = null;
341
- let desiredSections = localSections(manifest, root);
283
+ const local = localSections(manifest, root);
284
+ let desiredSections = local;
285
+ const history = selectedPage ? sectionHistory(previous, selectedPage.placement) : {base: null, localBase: null};
342
286
  if (selectedPage) {
343
- const local = desiredSections;
344
287
  const remote = remoteSections(selectedPage.pageContent, selectedPage.placement, manifest.folder);
345
- const base = previous.cms?.sections || null;
288
+ const {base, localBase} = history;
346
289
  const scope = sectionScope(local, remote, base, section);
347
290
  let chosen = strategy;
348
- reconciliation = resolveSections({local, remote, base, scope, strategy: chosen === "ask" ? "merge" : chosen});
291
+ reconciliation = resolveSections({local, remote, base, localBase, scope, strategy: chosen === "ask" ? "merge" : chosen});
349
292
  if (reconciliation.changes.length) {
350
293
  const summary = summarizeChanges(reconciliation.changes);
351
294
  for (const [kind, ids] of Object.entries(summary)) if (ids.length) ui.info(`${kind}: ${ids.join(", ")}`);
@@ -360,7 +303,7 @@ export async function deployProject({
360
303
  ],
361
304
  });
362
305
  if (chosen === "cancel") throw new Error("Deploy cancelled; CMS was not modified");
363
- reconciliation = resolveSections({local, remote, base, scope, strategy: chosen});
306
+ reconciliation = resolveSections({local, remote, base, localBase, scope, strategy: chosen});
364
307
  } else if (reconciliation.unsafe.length) {
365
308
  throw new Error(`Deploy stopped: unresolved remote changes (${reconciliation.unsafe.map((item) => item.id).join(", ")})`);
366
309
  }
@@ -393,11 +336,34 @@ export async function deployProject({
393
336
  throw new Error("CMS page changed during deploy. Nothing was modified; run deploy again.");
394
337
  }
395
338
  }
339
+ let targetJournal;
340
+ const beforeTargetCreate = async () => {
341
+ const now = new Date().toISOString();
342
+ targetJournal = writePendingDeployment(preset.id, manifest.folder, {
343
+ deploymentId: pending?.deploymentId || crypto.randomUUID(),
344
+ startedAt: pending?.startedAt || now, updatedAt: now,
345
+ phase: "preparing-target", scope: section || null, completed: pending?.completed || [],
346
+ sourcePlacement: selectedPage?.placement,
347
+ draft: selectedDraft?.draft,
348
+ }, root);
349
+ };
350
+ const onTargetCreated = async (created) => {
351
+ const targetBinding = nextBinding || {
352
+ pageId: created.pageId,
353
+ applicationId: selectedDraft.draft.applicationId,
354
+ layoutAreaId: placement.layoutAreaId, orderIndex: placement.orderIndex,
355
+ };
356
+ targetJournal = writePendingDeployment(preset.id, manifest.folder, {
357
+ ...targetJournal, phase: "target-created", updatedAt: new Date().toISOString(),
358
+ placement: {...placement, pageContentId: created.pageContentId},
359
+ targetBinding: {...targetBinding, pageId: created.pageId || targetBinding.pageId},
360
+ }, root);
361
+ };
396
362
  const page = selectedPage
397
363
  ? widgetPlan.operations.length
398
- ? await prepareExistingPage({client: api, placement: selectedPage.placement})
364
+ ? await prepareExistingPage({client: api, placement: selectedPage.placement, beforeTargetCreate, onTargetCreated})
399
365
  : {pageContent: selectedPage.pageContent, placement: selectedPage.placement}
400
- : await createPagePlacement({client: api, manifest, prompts: ui, selected: selectedDraft});
366
+ : await createPagePlacement({client: api, manifest, prompts: ui, selected: selectedDraft, beforeTargetCreate, onTargetCreated});
401
367
  nextBinding = {...(page.binding || nextBinding), lastPageContentId: page.placement.pageContentId};
402
368
  if (selectedPage && page.placement.pageContentId === selectedPage.placement.pageContentId &&
403
369
  pageRevision(page.pageContent) !== pageRevision(selectedPage.pageContent)) {
@@ -419,8 +385,8 @@ export async function deployProject({
419
385
  if (executionPlan.operations.length) {
420
386
  const now = new Date().toISOString();
421
387
  let journal = writePendingDeployment(preset.id, manifest.folder, {
422
- deploymentId: pending?.deploymentId || crypto.randomUUID(),
423
- startedAt: pending?.startedAt || now,
388
+ deploymentId: pending?.deploymentId || targetJournal?.deploymentId || crypto.randomUUID(),
389
+ startedAt: pending?.startedAt || targetJournal?.startedAt || now,
424
390
  updatedAt: now,
425
391
  phase: "syncing-widgets",
426
392
  scope: section || null,
@@ -474,8 +440,27 @@ export async function deployProject({
474
440
  "review the checkout before running deploy again."
475
441
  );
476
442
  }
443
+ const remaining = planWidgetChanges({
444
+ manifest,
445
+ placement: page.placement,
446
+ pageContent: verifiedContent,
447
+ root,
448
+ desiredSections,
449
+ sectionIds: section ? [section] : null,
450
+ });
451
+ if (remaining.operations.length) {
452
+ throw new Error(
453
+ "CMS result does not match the confirmed widget plan. The pending journal was preserved; " +
454
+ "review the checkout before running deploy again."
455
+ );
456
+ }
477
457
  const remoteAfter = remoteSections(verifiedContent, page.placement, manifest.folder);
478
- const storedSections = section ? {...(previous.cms?.sections || {})} : remoteAfter;
458
+ const storedSections = section ? {...(history.base || {})} : remoteAfter;
459
+ const storedLocalSections = section ? {...(history.localBase || {})} : {};
460
+ for (const id of sectionScope(local, remoteAfter, history.base, section)) {
461
+ // null distinguishes a confirmed local absence from an unknown legacy snapshot.
462
+ storedLocalSections[id] = local[id] ?? null;
463
+ }
479
464
  if (section) {
480
465
  if (remoteAfter[section] === undefined) delete storedSections[section];
481
466
  else storedSections[section] = remoteAfter[section];
@@ -485,6 +470,9 @@ export async function deployProject({
485
470
  cms: {
486
471
  verifiedAt: new Date().toISOString(),
487
472
  sections: storedSections,
473
+ localSections: storedLocalSections,
474
+ pageContentId: page.placement.pageContentId,
475
+ layoutAreaId: page.placement.layoutAreaId,
488
476
  },
489
477
  };
490
478
  writeDeploymentState(preset.id, manifest.folder, state, root);
@@ -494,6 +482,11 @@ export async function deployProject({
494
482
  let finalPageContent = verifiedContent;
495
483
  let published = false;
496
484
  if (await ui.confirmPublish()) {
485
+ const freshContent = await api.getContent(page.placement.pageContentId);
486
+ if (pageRevision(freshContent) !== pageRevision(verifiedContent)) {
487
+ throw new Error("CMS page changed while awaiting publication confirmation. Publication cancelled; review the checkout and run deploy again.");
488
+ }
489
+ finalPageContent = freshContent;
497
490
  const issues = publicationIssues(finalPageContent);
498
491
  if (issues.length) {
499
492
  ui.info(`Publication blocked; fill in ${issues.join(", ")} in Backoffice`);
@@ -66,15 +66,18 @@ function isPublishedVersion(content) {
66
66
  String(content.statusName || "").toLowerCase() === "published";
67
67
  }
68
68
 
69
- export async function selectPageVersion({client, pageId, versions, prompts}) {
69
+ export async function selectPageVersion({client, pageId, versions, prompts, preferredContentId}) {
70
70
  prompts ||= await defaultPrompts();
71
71
  versions ||= await client.getContentVersions(pageId);
72
72
  if (!versions?.length) throw new Error("The selected CMS page has no versions");
73
73
  if (versions.length === 1) return client.getContent(contentId(versions[0]));
74
74
  const published = versions.find(isPublishedVersion);
75
+ const checkout = versions.find((content) => contentId(content) === preferredContentId &&
76
+ (Number(content.statusId ?? content.status) === STATUS.checkout ||
77
+ String(content.statusName || "").toLowerCase() === "checkout"));
75
78
  const pageContentId = await prompts.select({
76
79
  message: "Source page version",
77
- initialValue: contentId(published || versions[0]),
80
+ initialValue: contentId(checkout || published || versions[0]),
78
81
  options: versions.map((content) => ({label: versionLabel(content), value: contentId(content)})),
79
82
  });
80
83
  return client.getContent(pageContentId);
@@ -213,12 +216,14 @@ export async function selectExistingPagePlacement({client, domain, prompts}) {
213
216
  export async function createPagePlacement(options) {
214
217
  const selected = options.selected || await selectNewPagePlacement(options);
215
218
  const {client} = options;
219
+ await options.beforeTargetCreate?.();
216
220
  const created = await client.createPage({
217
221
  applicationId: selected.draft.applicationId,
218
222
  layoutId: selected.draft.layoutId,
219
223
  name: selected.draft.pageName,
220
224
  });
221
225
  if (!created?.pageContentId) throw new Error("Backoffice did not return pageContentId for the new page");
226
+ await options.onTargetCreated?.(created);
222
227
  const pageContent = await client.getContent(created.pageContentId);
223
228
  const resolvedPageId = created.pageId || pageContent.pageId || pageIdFromContentId(created.pageContentId);
224
229
  if (!resolvedPageId) throw new Error("Backoffice did not return pageId for the new page");
@@ -235,11 +240,13 @@ export async function createPagePlacement(options) {
235
240
  };
236
241
  }
237
242
 
238
- export async function prepareExistingPage({client, placement, update = false}) {
243
+ export async function prepareExistingPage({client, placement, update = false, beforeTargetCreate, onTargetCreated}) {
239
244
  let pageContent = await client.getContent(placement.pageContentId);
240
245
  if (!update && [STATUS.published, STATUS.unpublished].includes(pageContent.status)) {
246
+ await beforeTargetCreate?.();
241
247
  const created = await client.updateStatus(placement.pageContentId, STATUS.checkout);
242
248
  if (!created?.pageContentId) throw new Error("Backoffice did not return a new page version");
249
+ await onTargetCreated?.(created);
243
250
  placement = {...placement, pageContentId: created.pageContentId};
244
251
  pageContent = await client.getContent(placement.pageContentId);
245
252
  }
@@ -288,7 +295,9 @@ export async function validateSavedPlacement({client, placement}) {
288
295
  }
289
296
 
290
297
  export async function selectBoundPagePlacement({client, binding, prompts}) {
291
- const pageContent = await selectPageVersion({client, pageId: binding.pageId, prompts});
298
+ const pageContent = await selectPageVersion({
299
+ client, pageId: binding.pageId, prompts, preferredContentId: binding.lastPageContentId,
300
+ });
292
301
  const placement = {
293
302
  pageContentId: contentId(pageContent),
294
303
  layoutAreaId: binding.layoutAreaId,
@@ -302,6 +311,10 @@ export function pageRevision(pageContent) {
302
311
  return JSON.stringify({
303
312
  id: pageContent._id || pageContent.pageContentId,
304
313
  modifiedTime: pageContent.modifiedTime || pageContent.lastOperationDateTime || null,
314
+ status: pageContent.status,
315
+ metadata: (pageContent.pageContents || []).map((content) => ({
316
+ languageId: content.languageId, title: content.title, perma: content.perma, seo: content.seo,
317
+ })),
305
318
  widgets: pageWidgets(pageContent).map((widget) => ({
306
319
  id: widget.contentWidgetId,
307
320
  area: widget.layoutAreaId,
@@ -1,18 +1,20 @@
1
- export function compareSections({local, remote, base}) {
1
+ export function compareSections({local, remote, base, localBase = base}) {
2
2
  const ids = [...new Set([...Object.keys(local), ...Object.keys(remote), ...Object.keys(base || {})])].sort();
3
3
  const changes = [];
4
4
  for (const id of ids) {
5
5
  const localValue = local[id];
6
6
  const remoteValue = remote[id];
7
7
  const baseValue = base?.[id];
8
+ const localChanged = localValue !== (localBase?.[id] ?? undefined);
9
+ const remoteChanged = remoteValue !== baseValue;
8
10
  if (localValue === remoteValue) continue;
9
- if (!base) {
11
+ if (!base || !localBase || (Object.hasOwn(base, id) && !Object.hasOwn(localBase, id))) {
10
12
  changes.push({id, kind: "unknown", local: localValue, remote: remoteValue});
11
- } else if (remoteValue === baseValue) {
13
+ } else if (localChanged && !remoteChanged) {
12
14
  changes.push({id, kind: "local", local: localValue, remote: remoteValue});
13
- } else if (localValue === baseValue) {
15
+ } else if (!localChanged && remoteChanged) {
14
16
  changes.push({id, kind: "remote", local: localValue, remote: remoteValue});
15
- } else {
17
+ } else if (localChanged && remoteChanged) {
16
18
  changes.push({id, kind: "conflict", local: localValue, remote: remoteValue});
17
19
  }
18
20
  }
@@ -26,19 +28,20 @@ export function summarizeChanges(changes) {
26
28
  ]));
27
29
  }
28
30
 
29
- export function resolveSections({local, remote, base, scope, strategy = "merge"}) {
31
+ export function resolveSections({local, remote, base, localBase = base, scope, strategy = "merge"}) {
30
32
  const selected = scope?.length ? new Set(scope) : new Set(Object.keys(local));
31
33
  const scopedLocal = Object.fromEntries(Object.entries(local).filter(([id]) => selected.has(id)));
32
34
  const scopedRemote = Object.fromEntries(Object.entries(remote).filter(([id]) => selected.has(id)));
33
35
  const scopedBase = base && Object.fromEntries(Object.entries(base).filter(([id]) => selected.has(id)));
34
- const changes = compareSections({local: scopedLocal, remote: scopedRemote, base: scopedBase});
36
+ const scopedLocalBase = localBase && Object.fromEntries(Object.entries(localBase).filter(([id]) => selected.has(id)));
37
+ const changes = compareSections({local: scopedLocal, remote: scopedRemote, base: scopedBase, localBase: scopedLocalBase});
35
38
  const unsafe = changes.filter((change) => change.kind === "conflict" || change.kind === "unknown");
36
39
  if (strategy === "merge" && unsafe.length) return {changes, unsafe, sections: null};
37
40
  const sections = {...remote};
38
41
  for (const id of selected) {
39
42
  const change = changes.find((item) => item.id === id);
40
43
  if (strategy === "remote" && change) continue;
41
- if (strategy === "force" || !change || change.kind === "local") {
44
+ if (strategy === "force" || change?.kind === "local") {
42
45
  if (local[id] === undefined) delete sections[id];
43
46
  else sections[id] = local[id];
44
47
  }
@@ -46,7 +46,10 @@ export function readPendingDeployment(site, folder, root = process.cwd()) {
46
46
  const validPlacement = pending.placement?.pageContentId && pending.placement?.layoutAreaId;
47
47
  const validBinding = pending.binding?.pageId && pending.binding?.layoutAreaId;
48
48
  const validRevision = pending.expectedRevision === undefined || typeof pending.expectedRevision === "string";
49
- if (pending.schemaVersion !== PENDING_VERSION || !pending.deploymentId || !validPlacement || !validBinding ||
49
+ const preparing = pending.phase === "preparing-target";
50
+ const created = pending.phase === "target-created" && validPlacement && pending.targetBinding?.layoutAreaId;
51
+ if (pending.schemaVersion !== PENDING_VERSION || !pending.deploymentId ||
52
+ (!preparing && !created && (!validPlacement || !validBinding)) ||
50
53
  !Array.isArray(pending.completed) || !validRevision) {
51
54
  throw new Error(`Invalid pending deployment: ${filePath}`);
52
55
  }
@@ -29,6 +29,31 @@ function widgetsForPlacement(pageContent, layoutAreaId, folder) {
29
29
  );
30
30
  }
31
31
 
32
+ const defaultWait = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
33
+
34
+ async function verifyMutation(client, placement, manifest, operation, widget, wait, verificationDelays) {
35
+ if (typeof client.getContent !== "function") return null;
36
+ for (let attempt = 0; ; attempt += 1) {
37
+ const pageContent = await client.getContent(placement.pageContentId);
38
+ const widgets = widgetsForPlacement(pageContent, placement.layoutAreaId, manifest.folder);
39
+ const current = widgets.find((candidate) =>
40
+ operation.type === "add"
41
+ ? candidate.cmsTitle === operation.title
42
+ : candidate.contentWidgetId === widget?.contentWidgetId
43
+ );
44
+ const applied = operation.type === "add"
45
+ ? current && (current.data?.content ?? current.content ?? "") === operation.content
46
+ : operation.type === "update"
47
+ ? current && (current.data?.content ?? current.content ?? "") === operation.content
48
+ : operation.type === "reorder"
49
+ ? current?.order === operation.desiredOrder
50
+ : !current;
51
+ if (applied) return {pageContent, widget: current || widget};
52
+ if (attempt >= verificationDelays.length) return null;
53
+ await wait(verificationDelays[attempt]);
54
+ }
55
+ }
56
+
32
57
  export function remoteSections(pageContent, placement, folder) {
33
58
  return Object.fromEntries(widgetsForPlacement(pageContent || {}, placement.layoutAreaId, folder).map((widget) => [
34
59
  widget.cmsTitle.slice(widget.cmsTitle.lastIndexOf(" | ") + 3), widget.data?.content ?? widget.content ?? "",
@@ -101,8 +126,13 @@ export async function syncWidgets({
101
126
  plan,
102
127
  beforeOperation,
103
128
  onOperation,
129
+ wait = defaultWait,
130
+ verificationDelays = [250, 500],
104
131
  }) {
105
132
  plan ||= planWidgetChanges({manifest, placement, pageContent, root, sectionIds});
133
+ if (plan.operations.length && typeof client.getContent !== "function") {
134
+ throw new Error("Backoffice content readback is required to verify widget changes");
135
+ }
106
136
  let added = 0;
107
137
  let updated = 0;
108
138
  let reordered = 0;
@@ -110,39 +140,50 @@ export async function syncWidgets({
110
140
  const addedWidgets = new Map();
111
141
 
112
142
  for (const operation of plan.operations) {
113
- await beforeOperation?.(operation);
114
143
  let widget = operation.widget || addedWidgets.get(operation.id);
115
- let refreshedPageContent = null;
116
- if (operation.type === "update") {
117
- await client.updateWidget(operation.title, widget.contentWidgetId, operation.content);
118
- updated += 1;
119
- } else if (operation.type === "add") {
120
- await client.addWidget({
121
- pageContentId: placement.pageContentId,
122
- layoutAreaId: placement.layoutAreaId,
123
- cmsTitle: operation.title,
124
- data: {content: operation.content},
125
- });
126
- refreshedPageContent = await client.getContent(placement.pageContentId);
127
- widget = widgetsForPlacement(refreshedPageContent, placement.layoutAreaId, manifest.folder)
128
- .find((candidate) => candidate.cmsTitle === operation.title);
129
- if (!widget) throw new Error(`Backoffice did not return the added widget: ${operation.title}`);
144
+ if (operation.type === "reorder" && widget?.order === operation.desiredOrder) continue;
145
+ await beforeOperation?.(operation);
146
+ let mutationError;
147
+ try {
148
+ if (operation.type === "update") {
149
+ await client.updateWidget(operation.title, widget.contentWidgetId, operation.content);
150
+ } else if (operation.type === "add") {
151
+ await client.addWidget({
152
+ pageContentId: placement.pageContentId,
153
+ layoutAreaId: placement.layoutAreaId,
154
+ cmsTitle: operation.title,
155
+ data: {content: operation.content},
156
+ });
157
+ } else if (operation.type === "reorder") {
158
+ await client.reorderWidget(widget.contentWidgetId, operation.desiredOrder);
159
+ } else if (operation.type === "remove") {
160
+ await client.removeWidget({
161
+ contentWidgetId: widget.contentWidgetId,
162
+ layoutAreaId: widget.layoutAreaId,
163
+ widgetId: widget.widgetId,
164
+ });
165
+ }
166
+ } catch (cause) {
167
+ mutationError = cause;
168
+ }
169
+ const verified = await verifyMutation(
170
+ client, placement, manifest, operation, widget, wait, verificationDelays
171
+ );
172
+ if (!verified) {
173
+ throw mutationError || new Error(`Backoffice did not confirm ${operation.type} for widget: ${operation.title}`);
174
+ }
175
+ const refreshedPageContent = verified.pageContent;
176
+ widget = verified.widget;
177
+ if (operation.type === "add") {
130
178
  addedWidgets.set(operation.id, widget);
131
179
  added += 1;
180
+ } else if (operation.type === "update") {
181
+ updated += 1;
132
182
  } else if (operation.type === "reorder") {
133
- await client.reorderWidget(widget.contentWidgetId, operation.desiredOrder);
134
183
  reordered += 1;
135
184
  } else if (operation.type === "remove") {
136
- await client.removeWidget({
137
- contentWidgetId: widget.contentWidgetId,
138
- layoutAreaId: widget.layoutAreaId,
139
- widgetId: widget.widgetId,
140
- });
141
185
  removed += 1;
142
186
  }
143
- if (onOperation && !refreshedPageContent) {
144
- refreshedPageContent = await client.getContent(placement.pageContentId);
145
- }
146
187
  await onOperation?.({
147
188
  type: operation.type,
148
189
  title: operation.title,