@taprootio/site-authoring 0.41.0 → 0.42.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.
@@ -0,0 +1,39 @@
1
+ // Generated from shared/url-safety.ts by scripts/sync-field-validation.mjs. Do not edit.
2
+ /**
3
+ * The renderer's safe-link rule. The generator, editor and CLI copies are
4
+ * written by scripts/sync-field-validation.mjs; edit this source only.
5
+ */
6
+ /**
7
+ * Check whether a URL string is safe for use in an `href` attribute.
8
+ * Allows `http:`, `https:`, `mailto:`, `tel:`, and site-relative paths
9
+ * (starting with `/` or `./`). Rejects `javascript:`, `data:`, `vbscript:`,
10
+ * and every other executable or unknown scheme.
11
+ *
12
+ * ASCII controls, backslashes, and protocol-relative paths are rejected
13
+ * before scheme validation because browsers normalize them inconsistently.
14
+ *
15
+ * Returns `false` for empty/whitespace-only strings.
16
+ */
17
+ export function isSafeUrl(url) {
18
+ if (/[\x00-\x1f\x7f\\]/u.test(url))
19
+ return false;
20
+ const cleaned = url.trim();
21
+ if (!cleaned)
22
+ return false;
23
+ if (cleaned.startsWith("//"))
24
+ return false;
25
+ if (cleaned.startsWith("/") || cleaned.startsWith("./"))
26
+ return true;
27
+ // Fragment-only and query-only links are safe.
28
+ if (cleaned.startsWith("#") || cleaned.startsWith("?"))
29
+ return true;
30
+ // Try parsing as an absolute URL. If it parses, validate the protocol.
31
+ try {
32
+ const parsed = new URL(cleaned);
33
+ return ["http:", "https:", "mailto:", "tel:"].includes(parsed.protocol);
34
+ }
35
+ catch {
36
+ // Not a valid absolute URL — treat as a relative path (safe).
37
+ return true;
38
+ }
39
+ }
@@ -6,6 +6,8 @@ import {
6
6
  buildAppearanceScalarOperations,
7
7
  footerPresentationOverlay,
8
8
  } from "../appearance-contract.js";
9
+ import { captureChromeResources, selectNameReportEligibility } from "../chrome-input.js";
10
+ import { completeChromeReport } from "../chrome-report.js";
9
11
  import { REFUSAL_UNCLASSIFIED, VERB_THEME_PUSH } from "../constants.js";
10
12
  import { MISSING_SETTING_MESSAGE, SiteAuthoringError } from "../errors.js";
11
13
  import { projectFooterSettingsForWorkspace } from "../footer-contract.js";
@@ -29,7 +31,7 @@ import {
29
31
  SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES,
30
32
  SETTINGS_TYPE_TAPROOT_STYLES,
31
33
  } from "../settings-catalog.js";
32
- import { missingThemeFields, requireSurfaceContexts, validateAndLintThemePair } from "../theme-validation.js";
34
+ import { missingThemeFields, requireSurfaceContexts, validateAndLintThemePair, withChromeWarnings } from "../theme-validation.js";
33
35
  import { ApiError } from "../transport.js";
34
36
  import {
35
37
  readWorkspaceJson,
@@ -62,7 +64,7 @@ function fail(code, message, field) {
62
64
  throw new SiteAuthoringError(code, message, { field });
63
65
  }
64
66
 
65
- export async function readSettingsDocument(workspaceDir, siteId, settingsType, expectedEntityId = siteId) {
67
+ async function readBoundSettingsDocument(workspaceDir, siteId, settingsType, expectedEntityId = siteId) {
66
68
  const file = `${SETTINGS_DIRECTORY}/${SETTINGS_FILES[settingsType]}`;
67
69
  if (!await workspaceFileExists(workspaceDir, file)) {
68
70
  fail("theme.settings_missing", `Workspace file '${file}' is missing. Run 'taproot-site pull' first.`, file);
@@ -80,7 +82,11 @@ export async function readSettingsDocument(workspaceDir, siteId, settingsType, e
80
82
  file,
81
83
  );
82
84
  }
83
- return document.settings;
85
+ return document;
86
+ }
87
+
88
+ export async function readSettingsDocument(workspaceDir, siteId, settingsType, expectedEntityId) {
89
+ return (await readBoundSettingsDocument(workspaceDir, siteId, settingsType, expectedEntityId)).settings;
84
90
  }
85
91
 
86
92
  /** The theme paths the styles document lacks, both schemes, in the order theme push reports them. */
@@ -119,7 +125,7 @@ export async function validateThemeWorkspace(
119
125
  expectedEntityIds,
120
126
  { deferContextValidation = false } = {},
121
127
  ) {
122
- const [style, brand, header, publishing] = await Promise.all([
128
+ const [style, brand, header, publishingDocument] = await Promise.all([
123
129
  readSettingsDocument(
124
130
  workspaceDir,
125
131
  siteId,
@@ -138,13 +144,14 @@ export async function validateThemeWorkspace(
138
144
  SETTINGS_TYPE_SITE_HEADER,
139
145
  expectedEntityIds?.get(SETTINGS_TYPE_SITE_HEADER),
140
146
  ),
141
- readSettingsDocument(
147
+ readBoundSettingsDocument(
142
148
  workspaceDir,
143
149
  siteId,
144
150
  SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES,
145
151
  expectedEntityIds?.get(SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES),
146
152
  ),
147
153
  ]);
154
+ const { settings: publishing } = publishingDocument;
148
155
  const documents = {
149
156
  [SETTINGS_TYPE_TAPROOT_STYLES]: style,
150
157
  [SETTINGS_TYPE_BRAND]: brand,
@@ -181,7 +188,7 @@ export async function validateThemeWorkspace(
181
188
  documents,
182
189
  knownImageIds,
183
190
  );
184
- return { style, brand, header, publishing, themes, scalarOperations, footerPresentation };
191
+ return { style, brand, header, publishing, publishingDocument, themes, scalarOperations, footerPresentation };
185
192
  }
186
193
 
187
194
  /**
@@ -248,11 +255,7 @@ function translateSaveRefusal(error) {
248
255
  * file, and the site's copy projected the way `pull` writes it — so the paths
249
256
  * reported are paths in the files an author edits.
250
257
  */
251
- function ownedDocuments(validated, presentation) {
252
- const projected = {};
253
- for (const group of SETTINGS_GROUPS) {
254
- projected[group.settingsType] = projectSettingsGroup(group, presentation);
255
- }
258
+ function ownedDocuments(validated, projected) {
256
259
  const fieldDefinitions = new Map(
257
260
  APPEARANCE_SCALAR_FIELDS.map(field => [`${field.settingsType}:${field.name}`, field]),
258
261
  );
@@ -295,8 +298,8 @@ function ownedDocuments(validated, presentation) {
295
298
  }
296
299
 
297
300
  /** The JSON paths at which each settings file differs from the site, remote first. */
298
- function describeDifferences(validated, presentation) {
299
- return ownedDocuments(validated, presentation).map((document_) => {
301
+ function describeDifferences(validated, projected) {
302
+ return ownedDocuments(validated, projected).map((document_) => {
300
303
  const differences = describeJsonDifferences(document_.remote, document_.local);
301
304
  return {
302
305
  file: document_.file,
@@ -363,10 +366,14 @@ export async function comparePresentation(client, siteId, validated, manifest) {
363
366
  const changeSetHash = computePresentationChangeSetHash(changeSet);
364
367
  const pending = readPendingPresentationSave(manifest);
365
368
  const replayable = pending !== undefined && pending.changeSetHash === changeSetHash;
366
- const differences = describeDifferences(validated, current);
369
+ const projected = Object.fromEntries(SETTINGS_GROUPS.map((group) => [
370
+ group.settingsType, projectSettingsGroup(group, current),
371
+ ]));
372
+ const differences = describeDifferences(validated, projected);
367
373
  return {
368
374
  baseline,
369
375
  current,
376
+ currentFooter: projected[SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES].footerSettings,
370
377
  stale,
371
378
  changeSet,
372
379
  changeSetHash,
@@ -378,32 +385,7 @@ export async function comparePresentation(client, siteId, validated, manifest) {
378
385
  };
379
386
  }
380
387
 
381
- export async function themePush(invocation) {
382
- const session = await openSession(invocation);
383
- const { client, config, siteId, onProgress } = session;
384
- const dryRun = invocation.dryRun === true;
385
- // One advisory line before this verb does any work, and only when the
386
- // exchange said the platform is paused. It changes nothing else: the write
387
- // still runs and its refusal still classifies as platform_paused (TR00692).
388
- if (!dryRun) warnIfExternalWritesPaused(session, VERB_THEME_PUSH);
389
- const appearanceContext = await readAppearanceWorkspaceContext(config.workspaceDir, siteId);
390
- const validated = await validateThemeWorkspace(
391
- config.workspaceDir,
392
- siteId,
393
- appearanceContext.knownImageIds,
394
- undefined,
395
- { deferContextValidation: true },
396
- );
397
- const { publishing, themes, scalarOperations } = validated;
398
- // The save's response replaces the workspace footer document, so refuse
399
- // while it still carries footer-content edits that footer push has not
400
- // saved. Context-only differences are theme push's own to write.
401
- requireFooterContentPushed(appearanceContext.footer, publishing.footerSettings);
402
- const baseline = readPresentationBaseline(appearanceContext.manifest);
403
- if (!dryRun && baseline === undefined) {
404
- throw presentationPullRequired();
405
- }
406
- onProgress(`Validated the complete light/dark theme pair and ${scalarOperations.length} appearance settings.`);
388
+ function reportPushWarnings(themes, onProgress) {
407
389
  for (const warning of themes.warnings) onProgress(`Espalier warning: ${warning}`);
408
390
  if (themes.warningsTruncated) {
409
391
  const hidden = themes.warningCount - themes.warnings.length;
@@ -411,77 +393,27 @@ export async function themePush(invocation) {
411
393
  `${hidden} more Espalier warning(s) not shown; resolve the ones above and run theme push --dry-run to see them.`,
412
394
  );
413
395
  }
414
- const warnings = {
396
+ return {
415
397
  items: themes.warnings,
416
398
  count: themes.warningCount,
417
399
  ...(themes.warningsTruncated ? { truncated: true } : {}),
418
400
  };
401
+ }
419
402
 
420
- // The fresh read serves both modes: the dry run compares against it, and
421
- // the push checks the complete post-save context state. Nothing before
422
- // this point, and nothing in a dry run after it, writes to the site.
423
- const comparison = await withRefusalGuidance(
424
- onProgress,
425
- "theme push",
426
- async () => await comparePresentation(client, siteId, validated, appearanceContext.manifest),
427
- );
428
- const { current, stale, changeSet, changeSetHash, pending, replayable, replaying, differences, changed } = comparison;
429
-
430
- if (dryRun) {
431
- for (const entry of differences) {
432
- if (entry.paths.length === 0 && entry.truncated !== true) continue;
433
- onProgress(`${entry.file} differs at: ${entry.paths.join(", ")}${entry.truncated ? ", and more" : ""}.`);
434
- }
435
- if (!changed) onProgress("The workspace's presentation matches the site; a push would change nothing.");
436
- if (baseline === undefined) {
437
- onProgress(
438
- "The pull manifest records no presentation baseline; a push would refuse until the workspace is re-pulled.",
439
- );
440
- } else if (replaying) {
441
- onProgress(
442
- `The site's presentation revision moved since this workspace was pulled (${baseline.revision} → `
443
- + `${current.revision}), and the manifest records a save of this same change set whose response was `
444
- + "lost; a push would replay it under its original baseline rather than refuse.",
445
- );
446
- } else if (stale) {
447
- onProgress(
448
- `The site's presentation revision moved since this workspace was pulled (${baseline.revision} → `
449
- + `${current.revision}); a push would be refused. Keep copies of the edited files, pull, and re-apply.`,
450
- );
451
- }
452
- onProgress("Dry run: nothing was written.");
453
- return successResult(VERB_THEME_PUSH, siteId, {
454
- dryRun: true,
455
- revision: {
456
- ...(baseline === undefined ? {} : { baseline: baseline.revision }),
457
- current: current.revision,
458
- stale: baseline === undefined ? undefined : stale,
459
- },
460
- ...(pending === undefined ? {} : {
461
- pendingSave: {
462
- ...(pending.startedAt === undefined ? {} : { startedAt: pending.startedAt }),
463
- sameChangeSet: replayable,
464
- },
465
- }),
466
- changed,
467
- differences,
468
- warnings,
469
- });
470
- }
471
-
472
- if (stale && !replaying) {
473
- // Refused here, before any request that could write, with the same
474
- // guidance the server's fence would give — and with the paths that
475
- // differ, which the server cannot know.
476
- if (pending !== undefined) {
477
- onProgress(
478
- "The manifest records an earlier save of a different change set whose response was lost; the site may hold "
479
- + "it. The pull that refreshes the baseline shows what the site holds now.",
480
- );
481
- }
482
- throw presentationMovedRefusal(comparison);
483
- }
403
+ async function completePushWarnings(appearance, resources, evidence, onProgress, chromeDependencies) {
404
+ const { themes } = appearance;
405
+ const { warnings } = await completeChromeReport({
406
+ themes,
407
+ appearance,
408
+ resources,
409
+ nameReportEnabled: selectNameReportEligibility(evidence),
410
+ }, chromeDependencies);
411
+ return reportPushWarnings(withChromeWarnings(themes, warnings), onProgress);
412
+ }
484
413
 
414
+ async function saveComparedPresentation(session, comparison) {
415
+ const { client, config, siteId, onProgress } = session;
416
+ const { baseline, changeSet, changeSetHash, pending, replaying } = comparison;
485
417
  const expectedRevision = replaying ? pending.expectedRevision : baseline.revision;
486
418
  if (replaying) {
487
419
  onProgress(
@@ -535,8 +467,10 @@ export async function themePush(invocation) {
535
467
  }
536
468
  throw translateSaveRefusal(error);
537
469
  }
470
+ return saved;
471
+ }
538
472
 
539
- const { presentation, applied } = saved;
473
+ async function adoptSavedFooter(workspaceDir, siteId, presentation, publishing) {
540
474
  const savedFooter = presentation.sitePublishingPreferences?.footerSettings;
541
475
  if (!isPlainObject(savedFooter)) {
542
476
  throw new SiteAuthoringError(
@@ -552,7 +486,7 @@ export async function themePush(invocation) {
552
486
  // than one that overwrites the save.
553
487
  const projectedFooter = projectFooterSettingsForWorkspace(savedFooter);
554
488
  await writeWorkspaceJson(
555
- config.workspaceDir,
489
+ workspaceDir,
556
490
  `${SETTINGS_DIRECTORY}/${SETTINGS_FILES[SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES]}`,
557
491
  {
558
492
  entityId: siteId,
@@ -560,9 +494,136 @@ export async function themePush(invocation) {
560
494
  settings: { ...publishing, footerSettings: projectedFooter },
561
495
  },
562
496
  );
563
- await advanceFooterManifest(config.workspaceDir, siteId, projectedFooter, undefined, {
497
+ await advanceFooterManifest(workspaceDir, siteId, projectedFooter, undefined, {
564
498
  presentationRevision: presentation.revision,
565
499
  });
500
+ return projectedFooter;
501
+ }
502
+
503
+ export async function themePush(invocation, chromeDependencies) {
504
+ const session = await openSession(invocation);
505
+ const { client, config, siteId, onProgress } = session;
506
+ const dryRun = invocation.dryRun === true;
507
+ // One advisory line before this verb does any work, and only when the
508
+ // exchange said the platform is paused. It changes nothing else: the write
509
+ // still runs and its refusal still classifies as platform_paused (TR00692).
510
+ if (!dryRun) warnIfExternalWritesPaused(session, VERB_THEME_PUSH);
511
+ const appearanceContext = await readAppearanceWorkspaceContext(config.workspaceDir, siteId);
512
+ const validated = await validateThemeWorkspace(
513
+ config.workspaceDir,
514
+ siteId,
515
+ appearanceContext.knownImageIds,
516
+ undefined,
517
+ { deferContextValidation: true },
518
+ );
519
+ const { publishing, scalarOperations } = validated;
520
+ // The save's response replaces the workspace footer document, so refuse
521
+ // while it still carries footer-content edits that footer push has not
522
+ // saved. Context-only differences are theme push's own to write.
523
+ requireFooterContentPushed(appearanceContext.footer, publishing.footerSettings);
524
+ const baseline = readPresentationBaseline(appearanceContext.manifest);
525
+ if (!dryRun && baseline === undefined) {
526
+ throw presentationPullRequired();
527
+ }
528
+ onProgress(`Validated the complete light/dark theme pair and ${scalarOperations.length} appearance settings.`);
529
+ let comparison;
530
+ let resources;
531
+ let saved;
532
+ try {
533
+ // Both modes check the complete proposed context state against the site.
534
+ comparison = await withRefusalGuidance(
535
+ onProgress,
536
+ "theme push",
537
+ async () => await comparePresentation(client, siteId, validated, appearanceContext.manifest),
538
+ );
539
+ if (!dryRun && comparison.stale && !comparison.replaying) {
540
+ // Report the paths that differ before sending a request that could write.
541
+ if (comparison.pending !== undefined) {
542
+ onProgress(
543
+ "The manifest records an earlier save of a different change set whose response was lost; the site may hold "
544
+ + "it. The pull that refreshes the baseline shows what the site holds now.",
545
+ );
546
+ }
547
+ throw presentationMovedRefusal(comparison);
548
+ }
549
+
550
+ // Keep the optional snapshot on this side of the save. Report completion
551
+ // never reads settings or manifests after the response has arrived.
552
+ resources = await captureChromeResources({ ...appearanceContext, siteId, workspaceDir: config.workspaceDir });
553
+ if (!dryRun) saved = await saveComparedPresentation(session, comparison);
554
+ } catch (error) {
555
+ reportPushWarnings(validated.themes, onProgress);
556
+ throw error;
557
+ }
558
+ const { current, stale, pending, replayable, replaying, differences, changed } = comparison;
559
+ const { manifest } = appearanceContext;
560
+
561
+ if (dryRun) {
562
+ // The save overlays the proposed context and variant on the site's
563
+ // footer, and leaves publishing preferences and asset delivery in place.
564
+ const warnings = await completePushWarnings(
565
+ validated,
566
+ { ...resources, footerSettings: comparison.currentFooter, presentation: current },
567
+ { current, manifest },
568
+ onProgress,
569
+ chromeDependencies,
570
+ );
571
+ for (const entry of differences) {
572
+ if (entry.paths.length === 0 && entry.truncated !== true) continue;
573
+ onProgress(`${entry.file} differs at: ${entry.paths.join(", ")}${entry.truncated ? ", and more" : ""}.`);
574
+ }
575
+ if (!changed) onProgress("The workspace's presentation matches the site; a push would change nothing.");
576
+ if (baseline === undefined) {
577
+ onProgress(
578
+ "The pull manifest records no presentation baseline; a push would refuse until the workspace is re-pulled.",
579
+ );
580
+ } else if (replaying) {
581
+ onProgress(
582
+ `The site's presentation revision moved since this workspace was pulled (${baseline.revision} → `
583
+ + `${current.revision}), and the manifest records a save of this same change set whose response was `
584
+ + "lost; a push would replay it under its original baseline rather than refuse.",
585
+ );
586
+ } else if (stale) {
587
+ onProgress(
588
+ `The site's presentation revision moved since this workspace was pulled (${baseline.revision} → `
589
+ + `${current.revision}); a push would be refused. Keep copies of the edited files, pull, and re-apply.`,
590
+ );
591
+ }
592
+ onProgress("Dry run: nothing was written.");
593
+ return successResult(VERB_THEME_PUSH, siteId, {
594
+ dryRun: true,
595
+ revision: {
596
+ ...(baseline === undefined ? {} : { baseline: baseline.revision }),
597
+ current: current.revision,
598
+ stale: baseline === undefined ? undefined : stale,
599
+ },
600
+ ...(pending === undefined ? {} : {
601
+ pendingSave: {
602
+ ...(pending.startedAt === undefined ? {} : { startedAt: pending.startedAt }),
603
+ sameChangeSet: replayable,
604
+ },
605
+ }),
606
+ changed,
607
+ differences,
608
+ warnings,
609
+ });
610
+ }
611
+
612
+ const { presentation, applied } = saved;
613
+ const projectedFooter = await adoptSavedFooter(config.workspaceDir, siteId, presentation, publishing).catch((error) => {
614
+ reportPushWarnings(validated.themes, onProgress);
615
+ throw error;
616
+ });
617
+ const warnings = await completePushWarnings(
618
+ {
619
+ ...validated,
620
+ footerPresentation: { context: projectedFooter.context, logoVariant: projectedFooter.logoVariant },
621
+ },
622
+ { ...resources, footerSettings: projectedFooter, presentation },
623
+ { saved, current, manifest },
624
+ onProgress,
625
+ chromeDependencies,
626
+ );
566
627
  onProgress(
567
628
  applied
568
629
  ? "Saved the complete presentation in one transaction: surface contexts and logo choices, appearance settings, and both "
@@ -1,10 +1,27 @@
1
- import { getSitePresentation, withRefusalGuidance } from "../api.js";
2
- import { LIMITS, VERB_THEME_RESOLVE } from "../constants.js";
1
+ import { AA_LARGE_RATIO, AA_TEXT_RATIO } from "@taprootio/espalier/shared/theme";
2
+
3
+ import { getNavigation, getSitePresentation, withRefusalGuidance } from "../api.js";
4
+ import { appearanceImageIds, footerPresentationOverlay, validateAppearanceScalarGroup } from "../appearance-contract.js";
5
+ import { CAPABILITY_CONTENT } from "../capabilities.js";
6
+ import { captureChromeResources } from "../chrome-input.js";
7
+ import { displayChromeContext, indexChromePaint } from "../chrome-output.js";
8
+ import { completeChromeReport } from "../chrome-report.js";
9
+ import { LIMITS, SURFACE_DOCS_PRESENTATION, SURFACE_STANDARD, VERB_THEME_RESOLVE } from "../constants.js";
3
10
  import { SiteAuthoringError } from "../errors.js";
11
+ import { footerImageIds, validateFooterDocument } from "../footer-contract.js";
12
+ import { appearanceResourceIds } from "../footer-workspace.js";
4
13
  import { CHECK_AREA, collectProblems, refuseProblems, withinByteBudget } from "../problems.js";
5
14
  import { boundedByBytes, openAnonymousSession, openSession, successResult } from "../session.js";
6
- import { projectSettingsGroup, SETTINGS_GROUPS, SETTINGS_TYPE_TAPROOT_STYLES } from "../settings-catalog.js";
7
- import { AA_LARGE_RATIO, AA_TEXT_RATIO, resolveThemePair, THEME_STYLES_FILE } from "../theme-resolve.js";
15
+ import {
16
+ projectSettingsGroup,
17
+ SETTINGS_GROUPS,
18
+ SETTINGS_TYPE_SITE_HEADER,
19
+ SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES,
20
+ SETTINGS_TYPE_TAPROOT_STYLES,
21
+ } from "../settings-catalog.js";
22
+ import { resolveThemePair, THEME_STYLES_FILE } from "../theme-resolve.js";
23
+ import { readManifest, readMediaManifest } from "../workspace.js";
24
+ import { validateNavigationWorkspaceDocument } from "./nav-push.js";
8
25
  import { missingThemeSettings, readSettingsDocument, requireNoMissingSettings } from "./theme-push.js";
9
26
 
10
27
  // A result must fit LIMITS.githubOutputBytes (64 KiB), and a theme may declare 128 contexts a scheme. The lists that
@@ -13,8 +30,12 @@ import { missingThemeSettings, readSettingsDocument, requireNoMissingSettings }
13
30
  const RESULT_ENVELOPE_BYTES = 4 * 1024;
14
31
  const FLAG_BYTE_BUDGET = 10 * 1024;
15
32
  const NAME_LIST_BYTE_BUDGET = 6 * 1024;
33
+ // The maximal indexed catalog and cards occupy 9,772 bytes. Adding 25% rounds up to 12 KiB.
34
+ export const CHROME_BYTE_BUDGET = 12 * 1024;
16
35
 
17
36
  const STYLES_GROUP = SETTINGS_GROUPS.find((group) => group.settingsType === SETTINGS_TYPE_TAPROOT_STYLES);
37
+ const HEADER_GROUP = SETTINGS_GROUPS.find((group) => group.settingsType === SETTINGS_TYPE_SITE_HEADER);
38
+ const PUBLISHING_GROUP = SETTINGS_GROUPS.find((group) => group.settingsType === SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES);
18
39
 
19
40
  /** The workspace's pair, read the way theme push reads it; or the site's, projected the way pull writes it. */
20
41
  async function readThemes(invocation) {
@@ -23,7 +44,7 @@ async function readThemes(invocation) {
23
44
  const presentation = await withRefusalGuidance(session.onProgress, "theme resolve", async () =>
24
45
  await getSitePresentation(session.client, session.siteId));
25
46
  const projected = projectSettingsGroup(STYLES_GROUP, presentation);
26
- return { siteId: session.siteId, source: "site", themes: [projected.lightTheme, projected.darkTheme] };
47
+ return { siteId: session.siteId, source: "site", style: projected, session, presentation };
27
48
  }
28
49
  const { config } = await openAnonymousSession({ ...invocation, client: null });
29
50
  if (config === undefined) {
@@ -41,7 +62,103 @@ async function readThemes(invocation) {
41
62
  const style = await readSettingsDocument(config.workspaceDir, config.siteId, SETTINGS_TYPE_TAPROOT_STYLES);
42
63
  // The same preflight push and validate run, so a stale workspace gets the same code and the full path list.
43
64
  requireNoMissingSettings(missingThemeSettings(style));
44
- return { siteId: config.siteId, source: "workspace", themes: [style.lightTheme, style.darkTheme] };
65
+ return { siteId: config.siteId, source: "workspace", style, config };
66
+ }
67
+
68
+ async function optionalEvidence(read) {
69
+ try {
70
+ return await read();
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ async function siteNavigation(session) {
77
+ const capabilities = session.exchanged?.capabilities;
78
+ if (session.surface !== SURFACE_STANDARD || !Array.isArray(capabilities) || !capabilities.includes(CAPABILITY_CONTENT)) {
79
+ return undefined;
80
+ }
81
+ return await optionalEvidence(async () => {
82
+ const { navItems } = await getNavigation(session.client, session.siteId, { requireEvidence: true });
83
+ return validateNavigationWorkspaceDocument({ siteId: session.siteId, navItems }, session.siteId);
84
+ });
85
+ }
86
+
87
+ async function readReportEvidence({ siteId, style, config, session, presentation }) {
88
+ let header;
89
+ let publishing;
90
+ let resources;
91
+ if (session) {
92
+ const [navigation, projectedHeader, projectedPublishing] = await Promise.all([
93
+ siteNavigation(session),
94
+ optionalEvidence(() => presentation.headerSettings === undefined ? undefined : projectSettingsGroup(HEADER_GROUP, presentation)),
95
+ optionalEvidence(() => presentation.sitePublishingPreferences === undefined
96
+ ? undefined
97
+ : projectSettingsGroup(PUBLISHING_GROUP, presentation)),
98
+ ]);
99
+ header = projectedHeader;
100
+ publishing = projectedPublishing;
101
+ resources = {
102
+ source: "site",
103
+ presentation,
104
+ navigation,
105
+ settingsOnly: session.surface === SURFACE_DOCS_PRESENTATION,
106
+ knownImageIds: new Set([
107
+ ...appearanceImageIds({ [SETTINGS_TYPE_TAPROOT_STYLES]: style }),
108
+ ...footerImageIds(publishing?.footerSettings),
109
+ ]),
110
+ };
111
+ } else {
112
+ const { workspaceDir } = config;
113
+ const [manifest, mediaManifest, authoredHeader, authoredPublishing] = await Promise.all([
114
+ optionalEvidence(() => readManifest(workspaceDir, siteId, { required: false })),
115
+ optionalEvidence(() => readMediaManifest(workspaceDir, siteId)),
116
+ optionalEvidence(() => readSettingsDocument(workspaceDir, siteId, SETTINGS_TYPE_SITE_HEADER)),
117
+ optionalEvidence(() => readSettingsDocument(workspaceDir, siteId, SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES)),
118
+ ]);
119
+ header = authoredHeader;
120
+ publishing = authoredPublishing;
121
+ resources = await captureChromeResources({
122
+ workspaceDir,
123
+ siteId,
124
+ manifest,
125
+ mediaManifest,
126
+ settingsOnly: config.authoringSurface === SURFACE_DOCS_PRESENTATION,
127
+ ...appearanceResourceIds(manifest, mediaManifest),
128
+ });
129
+ }
130
+
131
+ const acceptedHeader = header === undefined ? undefined : await optionalEvidence(() =>
132
+ validateAppearanceScalarGroup(SETTINGS_TYPE_SITE_HEADER, header, resources.knownImageIds));
133
+ const acceptedStyle = await optionalEvidence(() =>
134
+ validateAppearanceScalarGroup(SETTINGS_TYPE_TAPROOT_STYLES, style, resources.knownImageIds));
135
+ const footerSettings = await optionalEvidence(() => {
136
+ footerPresentationOverlay(publishing?.footerSettings);
137
+ return validateFooterDocument(publishing.footerSettings, resources);
138
+ });
139
+ return {
140
+ appearance: {
141
+ style: acceptedStyle ?? { lightTheme: style.lightTheme, darkTheme: style.darkTheme },
142
+ header: acceptedHeader,
143
+ publishing,
144
+ },
145
+ resources: { ...resources, footerSettings },
146
+ };
147
+ }
148
+
149
+ function selectChrome(report, { themeScheme, themeContext }) {
150
+ const matchesContext = (entry) => themeContext === undefined || entry.context === themeContext;
151
+ const entries = Object.fromEntries(Object.entries(report.entries)
152
+ .filter(([scheme]) => themeScheme === undefined || themeScheme === scheme)
153
+ .map(([scheme, surfaces]) => [scheme, surfaces.filter(matchesContext)]));
154
+ const flags = report.flags.filter((flag) => Object.hasOwn(entries, flag.scheme) && matchesContext(flag));
155
+ return {
156
+ ...indexChromePaint(entries),
157
+ unavailable: report.unavailable,
158
+ navigationUnavailable: report.navigationUnavailable,
159
+ flags: flags.map((flag) => ({ ...flag, context: displayChromeContext(flag.context).context })),
160
+ contrast: { pairs: Object.values(entries).flat().reduce((count, entry) => count + entry.pairs.length, 0), belowAa: flags.length },
161
+ };
45
162
  }
46
163
 
47
164
  /**
@@ -50,8 +167,9 @@ async function readThemes(invocation) {
50
167
  * each ink-on-surface pairing. Offline from the pulled workspace by default;
51
168
  * `--site` reads the site's own theme instead (and needs a credential).
52
169
  */
53
- export async function themeResolve(invocation) {
54
- const { siteId, source, themes: [lightTheme, darkTheme] } = await readThemes(invocation);
170
+ export async function themeResolve(invocation, chromeDependencies) {
171
+ const input = await readThemes(invocation);
172
+ const { siteId, source, style: { lightTheme, darkTheme } } = input;
55
173
  const problems = [];
56
174
  const resolution = await collectProblems(
57
175
  problems,
@@ -63,9 +181,12 @@ export async function themeResolve(invocation) {
63
181
  );
64
182
  refuseProblems(problems, "theme resolve");
65
183
 
66
- const flags = { ...boundedByBytes(resolution.flags, FLAG_BYTE_BUDGET), count: resolution.flags.length };
184
+ const evidence = await readReportEvidence(input);
185
+ const chrome = selectChrome(await completeChromeReport({ ...evidence, themes: resolution.encoded }, chromeDependencies), invocation);
186
+ const allFlags = [...resolution.flags, ...chrome.flags];
187
+ const flags = { ...boundedByBytes(allFlags, FLAG_BYTE_BUDGET), count: allFlags.length };
67
188
  const contexts = { ...boundedByBytes(resolution.contexts, NAME_LIST_BYTE_BUDGET), count: resolution.contexts.length };
68
- const surfaceBudget = LIMITS.githubOutputBytes - RESULT_ENVELOPE_BYTES - NAME_LIST_BYTE_BUDGET
189
+ const surfaceBudget = LIMITS.githubOutputBytes - RESULT_ENVELOPE_BYTES - NAME_LIST_BYTE_BUDGET - CHROME_BYTE_BUDGET
69
190
  - Buffer.byteLength(JSON.stringify({ flags, contexts }), "utf8");
70
191
  const entries = resolution.schemes.flatMap(({ scheme, surfaces }) => surfaces.map((surface) => ({ scheme, surface })));
71
192
  const shown = withinByteBudget(entries, surfaceBudget);
@@ -81,7 +202,15 @@ export async function themeResolve(invocation) {
81
202
  thresholds: { textRatio: AA_TEXT_RATIO, largeRatio: AA_LARGE_RATIO },
82
203
  contexts,
83
204
  schemes,
84
- contrast: resolution.contrast,
205
+ chrome: chrome.chrome,
206
+ chromeCatalog: chrome.chromeCatalog,
207
+ ...(chrome.unavailable ? { chromeUnavailable: true } : {}),
208
+ ...(chrome.navigationUnavailable ? { chromeNavigationUnavailable: true } : {}),
209
+ contrast: {
210
+ pairs: resolution.contrast.pairs + chrome.contrast.pairs,
211
+ belowAa: resolution.contrast.belowAa + chrome.contrast.belowAa,
212
+ belowApca: resolution.contrast.belowApca,
213
+ },
85
214
  flags,
86
215
  ...(omitted.length === 0
87
216
  ? {}