@capybara-hq/plugin-sdk 0.1.0-rc.1 → 0.1.0-rc.10

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 (91) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +47 -0
  3. package/agent-docs/concepts.md +63 -0
  4. package/agent-docs/connector-templates.md +48 -0
  5. package/agent-docs/extension-points/channel.md +15 -0
  6. package/agent-docs/extension-points/config-source.md +15 -0
  7. package/agent-docs/extension-points/connector.md +15 -0
  8. package/agent-docs/extension-points/counter.md +15 -0
  9. package/agent-docs/extension-points/directory.md +15 -0
  10. package/agent-docs/extension-points/file-preview.md +15 -0
  11. package/agent-docs/extension-points/identity-source.md +15 -0
  12. package/agent-docs/extension-points/model-provider.md +15 -0
  13. package/agent-docs/extension-points/object-store.md +15 -0
  14. package/agent-docs/extension-points/sandbox.md +15 -0
  15. package/agent-docs/extension-points/secret-store.md +15 -0
  16. package/agent-docs/extension-points/web-fetch.md +15 -0
  17. package/agent-docs/extension-points/web-search.md +15 -0
  18. package/agent-docs/extensions.md +87 -0
  19. package/agent-docs/plugin-format.md +99 -0
  20. package/agent-docs/setup.md +46 -0
  21. package/agent-docs/skills.md +44 -0
  22. package/agent-docs/tool-naming.md +21 -0
  23. package/dist/agent-template.d.ts +85 -0
  24. package/dist/agent-template.js +361 -2
  25. package/dist/cards.d.ts +7 -0
  26. package/dist/cards.js +4 -4
  27. package/dist/channel.d.ts +20 -1
  28. package/dist/config-ui.d.ts +131 -0
  29. package/dist/config-ui.js +602 -0
  30. package/dist/connector-auth.d.ts +2 -0
  31. package/dist/connector-auth.js +15 -0
  32. package/dist/ctx.d.ts +86 -4
  33. package/dist/define-extension.d.ts +5 -1
  34. package/dist/define-extension.js +1 -0
  35. package/dist/device-protocol.d.ts +118 -0
  36. package/dist/device-protocol.js +276 -0
  37. package/dist/directory.d.ts +11 -2
  38. package/dist/extension-point.d.ts +9 -0
  39. package/dist/extension-point.js +17 -12
  40. package/dist/file-preview.d.ts +9 -1
  41. package/dist/hooks.d.ts +76 -16
  42. package/dist/index.d.ts +15 -1
  43. package/dist/index.js +15 -1
  44. package/dist/marketplace.d.ts +55 -2
  45. package/dist/marketplace.js +73 -3
  46. package/dist/model.d.ts +60 -2
  47. package/dist/model.js +22 -0
  48. package/dist/org-access.d.ts +27 -0
  49. package/dist/org-access.js +35 -0
  50. package/dist/permissions.d.ts +20 -5
  51. package/dist/permissions.js +51 -15
  52. package/dist/plugin-manifest.d.ts +48 -5
  53. package/dist/plugin-manifest.js +93 -6
  54. package/dist/sandbox.d.ts +164 -62
  55. package/dist/sandbox.js +71 -14
  56. package/dist/secret.d.ts +4 -1
  57. package/dist/secret.js +5 -2
  58. package/dist/setup-check.d.ts +115 -0
  59. package/dist/setup-check.js +142 -0
  60. package/dist/setup-guide-parse.d.ts +121 -0
  61. package/dist/setup-guide-parse.js +350 -0
  62. package/dist/setup-guide-render.d.ts +45 -0
  63. package/dist/setup-guide-render.js +351 -0
  64. package/dist/setup-guide.d.ts +94 -0
  65. package/dist/setup-guide.js +336 -0
  66. package/dist/skill-invocation.d.ts +9 -5
  67. package/dist/skill-invocation.js +18 -8
  68. package/dist/skill.d.ts +23 -3
  69. package/dist/skill.js +31 -6
  70. package/dist/theme-assets.d.ts +39 -0
  71. package/dist/theme-assets.js +449 -0
  72. package/dist/theme-readability.d.ts +37 -0
  73. package/dist/theme-readability.js +145 -0
  74. package/dist/theme-tokens.generated.d.ts +275 -0
  75. package/dist/theme-tokens.generated.js +167 -0
  76. package/dist/theme.d.ts +152 -0
  77. package/dist/theme.js +392 -0
  78. package/dist/tool.d.ts +11 -3
  79. package/dist/ui-resolve.d.ts +40 -0
  80. package/dist/ui-resolve.js +54 -0
  81. package/dist/ui-slots.d.ts +43 -0
  82. package/dist/ui-slots.js +168 -0
  83. package/dist/ui.d.ts +114 -31
  84. package/dist/ui.js +0 -4
  85. package/dist/web.d.ts +105 -0
  86. package/dist/web.js +135 -0
  87. package/package.json +10 -2
  88. package/schemas/connector-template.v1.schema.json +3 -0
  89. package/schemas/marketplace.v1.schema.json +50 -0
  90. package/schemas/plugin.v1.schema.json +97 -4
  91. package/schemas/theme.v1.schema.json +225 -0
@@ -0,0 +1,142 @@
1
+ /**
2
+ * A check id an extension declares and registers. Ids with `:` belong to the kernel
3
+ * (`capybara:*`), so an extension cannot shadow a kernel check.
4
+ */
5
+ export const SETUP_CHECK_ID_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;
6
+ /** Limits of setup checks (spec §10.5). Characters are UTF-16 code units. */
7
+ export const SETUP_CHECK_LIMITS = Object.freeze({
8
+ /** Per run; the kernel aborts `signal` and records `unknown`. */
9
+ timeoutMs: 10_000,
10
+ /** Characters of `reason`, per language. */
11
+ reasonChars: 300,
12
+ /** Characters of `fix`, per language. */
13
+ fixChars: 500,
14
+ /** A cached result stays fresh this long (and for the same input fingerprint). */
15
+ freshMs: 300_000,
16
+ /** A forced rerun of one check and target at most this often. */
17
+ cooldownMs: 10_000,
18
+ /** Concurrent runs per org across all replicas. */
19
+ orgConcurrency: 8,
20
+ /** Run requests per account per minute. */
21
+ perAccountPerMinute: 30,
22
+ /** Ids in `permissions.setupChecks`. */
23
+ idsPerExtension: 32,
24
+ });
25
+ const STATUSES = ["ok", "failing", "unknown"];
26
+ const RESULT_KEYS = new Set(["status", "reason", "fix"]);
27
+ const TEXT_KEYS = new Set(["en", "zh"]);
28
+ // C0 controls except tab, LF, CR; DEL; C1 controls.
29
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is the point
30
+ const CONTROL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
31
+ // Bidi embeddings, overrides and isolates reorder what a reader sees (Trojan Source); the marks
32
+ // (LRM, RLM, ALM) stay allowed, real right-to-left names carry them.
33
+ const BIDI_RE = /[\u202a-\u202e\u2066-\u2069]/;
34
+ // Line and paragraph separators: invisible line breaks in plain text.
35
+ const SEPARATOR_RE = /[\u2028\u2029]/;
36
+ // A surrogate without its pair: not valid Unicode, and PostgreSQL jsonb refuses it.
37
+ const LONE_SURROGATE_RE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
38
+ // A key short and plain enough to name in a problem; others are not echoed, because the problem is
39
+ // logged and a truncated echo of a secret-valued key would slip past value redaction.
40
+ const ECHO_KEY_RE = /^[A-Za-z0-9_-]{1,32}$/;
41
+ /**
42
+ * Copies the own data properties of a plain object, or explains why it is not one. Accessors,
43
+ * symbol keys, non-enumerable keys and keys outside `allowed` are refused, so nothing runs while
44
+ * reading and nothing unlisted survives.
45
+ */
46
+ function plainCopy(label, x, allowed) {
47
+ if (typeof x !== "object" || x === null || Array.isArray(x)) {
48
+ return { problem: `${label} must be an object` };
49
+ }
50
+ const proto = Object.getPrototypeOf(x);
51
+ if (proto !== Object.prototype && proto !== null) {
52
+ return { problem: `${label} must be a plain object` };
53
+ }
54
+ const out = {};
55
+ for (const key of Reflect.ownKeys(x)) {
56
+ if (!allowed.has(key)) {
57
+ const shown = typeof key === "string" && ECHO_KEY_RE.test(key) ? `"${key}"` : "(not shown)";
58
+ return { problem: `${label} has an unknown key ${shown}` };
59
+ }
60
+ const d = Object.getOwnPropertyDescriptor(x, key);
61
+ if (!d || !("value" in d) || !d.enumerable) {
62
+ return { problem: `${label}.${String(key)} must be a plain data property` };
63
+ }
64
+ out[key] = d.value;
65
+ }
66
+ return out;
67
+ }
68
+ function text(label, x, max) {
69
+ const o = plainCopy(label, x, TEXT_KEYS);
70
+ if ("problem" in o)
71
+ return o;
72
+ const out = { en: "" };
73
+ for (const lang of ["en", "zh"]) {
74
+ const v = o[lang];
75
+ if (v === undefined && lang === "zh")
76
+ continue;
77
+ if (typeof v !== "string" || v === "") {
78
+ return { problem: `${label}.${lang} must be a non-empty string` };
79
+ }
80
+ if (v.length > max) {
81
+ return { problem: `${label}.${lang} is longer than ${max} characters` };
82
+ }
83
+ if (CONTROL_RE.test(v)) {
84
+ return { problem: `${label}.${lang} contains control characters` };
85
+ }
86
+ if (BIDI_RE.test(v)) {
87
+ return {
88
+ problem: `${label}.${lang} contains bidi embedding, override or isolate characters`,
89
+ };
90
+ }
91
+ if (SEPARATOR_RE.test(v)) {
92
+ return { problem: `${label}.${lang} contains line or paragraph separators` };
93
+ }
94
+ if (LONE_SURROGATE_RE.test(v)) {
95
+ return { problem: `${label}.${lang} is not well-formed UTF-16 (lone surrogate)` };
96
+ }
97
+ out[lang] = v;
98
+ }
99
+ return out;
100
+ }
101
+ /**
102
+ * The result as a fresh plain object holding only `status`, `reason` and `fix`, or why it is
103
+ * invalid (English). The kernel treats an invalid result as `unknown` and logs the problem. Run
104
+ * kernel redaction on the returned copy, then validate again (redaction can change the length).
105
+ */
106
+ export function validateSetupCheckResult(x) {
107
+ // A proxy (revoked, or with throwing traps) can throw while being read: that is an invalid
108
+ // result, never an exception the caller has to expect.
109
+ try {
110
+ return validateResult(x);
111
+ }
112
+ catch {
113
+ return { problem: "result could not be read (a proxy or an object that throws when read)" };
114
+ }
115
+ }
116
+ function validateResult(x) {
117
+ const o = plainCopy("result", x, RESULT_KEYS);
118
+ if ("problem" in o)
119
+ return o;
120
+ if (!STATUSES.includes(o.status)) {
121
+ return { problem: `result.status must be one of ${STATUSES.join(", ")}` };
122
+ }
123
+ const out = {
124
+ status: o.status,
125
+ };
126
+ if (o.reason !== undefined) {
127
+ const r = text("result.reason", o.reason, SETUP_CHECK_LIMITS.reasonChars);
128
+ if ("problem" in r)
129
+ return r;
130
+ out.reason = r;
131
+ }
132
+ if (o.fix !== undefined) {
133
+ const f = text("result.fix", o.fix, SETUP_CHECK_LIMITS.fixChars);
134
+ if ("problem" in f)
135
+ return f;
136
+ out.fix = f;
137
+ }
138
+ if (out.status === "failing" && !out.reason) {
139
+ return { problem: "result.reason is required when status is failing" };
140
+ }
141
+ return out;
142
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The line scanner and parser of setup guide documents (spec `2026-11-09-setup-guides-v2-design.md`
3
+ * §4.2). A guide is CommonMark + GFM with three line shapes the scanner recognizes in column 0
4
+ * outside fenced code: `::: mode <mode>` / `::: audience <audience>` (open a section), `:::` (close
5
+ * it) and `::check <check-id> <label>`. The scanner keeps line numbers: directive lines become blank
6
+ * lines and each check line becomes a level-6 heading holding a private-use marker, so it is a block
7
+ * of its own and can be found again after parsing.
8
+ */
9
+ import type { Nodes, Root } from "mdast";
10
+ /** `{{name}}`, spaces inside the braces allowed. */
11
+ export declare const SETUP_GUIDE_VARIABLE_RE: RegExp;
12
+ /** The private-use range the renderer reserves for its sentinels; refused in sources. */
13
+ export declare const SETUP_GUIDE_RESERVED_RE: RegExp;
14
+ /** Variable sentinel: `<n>`, n indexing the occurrences. */
15
+ export declare const SENTINEL_RE: RegExp;
16
+ /** The same sentinel percent-encoded, as micromark leaves it in a link destination. */
17
+ export declare const ENCODED_SENTINEL_RE: RegExp;
18
+ /** One issue of a document, with the 1-based source line when it has one. */
19
+ export interface SetupGuideParseIssue {
20
+ level: "error" | "warning";
21
+ line?: number;
22
+ message: string;
23
+ }
24
+ /** A `::: mode` / `::: audience` section of a document. */
25
+ export interface SetupGuideSection {
26
+ type: "mode" | "audience";
27
+ value: string;
28
+ /** Line of the opening directive. */
29
+ line: number;
30
+ /** Index of the enclosing section, or null. */
31
+ parent: number | null;
32
+ }
33
+ /** A `::check` line of a document. */
34
+ export interface SetupGuideCheckLine {
35
+ id: string;
36
+ label: string;
37
+ source: "plugin" | "kernel";
38
+ line: number;
39
+ /** Index of the innermost enclosing section, or null. */
40
+ section: number | null;
41
+ }
42
+ /** A fenced code block of a document. */
43
+ export interface SetupGuideCodeBlock {
44
+ /** The info string's first word; empty when missing. */
45
+ language: string;
46
+ title: string | null;
47
+ text: string;
48
+ line: number;
49
+ /** Index of the innermost enclosing section, or null. */
50
+ section: number | null;
51
+ }
52
+ /** The structure of a document (see {@link parseSetupGuide}). */
53
+ export interface ParsedSetupGuide {
54
+ /** The level-1 heading the document starts with, or null when it does not. */
55
+ title: string | null;
56
+ sections: SetupGuideSection[];
57
+ checks: SetupGuideCheckLine[];
58
+ codeBlocks: SetupGuideCodeBlock[];
59
+ /** Structural problems (place independent: modes, audiences and variables are not judged). */
60
+ issues: SetupGuideParseIssue[];
61
+ }
62
+ type LineKind = "text" | "fence" | "section-open" | "section-close" | "check";
63
+ /** @internal The scanner's result. */
64
+ export interface GuideScan {
65
+ lines: string[];
66
+ kinds: LineKind[];
67
+ /** The enclosing sections of each line, outermost first. */
68
+ stacks: number[][];
69
+ /** Check index of each check line. */
70
+ checkAt: Map<number, number>;
71
+ sections: SetupGuideSection[];
72
+ checks: SetupGuideCheckLine[];
73
+ issues: SetupGuideParseIssue[];
74
+ }
75
+ /** LF line endings. */
76
+ export declare function normalizeGuideSource(source: string): string;
77
+ /** @internal Classifies the lines of a (normalized) document. */
78
+ export declare function scanGuide(source: string): GuideScan;
79
+ /** @internal Whether line `i` is in the sections of `mode` and `audience`. */
80
+ export declare function lineSelected(scan: GuideScan, i: number, mode: string | null, audience: string | null): boolean;
81
+ /**
82
+ * @internal The Markdown the parser sees, line for line: unselected and directive lines blank, check
83
+ * lines as marker headings, other lines through `subst`.
84
+ */
85
+ export declare function preparedGuideText(scan: GuideScan, include: (i: number) => boolean, subst?: (text: string, i: number) => string): string;
86
+ /** @internal Parses Markdown (CommonMark + GFM) to mdast. */
87
+ export declare function parseGuideMarkdown(text: string): Root;
88
+ /** @internal The check index of a marker heading, or undefined. */
89
+ export declare function checkMarkerIndex(node: Nodes): number | undefined;
90
+ /** @internal The plain text of a node (values and image alts, joined). */
91
+ export declare function nodeText(node: Nodes): string;
92
+ /** @internal Visits nodes depth first in document order, with their depth (root's children = 1). */
93
+ export declare function visitGuide(node: Nodes, fn: (node: Nodes, depth: number, parent: Nodes | null) => void, depth?: number, parent?: Nodes | null): void;
94
+ /** @internal The title of a fence info string's meta: `{ title }`, or `{ bad }` for other text. */
95
+ export declare function fenceTitle(meta: string | null | undefined): {
96
+ title: string | null;
97
+ bad?: string;
98
+ };
99
+ /** @internal A variable occurrence the analysis replaced by a sentinel. */
100
+ export interface GuideVariableUse {
101
+ name: string;
102
+ line: number;
103
+ }
104
+ /** @internal Everything validation needs: the scan, the sentinel tree of all sections, the uses. */
105
+ export interface GuideAnalysis {
106
+ parsed: ParsedSetupGuide;
107
+ scan: GuideScan;
108
+ tree: Root;
109
+ uses: GuideVariableUse[];
110
+ }
111
+ /** @internal Replaces the sentinels (plain or percent-encoded) of `s` with `{{name}}`. */
112
+ export declare function revertSentinels(s: string, names: readonly string[]): string;
113
+ /** @internal Scans and parses a document with every section and every variable as a sentinel. */
114
+ export declare function analyzeSetupGuide(source: string): GuideAnalysis;
115
+ /**
116
+ * Parses a setup guide document into its title, sections, check lines and fenced code blocks, with
117
+ * the structural problems found (missing title, nesting, malformed directive lines, indented code,
118
+ * fence info strings, limits). Place-dependent rules are `validateSetupGuide`'s. Pure.
119
+ */
120
+ export declare function parseSetupGuide(source: string): ParsedSetupGuide;
121
+ export {};
@@ -0,0 +1,350 @@
1
+ import { fromMarkdown } from "mdast-util-from-markdown";
2
+ import { gfmFromMarkdown } from "mdast-util-gfm";
3
+ import { gfm } from "micromark-extension-gfm";
4
+ import { SETUP_CHECK_ID_RE } from "./setup-check.js";
5
+ /** Limits the parser enforces (equal to the matching entries of `SETUP_GUIDE_LIMITS`). */
6
+ const LIMITS = {
7
+ codeBlocks: 24,
8
+ checks: 16,
9
+ sections: 16,
10
+ titleChars: 100,
11
+ checkLabelChars: 80,
12
+ fenceTitleChars: 100,
13
+ depth: 16,
14
+ };
15
+ /** `{{name}}`, spaces inside the braces allowed. */
16
+ export const SETUP_GUIDE_VARIABLE_RE = /\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}/g;
17
+ // The plugin check id is the registration's (`ctx.setup.check`), so a guide can name only ids an
18
+ // extension can register; a kernel check is `capybara:` and the same id shape.
19
+ const PLUGIN_CHECK_RE = SETUP_CHECK_ID_RE;
20
+ const KERNEL_CHECK_RE = new RegExp(`^capybara:${SETUP_CHECK_ID_RE.source.slice(1)}`);
21
+ /** The private-use range the renderer reserves for its sentinels; refused in sources. */
22
+ export const SETUP_GUIDE_RESERVED_RE = /[-]/;
23
+ const FENCE_OPEN_RE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
24
+ const FENCE_CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
25
+ const SECTION_RE = /^(mode|audience)[ \t]+(\S+)$/;
26
+ const CHECK_LINE_RE = /^::check[ \t]+(\S+)(?:[ \t]+(.*?))?[ \t]*$/;
27
+ const FENCE_TITLE_RE = /^title="([^"]*)"$/;
28
+ /** Variable sentinel: `<n>`, n indexing the occurrences. */
29
+ export const SENTINEL_RE = /(\d+)/g;
30
+ /** The same sentinel percent-encoded, as micromark leaves it in a link destination. */
31
+ export const ENCODED_SENTINEL_RE = /%EE%80%80(\d+)%EE%80%81/gi;
32
+ const CHECK_MARKER_RE = /^(\d+)$/;
33
+ /** LF line endings. */
34
+ export function normalizeGuideSource(source) {
35
+ return source.replace(/\r\n?/g, "\n");
36
+ }
37
+ /** @internal Classifies the lines of a (normalized) document. */
38
+ export function scanGuide(source) {
39
+ const lines = source.split("\n");
40
+ const kinds = [];
41
+ const stacks = [];
42
+ const checkAt = new Map();
43
+ const sections = [];
44
+ const checks = [];
45
+ const issues = [];
46
+ const err = (line, message) => issues.push({ level: "error", line, message });
47
+ const stack = [];
48
+ let fence = null;
49
+ lines.forEach((text, i) => {
50
+ const line = i + 1;
51
+ stacks.push([...stack]);
52
+ if (fence !== null) {
53
+ kinds.push("fence");
54
+ const c = FENCE_CLOSE_RE.exec(text);
55
+ if (c !== null &&
56
+ c[1][0] === fence.char &&
57
+ c[1].length >= fence.len) {
58
+ fence = null;
59
+ }
60
+ return;
61
+ }
62
+ const f = FENCE_OPEN_RE.exec(text);
63
+ if (f !== null) {
64
+ const seq = f[2];
65
+ if (!(seq[0] === "`" && f[3].includes("`"))) {
66
+ kinds.push("fence");
67
+ fence = { char: seq[0], len: seq.length };
68
+ return;
69
+ }
70
+ }
71
+ if (text.startsWith(":::")) {
72
+ const rest = text.slice(3).trim();
73
+ if (rest === "") {
74
+ const open = stack.pop();
75
+ if (open === undefined) {
76
+ err(line, "`:::` closes no section");
77
+ kinds.push("text");
78
+ }
79
+ else
80
+ kinds.push("section-close");
81
+ return;
82
+ }
83
+ const m = SECTION_RE.exec(rest);
84
+ if (m === null) {
85
+ err(line, `"${text}" is not a section line; use "::: mode <mode>", "::: audience <audience>" or ":::"`);
86
+ kinds.push("text");
87
+ return;
88
+ }
89
+ if (text.includes("{{"))
90
+ err(line, "directive lines hold no variables");
91
+ const type = m[1];
92
+ const parentIndex = stack.at(-1);
93
+ if (parentIndex !== undefined) {
94
+ const parent = sections[parentIndex];
95
+ if (!(stack.length === 1 && parent.type === "audience" && type === "mode")) {
96
+ err(line, `sections do not nest (only a mode section inside an audience section); close the section of line ${parent.line} first`);
97
+ }
98
+ }
99
+ sections.push({ type, value: m[2], line, parent: parentIndex ?? null });
100
+ stack.push(sections.length - 1);
101
+ kinds.push("section-open");
102
+ return;
103
+ }
104
+ if (/^::check(?:\s|$)/.test(text)) {
105
+ const m = CHECK_LINE_RE.exec(text);
106
+ if (m === null) {
107
+ err(line, "a check line is `::check <check-id> <label>`");
108
+ kinds.push("text");
109
+ return;
110
+ }
111
+ const id = m[1];
112
+ const label = (m[2] ?? "").trim();
113
+ if (!PLUGIN_CHECK_RE.test(id) && !KERNEL_CHECK_RE.test(id)) {
114
+ err(line, `check id "${id}" must match ^[a-z0-9][a-z0-9-]{0,47}$ (a plugin check) or capybara:<id> (a kernel check)`);
115
+ }
116
+ if (label === "")
117
+ err(line, `check ${id} needs a label: \`::check ${id} <label>\``);
118
+ else if ([...label].length > LIMITS.checkLabelChars) {
119
+ err(line, `the label of check ${id} is longer than ${LIMITS.checkLabelChars} characters`);
120
+ }
121
+ if (text.includes("{{"))
122
+ err(line, "directive lines hold no variables (check labels are plain text)");
123
+ checks.push({
124
+ id,
125
+ label,
126
+ source: id.startsWith("capybara:") ? "kernel" : "plugin",
127
+ line,
128
+ section: stack.at(-1) ?? null,
129
+ });
130
+ checkAt.set(i, checks.length - 1);
131
+ kinds.push("check");
132
+ return;
133
+ }
134
+ kinds.push("text");
135
+ });
136
+ for (const open of stack) {
137
+ const s = sections[open];
138
+ err(s.line, `the section "::: ${s.type} ${s.value}" opened at line ${s.line} is not closed`);
139
+ }
140
+ return { lines, kinds, stacks, checkAt, sections, checks, issues };
141
+ }
142
+ /** @internal Whether line `i` is in the sections of `mode` and `audience`. */
143
+ export function lineSelected(scan, i, mode, audience) {
144
+ for (const s of scan.stacks[i]) {
145
+ const sec = scan.sections[s];
146
+ if (sec.type === "mode" ? sec.value !== mode : sec.value !== audience)
147
+ return false;
148
+ }
149
+ return true;
150
+ }
151
+ /**
152
+ * @internal The Markdown the parser sees, line for line: unselected and directive lines blank, check
153
+ * lines as marker headings, other lines through `subst`.
154
+ */
155
+ export function preparedGuideText(scan, include, subst = (t) => t) {
156
+ return scan.lines
157
+ .map((text, i) => {
158
+ if (!include(i))
159
+ return "";
160
+ const kind = scan.kinds[i];
161
+ if (kind === "section-open" || kind === "section-close")
162
+ return "";
163
+ if (kind === "check")
164
+ return `###### ${scan.checkAt.get(i)}`;
165
+ return subst(text, i);
166
+ })
167
+ .join("\n");
168
+ }
169
+ /** @internal Parses Markdown (CommonMark + GFM) to mdast. */
170
+ export function parseGuideMarkdown(text) {
171
+ return fromMarkdown(text, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
172
+ }
173
+ /** @internal The check index of a marker heading, or undefined. */
174
+ export function checkMarkerIndex(node) {
175
+ if (node.type !== "heading" || node.depth !== 6 || node.children.length !== 1)
176
+ return undefined;
177
+ const t = node.children[0];
178
+ if (t?.type !== "text")
179
+ return undefined;
180
+ const m = CHECK_MARKER_RE.exec(t.value);
181
+ return m === null ? undefined : Number(m[1]);
182
+ }
183
+ /** @internal The plain text of a node (values and image alts, joined). */
184
+ export function nodeText(node) {
185
+ if ("value" in node)
186
+ return node.value;
187
+ if (node.type === "image" || node.type === "imageReference")
188
+ return node.alt ?? "";
189
+ if ("children" in node)
190
+ return node.children.map(nodeText).join("");
191
+ return "";
192
+ }
193
+ /** @internal Visits nodes depth first in document order, with their depth (root's children = 1). */
194
+ export function visitGuide(node, fn, depth = 0, parent = null) {
195
+ if (depth > 0)
196
+ fn(node, depth, parent);
197
+ if ("children" in node) {
198
+ for (const c of node.children)
199
+ visitGuide(c, fn, depth + 1, node);
200
+ }
201
+ }
202
+ /** @internal The title of a fence info string's meta: `{ title }`, or `{ bad }` for other text. */
203
+ export function fenceTitle(meta) {
204
+ if (meta === null || meta === undefined || meta.trim() === "")
205
+ return { title: null };
206
+ const m = FENCE_TITLE_RE.exec(meta.trim());
207
+ return m === null ? { title: null, bad: meta.trim() } : { title: m[1] };
208
+ }
209
+ /** @internal Replaces the sentinels (plain or percent-encoded) of `s` with `{{name}}`. */
210
+ export function revertSentinels(s, names) {
211
+ const back = (whole, n) => {
212
+ const name = names[Number(n)];
213
+ return name === undefined ? whole : `{{${name}}}`;
214
+ };
215
+ return s.replace(SENTINEL_RE, back).replace(ENCODED_SENTINEL_RE, back);
216
+ }
217
+ /** @internal Scans and parses a document with every section and every variable as a sentinel. */
218
+ export function analyzeSetupGuide(source) {
219
+ const src = normalizeGuideSource(source);
220
+ const scan = scanGuide(src);
221
+ const issues = [...scan.issues];
222
+ const err = (line, message) => issues.push({ level: "error", ...(line !== undefined && { line }), message });
223
+ scan.lines.forEach((text, i) => {
224
+ if (text.includes("\u0000"))
225
+ err(i + 1, "the document contains NUL");
226
+ if (SETUP_GUIDE_RESERVED_RE.test(text)) {
227
+ err(i + 1, "the document contains a private-use character (U+E000–U+E0FF), which guides may not use");
228
+ }
229
+ });
230
+ const uses = [];
231
+ const text = preparedGuideText(scan, () => true, (t, i) => t.replace(SETUP_GUIDE_VARIABLE_RE, (_w, name) => {
232
+ uses.push({ name, line: i + 1 });
233
+ return `${uses.length - 1}`;
234
+ }));
235
+ const names = uses.map((u) => u.name);
236
+ const tree = parseGuideMarkdown(text);
237
+ const lineOf = (n) => n.position?.start.line;
238
+ const sectionOf = (line) => line === undefined ? null : (scan.stacks[line - 1]?.at(-1) ?? null);
239
+ // the title
240
+ let title = null;
241
+ const firstLine = scan.lines.findIndex((l) => l.trim() !== "");
242
+ const first = tree.children[0];
243
+ if (first?.type === "heading" &&
244
+ first.depth === 1 &&
245
+ lineOf(first) === firstLine + 1 &&
246
+ /^ {0,3}#(?:[ \t]|$)/.test(scan.lines[firstLine] ?? "")) {
247
+ title = revertSentinels(nodeText(first), names).trim();
248
+ if (title === "")
249
+ err(lineOf(first), "the title (the level-1 heading) is empty");
250
+ if ([...title].length > LIMITS.titleChars) {
251
+ err(lineOf(first), `the title is longer than ${LIMITS.titleChars} characters`);
252
+ }
253
+ }
254
+ else {
255
+ err(firstLine >= 0 ? firstLine + 1 : 1, "the document must start with a level-1 heading (# Title)");
256
+ }
257
+ const codeBlocks = [];
258
+ let deepest = 0;
259
+ let deepLine;
260
+ visitGuide(tree, (node, depth) => {
261
+ if (depth > deepest) {
262
+ deepest = depth;
263
+ deepLine = lineOf(node);
264
+ }
265
+ const line = lineOf(node);
266
+ if (node.type === "heading") {
267
+ if (checkMarkerIndex(node) !== undefined)
268
+ return;
269
+ if (node === first && title !== null)
270
+ return;
271
+ if (node.depth === 1) {
272
+ err(line, "only the title may be a level-1 heading; use ## to #### for the structure");
273
+ }
274
+ else if (node.depth > 4) {
275
+ err(line, "headings go from ## to ####");
276
+ }
277
+ if ([...revertSentinels(nodeText(node), names).trim()].length > LIMITS.titleChars) {
278
+ err(line, `a heading is longer than ${LIMITS.titleChars} characters`);
279
+ }
280
+ return;
281
+ }
282
+ if (node.type !== "code")
283
+ return;
284
+ const start = node.position?.start.offset ?? 0;
285
+ const fenced = /^[ \t]*(?:```|~~~)/.test(text.slice(start, start + 64));
286
+ if (!fenced) {
287
+ err(line, "indented code is not allowed; use a fenced code block with a language");
288
+ return;
289
+ }
290
+ const lang = node.lang ?? "";
291
+ const meta = node.meta ?? "";
292
+ if (/\d+/.test(lang + meta)) {
293
+ err(line, "variables are not allowed in a fence info string");
294
+ }
295
+ if (lang === "")
296
+ err(line, "a code block needs a language (```yaml, ```json, ```sh, ...)");
297
+ const t = fenceTitle(revertSentinels(meta, names));
298
+ if (t.bad !== undefined) {
299
+ err(line, `unexpected text in the info string ("${t.bad}"); only title="…" may follow the language`);
300
+ }
301
+ if (t.title !== null && [...t.title].length > LIMITS.fenceTitleChars) {
302
+ err(line, `a code block title is longer than ${LIMITS.fenceTitleChars} characters`);
303
+ }
304
+ codeBlocks.push({
305
+ language: revertSentinels(lang, names),
306
+ title: t.title,
307
+ text: revertSentinels(node.value, names),
308
+ line: line ?? 0,
309
+ section: sectionOf(line),
310
+ });
311
+ });
312
+ // a check line swallowed by an HTML block is no block of its own: its row would be missing
313
+ const placed = new Set();
314
+ for (const n of tree.children) {
315
+ const c = checkMarkerIndex(n);
316
+ if (c !== undefined)
317
+ placed.add(c);
318
+ }
319
+ scan.checks.forEach((c, i) => {
320
+ if (!placed.has(i)) {
321
+ err(c.line, `check ${c.id} is inside raw HTML and would not show; end the HTML with a blank line before the check line`);
322
+ }
323
+ });
324
+ if (deepest > LIMITS.depth)
325
+ err(deepLine, `content is nested deeper than ${LIMITS.depth} levels`);
326
+ if (codeBlocks.length > LIMITS.codeBlocks) {
327
+ err(undefined, `the document has ${codeBlocks.length} code blocks; at most ${LIMITS.codeBlocks}`);
328
+ }
329
+ if (scan.checks.length > LIMITS.checks) {
330
+ err(undefined, `the document has ${scan.checks.length} check lines; at most ${LIMITS.checks}`);
331
+ }
332
+ if (scan.sections.length > LIMITS.sections) {
333
+ err(undefined, `the document has ${scan.sections.length} sections; at most ${LIMITS.sections}`);
334
+ }
335
+ issues.sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
336
+ return {
337
+ parsed: { title, sections: scan.sections, checks: scan.checks, codeBlocks, issues },
338
+ scan,
339
+ tree,
340
+ uses,
341
+ };
342
+ }
343
+ /**
344
+ * Parses a setup guide document into its title, sections, check lines and fenced code blocks, with
345
+ * the structural problems found (missing title, nesting, malformed directive lines, indented code,
346
+ * fence info strings, limits). Place-dependent rules are `validateSetupGuide`'s. Pure.
347
+ */
348
+ export function parseSetupGuide(source) {
349
+ return analyzeSetupGuide(source).parsed;
350
+ }
@@ -0,0 +1,45 @@
1
+ import { type SetupGuideAudience, type SetupGuidePlace } from "./setup-guide.js";
2
+ /** A block of a rendered guide: sanitized Markdown, a code block, or a check row. */
3
+ export type SetupGuideBlock = {
4
+ kind: "markdown";
5
+ text: string;
6
+ } | {
7
+ kind: "code";
8
+ language: string;
9
+ title: string | null;
10
+ text: string;
11
+ } | {
12
+ kind: "check";
13
+ id: string;
14
+ label: string;
15
+ };
16
+ /** A guide document rendered for one mode, audience and set of values. */
17
+ export interface RenderedSetupGuideDoc {
18
+ title: string;
19
+ /** The modes the document's sections use, in the place's order (empty: no mode switch). */
20
+ modes: string[];
21
+ /** The audiences the document has sections for, in the place's order. */
22
+ audiences: SetupGuideAudience[];
23
+ blocks: SetupGuideBlock[];
24
+ /** The check rows, in document order. */
25
+ checks: {
26
+ id: string;
27
+ label: string;
28
+ source: "plugin" | "kernel";
29
+ }[];
30
+ /** Known variables without a value that the rendered text uses, in the place's order. */
31
+ unresolved: string[];
32
+ }
33
+ /**
34
+ * Renders a guide document for a place, mode and audience (spec §6, §7): sections selected, known
35
+ * variables with a value substituted and escaped for where they stand, unknown and unresolved ones
36
+ * left as written, the tree sanitized (raw HTML as text, images as links or alt text, links only to
37
+ * absolute https URLs or http(s) URLs built from a `url` variable, text kept from being auto-linked)
38
+ * and cut into blocks. Pure and deterministic.
39
+ */
40
+ export declare function renderSetupGuide(source: string, input: {
41
+ place: SetupGuidePlace;
42
+ mode: string | null;
43
+ audience: SetupGuideAudience;
44
+ values: Readonly<Record<string, string | null | undefined>>;
45
+ }): RenderedSetupGuideDoc;