feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:
- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
::host{name= address= user= port= capture=}; composeNotebook namespaces
an included notebook's params, steps, captures and templates by alias
(cycles, missing files, depth > 4 and child errors are reported on the
use line). Defaults may reference captures and builtins
({{shellbook.public_key}}); required params and secrets gate only steps
of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
add a created machine to Hosts and capture its name, reload when an
included notebook changes, run all checks only for active steps,
authoring snippets for when, use and host.
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
// Chained notebooks (`::use`): pure composition. The server loads the files; core only
|
||||
// namespaces and merges them, so display and execution keep using one notebook model.
|
||||
import type { Block, Diagnostic, Notebook, ParamDef, ParamValues, Step } from "./types";
|
||||
import { includePath } from "./parser";
|
||||
|
||||
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||
/** Maximum `::use` nesting (root -> a -> b -> c -> d). */
|
||||
export const MAX_INCLUDE_DEPTH = 4;
|
||||
/** Runtime names provided by the server, never namespaced: {{shellbook.public_key}}. */
|
||||
export const isBuiltin = (name: string) => name.startsWith("shellbook.");
|
||||
|
||||
/** Workspace paths a notebook includes directly, in document order. Invalid paths never reach I/O. */
|
||||
export function notebookIncludes(notebook: Notebook): string[] {
|
||||
const paths: string[] = [];
|
||||
const walk = (blocks: Block[]) => {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
|
||||
else if (block.type === "after" || block.type === "when" || block.type === "use") walk(block.blocks);
|
||||
}
|
||||
};
|
||||
walk(notebook.blocks);
|
||||
return [...new Set(paths)];
|
||||
}
|
||||
|
||||
const qualify = (alias: string, name: string) => `${alias}.${name}`;
|
||||
const rewrite = (text: string, alias: string) =>
|
||||
text.replace(template, (match, name: string) => isBuiltin(name) ? match : `{{${qualify(alias, name)}}}`);
|
||||
const scoped = (alias: string, scope?: string) => scope ? qualify(alias, scope) : alias;
|
||||
|
||||
function prefixStep(step: Step, alias: string): Step {
|
||||
const a = step.attrs;
|
||||
return {
|
||||
...step,
|
||||
script: rewrite(step.script, alias),
|
||||
attrs: {
|
||||
...a,
|
||||
id: qualify(alias, a.id),
|
||||
host: a.host === undefined ? undefined : rewrite(a.host, alias),
|
||||
capture: a.capture === undefined ? undefined : qualify(alias, a.capture),
|
||||
artifacts: a.artifacts.map(x => rewrite(x, alias)),
|
||||
uploads: a.uploads.map(u => ({ src: rewrite(u.src, alias), dst: rewrite(u.dst, alias) })),
|
||||
scope: scoped(alias, a.scope),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Namespace a composed notebook's blocks under alias (names, ids, templates, scopes). */
|
||||
function prefixBlocks(blocks: Block[], alias: string): Block[] {
|
||||
return blocks.map((block): Block => {
|
||||
switch (block.type) {
|
||||
case "markdown": return { ...block, text: rewrite(block.text, alias) };
|
||||
case "step": return { type: "step", step: prefixStep(block.step, alias) };
|
||||
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "host": return {
|
||||
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
|
||||
name: rewrite(block.name, alias), address: rewrite(block.address, alias),
|
||||
user: rewrite(block.user, alias), port: rewrite(block.port, alias),
|
||||
capture: block.capture === undefined ? undefined : qualify(alias, block.capture),
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function prefixParam(def: ParamDef, alias: string): ParamDef {
|
||||
return {
|
||||
...def,
|
||||
name: qualify(alias, def.name),
|
||||
default: def.default === undefined ? undefined : rewrite(def.default, alias),
|
||||
scope: scoped(alias, def.scope),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every step and host id in composed blocks (for duplicate detection). */
|
||||
function blockIds(blocks: Block[], into: string[] = []): string[] {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step") into.push(block.step.attrs.id);
|
||||
else if (block.type === "host") into.push(block.id);
|
||||
else if (block.type !== "markdown") blockIds(block.blocks, into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve `::use` blocks: the included notebook's params, steps, captures and ids are
|
||||
* namespaced by its alias ("ct.hostname") and merged into one notebook. `with` bindings
|
||||
* become the included params' defaults in the including notebook's namespace.
|
||||
* Missing files, cycles, nesting deeper than MAX_INCLUDE_DEPTH and errors inside an
|
||||
* included notebook become error diagnostics on the `::use` line.
|
||||
*/
|
||||
export function composeNotebook(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined): Notebook {
|
||||
return compose(path, notebook, load, [path]);
|
||||
}
|
||||
|
||||
function compose(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined, stack: string[]): Notebook {
|
||||
const diagnostics: Diagnostic[] = [...notebook.diagnostics];
|
||||
const params: ParamDef[] = [...notebook.params];
|
||||
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
|
||||
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
|
||||
if (block.type === "after" || block.type === "when") return { ...block, blocks: resolve(block.blocks) };
|
||||
if (block.type !== "use") return block;
|
||||
const line = block.range.startLine;
|
||||
// The parser already reported an invalid path; never hand it to the loader.
|
||||
if (!includePath(block.path)) return block;
|
||||
if (stack.includes(block.path)) { fail(`Notebook include cycle: ${[...stack, block.path].join(" -> ")}`, line); return block; }
|
||||
if (stack.length > MAX_INCLUDE_DEPTH) { fail(`Notebook includes are nested deeper than ${MAX_INCLUDE_DEPTH}`, line); return block; }
|
||||
const loaded = load(block.path);
|
||||
if (!loaded) { fail(`Included notebook not found: ${block.path}`, line); return block; }
|
||||
const child = compose(block.path, loaded, load, [...stack, block.path]);
|
||||
for (const d of child.diagnostics) if (d.severity === "error") fail(`${block.path}${d.line ? `:${d.line}` : ""}: ${d.message}`, line);
|
||||
const alias = block.scope;
|
||||
for (const [name, value] of Object.entries(block.bindings)) {
|
||||
const def = child.params.find(p => p.name === name && !p.scope);
|
||||
if (!def) fail(`with binds unknown parameter of ${block.path}: ${name}`, line);
|
||||
else if (def.type === "secret") fail(`with cannot bind secret ${name}; enter it in the form`, line);
|
||||
}
|
||||
for (const def of child.params) {
|
||||
const prefixed = prefixParam(def, alias);
|
||||
// Bindings are templates in the including notebook's namespace: not rewritten.
|
||||
if (!def.scope && def.type !== "secret" && Object.hasOwn(block.bindings, def.name)) prefixed.default = block.bindings[def.name];
|
||||
params.push(prefixed);
|
||||
}
|
||||
return { ...block, title: child.title, bindings: { ...block.bindings }, blocks: prefixBlocks(child.blocks, alias) };
|
||||
});
|
||||
const blocks = resolve(notebook.blocks);
|
||||
const seen = new Set<string>();
|
||||
for (const id of blockIds(blocks)) {
|
||||
if (seen.has(id) && id.includes(".")) fail(`Duplicate step id after including notebooks: ${id}`, 1);
|
||||
seen.add(id);
|
||||
}
|
||||
return { ...notebook, params, blocks, diagnostics };
|
||||
}
|
||||
|
||||
/** Find a step anywhere in the block tree (after, when and use containers). */
|
||||
export function findStep(blocks: Block[], id: string): Step | undefined {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.id === id) return block.step;
|
||||
if (block.type === "after" || block.type === "when" || block.type === "use") {
|
||||
const found = findStep(block.blocks, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a step or host block is shown and runnable: every enclosing `:::when` must match
|
||||
* the resolved parameter values. `:::after` only gates display, not execution.
|
||||
*/
|
||||
export function blockActive(notebook: Notebook, id: string, values: ParamValues): boolean {
|
||||
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.id === id) return active;
|
||||
if (block.type === "host" && block.id === id) return active;
|
||||
if (block.type === "when") {
|
||||
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
|
||||
if (found !== undefined) return found;
|
||||
} else if (block.type === "after" || block.type === "use") {
|
||||
const found = walk(block.blocks, active);
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
return walk(notebook.blocks, true) ?? false;
|
||||
}
|
||||
|
||||
/** Whether an included notebook's scope ("ct", "svc.ct") is active, i.e. its `::use` lies in matching `:::when` sections. The root scope ("") always is. */
|
||||
export function scopeActive(notebook: Notebook, scope: string, values: ParamValues): boolean {
|
||||
if (!scope) return true;
|
||||
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "use" && block.scope === scope) return active;
|
||||
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue;
|
||||
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
return walk(notebook.blocks, true) ?? false;
|
||||
}
|
||||
|
||||
/** Runtime names that steps or host blocks of the notebook set (`capture=`). */
|
||||
export function captureNames(blocks: Block[], into = new Set<string>()): Set<string> {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
|
||||
else if (block.type === "host" && block.capture) into.add(block.capture);
|
||||
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
+82
-27
@@ -1,8 +1,10 @@
|
||||
// Public API of @shellbook/core. Pure functions, no I/O.
|
||||
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
|
||||
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
|
||||
import { captureNames, isBuiltin } from "./compose";
|
||||
export type * from "./types";
|
||||
export type * from "./protocol";
|
||||
export { parseNotebook } from "./parser";
|
||||
export { parseNotebook, includePath } from "./parser";
|
||||
export { composeNotebook, notebookIncludes, findStep, blockActive, scopeActive, captureNames, isBuiltin, MAX_INCLUDE_DEPTH } from "./compose";
|
||||
|
||||
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||
const own = (object: object, key: string) => Object.hasOwn(object, key);
|
||||
@@ -17,15 +19,20 @@ export function shellQuote(value: string): string {
|
||||
return /^[A-Za-z0-9._/@:=+\-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
|
||||
/** Resolve defaults ({{other}} references) and validate all params by type. */
|
||||
/**
|
||||
* Resolve defaults ({{other}} references) and validate all params by type. Defaults may
|
||||
* also reference runtime values (captures such as {{ct.host}}, builtins {{shellbook.*}}).
|
||||
*/
|
||||
export function resolveParams(
|
||||
notebook: Notebook,
|
||||
values: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
runtime: ParamValues = {},
|
||||
): { values: ParamValues; errors: Record<string, string> } {
|
||||
const effective = dictionary();
|
||||
const errors = dictionary();
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const captures = captureNames(notebook.blocks);
|
||||
const active = new Set<string>();
|
||||
const resolve = (name: string): string => {
|
||||
if (own(effective, name)) return effective[name]!;
|
||||
@@ -34,9 +41,14 @@ export function resolveParams(
|
||||
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
|
||||
active.add(name);
|
||||
let value = own(values, name) ? values[name] ?? "" : "";
|
||||
let pending = false;
|
||||
if (!value && def.type !== "secret" && def.default !== undefined) {
|
||||
value = def.default.replace(template, (match, ref: string) => {
|
||||
const other = defs.get(ref);
|
||||
if (!other && (captures.has(ref) || isBuiltin(ref))) {
|
||||
if (own(runtime, ref) && runtime[ref]) return runtime[ref]!;
|
||||
errors[name] = `Available after the step that sets ${ref}`; pending = true; return match;
|
||||
}
|
||||
if (!other) { errors[name] = `Unknown default reference: ${ref}`; return match; }
|
||||
if (other.type === "secret") { errors[name] = "Defaults cannot reference secrets"; return match; }
|
||||
const resolved = resolve(ref);
|
||||
@@ -46,6 +58,8 @@ export function resolveParams(
|
||||
});
|
||||
}
|
||||
active.delete(name);
|
||||
// A default still waiting for a captured value is empty, not its literal template.
|
||||
if (pending) value = "";
|
||||
effective[name] = value;
|
||||
if (!value) {
|
||||
if (def.required) errors[name] ??= "Required parameter is missing";
|
||||
@@ -63,6 +77,42 @@ export function resolveParams(
|
||||
return { values: effective, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared template substitution for steps and host blocks. Required params gate only
|
||||
* blocks of their own scope: an included notebook's form does not block the parent.
|
||||
*/
|
||||
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
|
||||
const resolved = resolveParams(notebook, values, hostNames, runtime);
|
||||
const captures = captureNames(notebook.blocks);
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const invalid = dictionary();
|
||||
const missing = new Set<string>();
|
||||
for (const def of notebook.params) {
|
||||
if ((def.scope ?? "") !== (scope ?? "")) continue;
|
||||
if (def.required && !resolved.values[def.name]) missing.add(def.name);
|
||||
if ((def.required || def.type === "secret") && resolved.values[def.name]
|
||||
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
|
||||
}
|
||||
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
|
||||
const def = defs.get(name);
|
||||
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
|
||||
if (!def && !own(runtime, name)) {
|
||||
// A capture that has not run yet (or a builtin) is pending, not a typo.
|
||||
if (captures.has(name) || isBuiltin(name)) missing.add(name);
|
||||
else invalid[name] = "Unknown parameter or runtime value";
|
||||
return match;
|
||||
}
|
||||
const value = def ? resolved.values[name] : runtime[name];
|
||||
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
|
||||
if (!value) { missing.add(name); return match; }
|
||||
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
|
||||
// Never interpolate values with validation errors into scripts or metadata.
|
||||
if (own(invalid, name)) return match;
|
||||
return script ? shellQuote(value) : value;
|
||||
});
|
||||
return { substitute, invalid, missing };
|
||||
}
|
||||
|
||||
/**
|
||||
* The single script substitution path: display and execution consume this result.
|
||||
* Attributes use raw substitution and separate validation; secrets are env-only.
|
||||
@@ -74,27 +124,7 @@ export function renderStep(
|
||||
runtime: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
): RenderedStep {
|
||||
const resolved = resolveParams(notebook, values, hostNames);
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const invalid = dictionary();
|
||||
const missing = new Set<string>();
|
||||
for (const def of notebook.params) {
|
||||
if (def.required && !resolved.values[def.name]) missing.add(def.name);
|
||||
if ((def.required || def.type === "secret") && resolved.values[def.name]
|
||||
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
|
||||
}
|
||||
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
|
||||
const def = defs.get(name);
|
||||
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
|
||||
if (!def && !own(runtime, name)) { invalid[name] = "Unknown parameter or runtime value"; return match; }
|
||||
const value = def ? resolved.values[name] : runtime[name];
|
||||
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
|
||||
if (!value) { missing.add(name); return match; }
|
||||
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
|
||||
// Never interpolate values with validation errors into scripts or metadata.
|
||||
if (own(invalid, name)) return match;
|
||||
return script ? shellQuote(value) : value;
|
||||
});
|
||||
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
|
||||
const script = substitute(step.script, true);
|
||||
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
|
||||
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
|
||||
@@ -113,15 +143,40 @@ export function renderStep(
|
||||
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, missing: [...missing], invalid };
|
||||
}
|
||||
|
||||
/** Resolve a `::host` block with the same rules as hosts.yaml entries. */
|
||||
export function renderHost(
|
||||
notebook: Notebook,
|
||||
block: Extract<Block, { type: "host" }>,
|
||||
values: ParamValues,
|
||||
runtime: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
): RenderedHost {
|
||||
const { substitute, invalid, missing } = substitution(notebook, block.scope, values, runtime, hostNames);
|
||||
const name = substitute(block.name, false), address = substitute(block.address, false);
|
||||
const user = substitute(block.user, false), portText = substitute(block.port, false);
|
||||
const port = Number(portText);
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(name)) invalid.name ??= "Host name may only contain letters, digits, ., _ or -";
|
||||
if (!address || /[\s\0]/.test(address)) invalid.address ??= "Address cannot be empty or contain whitespace";
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(user)) invalid.user ??= "User may only contain letters, digits, ., _ or -";
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) invalid.port ??= "Port must be 1-65535";
|
||||
return { id: block.id, name, address, user, port, missing: [...missing], invalid };
|
||||
}
|
||||
|
||||
/** Substitute prose without quoting; secrets always appear masked. */
|
||||
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
|
||||
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
|
||||
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) ? values[name]! : match);
|
||||
}
|
||||
|
||||
/** Env vars for a run: every secret param under its exact name. Server-side only. */
|
||||
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
|
||||
/**
|
||||
* Env vars for a run: the secrets of the step's scope under their local name
|
||||
* (an included notebook's `ct.TOKEN` is `$TOKEN` in its own steps). Server-side only.
|
||||
*/
|
||||
export function secretEnv(notebook: Notebook, values: ParamValues, scope?: string): Record<string, string> {
|
||||
const env = dictionary();
|
||||
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
|
||||
for (const def of notebook.params) {
|
||||
if (def.type !== "secret" || (def.scope ?? "") !== (scope ?? "") || !own(values, def.name)) continue;
|
||||
env[def.scope ? def.name.slice(def.scope.length + 1) : def.name] = values[def.name]!;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,10 @@ 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"]);
|
||||
const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
/** Workspace notebook path relative to notebooks/: forward slashes, no `..`, Markdown only. */
|
||||
export const includePath = (value: string) =>
|
||||
/^[^\\\0\r\n:]+\.md$/.test(value) && value.split("/").every(part => part && part !== "." && part !== "..");
|
||||
|
||||
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
|
||||
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
|
||||
@@ -90,7 +94,9 @@ export function parseNotebook(source: string): Notebook {
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
const afterRefs: { id: string; line: number }[] = [];
|
||||
const aliases = new Set<string>();
|
||||
let stepNumber = 0;
|
||||
let hostNumber = 0;
|
||||
let heading: string | undefined;
|
||||
let i = start;
|
||||
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
|
||||
@@ -118,6 +124,70 @@ export function parseNotebook(source: string): Notebook {
|
||||
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
|
||||
markdownStart = i; continue;
|
||||
}
|
||||
const when = /^\s{0,3}:::when\{(.*)\}\s*$/.exec(line);
|
||||
if (when && depth < 100) {
|
||||
flush(); const begin = i++;
|
||||
const attrs = attributes(when[1]!, m => error(m, begin + 1));
|
||||
const [param, raw] = [...attrs][0] ?? [];
|
||||
const value = raw?.[0];
|
||||
if (attrs.size !== 1 || typeof value !== "string") error("when requires exactly one param=value[,value]", begin + 1);
|
||||
const values = typeof value === "string" ? value.split(",").map(v => v.trim()).filter(Boolean) : [];
|
||||
const def = notebook.params.find(p => p.name === param);
|
||||
if (param && !def) error(`when references unknown parameter: ${param}`, begin + 1);
|
||||
else if (def?.type === "secret") error("when cannot test a secret", begin + 1);
|
||||
else if (def?.options) for (const v of values) if (!def.options.includes(v)) error(`when value is not an option of ${param}: ${v}`, begin + 1);
|
||||
const children = parseBlocks(true, depth + 1);
|
||||
if (i === lines.length) error("Unclosed when container", begin + 1);
|
||||
else i++;
|
||||
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
|
||||
markdownStart = i; continue;
|
||||
}
|
||||
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line);
|
||||
if (leaf) {
|
||||
flush();
|
||||
const lineNo = i + 1;
|
||||
const attrs = attributes(leaf[2]!, m => error(m, lineNo));
|
||||
const get = (key: string): string | undefined => {
|
||||
const v = attrs.get(key);
|
||||
if (v && (v.length > 1 || v[0] === true)) error(`${key} requires one value`, lineNo);
|
||||
return typeof v?.[0] === "string" ? v[0] : undefined;
|
||||
};
|
||||
const range = { startLine: lineNo, endLine: lineNo };
|
||||
if (leaf[1] === "use") {
|
||||
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
|
||||
const path = get("notebook") ?? "";
|
||||
const alias = get("as") ?? "";
|
||||
if (!includePath(path)) error('use requires notebook="dir/name.md" (relative to notebooks/)', lineNo);
|
||||
if (!identifier.test(alias) || alias === "shellbook") error("use requires as=alias (letters, digits, _; not shellbook)", lineNo);
|
||||
else if (aliases.has(alias)) error(`Duplicate use alias: ${alias}`, lineNo);
|
||||
aliases.add(alias);
|
||||
const bindings = Object.create(null) as Record<string, string>;
|
||||
for (const value of attrs.get("with") ?? []) {
|
||||
if (value === true) { error("with requires name=value pairs", lineNo); continue; }
|
||||
// Values may contain commas; a new binding starts only at ",name=".
|
||||
for (const pair of value.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)) {
|
||||
const eq = pair.indexOf("=");
|
||||
const name = pair.slice(0, Math.max(eq, 0)).trim();
|
||||
if (eq <= 0 || !identifier.test(name)) error("with requires name=value pairs", lineNo);
|
||||
else if (Object.hasOwn(bindings, name)) error(`Duplicate with binding: ${name}`, lineNo);
|
||||
else bindings[name] = pair.slice(eq + 1).trim();
|
||||
}
|
||||
}
|
||||
blocks.push({ type: "use", scope: alias, path, bindings, blocks: [], range });
|
||||
} else {
|
||||
hostNumber++;
|
||||
for (const key of attrs.keys()) if (!["id", "name", "address", "user", "port", "capture"].includes(key)) error(`Unknown host attribute: ${key}`, lineNo);
|
||||
const id = get("id") || `host-${hostNumber}`;
|
||||
if (ids.has(id)) error(`Duplicate step id: ${id}`, lineNo);
|
||||
ids.add(id);
|
||||
const name = get("name"), address = get("address");
|
||||
if (!name || !address) error("host requires name and address", lineNo);
|
||||
const capture = get("capture");
|
||||
if (capture !== undefined && !identifier.test(capture)) error("Invalid capture name", lineNo);
|
||||
blocks.push({ type: "host", id, name: name ?? "", address: address ?? "", user: get("user") ?? "root", port: get("port") ?? "22", capture, range });
|
||||
}
|
||||
i++; markdownStart = i; continue;
|
||||
}
|
||||
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
||||
if (fence) {
|
||||
const begin = i;
|
||||
@@ -166,7 +236,7 @@ export function parseNotebook(source: string): Notebook {
|
||||
}
|
||||
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);
|
||||
if (capture && !identifier.test(capture)) error("Invalid capture name", begin + 1);
|
||||
const step: Step = {
|
||||
kind,
|
||||
lang: match[1]!,
|
||||
@@ -186,7 +256,7 @@ export function parseNotebook(source: string): Notebook {
|
||||
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);
|
||||
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
|
||||
i++;
|
||||
}
|
||||
flush(); return blocks;
|
||||
|
||||
@@ -35,8 +35,17 @@ export interface NotebookListResponse {
|
||||
// GET /api/notebooks/:path (path URL-encoded)
|
||||
export interface NotebookResponse {
|
||||
path: string;
|
||||
/** The notebook's own Markdown (what the editor saves). */
|
||||
source: string;
|
||||
/** Parsed and composed: `::use` blocks contain the included notebooks (namespaced). */
|
||||
notebook: Notebook;
|
||||
/** Workspace paths of all included notebooks (reload when one of them changes). */
|
||||
includes: string[];
|
||||
/**
|
||||
* Server-provided runtime values, e.g. "shellbook.public_key". The server sets them on
|
||||
* every run itself; clients merge them into the runtime they render with.
|
||||
*/
|
||||
builtins: ParamValues;
|
||||
/** Opaque version for optimistic concurrency on save. */
|
||||
version: string;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,11 @@ export interface ParamDef {
|
||||
label?: string;
|
||||
/** Only for type "choice". */
|
||||
options?: string[];
|
||||
/**
|
||||
* Set for params of an included notebook (`::use`): the alias path ("ct", "ct.base").
|
||||
* The name is then prefixed ("ct.hostname"); a secret's env var keeps the local name.
|
||||
*/
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
/** Param name -> current value. Missing key or "" means "not filled". */
|
||||
@@ -44,6 +49,8 @@ export interface StepAttrs {
|
||||
artifacts: string[];
|
||||
uploads: Upload[];
|
||||
timeoutSec: number;
|
||||
/** Alias path when the step comes from an included notebook (see ParamDef.scope). */
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
/** 1-based, inclusive line range in the notebook source. */
|
||||
@@ -72,8 +79,58 @@ export type Block =
|
||||
onFailure: boolean;
|
||||
blocks: Block[];
|
||||
range: SourceRange;
|
||||
}
|
||||
| {
|
||||
/** `:::when{param=a,b}` — shown, and its steps runnable, only while param is one of values. */
|
||||
type: "when";
|
||||
param: string;
|
||||
values: string[];
|
||||
blocks: Block[];
|
||||
range: SourceRange;
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* `::use{notebook="dir/x.md" as=alias with="p={{v}}"}` — another workspace notebook inline.
|
||||
* As parsed, `blocks` is empty; composeNotebook fills it with the namespaced content.
|
||||
*/
|
||||
type: "use";
|
||||
/** Alias path ("ct"; "ct.base" for nested includes). */
|
||||
scope: string;
|
||||
/** Workspace notebook path relative to notebooks/. */
|
||||
path: string;
|
||||
/** Included notebook's title (set by composeNotebook). */
|
||||
title?: string;
|
||||
/** Local param name of the included notebook -> default template in the including notebook. */
|
||||
bindings: Record<string, string>;
|
||||
blocks: Block[];
|
||||
range: SourceRange;
|
||||
}
|
||||
| {
|
||||
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
|
||||
type: "host";
|
||||
id: string;
|
||||
scope?: string;
|
||||
/** Templates, resolved like step attributes. */
|
||||
name: string;
|
||||
address: string;
|
||||
user: string;
|
||||
port: string;
|
||||
/** Runtime value set to the host name once it is in Hosts. */
|
||||
capture?: string;
|
||||
range: SourceRange;
|
||||
};
|
||||
|
||||
/** A `::host` block with all templates resolved. */
|
||||
export interface RenderedHost {
|
||||
id: string;
|
||||
name: string;
|
||||
address: string;
|
||||
user: string;
|
||||
port: number;
|
||||
missing: string[];
|
||||
invalid: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface Diagnostic {
|
||||
severity: "error" | "warning";
|
||||
message: string;
|
||||
|
||||
Reference in New Issue
Block a user