@taprootio/site-authoring 0.36.2 → 0.37.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.
@@ -95,7 +95,7 @@ import {
95
95
 
96
96
  export { getAppearanceReference, getFooterReference, getSettingsReference, getThemeReference };
97
97
 
98
- export const REFERENCE_VERSION = 57;
98
+ export const REFERENCE_VERSION = 58;
99
99
 
100
100
  // The date-limit examples `help forms` prints; tests run them through the form validator.
101
101
  export const FORM_DATE_WINDOW_FIELD = Object.freeze({
@@ -540,8 +540,10 @@ const WORKFLOW_REFERENCES = Object.freeze({
540
540
  + "the -300x200 thumbnail WordPress also stores), then run 'media upload' once for the whole media/ directory (at most 500 "
541
541
  + "files a run). It records every file in .taproot-site-media.json and reports counts and a bounded item list; "
542
542
  + "a run that stopped partway is safe to repeat, because identical files deduplicate.",
543
- "Check before sending. 'validate' (no credential, no request) checks every page source, media reference and "
543
+ "Check before sending. 'validate' (no credential, no request, unless --site) checks every page source, media reference and "
544
544
  + "setting in the workspace at once and lists every problem in error.problems with its file, code and field. "
545
+ + "'validate --site' also reads the site's image records and reports each placed image with no default description "
546
+ + "in imageFindings, with the 'media images describe' command to fix it. "
545
547
  + "'pages push --dry-run' then checks the pages against the live site — paths taken, templates, revisions, "
546
548
  + "videos — and sends nothing. 'plan' checks the whole workspace against the site and orders what is left "
547
549
  + "(media, pages, footer, theme, navigation); 'apply --plan <planHash>' runs exactly that plan.",
@@ -617,7 +619,8 @@ const WORKFLOW_REFERENCES = Object.freeze({
617
619
  + "release. --version prints what is running; status reports the latest known release as cliRelease.",
618
620
  `Select the site: ${CLI_BINARY_NAME} login, then ${CLI_BINARY_NAME} sites and ${CLI_BINARY_NAME} use <site-name-or-id>. `
619
621
  + "sites reports each site's kind and authoring surface. A standard site takes every verb. A managed Docs site "
620
- + "takes presentation only — pull, theme push, footer push, media upload, deploy, status — because its pages, "
622
+ + "takes presentation only — pull, theme push, footer push, media upload, deploy, status, and health, which "
623
+ + "returns covered: false there — because its pages, "
621
624
  + "navigation and redirects come from the Docs artifact; a prebuilt Docs site takes no verb at all.",
622
625
  `Pull the baseline: ${CLI_BINARY_NAME} pull writes settings/taproot-styles.json with both schemes' complete effective `
623
626
  + "themes (the stored theme resolved over the same defaults every consumer renders) beside brand.json, "
@@ -646,7 +649,8 @@ const WORKFLOW_REFERENCES = Object.freeze({
646
649
  `Validate offline: ${CLI_BINARY_NAME} validate checks the whole workspace at once — the complete pair, the `
647
650
  + "appearance files, the footer, every page, navigation and redirects — against the contracts the site enforces, "
648
651
  + "lists every problem in error.problems, and warns when a semanticMappings pin repeats the default on a token "
649
- + "your roles would have moved (the pin would keep the role from rendering).",
652
+ + "your roles would have moved (the pin would keep the role from rendering). validate stays offline unless you add "
653
+ + "--site, which also reads the site's image records to report placed images that have no default description.",
650
654
  `Plan a combined change: when pages, the footer, the theme and navigation all changed, ${CLI_BINARY_NAME} plan `
651
655
  + "checks them against the live site and lists the steps in the order they must run, each ready, blocked or "
652
656
  + `nothing to do; ${CLI_BINARY_NAME} apply --plan <planHash> runs them through the ordinary push verbs and refuses `
@@ -666,7 +670,10 @@ const WORKFLOW_REFERENCES = Object.freeze({
666
670
  + "favicon. When a requested handoff could not be minted, stagingPreview.reason says why and staging review mints "
667
671
  + "another (add --path <page> to open it on the page under review). The review session lasts five minutes: "
668
672
  + "see 'help preview' for what ends it. A page draft is "
669
- + "not needed to review a presentation change; preview page renders one persisted draft and is a different tool.",
673
+ + "not needed to review a presentation change; preview page renders one persisted draft and is a different tool. "
674
+ + `On a standard site ${CLI_BINARY_NAME} health --staging then reads the staged release's stored Site Health report: `
675
+ + "every finding with its workspace file and a fix, the ones new since production marked newSinceProduction. deploy "
676
+ + "--staging returns the same report as siteHealth. A fix reaches the report only after another deploy --staging.",
670
677
  `Promote only after review: ${CLI_BINARY_NAME} deploy --production promotes the completed staging deployment. `
671
678
  + "Never use production to discover what staging should have shown.",
672
679
  ]),
@@ -1058,7 +1065,7 @@ const WORKFLOW_REFERENCES = Object.freeze({
1058
1065
  summary: "Read and change site-owned image defaults by ID, or upload workspace-root-relative raster files and videos.",
1059
1066
  usage: `${CLI_BINARY_NAME} media images list|get|describe | media upload [path...]`,
1060
1067
  details: Object.freeze([
1061
- "media images list returns one page in images.items and images.nextPageToken; pass --page-size 1–100 (default 25) and --page-token with that exact cursor for the next page. --missing-description is a server-side filter for a null image-owned default, independent of placement alt text, captions or decorative mode. No per-result reads or page-body scans run. The authoritative default-completeness findings are in the frozen deployment report that status reads; local validate does not infer them from placement strings.",
1068
+ "media images list returns one page in images.items and images.nextPageToken; pass --page-size 1–100 (default 25) and --page-token with that exact cursor for the next page. --missing-description is a server-side filter for a null image-owned default, independent of placement alt text, captions or decorative mode. No per-result reads or page-body scans run. The authoritative default-completeness findings are in the stored deployment report that health --staging reads after staging. Before staging, validate --site and pages push report the images the workspace places whose default is missing (imageFindings, with the exact media images describe command), reading the site's image records; without --describe-missing-images they never infer a default from placement strings, and a placement's alt text only suggests the text for that command. pages push --describe-missing-images (also with --dry-run) is the one push path that fills a missing default: it sets each such image's default from the one alt text its selected custom or unset placements agree on, never over an existing description, and reports describedImages (set and skipped, each with its total, and the skip reason of every image it left).",
1062
1069
  "media images get <image-id> reads one library image in the selected site. Both reads expose imageId, uploadedName, defaultDescription (null when missing), descriptionRevision as a decimal string, width, height, processingState, previewUrl and responsivePreviewUrls. Preview URLs are for inspection, may expire, and are omitted from GITHUB_OUTPUT. They are not descriptions and these verbs write no workspace file.",
1063
1070
  "media images describe <image-id> --description <text> --expected-revision <n> saves the default; --clear replaces --description to remove it. Supply the exact revision from list/get, including 0. --if-missing is an atomic server condition, requires nonblank text, and refuses an existing default. Conflicts report media.image_description_conflict or media.image_description_exists with exit 1; read the current image and reconcile, never retry by overwriting it blindly. Input/option errors use exit 2.",
1064
1071
  "The server owns the 1000-Unicode-scalar limit: outer whitespace is trimmed, blank text becomes null, and oversized text is rejected without truncation. Descriptions may contain Unicode and newlines. The CLI preserves their text in JSON and never copies preview URLs or resolved defaults into page bodies. Site media management is required for all three verbs; profile/account/installation media are excluded. A default edit affects inherited usages at the next selected deployment; current published and in-flight snapshots keep their frozen text, while contextual overrides and decorative placements keep their choices.",
@@ -1729,9 +1736,15 @@ const FREE_FORM_REFERENCE = Object.freeze({
1729
1736
  + "written. Rename or remove it, then pull again.",
1730
1737
  renamedSourceError: "pages.source_conflict",
1731
1738
  conflict:
1732
- "Markdown is one-way, so a page edited on the site since the last pull cannot be rewritten as Markdown. pull "
1733
- + "refuses before changing anything under pages/ and preserves the site's version as internal state. A "
1734
- + "locally edited .pm.json is kept rather than overwritten, and only collides when the site changed too.",
1739
+ "Markdown is one-way, so a tracked Markdown page whose site state moved since the last pull cannot be "
1740
+ + "rewritten as Markdown: pull refuses before changing anything under pages/ and preserves the site's version "
1741
+ + "as internal state. The site moved when the page's stored-state revision moved, or its display date moved for "
1742
+ + "a page type that has one. A .pm.json page is refreshed when the site moved, and conflicts only when it also "
1743
+ + "has unpushed local edits (its body, or its title, path, description or author in the manifest). The revision "
1744
+ + "covers the stored body, title, path, short description and cover image. For an authored page (Markdown or "
1745
+ + "ProseMirror) approve, staging and production publication never move it; a legal page's version stamp is "
1746
+ + "written at publication and does move it; a place review's effective category is applied only to the "
1747
+ + "release, so a category override does not move it.",
1735
1748
  conflictError: "pages.pull_conflict",
1736
1749
  metadata:
1737
1750
  "A .pm.json page's title, path and description live in the manifest, not the file. Change the title or "
@@ -1762,8 +1775,9 @@ const FREE_FORM_REFERENCE = Object.freeze({
1762
1775
  "A reported conflict names the JSON paths at which the site's document differs from the copy this workspace "
1763
1776
  + "last reconciled with, in error.differences, which carries three states. Absent: the two documents were "
1764
1777
  + "never compared, because this workspace kept no copy of the site's previous version. Empty: they were "
1765
- + "compared and the body is identical, so the change was to the page's title, path, or description. "
1766
- + "Non-empty: the JSON paths at which the body differs.",
1778
+ + "compared and the body is identical, so the change was to the page's title, path, description, cover image "
1779
+ + "or display date, none of which is part of the body. Non-empty: the JSON paths at which the body differs. "
1780
+ + "These paths explain a refusal; they never decide whether it happens.",
1767
1781
  pushConflict:
1768
1782
  "pages push fails closed on a concurrent remote edit: the site reports each page's stored-state revision, the "
1769
1783
  + "workspace records the revision of what it last wrote or pulled, and a push whose target now carries a "
@@ -1778,7 +1792,9 @@ const FREE_FORM_REFERENCE = Object.freeze({
1778
1792
  + "update responses. It is opaque: compare it, never derive or parse it.",
1779
1793
  conflictRecovery:
1780
1794
  "Either push the local source to make the site match it, or delete the local source and pull again to adopt "
1781
- + "the site's document as that page's source.",
1795
+ + "the site's document as that page's source. A page whose conflict names no body difference (an empty "
1796
+ + "differences list) changed only its title, path, description, cover image or display date, so the "
1797
+ + "same two choices apply.",
1782
1798
  pushSelection:
1783
1799
  "pages push <path> validates the selected page exactly as a whole push would, including every cross-page "
1784
1800
  + "guard that can affect it. It does not convert or validate pages it is not sending; pages push with no "
@@ -1971,7 +1987,11 @@ const FREE_FORM_REFERENCE = Object.freeze({
1971
1987
  }),
1972
1988
  Object.freeze({
1973
1989
  command: `${CLI_BINARY_NAME} deploy --staging`,
1974
- result: "Deploy the staged build to the staging site.",
1990
+ result: "Deploy the staged build to the staging site; the result's siteHealth reports its stored Site Health warnings.",
1991
+ }),
1992
+ Object.freeze({
1993
+ command: `${CLI_BINARY_NAME} health --staging`,
1994
+ result: "Read the staged release's Site Health findings with a fix for each, and fix every new one (stage again to refresh the report).",
1975
1995
  }),
1976
1996
  Object.freeze({
1977
1997
  command: `${CLI_BINARY_NAME} deploy --production`,
@@ -2,7 +2,7 @@ import { sanitizeDiagnostic } from "./errors.js";
2
2
  import { boundedByBytes } from "./session.js";
3
3
  import rules from "./site-check-rules.json" with { type: "json" };
4
4
  import { isFormKey } from "./forms-contract.js";
5
- import { DESCRIPTION_MINIMUM_LENGTH, DESCRIPTION_WARN_LENGTH, localAuthoringMetadata, METADATA_RULE_IDS, pageStructureFindings, TITLE_MINIMUM_LENGTH, TITLE_WARN_LENGTH } from "./page-structure-checks.js";
5
+ import { DESCRIPTION_MINIMUM_LENGTH, DESCRIPTION_WARN_LENGTH, localAuthoringMetadata, METADATA_RULE_IDS, pageStructureFindings, RULE_IMAGE_DEFAULT_MISSING, TITLE_MINIMUM_LENGTH, TITLE_WARN_LENGTH } from "./page-structure-checks.js";
6
6
  import { missingPageLinkFindings, normalizedPathSet } from "./site-checks.js";
7
7
  import { documentTemplate, TEMPLATE_FREE_FORM, TEMPLATE_GENERATED } from "./typed-pages.js";
8
8
  import { displayPagePath } from "./workspace.js";
@@ -16,6 +16,25 @@ import { displayPagePath } from "./workspace.js";
16
16
  */
17
17
  export const SITE_CHECK_RULES = Object.freeze(rules.rules);
18
18
 
19
+ /** Why `validate` did not run the image description rule, which needs the site's image records (TR01371). */
20
+ export const IMAGE_CHECK_NOT_REQUESTED = "not_requested";
21
+ export const IMAGE_CHECK_DIRECTORY_ARGUMENT = "directory_argument";
22
+ export const IMAGE_CHECK_DOCS_SITE = "docs_site";
23
+ export const IMAGE_CHECK_READ_FAILED = "read_failed";
24
+ export const IMAGE_CHECK_READ_PARTLY_FAILED = "read_partly_failed";
25
+
26
+ /** The reason an image check was skipped, with the message the codes that have a remedy carry. */
27
+ export function imageCheckSkipped(code) {
28
+ const messages = {
29
+ [IMAGE_CHECK_NOT_REQUESTED]:
30
+ "Image descriptions need the site's image records. Run 'taproot-site validate --site' or 'taproot-site pages push --dry-run' to check them.",
31
+ [IMAGE_CHECK_DIRECTORY_ARGUMENT]:
32
+ "Image descriptions need the site's image records. Run 'taproot-site validate --site' from the workspace, or 'taproot-site pages push --dry-run'.",
33
+ [IMAGE_CHECK_DOCS_SITE]: "This is a managed Docs site, so the rule does not apply.",
34
+ };
35
+ return { ran: false, code, ...(messages[code] === undefined ? {} : { message: messages[code] }) };
36
+ }
37
+
19
38
  /** The CLI's sentence for each rule, keyed by rule id. A rule without an entry falls back to its id. */
20
39
  export const SITE_CHECK_WORDING = Object.freeze({
21
40
  "link.page_missing": (finding) => `links to ${finding.subject}, which is not a page of this site`,
@@ -66,6 +85,41 @@ export const SITE_CHECK_WORDING = Object.freeze({
66
85
  : "has no cover image and no images, so link previews show no picture",
67
86
  });
68
87
 
88
+ /**
89
+ * What to do about each rule the stored Site Health report can raise (TR01363). The report belongs to a release,
90
+ * so a page fix reaches it only after the page is pushed, approved and staged again.
91
+ */
92
+ export const AFTER_PAGE_FIX =
93
+ "then, for a page edit, run taproot-site pages push and taproot-site approve, and run taproot-site deploy --staging to refresh the report";
94
+ export const SITE_CHECK_REMEDIES = Object.freeze({
95
+ "link.page_missing": `Change the link to a page this site has, or create that page, ${AFTER_PAGE_FIX}.`,
96
+ "image.missing": `Remove the image from the page or replace it with one from the site's library, ${AFTER_PAGE_FIX}.`,
97
+ // Built for each image, because the command carries the image's own revision and text.
98
+ "a11y.image_default_missing": "Use the fix on the image finding, which names the exact command for that image.",
99
+ "form.none_chosen": `Choose a form in the Form block, or remove the block, ${AFTER_PAGE_FIX}.`,
100
+ "form.unreadable": `Place the form by its key (forms pull lists the site's forms), ${AFTER_PAGE_FIX}.`,
101
+ "form.missing": `Place a form the site has: run forms push if its file is new, or correct the key, ${AFTER_PAGE_FIX}.`,
102
+ "form.archived": `Place a form that is not archived, or restore this one in the app, ${AFTER_PAGE_FIX}.`,
103
+ "form.not_supported_on_site_type": `Remove the Form block, because forms are available on standard sites only, ${AFTER_PAGE_FIX}.`,
104
+ "seo.title_missing": `Give the page a title (front matter title:, or pages meta set), ${AFTER_PAGE_FIX}.`,
105
+ "seo.title_short": `Write a more specific title of ${TITLE_MINIMUM_LENGTH}–${TITLE_WARN_LENGTH} characters, ${AFTER_PAGE_FIX}.`,
106
+ "seo.title_long": `Shorten the title to ${TITLE_MINIMUM_LENGTH}–${TITLE_WARN_LENGTH} characters, ${AFTER_PAGE_FIX}.`,
107
+ "seo.description_missing": `Add a short description of what the page offers, ${AFTER_PAGE_FIX}.`,
108
+ "seo.description_short": `Add useful detail so the description runs ${DESCRIPTION_MINIMUM_LENGTH}–${DESCRIPTION_WARN_LENGTH} characters, ${AFTER_PAGE_FIX}.`,
109
+ "seo.description_long": `Shorten the description to ${DESCRIPTION_MINIMUM_LENGTH}–${DESCRIPTION_WARN_LENGTH} characters, ${AFTER_PAGE_FIX}.`,
110
+ "seo.description_matches_title": `Rewrite the description to say what readers will find, not repeat the title, ${AFTER_PAGE_FIX}.`,
111
+ });
112
+
113
+ /** An unknown rule id, cleaned and cut so every sentence that names it stays well inside the printed limit. */
114
+ const displayRuleId = (ruleId) => [...sanitizeDiagnostic(ruleId, "unknown")].slice(0, 200).join("");
115
+
116
+ /** The remedy for a rule, or one sentence naming the rule when this release has none for it. */
117
+ export function remedyForRule(ruleId) {
118
+ return Object.hasOwn(SITE_CHECK_REMEDIES, ruleId)
119
+ ? SITE_CHECK_REMEDIES[ruleId]
120
+ : `The report flagged the rule '${displayRuleId(ruleId)}', which this release has no remedy for; read its detail on the app's Site Health page.`;
121
+ }
122
+
69
123
  /** What a finding's `detail` names as the element that already claims the page's h1. */
70
124
  const H1_CLAIMANT = Object.freeze({
71
125
  heading: "the first level 1 heading",
@@ -75,12 +129,12 @@ const H1_CLAIMANT = Object.freeze({
75
129
 
76
130
  /** The sentence for a finding, falling back to the rule id for a rule this release has no words for. */
77
131
  export function describeSiteFinding(finding) {
78
- const words = SITE_CHECK_WORDING[finding.ruleId];
79
- return words === undefined ? `was flagged by the site check '${finding.ruleId}'` : words(finding);
132
+ const words = Object.hasOwn(SITE_CHECK_WORDING, finding.ruleId) ? SITE_CHECK_WORDING[finding.ruleId] : undefined;
133
+ return words === undefined ? `was flagged by the site check '${displayRuleId(finding.ruleId)}'` : words(finding);
80
134
  }
81
135
 
82
136
  // Progress names this many; the JSON list is bounded by bytes instead.
83
- const MAXIMUM_PROGRESS_LINES = 20;
137
+ export const MAXIMUM_PROGRESS_LINES = 20;
84
138
 
85
139
  const rulesRunningAt = (point) => SITE_CHECK_RULES.filter((rule) => rule.runsAt.includes(point)).map((rule) => rule.id);
86
140
 
@@ -119,6 +173,8 @@ export function evaluateOfflineSiteChecks({
119
173
  pagePaths,
120
174
  pagesComplete = true,
121
175
  formKeysChecked = true,
176
+ // Whether `validate --site` ran the image description rule (TR01371), or why it did not.
177
+ imageCheck = imageCheckSkipped(IMAGE_CHECK_NOT_REQUESTED),
122
178
  onProgress = () => {},
123
179
  }) {
124
180
  const known = normalizedPathSet([...pagePaths, ...(planned ?? []).map((page) => page.pagePath)]);
@@ -184,10 +240,20 @@ export function evaluateOfflineSiteChecks({
184
240
  !rule.runsAt.includes("validate") && !rule.runsAt.includes("health") && !rule.runsAt.includes("deploy")
185
241
  && rule.runsAt.includes("edit")
186
242
  ).map((rule) => rule.id),
187
- // A rule that had nothing to read: a truncated page manifest, or a workspace with no form files.
188
- ...(pagesComplete && formKeysChecked
243
+ // A rule that had nothing to read: a truncated page manifest, no site read for the images, or a workspace
244
+ // with no form files. In catalogue order.
245
+ ...(pagesComplete && formKeysChecked && imageCheck.ran
246
+ ? {}
247
+ : {
248
+ skipped: [
249
+ ...(pagesComplete ? [] : ["link.page_missing"]),
250
+ ...(imageCheck.ran ? [] : [RULE_IMAGE_DEFAULT_MISSING]),
251
+ ...(formKeysChecked ? [] : ["form.key_unknown"]),
252
+ ],
253
+ }),
254
+ ...(imageCheck.ran
189
255
  ? {}
190
- : { skipped: [...(pagesComplete ? [] : ["link.page_missing"]), ...(formKeysChecked ? [] : ["form.key_unknown"])] }),
256
+ : { imageCheckReason: { code: imageCheck.code, ...(imageCheck.message === undefined ? {} : { message: imageCheck.message }) } }),
191
257
  },
192
258
  };
193
259
  }
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "version": 2,
3
- "about": "The catalogue of site checks (TR01085, TR00947). Severity: 'error' blocks a deploy, 'warning' informs. Scope: 'page' rules read one page body plus cheap site lookups, 'site' rules read the site's own records, 'document' rules read only one document and its metadata, so the editor and the CLI evaluate them from shared/page-structure-checks.ts and the generator compiles deployment advice from the same pure evaluator. runsAt names the run points that evaluate the rule: save, validate (the CLI, offline), deploy, health, edit (the editor, over the open document in the browser). appliesTo, when present, limits a rule to those page types. subject and detail say what a finding's two values hold. The typed registry in Taproot.Domain/SiteChecks/SiteCheckRules.cs must list the same rules; SiteCheckTests fails on a difference.",
3
+ "about": "The catalogue of site checks (TR01085, TR00947). Severity: 'error' blocks a deploy, 'warning' informs. Scope: 'page' rules read one page body plus cheap site lookups, 'site' rules read the site's own records, 'document' rules read only one document and its metadata, so the editor and the CLI evaluate them from shared/page-structure-checks.ts and the generator compiles deployment advice from the same pure evaluator. runsAt names the run points that evaluate the rule: save, validate (the CLI, offline unless --site), deploy, health, edit (the editor, over the open document in the browser). appliesTo, when present, limits a rule to those page types. subject and detail say what a finding's two values hold. The typed registry in Taproot.Domain/SiteChecks/SiteCheckRules.cs must list the same rules; SiteCheckTests fails on a difference.",
4
4
  "runPoints": ["save", "validate", "deploy", "health", "edit"],
5
5
  "rules": [
6
6
  { "id": "link.page_missing", "severity": "warning", "scope": "page", "runsAt": ["save", "validate", "health"], "subject": "page_path", "detail": "none" },
7
7
  { "id": "image.missing", "severity": "warning", "scope": "page", "runsAt": ["save", "health"], "subject": "image_id", "detail": "none" },
8
- { "id": "a11y.image_default_missing", "severity": "warning", "scope": "site", "runsAt": ["deploy", "health"], "subject": "image_id", "detail": "none" },
8
+ { "id": "a11y.image_default_missing", "severity": "warning", "scope": "site", "runsAt": ["validate", "deploy", "health"], "subject": "image_id", "detail": "none" },
9
9
  { "id": "form.none_chosen", "severity": "error", "scope": "page", "runsAt": ["save", "deploy", "health"], "subject": "none", "detail": "none" },
10
10
  { "id": "form.unreadable", "severity": "error", "scope": "page", "runsAt": ["save", "deploy", "health"], "subject": "form_reference_text", "detail": "none" },
11
11
  { "id": "form.missing", "severity": "error", "scope": "page", "runsAt": ["save", "deploy", "health"], "subject": "form_id", "detail": "none" },
@@ -0,0 +1,252 @@
1
+ import { visitImageDescriptionObjects, imageDescriptionImageId } from "./content/image-description-document.js";
2
+ import { CLI_BINARY_NAME } from "./constants.js";
3
+ import { sanitizeDiagnostic } from "./errors.js";
4
+ import { AFTER_PAGE_FIX, describeSiteFinding, MAXIMUM_PROGRESS_LINES, remedyForRule } from "./site-check-findings.js";
5
+ import { displayPagePath } from "./workspace.js";
6
+
7
+ /**
8
+ * The finding shapes the CLI reports from the stored Site Health report, and the pieces `health`, `deploy
9
+ * --staging` and the pre-staging check share (TR01363). Page findings and image findings are separate lists, as
10
+ * in the report. Each carries a `fix` an agent can act on.
11
+ */
12
+
13
+ /** An image finding lists this many affected pages; `affectedPageCount` gives the total. */
14
+ export const MAXIMUM_AFFECTED_PAGES = 10;
15
+ // The server refuses a default description longer than this (`isImageDefaultDescription`).
16
+ const MAXIMUM_DESCRIPTION_SCALARS = 1000;
17
+ const IMAGE_RULE = "a11y.image_default_missing";
18
+
19
+ /** POSIX single-quotes text, so the shell hands the CLI exactly these characters. */
20
+ export function shellQuote(text) {
21
+ return `'${text.replaceAll("'", "'\\''")}'`;
22
+ }
23
+
24
+ // The printed command passes through `sanitizeDiagnostic` (2000 scalars), and the command around the text takes
25
+ // about 150 more, so the quoted text must leave room. An apostrophe becomes four scalars once quoted.
26
+ const MAXIMUM_QUOTED_SCALARS = 1800;
27
+
28
+ /**
29
+ * The trimmed, NFC-normalized text when it is safe to put in a describe command, else undefined. The server
30
+ * refuses over 1000 Unicode scalars and a lone surrogate; the rest is a CLI-side rule that keeps the printed shell
31
+ * command on one line, safe to run, and identical to the one in the JSON: control and line-separator characters,
32
+ * anything `sanitizeDiagnostic` would strip from the printed copy (bidi overrides and isolates), and text whose
33
+ * quoted form is too long to print whole.
34
+ */
35
+ export function usableDescription(value) {
36
+ if (typeof value !== "string") return undefined;
37
+ const text = value.trim().normalize("NFC");
38
+ if (text === "" || !text.isWellFormed() || [...text].length > MAXIMUM_DESCRIPTION_SCALARS) return undefined;
39
+ if (/[\p{Cc}\p{Zl}\p{Zp}]/u.test(text)) return undefined;
40
+ const quoted = shellQuote(text);
41
+ return [...quoted].length > MAXIMUM_QUOTED_SCALARS || sanitizeDiagnostic(quoted, "") !== quoted ? undefined : text;
42
+ }
43
+
44
+ function describeCommand(imageId, text, revision) {
45
+ return `${CLI_BINARY_NAME} media images describe ${imageId} --description=${shellQuote(text)}`
46
+ + ` --expected-revision ${revision} --if-missing`;
47
+ }
48
+
49
+ /** Production's report changes only when the owner promotes a release, so a fix for it says so. */
50
+ const promotionNote = (environment) =>
51
+ environment === "production" ? "; production's report updates once the owner promotes that release" : "";
52
+
53
+ const withoutPreview = (value) => [...sanitizeDiagnostic(value, "")].slice(0, 300).join("");
54
+
55
+ /**
56
+ * One image finding. Pure: every fact it needs is passed in.
57
+ *
58
+ * `descriptionRevision` and `hasDefault` come from the batched image read; `available` is false when that read
59
+ * succeeded without returning the image. `alts` are the distinct alt texts the workspace places for it, in
60
+ * manifest order. `affectedPages` are already resolved with their `file`. `environment` says which report the
61
+ * finding came from, and is absent before staging.
62
+ */
63
+ export function buildImageFinding({ imageId, name, descriptionRevision, hasDefault, available, alts = [], affectedPages, environment }) {
64
+ const suggestion = alts.map(usableDescription).find((text) => text !== undefined);
65
+ const base = {
66
+ rule: IMAGE_RULE,
67
+ imageId,
68
+ name: withoutPreview(name),
69
+ affectedPages: affectedPages.slice(0, MAXIMUM_AFFECTED_PAGES),
70
+ affectedPageCount: affectedPages.length,
71
+ };
72
+ if (available === false) {
73
+ return {
74
+ ...base,
75
+ imageAvailable: false,
76
+ fix: "This image is no longer in the site's library, so it cannot be described. Remove it from the pages that "
77
+ + `place it, or replace it with an image from the library, ${AFTER_PAGE_FIX}${promotionNote(environment)}.`,
78
+ };
79
+ }
80
+ const needs = suggestion === undefined ? { needsDescription: true } : { suggestedDescription: suggestion };
81
+ if (descriptionRevision === undefined) {
82
+ return {
83
+ ...base,
84
+ ...needs,
85
+ fix: `This image's state could not be read. Run ${CLI_BINARY_NAME} media images get ${imageId} for its description `
86
+ + "revision, then save the description with media images describe, passing --expected-revision and --if-missing, "
87
+ + `and run ${CLI_BINARY_NAME} deploy --staging to refresh the report${promotionNote(environment)}.`,
88
+ };
89
+ }
90
+ const common = { ...base, descriptionRevision, imageAvailable: true };
91
+ if (hasDefault === true) {
92
+ return {
93
+ ...common,
94
+ currentlyDescribed: true,
95
+ fix: "This image already has a default description, so the report is out of date. "
96
+ + `Run ${CLI_BINARY_NAME} deploy --staging to refresh the report${promotionNote(environment)}.`,
97
+ };
98
+ }
99
+ if (suggestion === undefined) {
100
+ return {
101
+ ...common,
102
+ currentlyDescribed: false,
103
+ needsDescription: true,
104
+ fix: "This image has no description and its placements carry no usable alt text. Write one, then save it with "
105
+ + `${CLI_BINARY_NAME} media images describe ${imageId}, passing --description, --expected-revision ${descriptionRevision} `
106
+ + `and --if-missing, then run ${CLI_BINARY_NAME} deploy --staging to refresh the report${promotionNote(environment)}.`,
107
+ };
108
+ }
109
+ return {
110
+ ...common,
111
+ currentlyDescribed: false,
112
+ suggestedDescription: suggestion,
113
+ fix: describeCommand(imageId, suggestion, descriptionRevision),
114
+ };
115
+ }
116
+
117
+ /**
118
+ * The comparison keys of a production report, or undefined when it cannot be compared against. A page finding is
119
+ * the same finding when its rule, page and full subject match; `findingKeys` holds those, built from the wire values
120
+ * before the subject is cut for display.
121
+ */
122
+ export function productionKeys(production) {
123
+ if (production?.status !== "complete" || production.truncated === true || !production.deploymentId) return undefined;
124
+ return {
125
+ pages: new Set(production.findingKeys),
126
+ images: new Set(production.images.map((image) => image.imageId)),
127
+ };
128
+ }
129
+
130
+ /** The stored page findings as the CLI reports them. `keys` is `productionKeys`, or undefined for "not compared". */
131
+ export function buildPageFindings(report, { fileByPageId, keys, environment }) {
132
+ return report.findings.map((finding, index) => {
133
+ const file = finding.pageId === undefined ? undefined : fileByPageId.get(finding.pageId);
134
+ return {
135
+ rule: finding.ruleId,
136
+ severity: finding.severity,
137
+ ...(finding.pageId === undefined ? {} : { path: displayPagePath(finding.pagePath), title: withoutPreview(finding.pageTitle) }),
138
+ ...(file === undefined ? {} : { file }),
139
+ subject: withoutPreview(finding.subject),
140
+ ...(finding.detail === "" ? {} : { detail: withoutPreview(finding.detail) }),
141
+ fix: `${remedyForRule(finding.ruleId).replace(/\.$/u, "")}${promotionNote(environment)}.`,
142
+ ...(keys === undefined ? {} : { newSinceProduction: !keys.pages.has(report.findingKeys[index]) }),
143
+ };
144
+ });
145
+ }
146
+
147
+ /** The pages an image finding names, resolved to workspace files where the manifest has them. */
148
+ export function resolveAffectedPages(pages, fileByPageId) {
149
+ return pages.map((page) => {
150
+ const file = fileByPageId.get(page.pageId);
151
+ return { path: displayPagePath(page.path), title: withoutPreview(page.title), ...(file === undefined ? {} : { file }) };
152
+ });
153
+ }
154
+
155
+ /** Page id to workspace source file, from a pulled workspace's manifest (empty without one). */
156
+ export function filesByPageId(manifest) {
157
+ const files = new Map();
158
+ for (const entry of manifest?.pages ?? []) {
159
+ if (typeof entry?.pageId === "string" && typeof entry.file === "string") files.set(entry.pageId, entry.file);
160
+ }
161
+ return files;
162
+ }
163
+
164
+ /**
165
+ * The alt text one converted page places for each image (TR01363, TR01371), as a fresh Map from lowercase image id
166
+ * to its distinct trimmed non-empty alts, in document order.
167
+ *
168
+ * Only a `custom` or unset placement counts: an `inherit` placement's stored alt is the hydrated default and may be
169
+ * stale, and a `decorative` one has no description. A banner's own image is described by the banner's `altText` and
170
+ * mode, never by its stored alt. The walk is recursive, so a very deep document throws a `RangeError`: callers keep
171
+ * a page's alts only when this returns, as `mergeAlts` is called after it.
172
+ */
173
+ export function altsFromDocument(document) {
174
+ const found = new Map();
175
+ const add = (imageId, alt) => {
176
+ const text = typeof alt === "string" ? alt.trim() : "";
177
+ if (typeof imageId !== "string" || text === "") return;
178
+ const key = imageId.toLowerCase();
179
+ const known = found.get(key) ?? [];
180
+ if (!known.includes(text)) found.set(key, [...known, text]);
181
+ };
182
+ const counts = (mode) => mode === undefined || mode === null || mode === "" || mode === "custom";
183
+ // The parent is visited before its nested image, so a banner can claim it first.
184
+ const bannerImages = new WeakSet();
185
+ visitImageDescriptionObjects(document, (image) => {
186
+ const imageId = imageDescriptionImageId(image);
187
+ if (imageId !== undefined && !bannerImages.has(image)) {
188
+ const album = "caption" in image && "urls" in image;
189
+ const field = "altText" in image || album ? "altText" : "alt";
190
+ if (counts(image.descriptionMode)) add(imageId, image[field]);
191
+ }
192
+ const nested = image.image;
193
+ if (
194
+ ("altText" in image || "descriptionMode" in image || "overlayText" in image)
195
+ && nested !== null && typeof nested === "object" && !Array.isArray(nested)
196
+ ) {
197
+ const bannerId = imageDescriptionImageId(nested);
198
+ if (bannerId !== undefined) {
199
+ bannerImages.add(nested);
200
+ if (counts(image.descriptionMode ?? nested.descriptionMode)) add(bannerId, image.altText);
201
+ }
202
+ }
203
+ });
204
+ return found;
205
+ }
206
+
207
+ /** Adds one page's alts to the running Map, keeping each image's distinct texts in the order pages were merged. */
208
+ export function mergeAlts(alts, found) {
209
+ for (const [imageId, texts] of found) {
210
+ const known = alts.get(imageId) ?? [];
211
+ alts.set(imageId, [...known, ...texts.filter((text) => !known.includes(text))]);
212
+ }
213
+ }
214
+
215
+ /** One progress line for an undescribed image, cleaned for the terminal; the JSON keeps the original values. */
216
+ export function imageFindingLine(item) {
217
+ const safe = (value) => sanitizeDiagnostic(value, "");
218
+ return `Warning: image ${safe(item.name) || safe(item.imageId)} (${safe(item.imageId)}) has no default image description; `
219
+ + `placed on ${item.affectedPageCount} page(s). Fix: ${safe(item.fix)}`;
220
+ }
221
+
222
+ /**
223
+ * One summary line and a line for each warning that is new since production (each warning when production was not
224
+ * compared), at most `MAXIMUM_PROGRESS_LINES`, each naming its fix.
225
+ */
226
+ export function reportHealthProgress(onProgress, { environment, checkedAt, status, findings, imageFindings, compared }) {
227
+ const incomplete = status === "incomplete"
228
+ ? " Coverage is incomplete, so this report is not a pass."
229
+ : "";
230
+ const total = findings.length + imageFindings.length;
231
+ // Every value here ends up on a terminal, and some come from the manifest or the server unchecked, so each is
232
+ // cleaned for display. The JSON result keeps the original values.
233
+ const safe = (value, fallback = "") => sanitizeDiagnostic(value, fallback);
234
+ const worth = [
235
+ ...findings.filter((item) => item.newSinceProduction !== false).map((item) =>
236
+ `Warning: ${safe(item.file ?? item.path, "site")} ${
237
+ describeSiteFinding({ ruleId: safe(item.rule), subject: safe(item.subject), detail: safe(item.detail) })
238
+ }. Fix: ${safe(item.fix)}`
239
+ ),
240
+ ...imageFindings.filter((item) => item.newSinceProduction !== false).map(imageFindingLine),
241
+ ];
242
+ const scope = environment === "staging" && compared === false
243
+ ? "not compared with production, so every warning is listed"
244
+ : environment === "staging"
245
+ ? `${worth.length} new since production`
246
+ : "production";
247
+ onProgress(`Site health (${environment}, checked ${checkedAt}): ${total} finding(s), ${scope}.${incomplete}`);
248
+ for (const line of worth.slice(0, MAXIMUM_PROGRESS_LINES)) onProgress(line);
249
+ if (worth.length > MAXIMUM_PROGRESS_LINES) {
250
+ onProgress(`Warning: ${worth.length - MAXIMUM_PROGRESS_LINES} more Site Health finding(s); see findings and imageFindings.`);
251
+ }
252
+ }
@@ -0,0 +1,49 @@
1
+ // Generated from shared/site-health-image-checks.ts by scripts/sync-field-validation.mjs. Do not edit.
2
+ /**
3
+ * Site Health's `a11y.image_default_missing` rule (TR01364): an image the site owns, that some page places, and
4
+ * whose default description is undefined.
5
+ *
6
+ * The generator runs this over a frozen deployment and the site-authoring CLI runs it over what a workspace
7
+ * places, so the rule has one owner. Both sides pass pages with an opaque `key` (the generator uses the page id,
8
+ * the CLI the workspace file) and the image records they hold. This file is dependency-free, so
9
+ * `node scripts/sync-field-validation.mjs` writes the generator copy and the CLI's compiled copy; edit only this
10
+ * file and re-run it. Findings carry values, never wording: each surface writes its own words.
11
+ */
12
+ /**
13
+ * Every undescribed image the pages place, one finding per image, in the order of `images`, with no cap (the
14
+ * caller applies its own). Each finding lists its pages in the order of `pages`, once per page even when that page
15
+ * places the image repeatedly. `siteId` is compared only with records that carry one. Image ids match by exact
16
+ * string, so callers pass the lowercase ids the API returns.
17
+ */
18
+ export function evaluateImageDefaultMissing(input) {
19
+ const usedBy = new Map();
20
+ for (const page of input.pages) {
21
+ const reference = { key: page.key, path: page.path, title: page.title };
22
+ for (const imageId of new Set(page.imageIds)) {
23
+ const usages = usedBy.get(imageId);
24
+ if (usages === undefined)
25
+ usedBy.set(imageId, [reference]);
26
+ else
27
+ usages.push(reference);
28
+ }
29
+ }
30
+ const findings = [];
31
+ for (const image of input.images) {
32
+ if (image.isMissing)
33
+ continue;
34
+ if (image.siteId !== undefined && image.siteId !== input.siteId)
35
+ continue;
36
+ if (image.defaultDescription !== undefined)
37
+ continue;
38
+ const affectedPages = usedBy.get(image.imageId);
39
+ if (affectedPages === undefined)
40
+ continue;
41
+ findings.push({
42
+ imageId: image.imageId,
43
+ name: image.name,
44
+ ...(image.previewUrl === undefined ? {} : { previewUrl: image.previewUrl }),
45
+ affectedPages: [...affectedPages],
46
+ });
47
+ }
48
+ return findings;
49
+ }