@taprootio/site-authoring 0.62.0 → 0.64.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.
Files changed (69) hide show
  1. package/README.md +63 -23
  2. package/package.json +2 -2
  3. package/src/api.js +149 -21
  4. package/src/appearance-contract.js +9 -0
  5. package/src/article-end-settings.js +295 -0
  6. package/src/changelog.json +39 -0
  7. package/src/chrome-input.js +1 -1
  8. package/src/cli.js +110 -26
  9. package/src/constants.js +7 -0
  10. package/src/content/components.js +130 -14
  11. package/src/content/cta-decoration-paint.js +321 -0
  12. package/src/content/form-placement-presentation.js +91 -0
  13. package/src/content/form-placement-presentation.json +6 -0
  14. package/src/content/free-form-section-registry.json +19 -1
  15. package/src/content/free-form-sections.js +64 -55
  16. package/src/content/markdown.js +13 -0
  17. package/src/content/tiptap-prosemirror.ts +72 -59
  18. package/src/content/validate-document.js +2 -0
  19. package/src/cta-artwork-warnings.js +164 -0
  20. package/src/errors.js +6 -0
  21. package/src/field-schema.json +6 -2
  22. package/src/field-validation.js +14 -5
  23. package/src/footer-workspace.js +7 -3
  24. package/src/form-references.js +71 -9
  25. package/src/forms-contract.js +3 -5
  26. package/src/heading-outline.js +7 -0
  27. package/src/output.js +2 -0
  28. package/src/page-article-end.js +66 -0
  29. package/src/page-block-catalog.js +54 -0
  30. package/src/page-form-presentation.js +104 -0
  31. package/src/page-structure-checks.js +7 -1
  32. package/src/placed-image-ids.js +15 -18
  33. package/src/presentation-reference.js +30 -52
  34. package/src/reference-help.js +97 -27
  35. package/src/reusable-blocks.js +429 -0
  36. package/src/reusable-placements.js +271 -0
  37. package/src/setting-reference.js +25 -1
  38. package/src/settings-catalog.js +1 -0
  39. package/src/site-check-findings.js +30 -2
  40. package/src/site-check-rules.json +1 -0
  41. package/src/site-checks.js +26 -2
  42. package/src/site-health-findings.js +25 -3
  43. package/src/site-health-image-checks.js +1 -1
  44. package/src/staging-check.js +108 -21
  45. package/src/staging-served.js +5 -49
  46. package/src/status-warning-paints.js +17 -0
  47. package/src/template-token-reach.json +14 -2
  48. package/src/theme-resolve.js +27 -0
  49. package/src/transport.js +41 -5
  50. package/src/typed-page-reference.js +55 -5
  51. package/src/typed-pages.js +27 -4
  52. package/src/verbs/approve.js +2 -1
  53. package/src/verbs/deploy.js +93 -15
  54. package/src/verbs/footer-push.js +4 -2
  55. package/src/verbs/forms-push.js +9 -0
  56. package/src/verbs/health.js +11 -6
  57. package/src/verbs/index.js +3 -0
  58. package/src/verbs/pages-blocks-pull.js +22 -0
  59. package/src/verbs/pages-push.js +89 -34
  60. package/src/verbs/plan.js +34 -5
  61. package/src/verbs/pull.js +213 -124
  62. package/src/verbs/status.js +20 -2
  63. package/src/verbs/theme-push.js +164 -14
  64. package/src/verbs/theme-resolve.js +114 -40
  65. package/src/verbs/validate.js +49 -18
  66. package/src/workspace-check.js +42 -5
  67. package/src/workspace-context-usage.js +54 -1
  68. package/src/workspace.js +37 -7
  69. package/test/fixtures/default-site-theme.json +1 -1
@@ -1,3 +1,29 @@
1
+ import {
2
+ ARTICLE_END_FILE,
3
+ articleEndChanges,
4
+ articleEndImageIds,
5
+ readArticleEndPresentation,
6
+ readArticleEndWorkspace,
7
+ reportArticleEndChanges,
8
+ requireSavedArticleEndBands,
9
+ resolveArticleEndWorkspace,
10
+ } from "../article-end-settings.js";
11
+ import {
12
+ appendReusableBlockReport,
13
+ checkReusableWorkspaceTargets,
14
+ readReusablePresentation,
15
+ readReusableWorkspace,
16
+ reportReusableChanges,
17
+ requireKnownReusableFormPresentation,
18
+ requireRetainedReusableContexts,
19
+ requireReusableSurface,
20
+ resolveReusableWorkspace,
21
+ reusableBlockChanges,
22
+ reusableFormPresentationChanged,
23
+ reusableWorkspaceEvidence,
24
+ reusableWorkspaceReport,
25
+ REUSABLE_BLOCKS_FILE,
26
+ } from "../reusable-blocks.js";
1
27
  import { getSitePresentation, saveSitePresentation, withRefusalGuidance } from "../api.js";
2
28
  import {
3
29
  APPEARANCE_FOOTER_FIELDS,
@@ -25,7 +51,7 @@ import {
25
51
  usageUnavailableLine,
26
52
  } from "../status-warning-paints.js";
27
53
  import { sharedThemeContextNames } from "../content/free-form-sections.js";
28
- import { REFUSAL_UNCLASSIFIED, VERB_THEME_PUSH } from "../constants.js";
54
+ import { REFUSAL_UNCLASSIFIED, SURFACE_STANDARD, VERB_THEME_PUSH } from "../constants.js";
29
55
  import { MISSING_SETTING_MESSAGE, SiteAuthoringError } from "../errors.js";
30
56
  import { projectFooterSettingsForWorkspace, validateFooterDocument } from "../footer-contract.js";
31
57
  import {
@@ -142,13 +168,21 @@ export function requireNoMissingSettings(missing) {
142
168
  );
143
169
  }
144
170
 
171
+ function requireCodeCopySurface(publishing, surface) {
172
+ if (publishing.codeCopyEnabled === true && surface !== undefined && surface !== SURFACE_STANDARD) {
173
+ throw new SiteAuthoringError("theme.code_copy_unsupported", "Code copy is available on Standard sites.", {
174
+ field: "site-publishing-preferences.codeCopyEnabled",
175
+ });
176
+ }
177
+ }
178
+
145
179
  /** Offline callers validate context names here; push waits for the current state to classify removals. */
146
180
  export async function validateThemeWorkspace(
147
181
  workspaceDir,
148
182
  siteId,
149
183
  knownImageIds,
150
184
  expectedEntityIds,
151
- { deferContextValidation = false, fixtureExport = false } = {},
185
+ { deferContextValidation = false, fixtureExport = false, authoringSurface, mediaManifest } = {},
152
186
  ) {
153
187
  const [style, brand, header, publishingDocument] = await Promise.all([
154
188
  readSettingsDocument(
@@ -177,6 +211,7 @@ export async function validateThemeWorkspace(
177
211
  ),
178
212
  ]);
179
213
  const { settings: publishing } = publishingDocument;
214
+ requireCodeCopySurface(publishing, authoringSurface);
180
215
  for (const name of ["tagDestinations", "recipeMetadataDestinations"]) {
181
216
  if (Object.hasOwn(publishing, name)) {
182
217
  publishing[name] = normalizeTagDestinations(publishing[name], `site-publishing-preferences.${name}`);
@@ -223,14 +258,16 @@ export async function validateThemeWorkspace(
223
258
  documents,
224
259
  knownImageIds,
225
260
  );
226
- return { style, brand, header, publishing, publishingDocument, themes, scalarOperations, footerPresentation };
261
+ const reusableBlocks = await readReusableWorkspace(workspaceDir, { authoringSurface, knownImageIds, mediaManifest, style });
262
+ const articleEnd = await readArticleEndWorkspace(workspaceDir, authoringSurface, { knownImageIds, mediaManifest, style });
263
+ return { style, brand, header, publishing, publishingDocument, themes, scalarOperations, footerPresentation, reusableBlocks, articleEnd };
227
264
  }
228
265
 
229
266
  /**
230
267
  * The change set the atomic save receives: every appearance scalar in
231
268
  * registry order, then the two encoded themes, plus the footer presentation fields.
232
269
  */
233
- function buildChangeSet(validated) {
270
+ function buildChangeSet(validated, reusableBlocks, articleEnd) {
234
271
  return {
235
272
  settings: [
236
273
  ...validated.scalarOperations.map((operation) => ({
@@ -246,6 +283,8 @@ function buildChangeSet(validated) {
246
283
  ],
247
284
  footerContext: validated.footerPresentation.context,
248
285
  footerLogoVariant: validated.footerPresentation.logoVariant,
286
+ ...(reusableBlocks === undefined ? {} : { reusableBlockDefinitions: { blocks: reusableBlocks } }),
287
+ ...(articleEnd === undefined ? {} : { articleEnd, articleEndBandEdit: true }),
249
288
  };
250
289
  }
251
290
 
@@ -383,7 +422,8 @@ function effectiveListingCardContext(validated, current) {
383
422
  * current, and whether a save whose response was lost would be replayed.
384
423
  * `theme push` and `plan` both decide from this (TR00823).
385
424
  */
386
- export async function comparePresentation(client, siteId, validated, manifest) {
425
+ export async function comparePresentation(client, siteId, validated, manifest, surface, { plannedPages, onProgress = () => {} } = {}) {
426
+ requireCodeCopySurface(validated.publishing, surface);
387
427
  const baseline = readPresentationBaseline(manifest);
388
428
  let current;
389
429
  try {
@@ -407,9 +447,53 @@ export async function comparePresentation(client, siteId, validated, manifest) {
407
447
  // answer already-current, or apply it if it never committed; anything else
408
448
  // it refuses itself. A pending record for a different change set proves
409
449
  // nothing about the site and takes the ordinary path.
410
- const changeSet = buildChangeSet(validated);
411
- const changeSetHash = computePresentationChangeSetHash(changeSet);
450
+ const reusable = readReusablePresentation(current);
451
+ if (validated.reusableBlocks === undefined) requireRetainedReusableContexts(reusable.blocks, validated.style);
452
+ if (validated.reusableBlocks !== undefined) {
453
+ requireReusableSurface(surface);
454
+ if (reusable.blocks === undefined) {
455
+ throw new SiteAuthoringError("theme.reusable_blocks_unsupported", "This site did not supply editable reusable blocks.", {
456
+ field: REUSABLE_BLOCKS_FILE,
457
+ });
458
+ }
459
+ }
460
+ const reusableBlocks = resolveReusableWorkspace(validated.reusableBlocks, reusableWorkspaceEvidence(reusable));
461
+ const reusableChanges = reusableBlockChanges(reusableBlocks, reusable.blocks);
462
+ const reusableTargets = checkReusableWorkspaceTargets(validated.reusableBlocks, manifest, plannedPages);
463
+ const articleEndSnapshot = readArticleEndPresentation(current);
464
+ if (validated.articleEnd !== undefined && articleEndSnapshot === undefined) {
465
+ throw new SiteAuthoringError("theme.article_end_unsupported", "This site did not supply editable article-end settings.", {
466
+ field: ARTICLE_END_FILE,
467
+ });
468
+ }
469
+ const definitions = reusableBlocks ?? reusable.blocks;
470
+ const tags = articleEndSnapshot?.tags;
471
+ if (validated.articleEnd === undefined) {
472
+ resolveArticleEndWorkspace(articleEndSnapshot?.document, { definitions, style: validated.style });
473
+ }
474
+ const articleEnd = resolveArticleEndWorkspace(validated.articleEnd, { definitions, tags, onProgress });
475
+ const articleChanges = articleEnd === undefined ? undefined : articleEndChanges(
476
+ resolveArticleEndWorkspace(articleEndSnapshot.document),
477
+ articleEnd, reusable.blocks, definitions, tags,
478
+ );
412
479
  const pending = readPendingPresentationSave(manifest);
480
+ const formPresentationChanged = reusableFormPresentationChanged(reusableBlocks, reusable.blocks);
481
+ if (formPresentationChanged) {
482
+ requireKnownReusableFormPresentation(reusableBlocks, reusable.blocks, manifest.reusableBlocks?.formReferences);
483
+ if (current.formPlacementPresentationWritesEnabled !== true) {
484
+ throw new SiteAuthoringError("theme.form_presentation_writes_unavailable",
485
+ "This site is not ready to save reusable Form presentation. Retry after its publishing update finishes.", {
486
+ field: REUSABLE_BLOCKS_FILE,
487
+ });
488
+ }
489
+ }
490
+ const baseChangeSet = buildChangeSet(validated, reusableBlocks, articleEnd);
491
+ const markedChangeSet = { ...baseChangeSet, reusableFormPresentationEdit: true };
492
+ // A committed save may already hold the proposed copy while its response was lost.
493
+ const replayMarked = reusableBlocks !== undefined && pending !== undefined
494
+ && pending.changeSetHash === computePresentationChangeSetHash(markedChangeSet);
495
+ const changeSet = formPresentationChanged || replayMarked ? markedChangeSet : baseChangeSet;
496
+ const changeSetHash = computePresentationChangeSetHash(changeSet);
413
497
  const replayable = pending !== undefined && pending.changeSetHash === changeSetHash;
414
498
  const projected = Object.fromEntries(SETTINGS_GROUPS.map((group) => [
415
499
  group.settingsType, projectSettingsGroup(group, current),
@@ -434,6 +518,18 @@ export async function comparePresentation(client, siteId, validated, manifest) {
434
518
  );
435
519
  }
436
520
  const differences = describeDifferences(validated, projected);
521
+ if (reusableChanges !== undefined) {
522
+ const paths = Object.values(reusableChanges).flatMap((rows) => rows.map(({ key }) => `blocks.${key}`));
523
+ differences.push({ file: REUSABLE_BLOCKS_FILE, paths });
524
+ }
525
+ if (articleChanges !== undefined) {
526
+ const paths = [];
527
+ if (articleChanges.current.defaultCta !== articleChanges.proposed.defaultCta) paths.push("defaultCtaKey");
528
+ if (articleChanges.proposed.defaultBandChanged) paths.push("defaultBand");
529
+ if (JSON.stringify(articleChanges.current.rules) !== JSON.stringify(articleChanges.proposed.rules)) paths.push("rules");
530
+ if (paths.length === 0) paths.push("rules");
531
+ differences.push({ file: ARTICLE_END_FILE, paths });
532
+ }
437
533
  return {
438
534
  baseline,
439
535
  current,
@@ -445,6 +541,9 @@ export async function comparePresentation(client, siteId, validated, manifest) {
445
541
  replayable,
446
542
  replaying: stale && replayable,
447
543
  differences,
544
+ reusableChanges,
545
+ reusableTargets,
546
+ articleChanges,
448
547
  changed: differences.some((entry) => entry.paths.length > 0 || entry.truncated === true),
449
548
  };
450
549
  }
@@ -547,7 +646,33 @@ async function saveComparedPresentation(session, comparison) {
547
646
  return saved;
548
647
  }
549
648
 
550
- async function adoptSavedFooter(workspaceDir, siteId, presentation, publishing) {
649
+ async function pinSavedArticleEndRules(workspaceDir, source, submitted, saved, authoringSurface) {
650
+ const pins = new Map();
651
+ for (const [index, rule] of (source?.rules ?? []).entries()) {
652
+ if (rule.tag === undefined || rule.tagId !== undefined) continue;
653
+ const tagId = submitted?.rules[index]?.tagId;
654
+ if (tagId === undefined || !saved?.rules.some(row => row.template === rule.template && row.tagId === tagId)) {
655
+ throw new SiteAuthoringError("api.article_end_contract", "Taproot did not confirm an article-end rule’s tag.", {
656
+ field: ARTICLE_END_FILE,
657
+ });
658
+ }
659
+ pins.set(`${rule.template}/${rule.tag}`, tagId);
660
+ }
661
+ if (pins.size === 0) return;
662
+ const current = await readArticleEndWorkspace(workspaceDir, authoringSurface);
663
+ if (current === undefined) return;
664
+ let changed = false;
665
+ const rules = current.rules.map(rule => {
666
+ if (rule.tag === undefined || rule.tagId !== undefined) return rule;
667
+ const tagId = pins.get(`${rule.template}/${rule.tag}`);
668
+ if (tagId === undefined) return rule;
669
+ changed = true;
670
+ return { ...rule, tagId };
671
+ });
672
+ if (changed) await writeWorkspaceJson(workspaceDir, ARTICLE_END_FILE, { ...current, rules });
673
+ }
674
+
675
+ async function adoptSavedFooter(workspaceDir, siteId, presentation, publishing, articleEnd, changeSet, authoringSurface) {
551
676
  const savedFooter = presentation.sitePublishingPreferences?.footerSettings;
552
677
  if (!isPlainObject(savedFooter)) {
553
678
  throw new SiteAuthoringError(
@@ -561,7 +686,17 @@ async function adoptSavedFooter(workspaceDir, siteId, presentation, publishing)
561
686
  // from the same response. Committed remotely before either local write, so
562
687
  // a failure here leaves a stale baseline that refuses the next push rather
563
688
  // than one that overwrites the save.
689
+ const savedReusable = readReusablePresentation(presentation);
690
+ if (changeSet.reusableFormPresentationEdit === true && (savedReusable.blocks === undefined ||
691
+ reusableFormPresentationChanged(changeSet.reusableBlockDefinitions.blocks, savedReusable.blocks))) {
692
+ throw new SiteAuthoringError("api.reusable_blocks_contract",
693
+ "Taproot did not confirm the reusable Form presentation. Pull settings to check the saved definition.",
694
+ { field: REUSABLE_BLOCKS_FILE });
695
+ }
564
696
  const projectedFooter = projectFooterSettingsForWorkspace(savedFooter);
697
+ const savedArticleEnd = readArticleEndPresentation(presentation);
698
+ requireSavedArticleEndBands(changeSet.articleEnd, savedArticleEnd?.document);
699
+ await pinSavedArticleEndRules(workspaceDir, articleEnd, changeSet.articleEnd, savedArticleEnd?.document, authoringSurface);
565
700
  const { tagDestinations, recipeMetadataDestinations } = presentation.sitePublishingPreferences ?? {};
566
701
  const settings = { ...publishing, footerSettings: projectedFooter };
567
702
  for (const [name, destinations] of Object.entries({ tagDestinations, recipeMetadataDestinations })) {
@@ -581,6 +716,9 @@ async function adoptSavedFooter(workspaceDir, siteId, presentation, publishing)
581
716
  tagDestinations,
582
717
  recipeMetadataDestinations,
583
718
  authoredTagSlugs: tagDestinationCatalogSlugs(presentation.tagDestinationCatalog),
719
+ reusableBlocks: reusableWorkspaceEvidence(savedReusable),
720
+ articleEndTags: savedArticleEnd?.tags,
721
+ articleEndOwnedImages: savedArticleEnd === undefined ? undefined : articleEndImageIds(savedArticleEnd.document),
584
722
  });
585
723
  return projectedFooter;
586
724
  }
@@ -595,7 +733,11 @@ export async function themePush(invocation, chromeDependencies) {
595
733
  siteId,
596
734
  appearanceContext.knownImageIds,
597
735
  undefined,
598
- { deferContextValidation: true },
736
+ {
737
+ deferContextValidation: true,
738
+ authoringSurface: config.authoringSurface ?? appearanceContext.manifest?.authoringSurface,
739
+ mediaManifest: appearanceContext.mediaManifest,
740
+ },
599
741
  );
600
742
  const { publishing, scalarOperations } = validated;
601
743
  // The save's response replaces the workspace footer document, so refuse
@@ -623,7 +765,7 @@ export async function themePush(invocation, chromeDependencies) {
623
765
  comparison = await withRefusalGuidance(
624
766
  onProgress,
625
767
  "theme push",
626
- async () => await comparePresentation(client, siteId, validated, appearanceContext.manifest),
768
+ async () => await comparePresentation(client, siteId, validated, appearanceContext.manifest, session.surface, { onProgress }),
627
769
  );
628
770
  if (!dryRun && comparison.stale && !comparison.replaying) {
629
771
  // Report the paths that differ before sending a request that could write.
@@ -647,6 +789,7 @@ export async function themePush(invocation, chromeDependencies) {
647
789
  siteId,
648
790
  // The candidate theme's full shared list, so a page naming a context only the candidate defines still counts.
649
791
  themeContexts: sharedThemeContextNames(validated.style.lightTheme, validated.style.darkTheme),
792
+ reusableDefinitions: validated.reusableBlocks,
650
793
  manifest: appearanceContext.manifest,
651
794
  mediaManifest: resources.mediaManifest,
652
795
  header: validated.header,
@@ -660,7 +803,10 @@ export async function themePush(invocation, chromeDependencies) {
660
803
  reportPushWarnings(validated.themes, onProgress);
661
804
  throw error;
662
805
  }
663
- const { current, stale, pending, replayable, replaying, differences, changed } = comparison;
806
+ const { current, stale, pending, replayable, replaying, differences, changed, reusableChanges, reusableTargets, articleChanges } = comparison;
807
+ reportReusableChanges(reusableChanges, onProgress);
808
+ const reusableBlocks = await reusableWorkspaceReport(validated.reusableBlocks, validated.style, reusableTargets, onProgress);
809
+
664
810
  const { manifest } = appearanceContext;
665
811
 
666
812
  if (dryRun) {
@@ -708,7 +854,7 @@ export async function themePush(invocation, chromeDependencies) {
708
854
  );
709
855
  }
710
856
  onProgress("Dry run: nothing was written.");
711
- return fitChromeAdditions(successResult(VERB_THEME_PUSH, siteId, {
857
+ const result = fitChromeAdditions(successResult(VERB_THEME_PUSH, siteId, {
712
858
  dryRun: true,
713
859
  revision: {
714
860
  ...(baseline === undefined ? {} : { baseline: baseline.revision }),
@@ -727,10 +873,13 @@ export async function themePush(invocation, chromeDependencies) {
727
873
  ...(tagDestinationWarnings === undefined ? {} : { tagDestinationWarnings }),
728
874
  ...pushWarnings,
729
875
  }));
876
+ return reportArticleEndChanges(appendReusableBlockReport(result, reusableBlocks, onProgress, reusableChanges), articleChanges, onProgress);
730
877
  }
731
878
 
732
879
  const { presentation, applied } = saved;
733
- const projectedFooter = await adoptSavedFooter(config.workspaceDir, siteId, presentation, publishing).catch((error) => {
880
+ const projectedFooter = await adoptSavedFooter(
881
+ config.workspaceDir, siteId, presentation, publishing, validated.articleEnd, comparison.changeSet, session.surface,
882
+ ).catch((error) => {
734
883
  reportPushWarnings(validated.themes, onProgress);
735
884
  throw error;
736
885
  });
@@ -757,10 +906,11 @@ export async function themePush(invocation, chromeDependencies) {
757
906
  ...scalarOperations.map((operation) => `${operation.settingsType}.${operation.setting}`),
758
907
  ...THEME_SETTINGS.map((setting) => `${SETTINGS_TYPE_TAPROOT_STYLES}.${setting}`),
759
908
  ];
760
- return fitChromeAdditions(successResult(VERB_THEME_PUSH, siteId, {
909
+ const result = fitChromeAdditions(successResult(VERB_THEME_PUSH, siteId, {
761
910
  applied,
762
911
  revision: presentation.revision,
763
912
  written: boundedList(written, 100),
764
913
  ...pushWarnings,
765
914
  }));
915
+ return reportArticleEndChanges(appendReusableBlockReport(result, reusableBlocks, onProgress, reusableChanges), articleChanges, onProgress);
766
916
  }
@@ -21,19 +21,21 @@ import {
21
21
  SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES,
22
22
  SETTINGS_TYPE_TAPROOT_STYLES,
23
23
  } from "../settings-catalog.js";
24
- import { readWorkspaceContextUsage } from "../workspace-context-usage.js";
24
+ import { readReusableWorkspace } from "../reusable-blocks.js";
25
+ import { contextUsageSettings, projectContextUsage, readWorkspaceContextUsage } from "../workspace-context-usage.js";
25
26
  import {
26
27
  contextScopedNames,
27
- hasContextScopedStatusWarning,
28
28
  notCountedLine,
29
29
  statusPaintFields,
30
30
  TEXT_USED_IN,
31
31
  statusWarningPaints,
32
32
  usageUnavailableLine,
33
33
  usedInOf,
34
+ warningUsageByteReserve,
35
+ withoutUsedIn,
34
36
  } from "../status-warning-paints.js";
35
37
  import { sharedThemeContextNames } from "../content/free-form-sections.js";
36
- import { resolveThemePair, THEME_STYLES_FILE } from "../theme-resolve.js";
38
+ import { CONTEXT_USAGE_OMITTED_LINE, resolveThemePair, TEXT_CONTEXT_USAGE, THEME_STYLES_FILE } from "../theme-resolve.js";
37
39
  import { abbreviateThemeContext } from "../theme-validation.js";
38
40
  import { buildTokenPaintCatalog } from "../token-reach.js";
39
41
  import { readManifest, readMediaManifest } from "../workspace.js";
@@ -113,11 +115,12 @@ async function sitePageInventory(session) {
113
115
  });
114
116
  }
115
117
 
116
- async function readReportEvidence({ siteId, style, config, session, presentation }, content) {
118
+ async function readReportEvidence({ siteId, style, config, session, presentation }, content, readWorkspaceUsage) {
117
119
  let header;
118
120
  let publishing;
119
121
  let resources;
120
122
  let readUsage;
123
+ let manifestReason;
121
124
  if (session) {
122
125
  const [navigation, pageInventory, projectedHeader, projectedPublishing] = await Promise.all([
123
126
  siteNavigation(session),
@@ -142,12 +145,17 @@ async function readReportEvidence({ siteId, style, config, session, presentation
142
145
  };
143
146
  } else {
144
147
  const { workspaceDir } = config;
145
- const [manifest, mediaManifest, authoredHeader, authoredPublishing] = await Promise.all([
146
- optionalEvidence(() => readManifest(workspaceDir, siteId, { required: false })),
148
+ const [manifestRead, mediaManifest, authoredHeader, authoredPublishing] = await Promise.all([
149
+ readManifest(workspaceDir, siteId).then(
150
+ (manifest) => ({ manifest }),
151
+ (error) => ({ reason: error instanceof SiteAuthoringError ? error.code : "site.failed" }),
152
+ ),
147
153
  optionalEvidence(() => readMediaManifest(workspaceDir, siteId)),
148
154
  optionalEvidence(() => readSettingsDocument(workspaceDir, siteId, SETTINGS_TYPE_SITE_HEADER)),
149
155
  optionalEvidence(() => readSettingsDocument(workspaceDir, siteId, SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES)),
150
156
  ]);
157
+ const { manifest, reason } = manifestRead;
158
+ manifestReason = reason;
151
159
  header = authoredHeader;
152
160
  publishing = authoredPublishing;
153
161
  resources = await captureChromeResources({
@@ -155,17 +163,21 @@ async function readReportEvidence({ siteId, style, config, session, presentation
155
163
  siteId,
156
164
  manifest,
157
165
  mediaManifest,
158
- settingsOnly: config.authoringSurface === SURFACE_DOCS_PRESENTATION,
166
+ settingsOnly: manifest?.settingsOnly === true || config.authoringSurface === SURFACE_DOCS_PRESENTATION
167
+ || manifest?.authoringSurface === SURFACE_DOCS_PRESENTATION,
159
168
  ...appearanceResourceIds(manifest, mediaManifest),
160
169
  });
161
- // A site read has no pulled pages, so only a workspace report says what uses a context. The read converts
162
- // every page, so the caller runs it only when a warning needs it.
163
- if (manifest !== undefined) {
164
- readUsage = async (contexts) => await optionalEvidence(() => readWorkspaceContextUsage({
170
+ // Each workspace resolve with named contexts pays for one conversion and validation of each page.
171
+ if (manifest !== undefined && !resources.settingsOnly) {
172
+ readUsage = async (contexts, themeContexts) => await optionalEvidence(async () => readWorkspaceUsage({
165
173
  workspaceDir,
166
174
  siteId,
167
175
  // The theme being evaluated, not the styles file on disk, so a context only this theme defines still counts.
168
- themeContexts: sharedThemeContextNames(style.lightTheme, style.darkTheme),
176
+ themeContexts,
177
+ reusableDefinitions: await optionalEvidence(() => readReusableWorkspace(workspaceDir, {
178
+ style, mediaManifest, authoringSurface: config.authoringSurface ?? manifest.authoringSurface,
179
+ knownImageIds: resources.knownImageIds,
180
+ })),
169
181
  manifest,
170
182
  mediaManifest,
171
183
  header,
@@ -193,6 +205,11 @@ async function readReportEvidence({ siteId, style, config, session, presentation
193
205
  publishing,
194
206
  },
195
207
  resources: { ...resources, footerSettings },
208
+ contextSettingsInput: session ? {
209
+ header: presentation.headerSettings,
210
+ publishing: presentation.sitePublishingPreferences,
211
+ } : { header, publishing },
212
+ manifestReason,
196
213
  readUsage,
197
214
  };
198
215
  }
@@ -204,10 +221,9 @@ function selectedWarnings(warnings, { themeScheme, themeContext }) {
204
221
  }
205
222
 
206
223
  /** The selected status warnings and their paint records, selected before the records are capped. */
207
- function statusPaintsFor(completeWarnings, selection, usage) {
224
+ function statusPaintsFor(completeWarnings, selection) {
208
225
  const warnings = selectedWarnings(completeWarnings, selection);
209
- // The `usedIn` lists are not part of what surfaces are sized against; they are added last, from the bytes left.
210
- return { warnings, records: statusWarningPaints(warnings, { usage, usedIn: false }) };
226
+ return { warnings, records: statusWarningPaints(warnings) };
211
227
  }
212
228
 
213
229
  function selectChrome(report, { themeScheme, themeContext }) {
@@ -331,7 +347,7 @@ function omission(entry, contextPositions, tooLarge) {
331
347
  return { scheme, context: label, ...(tooLarge ? { reason: "surface_too_large" } : {}) };
332
348
  }
333
349
 
334
- function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized, usage }) {
350
+ function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized, canReadUsage }) {
335
351
  const { scheme, surface } = entry;
336
352
  // Root retry keeps the named contexts and chrome in the same scheme.
337
353
  const context = surface.context ?? undefined;
@@ -339,17 +355,18 @@ function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeRep
339
355
  const narrowed = entries.filter((row) => matches(row, row.surface.context));
340
356
  const flags = resolution.flags.filter((flag) => matches(flag, flag.context));
341
357
  const chrome = selectChrome(chromeReport, { themeScheme: scheme, themeContext: context });
342
- const narrowedPaints = statusPaintsFor(resolution.encoded.completeWarnings, { themeScheme: scheme, themeContext: context }, usage);
358
+ const narrowedPaints = statusPaintsFor(resolution.encoded.completeWarnings, { themeScheme: scheme, themeContext: context });
343
359
  const envelope = reportEnvelope(siteId, source, contexts, narrowed, flags, chrome, narrowedPaints);
344
360
  const paints = paintsForReport(tokenCandidates(narrowed));
345
361
  const otherOmissions = narrowed.filter((row) => row !== entry)
346
362
  .map((row) => omission(row, contextPositions, oversized.has(row)));
347
363
  const bytes = (candidate) =>
348
364
  resultBytes(assembleReport(envelope, [{ ...entry, surface: candidate }], otherOmissions, paints));
365
+ const budget = LIMITS.githubOutputBytes - (canReadUsage ? warningUsageByteReserve(narrowedPaints.records) : 0);
349
366
  const unexpanded = bytes(surface);
350
- if (unexpanded > LIMITS.githubOutputBytes) return false;
351
- if (unexpanded + resolution.passingStopByteBound(surface) <= LIMITS.githubOutputBytes) return true;
352
- return bytes(resolution.enrichSurface(scheme, surface)) <= LIMITS.githubOutputBytes;
367
+ if (unexpanded > budget) return false;
368
+ if (unexpanded + resolution.passingStopByteBound(surface) <= budget) return true;
369
+ return bytes(resolution.enrichSurface(scheme, surface)) <= budget;
353
370
  }
354
371
 
355
372
  /**
@@ -358,12 +375,13 @@ function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeRep
358
375
  * each ink-on-surface pairing. Offline from the pulled workspace by default;
359
376
  * `--site` reads the site's own theme instead (and needs a credential).
360
377
  */
361
- export async function themeResolve(invocation, chromeDependencies) {
378
+ export async function themeResolve(invocation, { readWorkspaceUsage = readWorkspaceContextUsage, ...chromeDependencies } = {}) {
362
379
  const input = await readThemes(invocation);
363
380
  const { siteId, source, style: { lightTheme, darkTheme } } = input;
364
381
  const problems = [];
365
- let evidence = await readReportEvidence(input, invocation.content);
366
- const footer = evidence.resources.footerSettings;
382
+ const { readUsage, contextSettingsInput, manifestReason, ...reported } =
383
+ await readReportEvidence(input, invocation.content, readWorkspaceUsage);
384
+ const footer = reported.resources.footerSettings;
367
385
  const resolution = await collectProblems(
368
386
  problems,
369
387
  { area: CHECK_AREA.presentation, file: THEME_STYLES_FILE },
@@ -375,11 +393,27 @@ export async function themeResolve(invocation, chromeDependencies) {
375
393
  }),
376
394
  );
377
395
  refuseProblems(problems, "theme resolve");
378
- const { readUsage, ...reported } = evidence;
379
- const warned = selectedWarnings(resolution.encoded.completeWarnings, invocation);
380
- const needsUsage = hasContextScopedStatusWarning(warned);
381
- const usageRead = readUsage !== undefined && needsUsage ? await readUsage(contextScopedNames(warned)) : undefined;
382
- evidence = { ...reported, usage: usageRead?.usage };
396
+ const requestedContexts = new Set(invocation.themeContext === undefined ? resolution.contexts : [invocation.themeContext]);
397
+ const themeContexts = requestedContexts.size === 0 ? [] : sharedThemeContextNames(lightTheme, darkTheme);
398
+ const settings = contextUsageSettings(contextSettingsInput, new Set(themeContexts));
399
+ const scan = requestedContexts.size > 0 ? await readUsage?.(requestedContexts, themeContexts) : undefined;
400
+ const contextUsage = projectContextUsage({
401
+ scope: source,
402
+ contexts: requestedContexts,
403
+ settingsOnly: reported.resources.settingsOnly,
404
+ settings,
405
+ usage: scan?.usage,
406
+ skipped: scan?.skipped,
407
+ reason: source === "site" || reported.resources.settingsOnly
408
+ ? undefined
409
+ : manifestReason ?? (scan === undefined ? "site.failed" : scan.unavailable?.code),
410
+ });
411
+ const warningContexts = contextScopedNames(selectedWarnings(resolution.encoded.completeWarnings, invocation));
412
+ const warningRead = warningContexts.size > 0 ? scan : undefined;
413
+ const usage = warningRead?.usage === undefined
414
+ ? undefined
415
+ : new Map([...warningRead.usage].filter(([name]) => warningContexts.has(name)));
416
+ const evidence = { ...reported, usage };
383
417
 
384
418
  const chromeReport = await completeChromeReport({ ...evidence, themes: resolution.encoded }, chromeDependencies);
385
419
  const chrome = selectChrome(chromeReport, invocation);
@@ -394,10 +428,12 @@ export async function themeResolve(invocation, chromeDependencies) {
394
428
  })));
395
429
  const candidates = tokenCandidates(entries);
396
430
  const emptyPaints = paintsForReport(candidates);
397
- const statusPaints = statusPaintsFor(resolution.encoded.completeWarnings, invocation, evidence.usage);
431
+ const statusPaints = statusPaintsFor(resolution.encoded.completeWarnings, invocation);
432
+ const canReadUsage = readUsage !== undefined;
433
+ const budget = LIMITS.githubOutputBytes - (canReadUsage ? warningUsageByteReserve(statusPaints.records) : 0);
398
434
  const envelope = reportEnvelope(siteId, source, contexts, entries, resolution.flags, chrome, statusPaints);
399
435
  const oversized = new Set();
400
- const narrowingInputs = { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized, usage: evidence.usage };
436
+ const narrowingInputs = { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized, canReadUsage };
401
437
  // A scheme-only root retry includes omissions for that scheme's named contexts.
402
438
  const named = entries.filter(({ surface }) => surface.context !== null);
403
439
  const roots = entries.filter(({ surface }) => surface.context === null);
@@ -410,10 +446,10 @@ export async function themeResolve(invocation, chromeDependencies) {
410
446
  for (const [index, entry] of entries.entries()) {
411
447
  const labels = [...omitted, ...possibleOmissions.slice(index + 1)];
412
448
  const bytes = (candidate) => resultBytes(assembleReport(envelope, [...shown, candidate], labels, emptyPaints));
413
- if (bytes(entry) <= LIMITS.githubOutputBytes) {
449
+ if (bytes(entry) <= budget) {
414
450
  const surface = resolution.enrichSurface(entry.scheme, entry.surface);
415
451
  const expanded = { ...entry, surface };
416
- if (bytes(expanded) <= LIMITS.githubOutputBytes) {
452
+ if (bytes(expanded) <= budget) {
417
453
  shown.push(expanded);
418
454
  continue;
419
455
  }
@@ -433,22 +469,60 @@ export async function themeResolve(invocation, chromeDependencies) {
433
469
  const paintNames = [];
434
470
  for (const name of candidates) {
435
471
  const trial = assembleReport(envelope, shown, omitted, paintsForReport(candidates, [...paintNames, name]));
436
- if (resultBytes(trial) <= LIMITS.githubOutputBytes) {
472
+ if (resultBytes(trial) <= budget) {
437
473
  paintNames.push(name);
438
474
  result = trial;
439
475
  }
440
476
  }
441
- const fitted = withFittedSkippedLinks(result, chrome.skippedNavigationLinks);
442
477
  const listed = statusWarningPaints(statusPaints.warnings, { usage: evidence.usage });
443
- const withUsage = addUsageFields(fitted, { usedIn: usedInOf(listed), skipped: usageRead?.skipped });
478
+ if (listed.length > 0) result.statusWarningPaints = withoutUsedIn(listed);
479
+ const fitted = withFittedSkippedLinks(result, chrome.skippedNavigationLinks);
480
+ const usedIn = usedInOf(listed);
481
+ const withUsage = addUsageFields(fitted, { usedIn, skipped: warningRead?.skipped });
444
482
  // The table prints the skipped pages from the result; when the JSON could not hold them, the progress text does.
445
483
  const onProgress = invocation.onProgress ?? (() => {});
446
- if (usageRead?.skipped !== undefined && withUsage.contextUsageSkipped === undefined) {
447
- for (const line of notCountedLine(usageRead.skipped)) onProgress(line);
484
+ if (warningRead?.skipped !== undefined && withUsage.contextUsageSkipped === undefined) {
485
+ for (const line of notCountedLine(warningRead.skipped)) onProgress(line);
448
486
  }
449
- for (const line of usageUnavailableLine(usageRead?.unavailable)) onProgress(line);
450
- Object.defineProperty(withUsage, TEXT_USED_IN, { value: usedInOf(listed) });
451
- return withUsage;
487
+ for (const line of usageUnavailableLine(warningRead?.unavailable)) onProgress(line);
488
+ const withContextUsage = withFittedContextUsage(withUsage, contextUsage, invocation.themeContext, onProgress);
489
+ Object.defineProperty(withContextUsage, TEXT_USED_IN, { value: usedIn });
490
+ return withContextUsage;
491
+ }
492
+
493
+ /** Fit context counts from the bytes left by the complete report and its warning details. */
494
+ export function withFittedContextUsage(result, report, context, onProgress) {
495
+ if (report === undefined) return result;
496
+ const room = LIMITS.githubOutputBytes - resultBytes(result);
497
+ const fits = (contextUsage) => resultBytes({ contextUsage }) - 1 <= room;
498
+ if (fits(report)) return { ...result, contextUsage: report };
499
+
500
+ const narrowWith = context === undefined
501
+ ? `taproot-site theme resolve${report.scope === "site" ? " --site" : ""} --context <name>`
502
+ : undefined;
503
+ const contexts = [];
504
+ const fitted = { ...report, contexts, omitted: report.contexts.length };
505
+ const fittedResult = { ...result };
506
+ if (fits(fitted)) {
507
+ if (narrowWith !== undefined && fits({ ...fitted, narrowWith })) fitted.narrowWith = narrowWith;
508
+ for (const row of report.contexts) {
509
+ contexts.push(row);
510
+ fitted.omitted -= 1;
511
+ if (!fits(fitted)) {
512
+ contexts.pop();
513
+ fitted.omitted += 1;
514
+ }
515
+ }
516
+ fittedResult.contextUsage = fitted;
517
+ } else if (resultBytes({ contextUsageOmitted: true }) - 1 <= room) {
518
+ fittedResult.contextUsageOmitted = true;
519
+ } else {
520
+ onProgress(CONTEXT_USAGE_OMITTED_LINE);
521
+ }
522
+ Object.defineProperty(fittedResult, TEXT_CONTEXT_USAGE, {
523
+ value: { ...report, omitted: fitted.omitted, narrowWith },
524
+ });
525
+ return fittedResult;
452
526
  }
453
527
 
454
528
  /** Puts as many skipped-link rows back as the finished report has room for, keeping the count and truncation. */