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:
Florian Schmidt
2026-11-16 11:42:12 +01:00
parent 28e806d641
commit 845d6c828e
24 changed files with 1407 additions and 136 deletions
+82 -27
View File
@@ -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;
}