Files
ShellBook/packages/core/src/parser.ts
T
Florian Schmidt c993089f37 fix(core): normalize CRLF line endings in step scripts (#1)
Bash treats a trailing carriage return as part of the command, so notebooks saved with CRLF endings produced broken scripts.
2026-11-16 00:06:28 +01:00

199 lines
11 KiB
TypeScript

import { parseDocument } from "yaml";
import type { Block, Notebook, ParamDef, Step, StepAttrs } from "./types";
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
const paramTypes = new Set(["host", "name", "path", "string", "choice", "secret"]);
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
const result = new Map<string, (string | true)[]>();
let rest = text.trim();
while (rest) {
const key = /^[A-Za-z_][\w-]*/.exec(rest)?.[0];
if (!key) { error(`Malformed attributes: ${rest}`); break; }
rest = rest.slice(key.length);
let value: string | true = true;
if (rest.startsWith("=")) {
rest = rest.slice(1);
const quote = rest[0];
if (quote === '"' || quote === "'") {
rest = rest.slice(1);
value = "";
let closed = false;
while (rest) {
const c = rest[0]!;
rest = rest.slice(1);
if (c === quote) { closed = true; break; }
if (c === "\\" && (rest[0] === quote || rest[0] === "\\")) {
value += rest[0]; rest = rest.slice(1);
} else value += c;
}
if (!closed) error(`Unclosed quote for ${key}`);
} else {
value = /^\S*/.exec(rest)![0];
rest = rest.slice(value.length);
if (!value) error(`Missing value for ${key}`);
}
}
if (rest && !/^\s/.test(rest)) { error(`Expected whitespace after ${key}`); break; }
result.set(key, [...(result.get(key) ?? []), value]);
rest = rest.trimStart();
}
return result;
}
export function parseNotebook(source: string): Notebook {
const notebook: Notebook = { title: "Untitled", params: [], blocks: [], diagnostics: [] };
const rawLines = source.split("\n");
const lines = rawLines.map(line => line.replace(/\r$/, ""));
let hasTitle = false;
// A trailing newline terminates the preceding line; it does not create a source line.
if (lines.at(-1) === "") lines.pop();
const error = (message: string, line?: number) => notebook.diagnostics.push({ severity: "error", message, line });
let start = 0;
if (lines[0]?.replace(/^\uFEFF/, "") === "---") {
const end = lines.findIndex((line, i) => i > 0 && /^(---|\.\.\.)\s*$/.test(line));
if (end < 0) error("Unclosed frontmatter", 1);
else {
start = end + 1;
try {
const doc = parseDocument(lines.slice(1, end).join("\n"));
for (const e of doc.errors) error(`Invalid YAML: ${e.message}`, (e.linePos?.[0]?.line ?? 1) + 1);
const data: unknown = doc.toJS({ maxAliasCount: 100 });
if (!record(data)) error("Frontmatter must be a mapping", 1);
else {
if (typeof data.title === "string" && data.title.trim()) { notebook.title = data.title; hasTitle = true; }
else if (data.title !== undefined) error("title must be a non-empty string", 2);
if (data.params !== undefined && !record(data.params)) error("params must be a mapping", 2);
if (record(data.params)) for (const [name, raw] of Object.entries(data.params)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) error(`Invalid parameter name: ${name}`, 2);
if (!record(raw)) { error(`Parameter ${name} must be a mapping`, 2); continue; }
if (!paramTypes.has(String(raw.type))) { error(`Unknown param type for ${name}`, 2); continue; }
const def: ParamDef = { name, type: raw.type as ParamDef["type"], required: raw.required === true };
for (const key of Object.keys(raw)) if (!["type", "required", "default", "label", "options"].includes(key)) error(`Unknown parameter field ${key} for ${name}`, 2);
if (raw.required !== undefined && typeof raw.required !== "boolean") error(`required must be boolean for ${name}`, 2);
if (raw.default !== undefined) {
if (def.type === "secret") error(`Secret ${name} cannot have a default`, 2);
else if (typeof raw.default === "string" || typeof raw.default === "number" || typeof raw.default === "boolean") def.default = String(raw.default);
else error(`Invalid default for ${name}`, 2);
}
if (typeof raw.label === "string") def.label = raw.label;
else if (raw.label !== undefined) error(`Invalid label for ${name}`, 2);
if (Array.isArray(raw.options) && raw.options.every(x => typeof x === "string")) def.options = raw.options;
else if (raw.options !== undefined) error(`Invalid options for ${name}`, 2);
if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, 2);
notebook.params.push(def);
}
}
} catch { error("Invalid YAML frontmatter", 2); }
}
}
const ids = new Set<string>();
const afterRefs: { id: string; line: number }[] = [];
let stepNumber = 0;
let heading: string | undefined;
let i = start;
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
const blocks: Block[] = [];
let markdownStart = i;
const flush = () => {
if (i > markdownStart) blocks.push({ type: "markdown", text: rawLines.slice(markdownStart, i).join("\n") + (i < lines.length || /\n$/.test(source) ? "\n" : ""), range: { startLine: markdownStart + 1, endLine: i } });
};
while (i < lines.length) {
const line = lines[i]!;
if (/^\s{0,3}:::\s*$/.test(line) && nested) { flush(); return blocks; }
const after = /^\s{0,3}:::after\{(.*)\}\s*$/.exec(line);
if (after && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(after[1]!, m => error(m, begin + 1));
const ref = attrs.get("step")?.[0];
const id = typeof ref === "string" ? ref : "";
if (!id) error("after requires step=id", begin + 1);
for (const key of attrs.keys()) if (!["step", "failed"].includes(key)) error(`Unknown after attribute: ${key}`, begin + 1);
if (attrs.has("failed") && attrs.get("failed")![0] !== true) error("failed must be a flag", begin + 1);
afterRefs.push({ id, line: begin + 1 });
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed after container", begin + 1);
else i++;
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
if (fence) {
const begin = i;
const marker = fence[1]!;
const info = fence[2]!.trim();
const match = /^(sh|bash)\s+\{(run|check)(?:\s+([\s\S]*))?\}$/.exec(info);
let end = i + 1;
const closing = new RegExp(`^ {0,3}${marker[0]}{${marker.length},}\\s*$`);
while (end < lines.length && !closing.test(lines[end]!)) end++;
if (!match) { i = end < lines.length ? end + 1 : end; continue; }
flush();
stepNumber++;
if (end === lines.length) error("Unclosed step fence", begin + 1);
const attrs = attributes(match[3] ?? "", m => error(m, begin + 1));
const get = (key: string): string | undefined => {
const v = attrs.get(key)?.[0];
if (v === true) error(`${key} requires a value`, begin + 1);
return typeof v === "string" ? v : undefined;
};
for (const [key, vals] of attrs) {
if (!["host", "on", "id", "title", "sudo", "confirm", "capture", "artifacts", "upload", "timeout"].includes(key)) error(`Unknown attribute: ${key}`, begin + 1);
if (vals.length > 1 && key !== "upload") error(`Duplicate attribute: ${key}`, begin + 1);
if (["sudo", "confirm"].includes(key) && vals[0] !== true) error(`${key} must be a flag`, begin + 1);
}
const kind = match[2] as Step["kind"];
const title = get("title");
const id = get("id") || title?.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `step-${stepNumber}`;
if (ids.has(id)) error(`Duplicate step id: ${id}`, begin + 1);
ids.add(id);
const on = get("on");
if (on !== undefined && on !== "local") error("on must be local", begin + 1);
const host = get("host");
if (on && host) error("host and on cannot be combined", begin + 1);
const timeout = get("timeout");
const timeoutSec = timeout === undefined ? (kind === "run" ? 300 : 30) : Number(timeout);
if (!Number.isFinite(timeoutSec) || timeoutSec <= 0) error("timeout must be positive seconds", begin + 1);
const artifacts = get("artifacts")?.split(",").map(x => x.trim()) ?? [];
const uploads: StepAttrs["uploads"] = [];
for (const value of attrs.get("upload") ?? []) {
if (value === true) { error("upload requires src:dst", begin + 1); continue; }
for (const pair of value.split(",")) {
const colon = pair.indexOf(":");
if (colon <= 0 || colon === pair.length - 1) error("upload requires src:dst", begin + 1);
else uploads.push({ src: pair.slice(0, colon).trim(), dst: pair.slice(colon + 1).trim() });
}
}
if (kind === "check" && (attrs.has("artifacts") || attrs.has("upload"))) error("Checks cannot declare artifacts or uploads", begin + 1);
const capture = get("capture");
if (capture && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(capture)) error("Invalid capture name", begin + 1);
const step: Step = {
kind,
lang: match[1]!,
attrs: {
id, title, host: on === "local" ? undefined : host,
local: on === "local", sudo: attrs.has("sudo"),
confirm: kind === "run" && attrs.has("confirm"), capture,
artifacts: kind === "run" ? artifacts : [],
uploads: kind === "run" ? uploads : [], timeoutSec,
},
// LF-normalized: bash must never see a trailing \r from CRLF notebooks.
script: lines.slice(begin + 1, end).join("\n")
+ (end > begin + 1 && (end < lines.length || /\n$/.test(source)) ? "\n" : ""),
range: { startLine: begin + 1, endLine: end < lines.length ? end + 1 : end },
};
blocks.push({ type: "step", step });
i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
}
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line)) error("Malformed or unexpected directive", i + 1);
i++;
}
flush(); return blocks;
};
notebook.blocks = parseBlocks(false);
if (!hasTitle && heading) notebook.title = heading;
for (const ref of afterRefs) if (!ids.has(ref.id)) error(`after references unknown step: ${ref.id}`, ref.line);
return notebook;
}