// 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(); 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()): Set { 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; }