@diviops/mcp-server 1.5.29 → 1.5.31

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.
@@ -0,0 +1,783 @@
1
+ import { createHash } from "node:crypto";
2
+ const SUPPORTED_KIND = "tb_header_layout";
3
+ const UPLOADS_PREFIX = "/wp-content/uploads/";
4
+ const ABSOLUTE_URL_RE = /https?:\/\/[^\s"'<>\\)]+/g;
5
+ const GCID_RE = /\bgcid-[A-Za-z0-9_-]+\b/g;
6
+ const OFF_CANVAS_PATTERNS = [
7
+ { re: /\bcanvas-portal\b/gi, reason: "canvas portal reference" },
8
+ { re: /\boff[-_]?canvas\b/gi, reason: "off-canvas reference" },
9
+ {
10
+ re: /"_divi_off_canvas_data"/gi,
11
+ reason: "_divi_off_canvas_data meta reference",
12
+ },
13
+ {
14
+ re: /"_divi_dynamic_assets_canvases_used"/gi,
15
+ reason: "_divi_dynamic_assets_canvases_used meta reference",
16
+ },
17
+ {
18
+ re: /"(canvasId|canvas_id|canvasUUID|canvas_uuid)"\s*:/gi,
19
+ reason: "canvas UUID attribute",
20
+ },
21
+ ];
22
+ const SECRET_KEY_RE = /(app[_-]?password|password|secret|token|nonce|cookie|authorization|x[_-]?wp[_-]?nonce|x[_-]?et[_-]?nonce)/i;
23
+ const DEFAULT_BUILTIN_CUSTOMIZER_COLOR_IDS = new Set([
24
+ "gcid-primary-color",
25
+ "gcid-secondary-color",
26
+ "gcid-heading-color",
27
+ "gcid-body-color",
28
+ "gcid-link-color",
29
+ ]);
30
+ function decodeMarkup(markup) {
31
+ return markup.replace(/\\u([0-9a-fA-F]{4})/g, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
32
+ }
33
+ function sha256(value) {
34
+ return createHash("sha256").update(value).digest("hex");
35
+ }
36
+ function normalizeChecksum(checksum) {
37
+ if (!checksum)
38
+ return undefined;
39
+ return checksum.trim().replace(/^sha256:/i, "").toLowerCase();
40
+ }
41
+ function isSha256Hex(value) {
42
+ return /^[a-f0-9]{64}$/.test(value);
43
+ }
44
+ function normalizeDestinationChecksum(checksum) {
45
+ if (checksum === undefined || checksum === null)
46
+ return undefined;
47
+ if (typeof checksum === "string") {
48
+ const computed = normalizeChecksum(checksum);
49
+ if (!computed)
50
+ return undefined;
51
+ return { algorithm: "sha256", computed };
52
+ }
53
+ if (typeof checksum !== "object")
54
+ return undefined;
55
+ const algorithm = typeof checksum.algorithm === "string" ? checksum.algorithm.toLowerCase() : "";
56
+ const computed = normalizeChecksum(checksum.computed);
57
+ if (algorithm !== "sha256" || !computed)
58
+ return undefined;
59
+ return {
60
+ algorithm: "sha256",
61
+ computed,
62
+ input: checksum.input === "post_content" ? "post_content" : undefined,
63
+ };
64
+ }
65
+ function normalizeOrigin(origin, field) {
66
+ try {
67
+ const url = new URL(origin);
68
+ return new URL(url.origin);
69
+ }
70
+ catch {
71
+ throw new Error(`${field} must be an absolute origin URL.`);
72
+ }
73
+ }
74
+ function safeUrlForReport(parsed, origin = parsed.origin) {
75
+ const query = parsed.search ? "?[redacted]" : "";
76
+ const hash = parsed.hash ? "#[redacted]" : "";
77
+ return `${origin}${parsed.pathname}${query}${hash}`;
78
+ }
79
+ function uniqueSorted(values) {
80
+ return [...new Set(values)].sort((a, b) => a.localeCompare(b));
81
+ }
82
+ function collectIds(value) {
83
+ if (value === undefined)
84
+ return null;
85
+ const ids = new Set();
86
+ const walk = (node) => {
87
+ if (typeof node === "string") {
88
+ if (node.startsWith("gcid-"))
89
+ ids.add(node);
90
+ return;
91
+ }
92
+ if (Array.isArray(node)) {
93
+ for (const item of node)
94
+ walk(item);
95
+ return;
96
+ }
97
+ if (node && typeof node === "object") {
98
+ const record = node;
99
+ for (const [key, nested] of Object.entries(record)) {
100
+ if (key.startsWith("gcid-"))
101
+ ids.add(key);
102
+ if ((key === "id" || key === "name") &&
103
+ typeof nested === "string" &&
104
+ nested.startsWith("gcid-")) {
105
+ ids.add(nested);
106
+ }
107
+ walk(nested);
108
+ }
109
+ }
110
+ };
111
+ walk(value);
112
+ return ids;
113
+ }
114
+ function isGcid(value) {
115
+ return value.startsWith("gcid-");
116
+ }
117
+ function compactEvidenceSource(value) {
118
+ if (typeof value !== "string")
119
+ return undefined;
120
+ const normalized = value.trim().toLowerCase();
121
+ return /^[a-z0-9_.:-]+$/.test(normalized) ? normalized : undefined;
122
+ }
123
+ function normalizeEvidenceDigest(value) {
124
+ if (!value || typeof value !== "object")
125
+ return undefined;
126
+ const record = value;
127
+ const algorithm = typeof record.algorithm === "string" ? record.algorithm.toLowerCase() : "";
128
+ const computed = normalizeChecksum(typeof record.computed === "string" ? record.computed : undefined);
129
+ if (algorithm !== "sha256" || !computed || !isSha256Hex(computed))
130
+ return undefined;
131
+ return {
132
+ algorithm: "sha256",
133
+ input: compactEvidenceSource(record.input) ?? "resolved_color",
134
+ computed,
135
+ };
136
+ }
137
+ function normalizeGlobalColorEvidenceRecord(id, record, fallbackSource) {
138
+ if (!id || !isGcid(id) || !record || typeof record !== "object")
139
+ return undefined;
140
+ const candidate = record;
141
+ const digest = normalizeEvidenceDigest(candidate.digest);
142
+ const color = typeof candidate.color === "string" ? candidate.color : undefined;
143
+ const value = typeof candidate.value === "string" ? candidate.value : color;
144
+ const computedDigest = digest ??
145
+ (value
146
+ ? {
147
+ algorithm: "sha256",
148
+ input: "resolved_color",
149
+ computed: sha256(value),
150
+ }
151
+ : undefined);
152
+ if (!computedDigest)
153
+ return undefined;
154
+ return {
155
+ id,
156
+ source: compactEvidenceSource(candidate.source) ?? fallbackSource,
157
+ digest: computedDigest,
158
+ };
159
+ }
160
+ function collectGlobalColorValueEvidence(target) {
161
+ const evidence = new Map();
162
+ const add = (item) => {
163
+ if (item && !evidence.has(item.id))
164
+ evidence.set(item.id, item);
165
+ };
166
+ const explicit = target.global_color_value_evidence;
167
+ if (Array.isArray(explicit)) {
168
+ for (const item of explicit) {
169
+ const id = item && typeof item === "object" && typeof item.id === "string"
170
+ ? item.id
171
+ : undefined;
172
+ add(normalizeGlobalColorEvidenceRecord(id, item));
173
+ }
174
+ }
175
+ else if (explicit && typeof explicit === "object") {
176
+ for (const [key, item] of Object.entries(explicit)) {
177
+ const recordId = item && typeof item === "object" && typeof item.id === "string"
178
+ ? item.id
179
+ : undefined;
180
+ add(normalizeGlobalColorEvidenceRecord(recordId ?? key, item));
181
+ }
182
+ }
183
+ const colors = target.global_colors;
184
+ if (Array.isArray(colors)) {
185
+ for (const item of colors) {
186
+ if (!item || typeof item !== "object")
187
+ continue;
188
+ const record = item;
189
+ const id = typeof record.id === "string"
190
+ ? record.id
191
+ : typeof record.name === "string"
192
+ ? record.name
193
+ : undefined;
194
+ add(normalizeGlobalColorEvidenceRecord(id, record, "global_colors"));
195
+ }
196
+ }
197
+ else if (colors && typeof colors === "object") {
198
+ for (const [key, item] of Object.entries(colors)) {
199
+ add(normalizeGlobalColorEvidenceRecord(key, item, "global_colors"));
200
+ }
201
+ }
202
+ return evidence;
203
+ }
204
+ function collectSecretLikeKeys(value, path = "$") {
205
+ if (!value || typeof value !== "object")
206
+ return [];
207
+ if (Array.isArray(value)) {
208
+ return value.flatMap((item, index) => collectSecretLikeKeys(item, `${path}[${index}]`));
209
+ }
210
+ const hits = [];
211
+ for (const [key, nested] of Object.entries(value)) {
212
+ const nextPath = `${path}.${key}`;
213
+ if (SECRET_KEY_RE.test(key))
214
+ hits.push(nextPath);
215
+ hits.push(...collectSecretLikeKeys(nested, nextPath));
216
+ }
217
+ return hits;
218
+ }
219
+ function canonicalize(value) {
220
+ if (Array.isArray(value))
221
+ return value.map(canonicalize);
222
+ if (!value || typeof value !== "object")
223
+ return value;
224
+ return Object.fromEntries(Object.entries(value)
225
+ .filter(([, nested]) => nested !== undefined)
226
+ .sort(([a], [b]) => a.localeCompare(b))
227
+ .map(([key, nested]) => [key, canonicalize(nested)]));
228
+ }
229
+ function canonicalJson(value) {
230
+ return JSON.stringify(canonicalize(value));
231
+ }
232
+ function findUrls(markup, sourceOrigin, targetOrigin) {
233
+ const decoded = decodeMarkup(markup);
234
+ const hits = [];
235
+ const seen = new Set();
236
+ let match;
237
+ ABSOLUTE_URL_RE.lastIndex = 0;
238
+ while ((match = ABSOLUTE_URL_RE.exec(decoded)) !== null) {
239
+ let parsed;
240
+ try {
241
+ parsed = new URL(match[0]);
242
+ }
243
+ catch {
244
+ continue;
245
+ }
246
+ const key = parsed.href;
247
+ if (seen.has(key))
248
+ continue;
249
+ seen.add(key);
250
+ const sameSourceHost = parsed.host === sourceOrigin.host;
251
+ const sameTargetHost = parsed.host === targetOrigin.host;
252
+ const isUpload = parsed.pathname.startsWith(UPLOADS_PREFIX);
253
+ let classification;
254
+ let rewriteTo;
255
+ if (sameSourceHost && isUpload) {
256
+ classification = "source_upload_rewrite";
257
+ rewriteTo = safeUrlForReport(parsed, targetOrigin.origin);
258
+ }
259
+ else if (sameSourceHost) {
260
+ classification = "source_non_upload_operator_review";
261
+ }
262
+ else if (sameTargetHost) {
263
+ classification = "target_origin";
264
+ }
265
+ else {
266
+ classification = "third_party_no_rewrite";
267
+ }
268
+ hits.push({
269
+ url: safeUrlForReport(parsed),
270
+ host: parsed.host,
271
+ path: parsed.pathname,
272
+ query_redacted: parsed.search ? true : undefined,
273
+ hash_redacted: parsed.hash ? true : undefined,
274
+ credentials_redacted: parsed.username || parsed.password ? true : undefined,
275
+ classification,
276
+ rewrite_to: rewriteTo,
277
+ });
278
+ }
279
+ return hits;
280
+ }
281
+ function findAttachmentRefs(markup) {
282
+ const decoded = decodeMarkup(markup);
283
+ const refs = new Map();
284
+ const addRef = (property, sourceId) => {
285
+ if (!Number.isFinite(sourceId) || sourceId <= 0)
286
+ return;
287
+ refs.set(`${property}:${sourceId}`, { property, source_id: sourceId });
288
+ };
289
+ collectAttachmentRefsFromDiviAttrs(decoded, addRef);
290
+ return [...refs.values()].sort((a, b) => a.source_id - b.source_id);
291
+ }
292
+ function collectAttachmentRefsFromDiviAttrs(markup, addRef) {
293
+ const blockRe = /<!--\s+(?:\/)?wp:([A-Za-z0-9_-]+\/[A-Za-z0-9_-]+)(.*?)(?:\/)?-->/gs;
294
+ let match;
295
+ while ((match = blockRe.exec(markup)) !== null) {
296
+ const blockName = match[1];
297
+ if (!blockName.startsWith("divi/"))
298
+ continue;
299
+ const attrsText = jsonObjectFromBlockCommentTail(match[2] ?? "");
300
+ if (!attrsText)
301
+ continue;
302
+ try {
303
+ collectAttachmentRefsFromValue(JSON.parse(attrsText), "", false, addRef);
304
+ }
305
+ catch {
306
+ continue;
307
+ }
308
+ }
309
+ }
310
+ function jsonObjectFromBlockCommentTail(tail) {
311
+ const start = tail.indexOf("{");
312
+ const end = tail.lastIndexOf("}");
313
+ if (start < 0 || end < start)
314
+ return undefined;
315
+ return tail.slice(start, end + 1);
316
+ }
317
+ function collectAttachmentRefsFromValue(value, parentKey, inMediaContext, addRef) {
318
+ if (Array.isArray(value)) {
319
+ for (const nested of value) {
320
+ collectAttachmentRefsFromValue(nested, parentKey, inMediaContext, addRef);
321
+ }
322
+ return;
323
+ }
324
+ if (!value || typeof value !== "object")
325
+ return;
326
+ const record = value;
327
+ const objectMediaContext = inMediaContext || isMediaContextObject(record, parentKey);
328
+ for (const [key, nested] of Object.entries(record)) {
329
+ const sourceId = numericSourceId(nested);
330
+ if (isMediaAttachmentIdKey(key) && sourceId) {
331
+ addRef(key, sourceId);
332
+ continue;
333
+ }
334
+ if (key === "id" && objectMediaContext && sourceId) {
335
+ addRef(key, sourceId);
336
+ continue;
337
+ }
338
+ collectAttachmentRefsFromValue(nested, key, objectMediaContext, addRef);
339
+ }
340
+ }
341
+ function isMediaContextObject(value, parentKey) {
342
+ if (/(?:image|media|attachment|gallery|video|audio|poster|logo|avatar|icon)/i.test(parentKey)) {
343
+ return true;
344
+ }
345
+ return Object.entries(value).some(([key, nested]) => {
346
+ if (isMediaAttachmentIdKey(key))
347
+ return true;
348
+ return typeof nested === "string" && nested.includes(UPLOADS_PREFIX);
349
+ });
350
+ }
351
+ function isMediaAttachmentIdKey(key) {
352
+ return [
353
+ "imageId",
354
+ "mediaId",
355
+ "attachmentId",
356
+ "backgroundImageId",
357
+ "videoId",
358
+ "audioId",
359
+ ].includes(key);
360
+ }
361
+ function numericSourceId(value) {
362
+ if (typeof value === "number" && Number.isInteger(value) && value > 0)
363
+ return value;
364
+ if (typeof value === "string" && /^\d+$/.test(value))
365
+ return Number.parseInt(value, 10);
366
+ return undefined;
367
+ }
368
+ function numericTargetId(value) {
369
+ if (typeof value === "number" && Number.isInteger(value) && value > 0)
370
+ return value;
371
+ if (typeof value === "string" && /^\d+$/.test(value))
372
+ return Number.parseInt(value, 10);
373
+ return undefined;
374
+ }
375
+ function resolveAttachment(sourceId, target) {
376
+ const direct = target.attachment_remaps?.[String(sourceId)];
377
+ const directId = numericTargetId(direct);
378
+ if (directId) {
379
+ return {
380
+ status: "proven_remap",
381
+ target_id: directId,
382
+ proof: "attachment_remaps",
383
+ };
384
+ }
385
+ if (Array.isArray(direct)) {
386
+ const ids = direct.map(numericTargetId).filter((id) => id !== undefined);
387
+ if (ids.length === 1) {
388
+ return {
389
+ status: "proven_remap",
390
+ target_id: ids[0],
391
+ proof: "attachment_remaps",
392
+ };
393
+ }
394
+ if (ids.length > 1)
395
+ return { status: "ambiguous_remap", proof: "attachment_remaps" };
396
+ }
397
+ if (direct && typeof direct === "object") {
398
+ const record = direct;
399
+ const targetId = numericTargetId(record.target_id);
400
+ if (targetId) {
401
+ return {
402
+ status: "proven_remap",
403
+ target_id: targetId,
404
+ proof: typeof record.proof === "string" ? record.proof : "attachment_remaps",
405
+ };
406
+ }
407
+ if (Array.isArray(record.target_ids)) {
408
+ const ids = record.target_ids
409
+ .map(numericTargetId)
410
+ .filter((id) => id !== undefined);
411
+ if (ids.length === 1) {
412
+ return {
413
+ status: "proven_remap",
414
+ target_id: ids[0],
415
+ proof: "attachment_remaps",
416
+ };
417
+ }
418
+ if (ids.length > 1)
419
+ return { status: "ambiguous_remap", proof: "attachment_remaps" };
420
+ }
421
+ }
422
+ const candidates = (target.attachments ?? []).filter((attachment) => {
423
+ return (attachment.source_id === sourceId ||
424
+ attachment.source_attachment_id === sourceId);
425
+ });
426
+ const targetIds = uniqueSorted(candidates
427
+ .map((candidate) => numericTargetId(candidate.target_id ?? candidate.id))
428
+ .filter((id) => id !== undefined)
429
+ .map(String)).map((id) => Number.parseInt(id, 10));
430
+ if (targetIds.length === 1) {
431
+ return {
432
+ status: "proven_remap",
433
+ target_id: targetIds[0],
434
+ proof: candidates.find((candidate) => candidate.proof)?.proof ?? "target_attachments",
435
+ };
436
+ }
437
+ if (targetIds.length > 1)
438
+ return { status: "ambiguous_remap", proof: "target_attachments" };
439
+ return { status: "missing_remap" };
440
+ }
441
+ function findGcidRefs(markup, target) {
442
+ const decoded = decodeMarkup(markup);
443
+ const refs = new Set();
444
+ let match;
445
+ GCID_RE.lastIndex = 0;
446
+ while ((match = GCID_RE.exec(decoded)) !== null)
447
+ refs.add(match[0]);
448
+ const targetColors = collectIds(target.global_colors);
449
+ const builtinColors = collectIds(target.builtin_customizer_color_ids) ??
450
+ DEFAULT_BUILTIN_CUSTOMIZER_COLOR_IDS;
451
+ const valueEvidence = collectGlobalColorValueEvidence(target);
452
+ return uniqueSorted(refs).map((id) => {
453
+ const evidence = valueEvidence.get(id);
454
+ if (targetColors?.has(id)) {
455
+ return { id, status: "target_global_color", value_evidence: evidence };
456
+ }
457
+ if (builtinColors.has(id)) {
458
+ return { id, status: "builtin_customizer_color", value_evidence: evidence };
459
+ }
460
+ if (targetColors === null)
461
+ return { id, status: "missing_target_context" };
462
+ return { id, status: "missing_definition" };
463
+ });
464
+ }
465
+ function findOffCanvasRefs(markup) {
466
+ const decoded = decodeMarkup(markup);
467
+ const refs = new Map();
468
+ for (const pattern of OFF_CANVAS_PATTERNS) {
469
+ pattern.re.lastIndex = 0;
470
+ let match;
471
+ while ((match = pattern.re.exec(decoded)) !== null) {
472
+ refs.set(`${pattern.reason}:${match[0]}`, {
473
+ token: match[0],
474
+ reason: pattern.reason,
475
+ });
476
+ }
477
+ }
478
+ return [...refs.values()].sort((a, b) => a.token.localeCompare(b.token));
479
+ }
480
+ function groupUrlPathsByHost(urls) {
481
+ const grouped = {};
482
+ for (const url of urls) {
483
+ grouped[url.host] ??= new Set();
484
+ grouped[url.host].add(url.path);
485
+ }
486
+ return Object.fromEntries(Object.entries(grouped)
487
+ .sort(([a], [b]) => a.localeCompare(b))
488
+ .map(([host, paths]) => [host, uniqueSorted(paths)]));
489
+ }
490
+ function cachePlan(target, offCanvasRefs) {
491
+ const scope = target.cache_scope ?? "theme_builder_global";
492
+ const destination = target.destination_id
493
+ ? `${target.destination_kind}#${target.destination_id}`
494
+ : target.destination_kind;
495
+ const steps = [
496
+ {
497
+ kind: "divi_static_resources_remove",
498
+ target: scope,
499
+ note: "Run Divi static-resource removal for the affected Theme Builder/global rendering scope.",
500
+ },
501
+ {
502
+ kind: "delete_post_meta",
503
+ target: `${destination}::_divi_dynamic_assets_cached_feature_used`,
504
+ note: "Delete stale dynamic-assets feature usage metadata after a future write.",
505
+ },
506
+ ];
507
+ if (offCanvasRefs.length > 0) {
508
+ steps.push({
509
+ kind: "delete_post_meta",
510
+ target: `${destination}::_divi_dynamic_assets_canvases_used`,
511
+ note: "Required only when a future off-canvas implementation owns canvas remapping.",
512
+ });
513
+ }
514
+ return { scope, steps };
515
+ }
516
+ function stableIssueSummaries(issues) {
517
+ return [...issues]
518
+ .map((issue) => ({
519
+ code: issue.code,
520
+ detail: issue.detail ?? null,
521
+ }))
522
+ .sort((a, b) => canonicalJson(a).localeCompare(canonicalJson(b)));
523
+ }
524
+ function buildConfirmationBinding(report) {
525
+ const input = {
526
+ source: {
527
+ origin: report.source.origin,
528
+ object_kind: report.source.object_kind,
529
+ object_id: report.source.object_id,
530
+ checksum: {
531
+ algorithm: "sha256",
532
+ computed: report.source.checksum.computed,
533
+ },
534
+ },
535
+ target: {
536
+ origin: report.target.origin,
537
+ destination_kind: report.target.destination_kind,
538
+ destination_id: report.target.destination_id,
539
+ destination_checksum: report.target.destination_checksum ?? null,
540
+ },
541
+ rewrite_plan: report.rewrite_plan,
542
+ cache_plan: report.cache_plan,
543
+ blockers: stableIssueSummaries(report.blockers),
544
+ operator_actions: stableIssueSummaries(report.operator_actions),
545
+ off_canvas: {
546
+ refused: report.findings.off_canvas.length > 0,
547
+ refs: report.findings.off_canvas,
548
+ },
549
+ attachment_remap_proof: report.findings.attachments
550
+ .map((attachment) => ({
551
+ source_id: attachment.source_id,
552
+ status: attachment.status,
553
+ target_id: attachment.target_id,
554
+ proof: attachment.proof,
555
+ }))
556
+ .sort((a, b) => canonicalJson(a).localeCompare(canonicalJson(b))),
557
+ global_color_resolution: report.findings.global_colors
558
+ .map((color) => ({
559
+ id: color.id,
560
+ status: color.status,
561
+ value_evidence: color.value_evidence ?? null,
562
+ }))
563
+ .sort((a, b) => canonicalJson(a).localeCompare(canonicalJson(b))),
564
+ };
565
+ const schema = "diviops.cross_env.header_preflight.confirmation_binding.v1";
566
+ const fingerprint = sha256(canonicalJson({ schema, input }));
567
+ return {
568
+ schema,
569
+ algorithm: "sha256",
570
+ fingerprint,
571
+ input: canonicalize(input),
572
+ };
573
+ }
574
+ export function preflightCrossEnvHeaderSync(input) {
575
+ const sourceOrigin = normalizeOrigin(input.source.origin, "source.origin");
576
+ const targetOrigin = normalizeOrigin(input.target.origin, "target.origin");
577
+ const computedChecksum = sha256(input.source.markup);
578
+ const providedChecksum = normalizeChecksum(input.source.checksum);
579
+ const destinationChecksum = normalizeDestinationChecksum(input.target.destination_checksum);
580
+ const checksumMatches = providedChecksum === undefined ? null : providedChecksum === computedChecksum;
581
+ const blockers = [];
582
+ const operatorActions = [];
583
+ const secretLikeKeys = collectSecretLikeKeys(input);
584
+ if (secretLikeKeys.length > 0) {
585
+ blockers.push({
586
+ code: "secret_like_input_key",
587
+ message: "Preflight inputs must be secret-free.",
588
+ detail: { keys: secretLikeKeys },
589
+ });
590
+ }
591
+ if (input.source.object_kind !== SUPPORTED_KIND) {
592
+ blockers.push({
593
+ code: "unsupported_source_kind",
594
+ message: "MVP only supports tb_header_layout source payloads.",
595
+ detail: { received: input.source.object_kind },
596
+ });
597
+ }
598
+ if (input.target.destination_kind !== SUPPORTED_KIND) {
599
+ blockers.push({
600
+ code: "unsupported_destination_kind",
601
+ message: "MVP only supports tb_header_layout destinations.",
602
+ detail: { received: input.target.destination_kind },
603
+ });
604
+ }
605
+ if (input.target.destination_id === undefined || input.target.destination_id === "") {
606
+ operatorActions.push({
607
+ code: "missing_destination_id",
608
+ message: "Provide the existing target Theme Builder header layout ID.",
609
+ });
610
+ }
611
+ if (input.target.cache_scope === undefined || input.target.cache_scope === "") {
612
+ operatorActions.push({
613
+ code: "missing_cache_scope",
614
+ message: "Provide the expected cache scope after apply.",
615
+ });
616
+ }
617
+ if (providedChecksum === undefined) {
618
+ operatorActions.push({
619
+ code: "missing_source_checksum",
620
+ message: "Provide a sha256 checksum for the source markup payload.",
621
+ });
622
+ }
623
+ else if (!checksumMatches) {
624
+ blockers.push({
625
+ code: "source_checksum_mismatch",
626
+ message: "Source markup checksum does not match the provided checksum.",
627
+ detail: { provided: providedChecksum, computed: computedChecksum },
628
+ });
629
+ }
630
+ if (!destinationChecksum) {
631
+ operatorActions.push({
632
+ code: "missing_destination_checksum",
633
+ message: "Provide the current target layout sha256 checksum before future apply confirmation.",
634
+ });
635
+ }
636
+ else if (!isSha256Hex(destinationChecksum.computed)) {
637
+ blockers.push({
638
+ code: "invalid_destination_checksum",
639
+ message: "Target destination checksum must be a sha256 hex digest.",
640
+ detail: { algorithm: destinationChecksum.algorithm },
641
+ });
642
+ }
643
+ const urls = findUrls(input.source.markup, sourceOrigin, targetOrigin);
644
+ for (const url of urls) {
645
+ if (url.classification === "source_non_upload_operator_review") {
646
+ operatorActions.push({
647
+ code: "source_url_not_upload_path",
648
+ message: "Source-origin absolute URL is not a compatible WordPress uploads URL.",
649
+ detail: { url: url.url, path: url.path },
650
+ });
651
+ }
652
+ }
653
+ const attachments = findAttachmentRefs(input.source.markup).map((ref) => {
654
+ const resolution = resolveAttachment(ref.source_id, input.target);
655
+ return { ...ref, ...resolution };
656
+ });
657
+ for (const attachment of attachments) {
658
+ if (attachment.status === "missing_remap") {
659
+ operatorActions.push({
660
+ code: "missing_attachment_remap",
661
+ message: "Provide a proven target attachment remap before apply.",
662
+ detail: { source_id: attachment.source_id, property: attachment.property },
663
+ });
664
+ }
665
+ else if (attachment.status === "ambiguous_remap") {
666
+ operatorActions.push({
667
+ code: "ambiguous_attachment_remap",
668
+ message: "Attachment remap resolves to multiple possible target IDs.",
669
+ detail: { source_id: attachment.source_id, property: attachment.property },
670
+ });
671
+ }
672
+ }
673
+ const globalColors = findGcidRefs(input.source.markup, input.target);
674
+ for (const color of globalColors) {
675
+ if (color.status === "missing_target_context") {
676
+ operatorActions.push({
677
+ code: "missing_global_color_context",
678
+ message: "Provide target global colors or built-in customizer color IDs.",
679
+ detail: { id: color.id },
680
+ });
681
+ }
682
+ else if (color.status === "missing_definition") {
683
+ blockers.push({
684
+ code: "missing_gcid_definition",
685
+ message: "Referenced gcid-* is not defined on the target and is not a built-in customizer color.",
686
+ detail: { id: color.id },
687
+ });
688
+ }
689
+ else if (!color.value_evidence) {
690
+ operatorActions.push({
691
+ code: "missing_global_color_value_evidence",
692
+ message: "Provide target global color value evidence before apply confirmation.",
693
+ detail: { id: color.id, status: color.status },
694
+ });
695
+ }
696
+ }
697
+ const offCanvas = findOffCanvasRefs(input.source.markup);
698
+ if (offCanvas.length > 0) {
699
+ blockers.push({
700
+ code: "off_canvas_wiring_unsupported",
701
+ message: "Off-canvas/canvas wiring requires a 3-piece remap and is refused in this MVP.",
702
+ detail: { refs: offCanvas },
703
+ });
704
+ }
705
+ const urlRewrites = urls
706
+ .filter((url) => url.classification === "source_upload_rewrite" && url.rewrite_to)
707
+ .map((url) => ({ from: url.url, to: url.rewrite_to }));
708
+ const attachmentReplacements = attachments
709
+ .filter((attachment) => attachment.status === "proven_remap" && attachment.target_id)
710
+ .reduce((replacements, attachment) => {
711
+ const next = {
712
+ from_source_id: attachment.source_id,
713
+ to_target_id: attachment.target_id,
714
+ proof: attachment.proof,
715
+ };
716
+ if (!replacements.some((existing) => existing.from_source_id === next.from_source_id)) {
717
+ replacements.push(next);
718
+ }
719
+ return replacements;
720
+ }, []);
721
+ const missingAttachmentRemaps = attachments
722
+ .filter((attachment) => attachment.status !== "proven_remap")
723
+ .map((attachment) => attachment.source_id);
724
+ const verdict = blockers.length > 0
725
+ ? "refused"
726
+ : operatorActions.length > 0
727
+ ? "operator_action_required"
728
+ : "safe_dry_run";
729
+ const report = {
730
+ type: "cross_env_header_preflight",
731
+ dry_run: true,
732
+ verdict,
733
+ source: {
734
+ origin: sourceOrigin.origin,
735
+ object_kind: input.source.object_kind,
736
+ object_id: input.source.object_id,
737
+ object_title: input.source.object_title,
738
+ checksum: {
739
+ algorithm: "sha256",
740
+ provided: providedChecksum,
741
+ computed: computedChecksum,
742
+ matches: checksumMatches,
743
+ },
744
+ },
745
+ target: {
746
+ origin: targetOrigin.origin,
747
+ destination_kind: input.target.destination_kind,
748
+ destination_id: input.target.destination_id,
749
+ destination_title: input.target.destination_title,
750
+ cache_scope: input.target.cache_scope,
751
+ destination_checksum: destinationChecksum,
752
+ },
753
+ findings: {
754
+ urls: {
755
+ by_host: groupUrlPathsByHost(urls),
756
+ occurrences: urls,
757
+ },
758
+ attachments,
759
+ global_colors: globalColors,
760
+ off_canvas: offCanvas,
761
+ },
762
+ rewrite_plan: {
763
+ url_rewrites: urlRewrites,
764
+ attachment_replacements: attachmentReplacements,
765
+ third_party_urls_kept: urls
766
+ .filter((url) => url.classification === "third_party_no_rewrite")
767
+ .map((url) => url.url),
768
+ missing_attachment_remaps: uniqueSorted(missingAttachmentRemaps.map(String)).map((id) => Number.parseInt(id, 10)),
769
+ },
770
+ cache_plan: cachePlan(input.target, offCanvas),
771
+ blockers,
772
+ operator_actions: operatorActions,
773
+ notes: [
774
+ "Preflight only: no WordPress write/apply path exists in this slice.",
775
+ "The rewrite plan is descriptive and does not mutate markup.",
776
+ "Fail-closed behavior is intentional for missing attachment remaps, missing gcid definitions, and off-canvas wiring.",
777
+ ],
778
+ };
779
+ return {
780
+ ...report,
781
+ confirmation_binding: buildConfirmationBinding(report),
782
+ };
783
+ }