@taprootio/site-authoring 0.55.0 → 0.59.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 (65) hide show
  1. package/README.md +91 -22
  2. package/package.json +2 -2
  3. package/src/api.js +90 -17
  4. package/src/authors-contract.js +71 -3
  5. package/src/block-flow.js +4 -2
  6. package/src/changelog.json +104 -0
  7. package/src/chrome-additions.js +106 -0
  8. package/src/chrome-features.js +43 -10
  9. package/src/chrome-input.js +137 -30
  10. package/src/chrome-report.js +4 -2
  11. package/src/cli.js +144 -38
  12. package/src/constants.js +1 -0
  13. package/src/content/button-styles.js +27 -0
  14. package/src/content/components.js +76 -10
  15. package/src/content/free-form-section-registry.json +9 -0
  16. package/src/content/free-form-sections.js +55 -16
  17. package/src/content/markdown.js +133 -56
  18. package/src/content/media-presentation.js +37 -0
  19. package/src/content/tiptap-prosemirror.ts +26 -10
  20. package/src/credentials.js +2 -1
  21. package/src/delivery-check.js +10 -2
  22. package/src/font-catalog.js +9 -6
  23. package/src/footer-content.js +1 -1
  24. package/src/footer-contract.js +3 -0
  25. package/src/footer-draft-hash.js +1 -0
  26. package/src/heading-outline.js +94 -6
  27. package/src/image-description-contract.js +5 -3
  28. package/src/image-description-write.js +26 -0
  29. package/src/index.js +1 -0
  30. package/src/output.js +2 -1
  31. package/src/page-metadata.js +15 -13
  32. package/src/page-structure-checks.js +14 -25
  33. package/src/placed-image-ids.js +42 -17
  34. package/src/presentation-reference.js +63 -18
  35. package/src/problems.js +147 -4
  36. package/src/reference-help.js +122 -60
  37. package/src/site-check-findings.js +2 -3
  38. package/src/site-check-rules.json +0 -1
  39. package/src/site-health-findings.js +7 -9
  40. package/src/site-health-image-checks.js +4 -1
  41. package/src/site-health-precheck.js +23 -6
  42. package/src/site-navigation-groups.js +16 -0
  43. package/src/status-warning-paints.js +175 -0
  44. package/src/template-token-reach.json +13 -18
  45. package/src/theme-proposals.js +143 -55
  46. package/src/theme-resolve.js +14 -1
  47. package/src/theme-validation.js +70 -38
  48. package/src/token-reach.js +20 -0
  49. package/src/typed-page-reference.js +25 -3
  50. package/src/typed-pages.js +73 -14
  51. package/src/verbs/authors.js +198 -33
  52. package/src/verbs/changelog.js +23 -2
  53. package/src/verbs/delivery-check.js +43 -9
  54. package/src/verbs/index.js +4 -2
  55. package/src/verbs/media-images.js +4 -4
  56. package/src/verbs/pages-push.js +138 -67
  57. package/src/verbs/plan.js +28 -20
  58. package/src/verbs/pull.js +226 -26
  59. package/src/verbs/theme-push.js +59 -15
  60. package/src/verbs/theme-resolve.js +109 -11
  61. package/src/verbs/validate.js +97 -16
  62. package/src/workspace-check.js +4 -4
  63. package/src/workspace-context-usage.js +180 -0
  64. package/src/workspace.js +48 -1
  65. package/test/fixtures/default-site-theme.json +1 -1
@@ -1,9 +1,10 @@
1
1
  import { AA_LARGE_RATIO, AA_TEXT_RATIO, SEMANTIC_COLOR_NAMES } from "@taprootio/espalier/shared/theme";
2
2
 
3
- import { getNavigation, getSitePresentation, withRefusalGuidance } from "../api.js";
3
+ import { getNavigation, getSitePresentation, isGonePage, listSitePages, withRefusalGuidance } from "../api.js";
4
4
  import { appearanceImageIds, footerPresentationOverlay, validateAppearanceScalarGroup } from "../appearance-contract.js";
5
5
  import { BREADCRUMB_ARTWORK_FIELDS } from "../breadcrumb-artwork.js";
6
6
  import { CAPABILITY_CONTENT } from "../capabilities.js";
7
+ import { addUsageFields, boundSkippedLinks } from "../chrome-additions.js";
7
8
  import { captureChromeResources } from "../chrome-input.js";
8
9
  import { displayChromeContext, displayChromeRatio, indexChromePaint } from "../chrome-output.js";
9
10
  import { completeChromeReport, RECIPE_TAG_ICON_CONTRAST } from "../chrome-report.js";
@@ -20,6 +21,18 @@ import {
20
21
  SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES,
21
22
  SETTINGS_TYPE_TAPROOT_STYLES,
22
23
  } from "../settings-catalog.js";
24
+ import { readWorkspaceContextUsage } from "../workspace-context-usage.js";
25
+ import {
26
+ contextScopedNames,
27
+ hasContextScopedStatusWarning,
28
+ notCountedLine,
29
+ statusPaintFields,
30
+ TEXT_USED_IN,
31
+ statusWarningPaints,
32
+ usageUnavailableLine,
33
+ usedInOf,
34
+ } from "../status-warning-paints.js";
35
+ import { sharedThemeContextNames } from "../content/free-form-sections.js";
23
36
  import { resolveThemePair, THEME_STYLES_FILE } from "../theme-resolve.js";
24
37
  import { abbreviateThemeContext } from "../theme-validation.js";
25
38
  import { buildTokenPaintCatalog } from "../token-reach.js";
@@ -88,13 +101,27 @@ async function siteNavigation(session) {
88
101
  });
89
102
  }
90
103
 
91
- async function readReportEvidence({ siteId, style, config, session, presentation }) {
104
+ /** The site's page inventory, so approved and draft pages resolve as staging renders them. */
105
+ async function sitePageInventory(session) {
106
+ const capabilities = session.exchanged?.capabilities;
107
+ if (session.surface !== SURFACE_STANDARD || !Array.isArray(capabilities) || !capabilities.includes(CAPABILITY_CONTENT)) {
108
+ return undefined;
109
+ }
110
+ return await optionalEvidence(async () => {
111
+ const { pages, truncated } = await listSitePages(session.client, session.siteId);
112
+ return { pages: pages.filter((page) => !isGonePage(page)), truncated };
113
+ });
114
+ }
115
+
116
+ async function readReportEvidence({ siteId, style, config, session, presentation }, content) {
92
117
  let header;
93
118
  let publishing;
94
119
  let resources;
120
+ let readUsage;
95
121
  if (session) {
96
- const [navigation, projectedHeader, projectedPublishing] = await Promise.all([
122
+ const [navigation, pageInventory, projectedHeader, projectedPublishing] = await Promise.all([
97
123
  siteNavigation(session),
124
+ sitePageInventory(session),
98
125
  optionalEvidence(() => presentation.headerSettings === undefined ? undefined : projectSettingsGroup(HEADER_GROUP, presentation)),
99
126
  optionalEvidence(() => presentation.sitePublishingPreferences === undefined
100
127
  ? undefined
@@ -106,6 +133,7 @@ async function readReportEvidence({ siteId, style, config, session, presentation
106
133
  source: "site",
107
134
  presentation,
108
135
  navigation,
136
+ pageInventory,
109
137
  settingsOnly: session.surface === SURFACE_DOCS_PRESENTATION,
110
138
  knownImageIds: new Set([
111
139
  ...appearanceImageIds({ [SETTINGS_TYPE_TAPROOT_STYLES]: style }),
@@ -130,6 +158,22 @@ async function readReportEvidence({ siteId, style, config, session, presentation
130
158
  settingsOnly: config.authoringSurface === SURFACE_DOCS_PRESENTATION,
131
159
  ...appearanceResourceIds(manifest, mediaManifest),
132
160
  });
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({
165
+ workspaceDir,
166
+ siteId,
167
+ // 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),
169
+ manifest,
170
+ mediaManifest,
171
+ header,
172
+ footerSettings: publishing?.footerSettings,
173
+ content,
174
+ contexts,
175
+ }));
176
+ }
133
177
  }
134
178
 
135
179
  const acceptedHeader = header === undefined ? undefined : await optionalEvidence(() =>
@@ -138,7 +182,8 @@ async function readReportEvidence({ siteId, style, config, session, presentation
138
182
  validateAppearanceScalarGroup(SETTINGS_TYPE_TAPROOT_STYLES, style, resources.knownImageIds));
139
183
  const footerSettings = await optionalEvidence(() => {
140
184
  footerPresentationOverlay(publishing?.footerSettings);
141
- return validateFooterDocument(publishing.footerSettings, resources);
185
+ // Page targets are classified by the page inventory, so one absent page cannot discard the footer.
186
+ return validateFooterDocument(publishing.footerSettings, { knownImageIds: resources.knownImageIds });
142
187
  });
143
188
  return {
144
189
  appearance: {
@@ -147,9 +192,23 @@ async function readReportEvidence({ siteId, style, config, session, presentation
147
192
  publishing,
148
193
  },
149
194
  resources: { ...resources, footerSettings },
195
+ readUsage,
150
196
  };
151
197
  }
152
198
 
199
+ /** Status warnings for the scheme and context the report was asked about. */
200
+ function selectedWarnings(warnings, { themeScheme, themeContext }) {
201
+ return warnings.filter((warning) => (themeScheme === undefined || warning.startsWith(`${themeScheme}: `))
202
+ && (themeContext === undefined || warning.includes(`: contexts.${themeContext}: `)));
203
+ }
204
+
205
+ /** The selected status warnings and their paint records, selected before the records are capped. */
206
+ function statusPaintsFor(completeWarnings, selection, usage) {
207
+ const warnings = selectedWarnings(completeWarnings, selection);
208
+ // The `usedIn` lists are not part of what surfaces are sized against; they are added last, from the bytes left.
209
+ return { warnings, records: statusWarningPaints(warnings, { usage, usedIn: false }) };
210
+ }
211
+
153
212
  function selectChrome(report, { themeScheme, themeContext }) {
154
213
  const matchesContext = (entry) => themeContext === undefined || entry.context === themeContext;
155
214
  const entries = Object.fromEntries(Object.entries(report.entries)
@@ -161,6 +220,8 @@ function selectChrome(report, { themeScheme, themeContext }) {
161
220
  ...indexChromePaint(entries),
162
221
  unavailable: report.unavailable,
163
222
  navigationUnavailable: report.navigationUnavailable,
223
+ // TR01420: this report skips fitChromeAdditions, so bound the list here.
224
+ skippedNavigationLinks: report.skippedNavigationLinks === undefined ? undefined : boundSkippedLinks(report.skippedNavigationLinks),
164
225
  flags: flags.map((flag) => ({ ...flag, context: displayChromeContext(flag.context).context })),
165
226
  contrast: { pairs: Object.values(entries).flat().reduce((count, entry) => count + entry.pairs.length, badgePairs.length), belowAa: flags.filter(({ code }) => code !== RECIPE_TAG_ICON_CONTRAST).length },
166
227
  };
@@ -179,7 +240,17 @@ function resultBytes(result) {
179
240
  return Buffer.byteLength(JSON.stringify(result), "utf8");
180
241
  }
181
242
 
182
- function reportEnvelope(siteId, source, contexts, entries, semanticFlags, chrome) {
243
+ /**
244
+ * The skipped-link detail cut to its count, an empty list and its truncation marker. Surface fitting sizes every
245
+ * candidate with this, so long draft-link paths cannot turn a fitting surface into
246
+ * `theme.resolve_surface_too_large`; the rows are fitted only after the surfaces are chosen, from the bytes they
247
+ * leave.
248
+ */
249
+ export function skippedLinkSkeleton(skipped) {
250
+ return { ...skipped, items: [], truncated: true };
251
+ }
252
+
253
+ function reportEnvelope(siteId, source, contexts, entries, semanticFlags, chrome, statusPaints) {
183
254
  const allFlags = [...semanticFlags, ...chrome.flags];
184
255
  const flags = { ...boundedByBytes(allFlags, FLAG_BYTE_BUDGET), count: allFlags.length };
185
256
  const contrast = { pairs: chrome.contrast.pairs, belowAa: chrome.contrast.belowAa, belowApca: 0 };
@@ -199,6 +270,8 @@ function reportEnvelope(siteId, source, contexts, entries, semanticFlags, chrome
199
270
  chromeCatalog: chrome.chromeCatalog,
200
271
  ...(chrome.unavailable ? { chromeUnavailable: true } : {}),
201
272
  ...(chrome.navigationUnavailable ? { chromeNavigationUnavailable: true } : {}),
273
+ ...(chrome.skippedNavigationLinks?.count > 0 ? { skippedNavigationLinks: skippedLinkSkeleton(chrome.skippedNavigationLinks) } : {}),
274
+ ...statusPaintFields(statusPaints.warnings, statusPaints.records),
202
275
  contrast,
203
276
  flags,
204
277
  });
@@ -257,7 +330,7 @@ function omission(entry, contextPositions, tooLarge) {
257
330
  return { scheme, context: label, ...(tooLarge ? { reason: "surface_too_large" } : {}) };
258
331
  }
259
332
 
260
- function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized }) {
333
+ function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized, usage }) {
261
334
  const { scheme, surface } = entry;
262
335
  // Root retry keeps the named contexts and chrome in the same scheme.
263
336
  const context = surface.context ?? undefined;
@@ -265,7 +338,8 @@ function canShowAfterNarrowing(entry, { resolution, entries, contexts, chromeRep
265
338
  const narrowed = entries.filter((row) => matches(row, row.surface.context));
266
339
  const flags = resolution.flags.filter((flag) => matches(flag, flag.context));
267
340
  const chrome = selectChrome(chromeReport, { themeScheme: scheme, themeContext: context });
268
- const envelope = reportEnvelope(siteId, source, contexts, narrowed, flags, chrome);
341
+ const narrowedPaints = statusPaintsFor(resolution.encoded.completeWarnings, { themeScheme: scheme, themeContext: context }, usage);
342
+ const envelope = reportEnvelope(siteId, source, contexts, narrowed, flags, chrome, narrowedPaints);
269
343
  const paints = paintsForReport(tokenCandidates(narrowed));
270
344
  const otherOmissions = narrowed.filter((row) => row !== entry)
271
345
  .map((row) => omission(row, contextPositions, oversized.has(row)));
@@ -287,7 +361,7 @@ export async function themeResolve(invocation, chromeDependencies) {
287
361
  const input = await readThemes(invocation);
288
362
  const { siteId, source, style: { lightTheme, darkTheme } } = input;
289
363
  const problems = [];
290
- const evidence = await readReportEvidence(input);
364
+ let evidence = await readReportEvidence(input, invocation.content);
291
365
  const footer = evidence.resources.footerSettings;
292
366
  const resolution = await collectProblems(
293
367
  problems,
@@ -300,6 +374,11 @@ export async function themeResolve(invocation, chromeDependencies) {
300
374
  }),
301
375
  );
302
376
  refuseProblems(problems, "theme resolve");
377
+ const { readUsage, ...reported } = evidence;
378
+ const warned = selectedWarnings(resolution.encoded.completeWarnings, invocation);
379
+ const needsUsage = hasContextScopedStatusWarning(warned);
380
+ const usageRead = readUsage !== undefined && needsUsage ? await readUsage(contextScopedNames(warned)) : undefined;
381
+ evidence = { ...reported, usage: usageRead?.usage };
303
382
 
304
383
  const chromeReport = await completeChromeReport({ ...evidence, themes: resolution.encoded }, chromeDependencies);
305
384
  const chrome = selectChrome(chromeReport, invocation);
@@ -314,9 +393,10 @@ export async function themeResolve(invocation, chromeDependencies) {
314
393
  })));
315
394
  const candidates = tokenCandidates(entries);
316
395
  const emptyPaints = paintsForReport(candidates);
317
- const envelope = reportEnvelope(siteId, source, contexts, entries, resolution.flags, chrome);
396
+ const statusPaints = statusPaintsFor(resolution.encoded.completeWarnings, invocation, evidence.usage);
397
+ const envelope = reportEnvelope(siteId, source, contexts, entries, resolution.flags, chrome, statusPaints);
318
398
  const oversized = new Set();
319
- const narrowingInputs = { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized };
399
+ const narrowingInputs = { resolution, entries, contexts, chromeReport, contextPositions, siteId, source, oversized, usage: evidence.usage };
320
400
  // A scheme-only root retry includes omissions for that scheme's named contexts.
321
401
  const named = entries.filter(({ surface }) => surface.context !== null);
322
402
  const roots = entries.filter(({ surface }) => surface.context === null);
@@ -357,5 +437,23 @@ export async function themeResolve(invocation, chromeDependencies) {
357
437
  result = trial;
358
438
  }
359
439
  }
360
- return result;
440
+ const fitted = withFittedSkippedLinks(result, chrome.skippedNavigationLinks);
441
+ const listed = statusWarningPaints(statusPaints.warnings, { usage: evidence.usage });
442
+ const withUsage = addUsageFields(fitted, { usedIn: usedInOf(listed), skipped: usageRead?.skipped });
443
+ // The table prints the skipped pages from the result; when the JSON could not hold them, the progress text does.
444
+ const onProgress = invocation.onProgress ?? (() => {});
445
+ if (usageRead?.skipped !== undefined && withUsage.contextUsageSkipped === undefined) {
446
+ for (const line of notCountedLine(usageRead.skipped)) onProgress(line);
447
+ }
448
+ for (const line of usageUnavailableLine(usageRead?.unavailable)) onProgress(line);
449
+ Object.defineProperty(withUsage, TEXT_USED_IN, { value: usedInOf(listed) });
450
+ return withUsage;
451
+ }
452
+
453
+ /** Puts as many skipped-link rows back as the finished report has room for, keeping the count and truncation. */
454
+ export function withFittedSkippedLinks(result, skipped) {
455
+ if (!(skipped?.count > 0)) return result;
456
+ const skeletonBytes = resultBytes(skippedLinkSkeleton(skipped));
457
+ const room = skeletonBytes + LIMITS.githubOutputBytes - resultBytes(result);
458
+ return { ...result, skippedNavigationLinks: boundSkippedLinks(skipped, Math.max(room, 0)) };
361
459
  }
@@ -2,8 +2,26 @@ import { lstat, realpath } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
4
  import { NAVIGATION_MAXIMUM_DEPTH, withRefusalGuidance } from "../api.js";
5
- import { CHROME_OFFLINE_PAGE_LIMITATION, CHROME_REPORT_NAME_RULE, selectNameReportEligibility } from "../chrome-input.js";
5
+ import {
6
+ CHROME_OFFLINE_PAGE_LIMITATION,
7
+ CHROME_REPORT_NAME_RULE,
8
+ describeSkippedLinks,
9
+ selectNameReportEligibility,
10
+ } from "../chrome-input.js";
6
11
  import { completeChromeReport } from "../chrome-report.js";
12
+ import { addUsageFields, fitChromeAdditions } from "../chrome-additions.js";
13
+ import { buildContextUsage } from "../workspace-context-usage.js";
14
+ import {
15
+ contextScopedNames,
16
+ hasContextScopedStatusWarning,
17
+ notCountedLine,
18
+ statusPaintFields,
19
+ statusPaintLines,
20
+ statusWarningPaints,
21
+ usageUnavailableLine,
22
+ usedInOf,
23
+ withoutUsedIn,
24
+ } from "../status-warning-paints.js";
7
25
  import { loadSiteConfig } from "../config.js";
8
26
  import { SURFACE_DOCS_PRESENTATION, VERB_VALIDATE } from "../constants.js";
9
27
  import { freeFormRootPresentation } from "../content/free-form-sections.js";
@@ -24,7 +42,7 @@ import { footerFitInputFromSettings } from "../footer-brand-inputs.js";
24
42
  import { appearanceManifestEntry, footerManifestEntry } from "../footer-workspace.js";
25
43
  import { FORMS_DIRECTORY } from "../forms-contract.js";
26
44
  import { authorWarnings, descriptionWarnings } from "../page-metadata.js";
27
- import { CHECK_AREA, collectProblems, refuseProblems } from "../problems.js";
45
+ import { CHECK_AREA, appendAll, collectProblems, omittedFileCodes, refuseProblems } from "../problems.js";
28
46
  import { isRedirectMapRevision, REDIRECT_KIND_GONE, REDIRECTS_FILE_NAME } from "../redirects-contract.js";
29
47
  import { boundedList, openSession, successResult } from "../session.js";
30
48
  import {
@@ -636,15 +654,22 @@ function requireFixtureRecordsMatch(manifest, checked) {
636
654
  }
637
655
  }
638
656
 
639
- function reportThemeWarnings(presentation, onProgress) {
657
+ function reportThemeWarnings(presentation, paints, onProgress) {
640
658
  if (presentation === undefined) return;
641
- for (const warning of presentation.themes.warnings) onProgress(`Espalier warning: ${warning}`);
659
+ for (const warning of presentation.themes.warnings) {
660
+ onProgress(`Espalier warning: ${warning}`);
661
+ for (const line of statusPaintLines(paints, warning)) onProgress(line);
662
+ }
642
663
  if (presentation.themes.warningsTruncated) {
643
664
  const hidden = presentation.themes.warningCount - presentation.themes.warnings.length;
644
665
  onProgress(`${hidden} more Espalier warning(s) not shown; resolve the ones above and run validate again to see them.`);
645
666
  }
646
667
  }
647
668
 
669
+ function withStatusPaints(warnings, records) {
670
+ return records === undefined ? {} : statusPaintFields(warnings, records);
671
+ }
672
+
648
673
  /** The part of a success result both kinds of workspace share. */
649
674
  function validatedSummary(checked, pages) {
650
675
  const { presentation, navigation, redirects, forms } = checked;
@@ -675,6 +700,8 @@ function validatedSummary(checked, pages) {
675
700
  count: presentation.themes.warningCount,
676
701
  ...(presentation.themes.warningsTruncated ? { truncated: true } : {}),
677
702
  },
703
+ ...withStatusPaints(presentation.themes.warnings, withoutUsedIn(checked.statusWarningPaints)),
704
+ ...(checked.skippedNavigationLinks === undefined ? {} : { skippedNavigationLinks: checked.skippedNavigationLinks }),
678
705
  };
679
706
  }
680
707
 
@@ -732,10 +759,10 @@ async function offlineSiteChecks(checked, manifest, mediaManifest, onProgress, i
732
759
  });
733
760
  }
734
761
 
735
- async function completeValidationWarnings(checked, resources, options, onProgress) {
762
+ async function completeValidationWarnings(checked, resources, options, onProgress, problems) {
736
763
  if (options.reportChrome && resources.valid) {
737
764
  const appearance = checked.presentation;
738
- const { warnings } = await completeChromeReport({
765
+ const { warnings, skippedNavigationLinks } = await completeChromeReport({
739
766
  themes: appearance.themes,
740
767
  appearance,
741
768
  resources: {
@@ -748,8 +775,62 @@ async function completeValidationWarnings(checked, resources, options, onProgres
748
775
  nameReportEnabled: options.nameReportEnabled,
749
776
  }, { loadFit: options.loadChromeFit });
750
777
  appearance.themes = withChromeWarnings(appearance.themes, warnings);
778
+ if (skippedNavigationLinks?.count > 0) {
779
+ checked.skippedNavigationLinks = skippedNavigationLinks;
780
+ onProgress(describeSkippedLinks(skippedNavigationLinks));
781
+ }
782
+ }
783
+ // The page reads and checks above stay unconditional; only the usage collection and its reporting wait for a
784
+ // warning that names a context.
785
+ const contextUsage = checked.settingsOnly || checked.presentation === undefined
786
+ || !hasContextScopedStatusWarning(checked.presentation.themes.warnings)
787
+ ? undefined
788
+ : pageContextUsage(checked, problems);
789
+ checked.contextUsage = contextUsage;
790
+ checked.statusWarningPaints = checked.presentation === undefined
791
+ ? []
792
+ : statusWarningPaints(checked.presentation.themes.warnings, { usage: contextUsage?.usage });
793
+ reportThemeWarnings(checked.presentation, checked.statusWarningPaints, onProgress);
794
+ for (const line of [...notCountedLine(contextUsage?.skipped), ...usageUnavailableLine(contextUsage?.unavailable)]) {
795
+ onProgress(line);
796
+ }
797
+ }
798
+
799
+ /**
800
+ * The context usage `validate` reports, from the documents it already converted. A planned page counts only when no
801
+ * pages-area problem names it, because a page can pass planning and still be refused later (an unknown form, a
802
+ * fixture binding). Every file with such a problem is listed with its first problem code, and a contested page path
803
+ * lists both claimants as `pages.path_conflict`, which takes precedence.
804
+ */
805
+ export function pageContextUsage(checked, problems) {
806
+ const pageProblems = problems.filter((problem) => problem.area === CHECK_AREA.pages && problem.file !== undefined);
807
+ const codes = new Map();
808
+ for (const problem of pageProblems) if (!codes.has(problem.file)) codes.set(problem.file, problem.code);
809
+ for (const problem of pageProblems) if (problem.code === "pages.path_conflict") codes.set(problem.file, problem.code);
810
+ // A file whose every problem fell past the problem cap has no row left, but it is still refused.
811
+ for (const dropped of omittedFileCodes(problems)) {
812
+ if (dropped.area === CHECK_AREA.pages && !codes.has(dropped.file)) codes.set(dropped.file, dropped.code);
751
813
  }
752
- reportThemeWarnings(checked.presentation, onProgress);
814
+ for (const file of checked.pages?.conflictedFiles ?? []) codes.set(file, "pages.path_conflict");
815
+ // A walk that failed leaves no planning result, and its problem names no file.
816
+ const walkFailure = checked.pages === undefined
817
+ ? problems.find((problem) => problem.area === CHECK_AREA.pages && problem.file === undefined)
818
+ : undefined;
819
+ return buildContextUsage({
820
+ header: checked.presentation.header,
821
+ footerSettings: checked.footer?.footerSettings,
822
+ contexts: contextScopedNames(checked.presentation.themes.warnings),
823
+ pages: (checked.pages?.planned ?? []).filter((page) => !codes.has(page.file)),
824
+ skipped: [...codes].map(([file, code]) => ({ file, code })),
825
+ ...(walkFailure === undefined ? {} : {
826
+ unavailable: { code: walkFailure.code, ...(walkFailure.field === undefined ? {} : { field: walkFailure.field }) },
827
+ }),
828
+ });
829
+ }
830
+
831
+ /** The context-usage fields, added to a finished result from the bytes it has left. */
832
+ function withContextUsage(result, checked) {
833
+ return addUsageFields(result, { usedIn: usedInOf(checked.statusWarningPaints), skipped: checked.contextUsage?.skipped });
753
834
  }
754
835
 
755
836
  /**
@@ -867,7 +948,7 @@ export async function validateFixture(invocation = {}, {
867
948
  content: invocation.content,
868
949
  onProgress,
869
950
  });
870
- problems.push(...checked.problems);
951
+ appendAll(problems, checked.problems);
871
952
 
872
953
  const manifestByFile = new Map(manifest.pages.map((entry) => [entry.file, entry]));
873
954
  const validatedPages = [];
@@ -886,7 +967,7 @@ export async function validateFixture(invocation = {}, {
886
967
  if (checked.forms !== undefined) requireFixtureFormsBound(manifest.forms, checked.forms);
887
968
  });
888
969
  const options = { ...reporting, nameReportEnabled: selectNameReportEligibility({ manifest }) };
889
- await completeValidationWarnings(checked, { manifest, mediaManifest, valid: problems.length === 0 }, options, onProgress);
970
+ await completeValidationWarnings(checked, { manifest, mediaManifest, valid: problems.length === 0 }, options, onProgress, problems);
890
971
  refuseProblems(problems, "validate found problems in the fixture");
891
972
 
892
973
  const hints = pageHints(checked, onProgress);
@@ -899,7 +980,7 @@ export async function validateFixture(invocation = {}, {
899
980
  onProgress(
900
981
  `Validated ${validatedPages.length} page(s), ${checked.navigation.items} navigation item(s), two themes, appearance, and footer without credentials or mutation.`,
901
982
  );
902
- return successResult(VERB_VALIDATE, manifest.siteId, {
983
+ return withContextUsage(fitChromeAdditions(successResult(VERB_VALIDATE, manifest.siteId, {
903
984
  offline: true,
904
985
  fixture: {
905
986
  contractVersion: FIXTURE_CONTRACT_VERSION,
@@ -928,7 +1009,7 @@ export async function validateFixture(invocation = {}, {
928
1009
  "preview or published rendering",
929
1010
  ],
930
1011
  nextStep: "Run a real pull and authorized preview before approval or deployment.",
931
- });
1012
+ })), checked);
932
1013
  }
933
1014
 
934
1015
  /**
@@ -949,7 +1030,7 @@ async function validatePulledWorkspace(workspaceDir, siteId, invocation, onProgr
949
1030
  onProgress,
950
1031
  });
951
1032
  const options = { ...reporting, nameReportEnabled: selectNameReportEligibility({ manifest }) };
952
- await completeValidationWarnings(checked, { manifest, mediaManifest, valid: checked.problems.length === 0 }, options, onProgress);
1033
+ await completeValidationWarnings(checked, { manifest, mediaManifest, valid: checked.problems.length === 0 }, options, onProgress, checked.problems);
953
1034
  refuseProblems(checked.problems, "validate found problems in the workspace");
954
1035
 
955
1036
  // Only --site reads the site; without it the image rule is skipped with the reason (TR01371).
@@ -991,7 +1072,7 @@ async function validatePulledWorkspace(workspaceDir, siteId, invocation, onProgr
991
1072
  ? "footer without credentials or mutation; the workspace places no images, so the site was not read."
992
1073
  : "footer without credentials or mutation."),
993
1074
  );
994
- const base = successResult(VERB_VALIDATE, siteId, {
1075
+ const base = fitChromeAdditions(successResult(VERB_VALIDATE, siteId, {
995
1076
  offline: !readSite,
996
1077
  workspace: { manifest: MANIFEST_FILE_NAME, settingsOnly: checked.settingsOnly },
997
1078
  ...validatedSummary(checked, pages),
@@ -1020,12 +1101,12 @@ async function validatePulledWorkspace(workspaceDir, siteId, invocation, onProgr
1020
1101
  "preview or published rendering",
1021
1102
  ],
1022
1103
  nextStep: "Run 'taproot-site plan' to check the workspace against the live site and see the ordered apply.",
1023
- });
1024
- if (site.block === undefined) return base;
1104
+ }));
1105
+ if (site.block === undefined) return withContextUsage(base, checked);
1025
1106
  const fitted = fitPrecheckToBudget(
1026
1107
  base,
1027
1108
  { imageFindings: site.block.imageFindings, notInSiteLibrary: site.block.notInSiteLibrary },
1028
1109
  ["notInSiteLibrary", "imageFindings"],
1029
1110
  );
1030
- return { ...base, ...fitted };
1111
+ return withContextUsage({ ...base, ...fitted }, checked);
1031
1112
  }
@@ -7,7 +7,7 @@ import { FORMS_DIRECTORY } from "./forms-contract.js";
7
7
  import { readWorkspaceForms } from "./forms-workspace.js";
8
8
  import { describeSiteFinding } from "./site-check-findings.js";
9
9
  import { unknownFormKeyFindings } from "./site-checks.js";
10
- import { CHECK_AREA, collectProblems, problemsOf } from "./problems.js";
10
+ import { CHECK_AREA, appendAll, collectProblems, problemsOf } from "./problems.js";
11
11
  import { normalizeRedirectPath, REDIRECTS_FILE_NAME, validateRedirectsDocument } from "./redirects-contract.js";
12
12
  import { boundedByBytes } from "./session.js";
13
13
  import { SETTINGS_TYPE_SITE_PUBLISHING_PREFERENCES } from "./settings-catalog.js";
@@ -146,7 +146,7 @@ export async function checkWorkspace({
146
146
  : sharedThemeContextNames(presentation.style.lightTheme, presentation.style.darkTheme),
147
147
  onProgress,
148
148
  }));
149
- if (pages !== undefined) problems.push(...pages.problems);
149
+ if (pages !== undefined) appendAll(problems, pages.problems);
150
150
  const listingTagProblems = pages === undefined ? [] : latestPostsTagProblems(pages.planned, manifest);
151
151
  const latestPostsWarnings = { count: listingTagProblems.length, ...boundedByBytes(listingTagProblems, 8 * 1024) };
152
152
  for (const { message } of latestPostsWarnings.items) onProgress("Warning: " + message);
@@ -178,7 +178,7 @@ export async function checkWorkspace({
178
178
  const known = new Set(forms.map((form) => form.key));
179
179
  for (const page of pages.planned) {
180
180
  for (const finding of unknownFormKeyFindings(placedFormKeys(page.document), known)) {
181
- problems.push(...problemsOf(
181
+ appendAll(problems, problemsOf(
182
182
  new SiteAuthoringError(
183
183
  "pages.form_unknown",
184
184
  `'${page.file}' ${describeSiteFinding(finding)}.`,
@@ -242,7 +242,7 @@ async function checkRedirects(workspaceDir, siteId, manifest, sources) {
242
242
  for (const entry of redirects.entries) {
243
243
  const key = entry.path.toLowerCase();
244
244
  if (!pagePaths.has(key)) continue;
245
- problems.push(...problemsOf(new SiteAuthoringError(
245
+ appendAll(problems, problemsOf(new SiteAuthoringError(
246
246
  "redirects.path_occupied",
247
247
  `Redirect source '${entry.path}' is a page in this workspace, so it cannot also be a redirect source.`,
248
248
  { field: `entries[${authoredIndexByPath.get(key) ?? 0}].path` },
@@ -0,0 +1,180 @@
1
+ import { FREE_FORM_SECTION_REGISTRY, namedContext } from "./content/free-form-sections.js";
2
+ import { SiteAuthoringError } from "./errors.js";
3
+ import { problemsOf } from "./problems.js";
4
+ import { contentDocuments } from "./typed-pages.js";
5
+ import { PAGE_SOURCE_EXTENSIONS, PAGES_DIRECTORY, retiredSourcesByFile, walkWorkspaceFiles } from "./workspace.js";
6
+ import {
7
+ convertWorkspacePageSource,
8
+ isRetiredGeneratedSource,
9
+ readWorkspacePageSource,
10
+ requireCompletePageMetadata,
11
+ validateWorkspacePageDocument,
12
+ } from "./verbs/pages-push.js";
13
+
14
+ // The list a warning or the skipped report carries holds at most this many rows, whatever the true total.
15
+ export const MAXIMUM_LISTED_USES = 20;
16
+
17
+ const KIND_SECTION = "section";
18
+ const KIND_CTA = "cta";
19
+
20
+ /**
21
+ * Counts which theme contexts a workspace uses (TR01419), one document at a time so a large workspace never holds
22
+ * every converted document in memory. The header and footer name theirs in settings; sections and calls to action
23
+ * name theirs inside page documents. Only the `contexts` names are counted, so a workspace of raw documents with
24
+ * many arbitrary context strings cannot grow the map.
25
+ *
26
+ * Each section or call-to-action use also records where it is (TR01426): the page file, its kind, and its 1-based
27
+ * ordinal among every section (or every call to action) of the page, in document order. Documents arrive in the
28
+ * workspace page walk's order, so the first rows kept are the first in that order.
29
+ */
30
+ export function createContextUsageCounter({ header, footerSettings, contexts } = {}) {
31
+ const usage = new Map();
32
+ let documents = 0;
33
+ const entry = (name) => {
34
+ if (!contexts?.has(name)) return undefined;
35
+ if (!usage.has(name)) usage.set(name, { header: false, footer: false, sections: 0, ctas: 0, items: [], total: 0 });
36
+ return usage.get(name);
37
+ };
38
+ if (typeof header?.context === "string" && header.context !== "") {
39
+ const used = entry(header.context);
40
+ if (used !== undefined) used.header = true;
41
+ }
42
+ if (footerSettings?.enabled === true && typeof footerSettings?.context === "string" && footerSettings.context !== "") {
43
+ const used = entry(footerSettings.context);
44
+ if (used !== undefined) used.footer = true;
45
+ }
46
+ return {
47
+ add(document, file) {
48
+ // Tallied apart and merged at the end, so a walk that throws adds nothing.
49
+ const found = [];
50
+ // A typed page's documents are numbered as one sequence, in the order `contentDocuments` returns them.
51
+ const ordinals = { [KIND_SECTION]: 0, [KIND_CTA]: 0 };
52
+ for (const { doc } of contentDocuments(document)) {
53
+ // An explicit stack: a raw document can nest deeper than the call stack allows.
54
+ const pending = [doc];
55
+ while (pending.length > 0) {
56
+ const node = pending.pop();
57
+ if (node === null || typeof node !== "object") continue;
58
+ const kind = node.type === FREE_FORM_SECTION_REGISTRY.section.nodeType
59
+ ? KIND_SECTION
60
+ : node.type === "componentBlock" && node.attrs?.componentType === "cta"
61
+ ? KIND_CTA
62
+ : undefined;
63
+ if (kind !== undefined) ordinals[kind] += 1;
64
+ const named = kind === undefined ? undefined : namedContext(node);
65
+ if (named?.context) found.push({ name: named.context, kind, position: ordinals[kind] });
66
+ // The stack is last in, first out, so children go in reversed to be visited in order. A loop, not a
67
+ // spread: a very wide array would overflow the call stack as arguments.
68
+ if (Array.isArray(node.content)) {
69
+ for (let index = node.content.length - 1; index >= 0; index -= 1) pending.push(node.content[index]);
70
+ }
71
+ }
72
+ }
73
+ documents += 1;
74
+ for (const { name, kind, position } of found) {
75
+ const used = entry(name);
76
+ if (used === undefined) continue;
77
+ used[kind === KIND_SECTION ? "sections" : "ctas"] += 1;
78
+ used.total += 1;
79
+ if (used.items.length < MAXIMUM_LISTED_USES) used.items.push({ file, kind, position });
80
+ }
81
+ },
82
+ /** With no page documents the workspace says nothing about use, so callers make no claim. */
83
+ result: () => documents === 0
84
+ ? undefined
85
+ : new Map([...usage].map(([name, { items, total, ...counts }]) => [
86
+ name,
87
+ { ...counts, usedIn: { items, total, truncated: total > items.length } },
88
+ ])),
89
+ };
90
+ }
91
+
92
+ /** The skipped pages as a bounded report with the true total, or nothing when none were skipped. */
93
+ function skippedReport(skipped) {
94
+ if (skipped.length === 0) return undefined;
95
+ return {
96
+ items: skipped.slice(0, MAXIMUM_LISTED_USES).map(({ file, code }) => ({ file, code })),
97
+ total: skipped.length,
98
+ truncated: skipped.length > MAXIMUM_LISTED_USES,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * The one builder of the context usage every verb reports: the counts and positions, the pages that could not be
104
+ * counted with their first problem code, and, when the page inventory itself could not be read, why (TR01426).
105
+ * `pages` are `{ file, document }` rows already converted and checked; `skipped` are `{ file, code }` rows.
106
+ */
107
+ export function buildContextUsage({ header, footerSettings, contexts, pages = [], skipped = [], unavailable } = {}) {
108
+ const counter = createContextUsageCounter({ header, footerSettings, contexts });
109
+ for (const { file, document } of pages) counter.add(document, file);
110
+ return { usage: counter.result(), skipped: skippedReport(skipped), ...(unavailable === undefined ? {} : { unavailable }) };
111
+ }
112
+
113
+ /** The code a page's refusal is listed under: the first problem's own, as `validate` reports it. */
114
+ export function firstProblemCode(error) {
115
+ return error instanceof SiteAuthoringError ? problemsOf(error)[0].code : "site.failed";
116
+ }
117
+
118
+ /** Why the page inventory could not be read: the walk's error code and any path it names. */
119
+ function unavailableReason(error) {
120
+ const known = error instanceof SiteAuthoringError;
121
+ return {
122
+ code: known ? error.code : "site.failed",
123
+ ...(known && error.field !== undefined ? { field: error.field } : {}),
124
+ };
125
+ }
126
+
127
+ /**
128
+ * The usage for a pulled workspace read from disk. Pages come from the same bounded walk `validate` uses, with the
129
+ * manifest supplying metadata, so a page added after pull still counts. A page counts only when it reads, converts
130
+ * and passes the content check `validate` runs against `themeContexts` (the candidate theme's full shared context
131
+ * list, never the file on disk); any other page is listed in `skipped` with its first problem code. A source the
132
+ * manifest retired is not a page to count. When the walk itself fails, `unavailable` says why and nothing is claimed.
133
+ */
134
+ export async function readWorkspaceContextUsage({
135
+ workspaceDir,
136
+ siteId,
137
+ manifest,
138
+ mediaManifest,
139
+ header,
140
+ footerSettings,
141
+ content,
142
+ contexts,
143
+ themeContexts,
144
+ }) {
145
+ const counter = createContextUsageCounter({ header, footerSettings, contexts });
146
+ const manifestByFile = new Map(
147
+ (manifest?.pages ?? []).filter((entry) => typeof entry?.file === "string").map((entry) => [entry.file, entry]),
148
+ );
149
+ const retired = retiredSourcesByFile(manifest);
150
+ let files;
151
+ try {
152
+ files = await walkWorkspaceFiles(workspaceDir, PAGES_DIRECTORY, PAGE_SOURCE_EXTENSIONS);
153
+ } catch (error) {
154
+ return { usage: undefined, skipped: undefined, unavailable: unavailableReason(error) };
155
+ }
156
+ const skipped = [];
157
+ for (const file of files) {
158
+ if (!manifestByFile.has(file) && retired.has(file)) continue;
159
+ try {
160
+ const source = requireCompletePageMetadata(
161
+ await readWorkspacePageSource({ workspaceDir, file, manifestEntry: manifestByFile.get(file) }),
162
+ );
163
+ // A retired generated kind is no page to count (TR01308), as `validate` treats it; other kinds still refuse.
164
+ if (isRetiredGeneratedSource(source)) continue;
165
+ const document = await convertWorkspacePageSource({ source, mediaManifest, content });
166
+ await validateWorkspacePageDocument({
167
+ workspaceDir,
168
+ siteId,
169
+ file,
170
+ document,
171
+ content,
172
+ getSharedThemeContexts: async () => themeContexts,
173
+ });
174
+ counter.add(document, file);
175
+ } catch (error) {
176
+ skipped.push({ file, code: firstProblemCode(error) });
177
+ }
178
+ }
179
+ return { usage: counter.result(), skipped: skippedReport(skipped) };
180
+ }