@taprootio/site-authoring 0.61.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 (71) hide show
  1. package/README.md +97 -23
  2. package/package.json +2 -2
  3. package/src/api.js +149 -21
  4. package/src/appearance-contract.js +27 -0
  5. package/src/article-appearance.js +19 -0
  6. package/src/article-appearance.json +9 -0
  7. package/src/article-end-settings.js +295 -0
  8. package/src/changelog.json +49 -0
  9. package/src/chrome-input.js +1 -1
  10. package/src/cli.js +110 -26
  11. package/src/constants.js +7 -0
  12. package/src/content/components.js +130 -14
  13. package/src/content/cta-decoration-paint.js +321 -0
  14. package/src/content/form-placement-presentation.js +91 -0
  15. package/src/content/form-placement-presentation.json +6 -0
  16. package/src/content/free-form-section-registry.json +19 -1
  17. package/src/content/free-form-sections.js +64 -55
  18. package/src/content/markdown.js +13 -0
  19. package/src/content/tiptap-prosemirror.ts +72 -59
  20. package/src/content/validate-document.js +2 -0
  21. package/src/cta-artwork-warnings.js +164 -0
  22. package/src/errors.js +6 -0
  23. package/src/field-schema.json +6 -2
  24. package/src/field-validation.js +14 -5
  25. package/src/footer-workspace.js +7 -3
  26. package/src/form-references.js +71 -9
  27. package/src/forms-contract.js +3 -5
  28. package/src/heading-outline.js +7 -0
  29. package/src/output.js +2 -0
  30. package/src/page-article-end.js +66 -0
  31. package/src/page-block-catalog.js +54 -0
  32. package/src/page-form-presentation.js +104 -0
  33. package/src/page-structure-checks.js +7 -1
  34. package/src/placed-image-ids.js +15 -18
  35. package/src/presentation-reference.js +31 -53
  36. package/src/reference-help.js +97 -27
  37. package/src/reusable-blocks.js +429 -0
  38. package/src/reusable-placements.js +271 -0
  39. package/src/setting-reference.js +57 -1
  40. package/src/settings-catalog.js +3 -0
  41. package/src/site-check-findings.js +30 -2
  42. package/src/site-check-rules.json +1 -0
  43. package/src/site-checks.js +26 -2
  44. package/src/site-health-findings.js +25 -3
  45. package/src/site-health-image-checks.js +1 -1
  46. package/src/staging-check.js +108 -21
  47. package/src/staging-served.js +5 -49
  48. package/src/status-warning-paints.js +17 -0
  49. package/src/template-token-reach.json +20 -2
  50. package/src/theme-resolve.js +27 -0
  51. package/src/transport.js +41 -5
  52. package/src/typed-page-reference.js +55 -5
  53. package/src/typed-pages.js +27 -4
  54. package/src/verbs/approve.js +2 -1
  55. package/src/verbs/deploy.js +93 -15
  56. package/src/verbs/footer-push.js +4 -2
  57. package/src/verbs/forms-push.js +9 -0
  58. package/src/verbs/health.js +11 -6
  59. package/src/verbs/index.js +3 -0
  60. package/src/verbs/pages-blocks-pull.js +22 -0
  61. package/src/verbs/pages-push.js +89 -34
  62. package/src/verbs/plan.js +34 -5
  63. package/src/verbs/pull.js +213 -124
  64. package/src/verbs/status.js +20 -2
  65. package/src/verbs/theme-push.js +170 -20
  66. package/src/verbs/theme-resolve.js +114 -40
  67. package/src/verbs/validate.js +49 -18
  68. package/src/workspace-check.js +42 -5
  69. package/src/workspace-context-usage.js +54 -1
  70. package/src/workspace.js +37 -7
  71. package/test/fixtures/default-site-theme.json +1 -1
@@ -0,0 +1,164 @@
1
+ import { AA_NON_TEXT_RATIO, AA_TEXT_RATIO, wcagRatio } from "@taprootio/espalier/shared/theme";
2
+ import { CTA_BUTTON_STYLE_DEFAULT, resolveButtonStyle } from "./content/button-styles.js";
3
+ import { effectiveCtaArtScrim, normalizeCtaDecoration } from "./content/cta-decoration-paint.js";
4
+ import { namedContext } from "./content/free-form-sections.js";
5
+ import { boundedByBytes } from "./session.js";
6
+ import { SITE_FINDINGS_MAX_BYTES } from "./site-check-findings.js";
7
+ import { loadThemeEngines } from "./theme-resolve.js";
8
+ import { contentDocuments } from "./typed-pages.js";
9
+
10
+ const BLACK = { r: 0, g: 0, b: 0 };
11
+ const OUTLINE_FILL = "--esp-button-outline-background";
12
+ const OUTLINE_BORDER = "--esp-button-outline-border-color";
13
+
14
+ function luminance(color) {
15
+ return (wcagRatio(color, BLACK) - 1) * 0.05;
16
+ }
17
+
18
+ function possibleContrast(ink, background, exposed) {
19
+ const blend = (end) => Object.fromEntries(
20
+ Object.entries(background).map(([key, channel]) => [key, channel * (1 - exposed) + end * exposed]),
21
+ );
22
+ const inkLuminance = luminance(ink);
23
+ const dark = blend(0);
24
+ const light = blend(1);
25
+ return inkLuminance >= luminance(dark) && inkLuminance <= luminance(light)
26
+ ? 1
27
+ : Math.min(wcagRatio(ink, dark), wcagRatio(ink, light));
28
+ }
29
+
30
+ function readArtwork(page) {
31
+ const art = [];
32
+ for (const { doc, path } of contentDocuments(page.document)) {
33
+ const pending = [{ node: doc, path, context: undefined }];
34
+ while (pending.length > 0) {
35
+ const current = pending.pop();
36
+ const { node } = current;
37
+ const context = namedContext(node)?.context || current.context;
38
+ if (node?.type === "componentBlock" && node.attrs?.componentType === "cta") {
39
+ try {
40
+ const data = JSON.parse(node.attrs.componentData);
41
+ const { decoration } = normalizeCtaDecoration(data?.decoration);
42
+ const key = page.reusableCtaKeys?.get(current.path);
43
+ if (decoration || key !== undefined) {
44
+ art.push({
45
+ page,
46
+ path: current.path + (key === undefined ? "/attrs/componentData/decoration" : "/attrs/componentData/reusableKey"),
47
+ context,
48
+ data,
49
+ decoration,
50
+ key,
51
+ });
52
+ }
53
+ } catch {
54
+ // Document validation reports malformed component data.
55
+ }
56
+ }
57
+ for (let index = (node?.content?.length ?? 0) - 1; index >= 0; index -= 1) {
58
+ pending.push({ node: node.content[index], path: `${current.path}/content/${index}`, context });
59
+ }
60
+ }
61
+ }
62
+ return art;
63
+ }
64
+
65
+ function componentChecks(data, surface) {
66
+ const token = (name) => surface.tokens.find((entry) => entry.token === name)?.resolved;
67
+ const prop = (name) => surface.componentProperties.find((entry) => entry.name === name);
68
+ const panel = token("background");
69
+ const checks = [];
70
+ const add = (content, ink, ground = panel, minimum = AA_TEXT_RATIO, exposed = true) => {
71
+ checks.push({ content, ink, ground, minimum, exposed });
72
+ };
73
+ if (data.heading?.trim()) add("heading", token("headings"));
74
+ if (data.description?.trim()) add("description", token("text"));
75
+ if (data.buttonText?.trim() && data.buttonUrl?.trim()) {
76
+ const style = resolveButtonStyle(data.buttonStyle, CTA_BUTTON_STYLE_DEFAULT);
77
+ if (style === "outline") {
78
+ const fill = prop(OUTLINE_FILL);
79
+ const ink = fill?.ink?.resolved ?? token("link");
80
+ add("outline button label", ink, fill?.resolved ?? panel, AA_TEXT_RATIO, !fill);
81
+ add("outline button border", prop(OUTLINE_BORDER)?.resolved ?? ink, panel, AA_NON_TEXT_RATIO);
82
+ } else if (style === "text") {
83
+ add("button label", token("text"));
84
+ } else if (data.variant === "danger") {
85
+ // Espalier recomputes the scoped action colors for the intent on the button.
86
+ // The public theme fit report does not expose that pair.
87
+ checks.push({ content: "filled danger button label" });
88
+ } else {
89
+ // A filled action carries its own contrast pair above the artwork.
90
+ add("filled button label", token("actionText"), token("actionBackground"), AA_TEXT_RATIO, false);
91
+ }
92
+ }
93
+ return checks;
94
+ }
95
+
96
+ function srgb(color, css) {
97
+ if (css === undefined) return undefined;
98
+ const parsed = color.parseCssColor(css);
99
+ if (parsed === null) return undefined;
100
+ const mapped = color.oklchToSRGB(color.gamutMapToSRGB(parsed));
101
+ return { r: color.clampChannel(mapped.r), g: color.clampChannel(mapped.g), b: color.clampChannel(mapped.b) };
102
+ }
103
+
104
+ export async function ctaContrastFindings(ctas, styles, loadEngines = loadThemeEngines) {
105
+ if (ctas.length === 0) return [];
106
+ let suite;
107
+ let engines;
108
+ if (styles?.lightTheme && styles?.darkTheme) {
109
+ try {
110
+ engines = await loadEngines();
111
+ suite = engines.fit.themeFitReportSuite(styles.lightTheme, styles.darkTheme);
112
+ } catch {
113
+ // Report unavailable paint evidence below, the same as missing theme files.
114
+ }
115
+ }
116
+
117
+ const items = [];
118
+ function warn({ file, path, context, key }, scheme, code, message) {
119
+ items.push({ file, path, scheme, ...(context ? { context } : {}), ...(key === undefined ? {} : { key }), code, message });
120
+ }
121
+ for (const cta of ctas) {
122
+ const exposure = cta.decoration === undefined ? 0 : cta.decoration.opacity * (1 - effectiveCtaArtScrim(cta.decoration));
123
+ for (const scheme of ["light", "dark"]) {
124
+ const surface = suite?.[scheme].find((entry) => entry.surface === (cta.context || engines.fit.ROOT_SURFACE));
125
+ if (!surface) {
126
+ warn(cta, scheme, "unavailable", "The effective panel colors are unavailable; check the CTA's copy and button in this scheme.");
127
+ continue;
128
+ }
129
+ for (const check of componentChecks(cta.data, surface)) {
130
+ const ink = srgb(engines.color, check.ink);
131
+ const ground = srgb(engines.color, check.ground);
132
+ if (!ink || !ground) {
133
+ warn(cta, scheme, "unavailable", `The ${check.content} colors are unavailable in this scheme.`);
134
+ continue;
135
+ }
136
+ const ratio = possibleContrast(ink, ground, check.exposed ? exposure : 0);
137
+ if (ratio < check.minimum) {
138
+ const detail = check.exposed && exposure > 0
139
+ ? "could fall below WCAG AA over the artwork. Strengthen the scrim, lower the opacity, or change the theme colors."
140
+ : "falls below WCAG AA. Adjust the theme colors.";
141
+ warn(cta, scheme, "below_aa", `The CTA ${check.content} ${detail}`);
142
+ }
143
+ }
144
+ }
145
+ }
146
+ return items;
147
+ }
148
+
149
+ /** Reports possible low contrast without reading an image or requiring credentials. */
150
+ export async function ctaArtworkWarnings(planned, styles, onProgress = () => {}, loadEngines = loadThemeEngines) {
151
+ const artwork = (planned ?? []).flatMap((page) => page.document ? readArtwork(page) : []);
152
+ if (artwork.length === 0) return {};
153
+ const items = (await ctaContrastFindings(artwork.map(({ page, ...cta }) => ({ ...cta, file: page.file })), styles, loadEngines))
154
+ .map(({ code, ...finding }) => ({ ...finding, code: `cta.${finding.key === undefined ? "artwork" : "workspace"}_contrast_${code}` }));
155
+ for (const item of items.slice(0, 20)) onProgress(`Warning: ${item.file} ${item.path} (${item.scheme}). ${item.message}`);
156
+ const reported = boundedByBytes(items, SITE_FINDINGS_MAX_BYTES);
157
+ return items.length === 0 ? {} : {
158
+ ctaArtworkWarnings: {
159
+ total: items.length,
160
+ items: reported.items,
161
+ ...(reported.truncated ? { truncated: true } : {}),
162
+ },
163
+ };
164
+ }
package/src/errors.js CHANGED
@@ -130,6 +130,12 @@ export class SiteAuthoringError extends Error {
130
130
  this.previewDiagnostic = normalizePreviewDiagnostic(options.previewDiagnostic);
131
131
  this.field = typeof options.field === "string" ? sanitizeDiagnostic(options.field, "") : undefined;
132
132
  this.status = typeof options.status === "string" ? sanitizeDiagnostic(options.status, "") : undefined;
133
+ if (typeof options.reason === "string") this.reason = sanitizeDiagnostic(options.reason, "");
134
+ if (typeof options.nextStep === "string") this.nextStep = sanitizeDiagnostic(options.nextStep, "");
135
+ if (typeof options.stageAgainReason === "string" && /^[a-z][a-z0-9_]{0,63}$/u.test(options.stageAgainReason)
136
+ && !options.stageAgainReason.startsWith("tr_")) {
137
+ this.stageAgainReason = options.stageAgainReason;
138
+ }
133
139
  // The site check rule (shared/site-check-rules.json) this refusal comes from, when it comes from one.
134
140
  this.rule = typeof options.rule === "string" && /^[a-z0-9_.]+$/u.test(options.rule) ? options.rule : undefined;
135
141
  this.alternatives = Array.isArray(options.alternatives)
@@ -23,14 +23,18 @@
23
23
  "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
24
24
  },
25
25
  "presentation": {
26
- "description": "Sparse embedded-form appearance choices. Omitted properties inherit the site's staged defaults; explicit false disables a choice. Omit the object when all choices inherit.",
26
+ "description": "Sparse embedded-form appearance choices. Background, border, and shadow inherit the site's staged defaults when omitted. Explicit false disables each surface choice. The required-field legend is a per-form choice. Omit the object when no choices are set.",
27
27
  "type": "object",
28
28
  "minProperties": 1,
29
29
  "additionalProperties": false,
30
30
  "properties": {
31
31
  "background": { "type": "boolean" },
32
32
  "border": { "type": "boolean" },
33
- "shadow": { "type": "boolean" }
33
+ "shadow": { "type": "boolean" },
34
+ "hideRequiredLegend": {
35
+ "description": "True hides the required-field legend. False or omission shows it when there are required fields. Required fields keep their indicators and validation.",
36
+ "type": "boolean"
37
+ }
34
38
  }
35
39
  },
36
40
  "submit_label": {
@@ -13,9 +13,8 @@
13
13
  * .NET agree. Keep `shared/field-schema.json` in step with the constants below;
14
14
  * a test compares them.
15
15
  *
16
- * The generator's client and the published site-authoring package cannot import
17
- * this file, so `node scripts/sync-field-validation.mjs` writes their copies;
18
- * edit only this file and re-run it.
16
+ * The generator and published site-authoring package carry copies written by
17
+ * `node scripts/sync-field-validation.mjs`. Edit this file and re-run it.
19
18
  */
20
19
  export const FIELD_TYPES = [
21
20
  "text",
@@ -106,6 +105,16 @@ export function contactFieldId(definition) {
106
105
  const emails = definition.fields.filter((field) => field.type === "email");
107
106
  return emails.length === 1 ? emails[0].id : undefined;
108
107
  }
108
+ /** A validated definition can capture newsletter consent when its contact email and a consent field are required. */
109
+ export function hasRequiredContactEmailAndConsent(definition) {
110
+ const contact = contactFieldId(definition);
111
+ return definition.fields.some((field) => field.id === contact && field.type === "email" && field.required === true)
112
+ && definition.fields.some((field) => field.type === "consent");
113
+ }
114
+ /** Two fields leave room for exactly the required contact email and one consent field. */
115
+ export function isCompactFormEligible(definition) {
116
+ return definition.fields.length === 2 && hasRequiredContactEmailAndConsent(definition);
117
+ }
109
118
  const DEFINITION_KEYS = ["fields", "contact_field", "submit_label", "after_submit", "newsletter_audience_id", "presentation"];
110
119
  const BASE_FIELD_KEYS = ["id", "type", "label", "hint"];
111
120
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -425,7 +434,7 @@ export function validateDefinition(definition) {
425
434
  }
426
435
  return errors;
427
436
  }
428
- /** The button text and the after-submit choice, which sit beside the fields in a definition. */
437
+ /** Optional settings that sit beside the fields in a definition. */
429
438
  function validateFormSettings(definition, errors) {
430
439
  if ("presentation" in definition) {
431
440
  const presentation = definition.presentation;
@@ -434,7 +443,7 @@ function validateFormSettings(definition, errors) {
434
443
  }
435
444
  else {
436
445
  for (const key of sortedKeys(presentation)) {
437
- if (key !== "background" && key !== "border" && key !== "shadow") {
446
+ if (key !== "background" && key !== "border" && key !== "shadow" && key !== "hideRequiredLegend") {
438
447
  errors.push({ path: `presentation.${key}`, code: "unknown_property" });
439
448
  }
440
449
  else if (typeof presentation[key] !== "boolean") {
@@ -62,10 +62,10 @@ export async function readFooterWorkspaceContext(workspaceDir, siteId) {
62
62
 
63
63
  /** Collect the identities present in the available, site-bound inventory. */
64
64
  export function appearanceResourceIds(manifest, mediaManifest) {
65
- const knownPageResourceIds = manifest === undefined
65
+ const knownPageResourceIds = manifest === undefined || manifest.settingsOnly === true
66
66
  ? undefined
67
67
  : new Set(manifest.pages.map((page) => page?.resourceId).filter(isCanonicalUuid));
68
- const imageIds = [manifest?.footer?.imageIds, manifest?.appearance?.imageIds]
68
+ const imageIds = [manifest?.footer?.imageIds, manifest?.appearance?.imageIds, manifest?.reusableBlocks?.imageIds, manifest?.articleEndOwnedImages]
69
69
  .flatMap((ids) => Array.isArray(ids) ? ids : []);
70
70
  const knownImageIds = new Set([
71
71
  ...imageIds,
@@ -89,7 +89,7 @@ export async function advanceFooterManifest(
89
89
  siteId,
90
90
  footerSettings,
91
91
  expectedDraftHash,
92
- { presentationRevision, tagDestinations, authoredTagSlugs, recipeMetadataDestinations } = {},
92
+ { presentationRevision, tagDestinations, authoredTagSlugs, recipeMetadataDestinations, reusableBlocks, articleEndTags, articleEndOwnedImages } = {},
93
93
  ) {
94
94
  const manifest = await readManifest(workspaceDir, siteId);
95
95
  const prior = requireFooterMetadata(manifest);
@@ -112,6 +112,10 @@ export async function advanceFooterManifest(
112
112
  if (presentationRevision !== undefined) {
113
113
  manifest.presentation = presentationManifestEntry(presentationRevision, tagDestinations, authoredTagSlugs, recipeMetadataDestinations);
114
114
  }
115
+ if (reusableBlocks !== undefined) manifest.reusableBlocks = reusableBlocks;
116
+ if (articleEndTags !== undefined) manifest.articleEndTags = articleEndTags;
117
+ if (articleEndOwnedImages?.length === 0) delete manifest.articleEndOwnedImages;
118
+ else if (articleEndOwnedImages !== undefined) manifest.articleEndOwnedImages = articleEndOwnedImages;
115
119
  await writeManifest(workspaceDir, manifest);
116
120
  return hash;
117
121
  }
@@ -1,5 +1,10 @@
1
+ import { isCompactFormEligible } from "./field-validation.js";
2
+ import { stableJson } from "./footer-draft-hash.js";
3
+ import { readFormPlacementPresentation } from "./content/form-placement-presentation.js";
4
+ import { recordedForm } from "./forms-workspace.js";
1
5
  import { listSiteForms } from "./forms-api.js";
2
6
  import { contentDocuments, parseComponentData } from "./typed-pages.js";
7
+ import { workspaceContentHash } from "./workspace.js";
3
8
 
4
9
  /**
5
10
  * Where the workspace and the site spell a placed form differently (TR01216).
@@ -25,7 +30,7 @@ function formBlocks(document_) {
25
30
  if (value.type === "componentBlock" && value.attrs?.componentType === FORM_COMPONENT) {
26
31
  const data = typeof value.attrs.componentData === "string"
27
32
  ? parseComponentData(value.attrs.componentData)
28
- : undefined;
33
+ : value.attrs.componentData;
29
34
  if (data !== null && typeof data === "object" && !Array.isArray(data)) found.push({ attrs: value.attrs, data });
30
35
  return;
31
36
  }
@@ -36,6 +41,29 @@ function formBlocks(document_) {
36
41
  return found;
37
42
  }
38
43
 
44
+ /** A sorted multiset of direct Form copy, independent of block order and layout. */
45
+ export function formPresentationHash(document_) {
46
+ const rows = [];
47
+ for (const { data } of formBlocks(document_)) {
48
+ const identity = data.formKey ?? data.formId;
49
+ if (typeof identity !== "string" || Object.hasOwn(data, "reusableKey")) continue;
50
+ const presentation = readFormPlacementPresentation(data);
51
+ if (Object.keys(presentation).length > 0) rows.push(stableJson([identity, presentation]));
52
+ }
53
+ return rows.length === 0 ? undefined : workspaceContentHash(JSON.stringify(rows.sort()));
54
+ }
55
+
56
+ /** Contexts of direct Form placements, in their first document order. */
57
+ export function formPlacementContexts(document_) {
58
+ const contexts = new Set();
59
+ for (const { data } of formBlocks(document_)) {
60
+ if (Object.hasOwn(data, "reusableKey")) continue;
61
+ const { context } = readFormPlacementPresentation(data);
62
+ if (context !== undefined) contexts.add(context);
63
+ }
64
+ return [...contexts];
65
+ }
66
+
39
67
  /** The distinct form keys a workspace document places, in document order. */
40
68
  export function placedFormKeys(document_) {
41
69
  const keys = [];
@@ -45,9 +73,38 @@ export function placedFormKeys(document_) {
45
73
  return keys;
46
74
  }
47
75
 
76
+ /** Local definitions take precedence over version-matched catalog evidence. */
77
+ export function compactFormEvidence(manifest, localForms) {
78
+ const definitions = new Map((localForms ?? []).map(({ key, document }) => [key, document.definition]));
79
+ const forms = manifest?.pageBlockCatalog?.forms;
80
+ const catalog = new Map((Array.isArray(forms) ? forms : []).map((row) => [row?.key, row]));
81
+ return (key, matchingCatalogRow) => {
82
+ if (definitions.has(key)) return { eligible: isCompactFormEligible(definitions.get(key)), source: "workspace" };
83
+ // A reusable Form and its options come from the same draft catalog read.
84
+ // Inline Form keys need the independent form version recorded at pull.
85
+ const row = matchingCatalogRow ?? catalog.get(key);
86
+ if (row?.archived !== false || typeof row.compactEligible !== "boolean") return undefined;
87
+ if (matchingCatalogRow === undefined) {
88
+ const baseline = recordedForm(manifest ?? {}, key);
89
+ if (!baseline || row.version !== baseline.version || row.formId !== baseline.id) return undefined;
90
+ }
91
+ return { eligible: row.compactEligible, source: "catalog" };
92
+ };
93
+ }
94
+
95
+ export function placedCompactFormKeys(document_) {
96
+ return [...new Set(formBlocks(document_).filter(({ data }) => data.layout === "compact" &&
97
+ typeof data.formKey === "string").map(({ data }) => data.formKey))];
98
+ }
99
+
100
+ /** Form ids in the stored body, before pull translates them to workspace keys. */
101
+ export function placedFormIds(document_) {
102
+ return new Set(formBlocks(document_).map(({ data }) => data.formId).filter((id) => typeof id === "string"));
103
+ }
104
+
48
105
  /** Whether a document read from the site places any form by id. */
49
106
  export function placesFormIds(document_) {
50
- return formBlocks(document_).some(({ data }) => typeof data.formId === "string");
107
+ return placedFormIds(document_).size > 0;
51
108
  }
52
109
 
53
110
  /**
@@ -59,9 +116,8 @@ export function withFormIds(document_, idByKey) {
59
116
  return translate(document_, (data) => {
60
117
  const id = typeof data.formKey === "string" ? idByKey.get(data.formKey) : undefined;
61
118
  if (id === undefined) return undefined;
62
- const rest = { ...data };
63
- delete rest.formKey;
64
- return { ...rest, formId: id };
119
+ const { layout } = data;
120
+ return { formId: id, ...(layout === undefined ? {} : { layout }), ...readFormPlacementPresentation(data) };
65
121
  });
66
122
  }
67
123
 
@@ -89,15 +145,21 @@ function translate(document_, convert) {
89
145
  return copy;
90
146
  }
91
147
 
148
+ export function liveFormIndexReader(client, siteId) {
149
+ let index;
150
+ return () => index ??= readFormIndex(client, siteId);
151
+ }
152
+
92
153
  /** The site's forms by key and by id, archived ones marked. One request serves a whole push or pull. */
93
- export async function readFormIndex(client, siteId) {
154
+ export async function readFormIndex(client, siteId, catalogForms) {
94
155
  const idByKey = new Map();
95
156
  const keyById = new Map();
96
157
  const archivedKeys = new Set();
97
- for (const form of await listSiteForms(client, siteId)) {
98
- keyById.set(form.id, form.key);
158
+ for (const form of catalogForms ?? await listSiteForms(client, siteId)) {
159
+ const id = form.formId ?? form.id;
160
+ keyById.set(id, form.key);
99
161
  if (form.archived) archivedKeys.add(form.key);
100
- else idByKey.set(form.key, form.id);
162
+ else idByKey.set(form.key, id);
101
163
  }
102
164
  return { idByKey, keyById, archivedKeys };
103
165
  }
@@ -1,5 +1,5 @@
1
1
  import { SiteAuthoringError } from "./errors.js";
2
- import { contactFieldId, validateDefinition } from "./field-validation.js";
2
+ import { contactFieldId, hasRequiredContactEmailAndConsent, validateDefinition } from "./field-validation.js";
3
3
 
4
4
  /**
5
5
  * The workspace contract for a form (TR01061).
@@ -87,7 +87,7 @@ function hasUnstorableCharacters(text) {
87
87
  return /\u0000|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(text);
88
88
  }
89
89
 
90
- function anyUnstorableString(value) {
90
+ export function anyUnstorableString(value) {
91
91
  if (typeof value === "string") return hasUnstorableCharacters(value);
92
92
  if (Array.isArray(value)) return value.some(anyUnstorableString);
93
93
  if (value !== null && typeof value === "object") {
@@ -104,9 +104,7 @@ function describeDefinitionErrors(errors) {
104
104
 
105
105
  /** Checks newsletter admission after the definition has passed shared validation. */
106
106
  export function validateNewsletterDefinition(file, definition) {
107
- const fields = definition.fields;
108
- const contact = fields.find((field) => field.id === contactFieldId(definition));
109
- if (contact?.type !== "email" || contact.required !== true || !fields.some((field) => field.type === "consent")) {
107
+ if (!hasRequiredContactEmailAndConsent(definition)) {
110
108
  throw invalid(file, "a newsletter sink requires a required email contact field and at least one consent checkbox.", "definition");
111
109
  }
112
110
  }
@@ -76,6 +76,13 @@ export function componentFixedHeadingLevel(type, data, state) {
76
76
  return 2;
77
77
  return undefined;
78
78
  }
79
+ /** A block's own heading sits below the current heading without changing the page outline. */
80
+ export function childComponentHeadingLevel(state) {
81
+ return Math.min(6, (state?.level ?? 1) + 1);
82
+ }
83
+ export function formPlacementHeadingLevel(heading, state) {
84
+ return nonBlank(heading) ? childComponentHeadingLevel(state) : undefined;
85
+ }
79
86
  function nonBlank(value) {
80
87
  return typeof value === "string" && value.trim() !== "";
81
88
  }
package/src/output.js CHANGED
@@ -41,6 +41,8 @@ export function failureResult(error) {
41
41
  if (error.field) result.error.field = error.field;
42
42
  // The site's reason for a refused field, so an agent reading only JSON learns what to change (TR01433).
43
43
  if (typeof error.reason === "string" && error.reason !== "") result.error.reason = error.reason;
44
+ if (error.nextStep) result.error.nextStep = error.nextStep;
45
+ if (error.stageAgainReason) result.error.stageAgainReason = error.stageAgainReason;
44
46
  if (error.rule) result.error.rule = error.rule;
45
47
  if (error.details?.length) result.error.details = error.details;
46
48
  if (error.status) result.error.status = error.status;
@@ -0,0 +1,66 @@
1
+ import { getSiteAuthoringCapabilities } from "./api.js";
2
+ import { SiteAuthoringError } from "./errors.js";
3
+ import { CHECK_AREA, collectProblems } from "./problems.js";
4
+ import { ApiError } from "./transport.js";
5
+ import { documentTemplate, supportsArticleEnd } from "./typed-pages.js";
6
+
7
+ function articleEndConflict(file) {
8
+ return new SiteAuthoringError(
9
+ "pages.push_conflict",
10
+ `The article-end preference in '${file}' differs from the site. Pull and reconcile the page before changing it.`,
11
+ { field: "articleEnd" },
12
+ );
13
+ }
14
+
15
+ function articleEndUnavailable() {
16
+ return new SiteAuthoringError(
17
+ "pages.article_end_unsupported",
18
+ "This site does not support writing the article-end preference. Use an updated Standard site.",
19
+ { field: "articleEnd" },
20
+ );
21
+ }
22
+
23
+ export function articleEndWriteIntent({ file, document, target, baseline, observed }) {
24
+ if (!supportsArticleEnd(documentTemplate(document))) return undefined;
25
+ const articleEnd = document.articleEnd !== false;
26
+ if (target === undefined) return articleEnd ? undefined : { articleEnd };
27
+ if (target.articleEnd === undefined) {
28
+ if (!articleEnd || baseline?.articleEnd === false || observed?.articleEnd === false) throw articleEndUnavailable();
29
+ return undefined;
30
+ }
31
+ if (target.articleEnd === articleEnd) return undefined;
32
+
33
+ const seen = observed?.revision === target.bodyRevision && observed?.articleEnd !== undefined ? observed : baseline;
34
+ if (target.bodyRevision === undefined || seen?.revision !== target.bodyRevision || seen?.articleEnd !== target.articleEnd) {
35
+ throw articleEndConflict(file);
36
+ }
37
+ return { articleEnd, expectedBodyRevision: target.bodyRevision };
38
+ }
39
+
40
+ export async function preflightArticleEndWrites(client, siteId, plan, confirmedCapabilities) {
41
+ const write = plan.planned.find((page) => page.articleEndWrite !== undefined);
42
+ if (write === undefined) return undefined;
43
+ return await collectProblems(plan.problems, { area: CHECK_AREA.pages, file: write.file }, async () => {
44
+ const capabilities = confirmedCapabilities ?? await getSiteAuthoringCapabilities(client, siteId);
45
+ if (capabilities?.articleEndOptOutWritesEnabled !== true) throw articleEndUnavailable();
46
+ return capabilities;
47
+ });
48
+ }
49
+
50
+ export function translateArticleEndRefusal(error, page) {
51
+ if (page.articleEndWrite === undefined || !(error instanceof ApiError)) return error;
52
+ if (error.hasField("SuppressArticleEnd")) return articleEndUnavailable();
53
+ if (error.hasField("ExpectedBodyRevision")) return articleEndConflict(page.file);
54
+ return error;
55
+ }
56
+
57
+ /** A concurrent preference returned by an ordinary write is not a reconciliation. */
58
+ export function articleEndBaselineAfterWrite(previous, page, summary) {
59
+ const matched = summary.articleEnd === undefined || summary.articleEnd === (page.document.articleEnd !== false);
60
+ const articleEnd = matched ? summary.articleEnd ?? previous?.articleEnd : previous?.articleEnd;
61
+ const revision = matched ? summary.bodyRevision : previous?.revision;
62
+ return {
63
+ ...(articleEnd === undefined ? {} : { articleEnd }),
64
+ ...(revision === undefined ? {} : { revision }),
65
+ };
66
+ }
@@ -0,0 +1,54 @@
1
+ import { sitePath } from "./api.js";
2
+ import { HTTP_NOT_FOUND, REFUSAL_UNCLASSIFIED } from "./constants.js";
3
+ import { SiteAuthoringError } from "./errors.js";
4
+ import { reusableDefinitionRows, reusableFormRows } from "./reusable-blocks.js";
5
+ import { declaredThemeContextNames } from "./theme-contexts.js";
6
+ import { ApiError } from "./transport.js";
7
+
8
+ const HTTP_METHOD_NOT_ALLOWED = 405;
9
+ const HTTP_NOT_IMPLEMENTED = 501;
10
+ const GRPC_UNIMPLEMENTED = 12;
11
+
12
+ function invalidCatalog() {
13
+ return new SiteAuthoringError("api.page_block_catalog", "Taproot returned an invalid page block catalog.", { field: "forms" });
14
+ }
15
+
16
+ export async function getSitePageBlockCatalog(client, siteId) {
17
+ let response;
18
+ try {
19
+ response = await client.request(sitePath(siteId, "page-block-catalog"));
20
+ } catch (error) {
21
+ if (error instanceof ApiError && error.fields.length === 0 && error.refusalKind() === REFUSAL_UNCLASSIFIED) {
22
+ const bareStatus = error.grpcCode === undefined
23
+ && [HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_NOT_IMPLEMENTED].includes(error.httpStatus);
24
+ if (bareStatus || (error.httpStatus === HTTP_NOT_IMPLEMENTED && error.grpcCode === GRPC_UNIMPLEMENTED)) {
25
+ return undefined;
26
+ }
27
+ }
28
+ throw error;
29
+ }
30
+ if (response === null || typeof response !== "object" || Array.isArray(response)) throw invalidCatalog();
31
+ if (response.placementWritesEnabled !== undefined && typeof response.placementWritesEnabled !== "boolean") throw invalidCatalog();
32
+ const { formPlacementPresentationWritesEnabled, formPlacementContextNames } = response;
33
+ if (formPlacementPresentationWritesEnabled !== undefined && typeof formPlacementPresentationWritesEnabled !== "boolean") {
34
+ throw invalidCatalog();
35
+ }
36
+ if (formPlacementContextNames !== undefined && (!Array.isArray(formPlacementContextNames)
37
+ || formPlacementContextNames.some((name) => typeof name !== "string" || name !== name.trim())
38
+ || declaredThemeContextNames({ contexts: Object.fromEntries(formPlacementContextNames.map((name) => [name, {}])) }).length
39
+ !== formPlacementContextNames.length)) {
40
+ throw invalidCatalog();
41
+ }
42
+ const forms = reusableFormRows(response.forms, "forms");
43
+ const definitions = reusableDefinitionRows(response.definitions, { preview: true });
44
+ return {
45
+ ...(response.placementWritesEnabled === undefined ? {} : { placementWritesEnabled: response.placementWritesEnabled }),
46
+ ...(formPlacementPresentationWritesEnabled === undefined ? {} : { formPlacementPresentationWritesEnabled }),
47
+ // Protobuf omits an empty list. The rollout flag tells us this server has the context projection.
48
+ ...(formPlacementContextNames !== undefined || formPlacementPresentationWritesEnabled !== undefined
49
+ ? { formPlacementContextNames: formPlacementContextNames ?? [] }
50
+ : {}),
51
+ ...(forms === undefined ? {} : { forms }),
52
+ ...(definitions === undefined ? {} : { definitions }),
53
+ };
54
+ }