stock-bot/scripts/export-notebook-snapshot.ts

310 lines
10 KiB
TypeScript

/**
* Runnable CLI wrapper for `marimo check`-gated static HTML notebook exports.
*
* Enforces D9 (`design/PLATFORM-PLAN.md`): runs `marimo check --format=json`
* before `marimo export html` and publishes the HTML atomically via a sibling
* temp file. Emits the frozen JSON `NotebookSnapshotReceipt` to stdout on
* success, or a single concise error line to stderr with zero stdout bytes and
* exit code 1 on any validation, check, export, or timeout failure.
*/
import { resolve } from 'node:path';
import {
DEFAULT_MARIMO_COMMAND,
DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS,
type NotebookCommandRunner,
NotebookSnapshotError,
type NotebookSnapshotFs,
exportNotebookSnapshot,
} from '@stock-bot/research';
import {
createNodeNotebookCommandRunner,
createNodeNotebookSnapshotFs,
} from '@stock-bot/research/notebook-snapshot-node';
const STRICT_POSITIVE_INT_RE = /^[1-9]\d*$/;
export interface ExportNotebookSnapshotStream {
write(chunk: string): boolean;
}
export interface ParseExportNotebookSnapshotArgsOptions {
readonly cwd?: string;
readonly env?: Readonly<Record<string, string | undefined>>;
}
export interface ParsedExportNotebookSnapshotRun {
readonly kind: 'run';
readonly notebookPath: string;
readonly outputPath: string;
readonly marimoCommand: string;
readonly timeoutMs: number;
readonly cwd?: string;
readonly allowedNotebookRoot?: string;
readonly allowedOutputRoot?: string;
}
export interface ParsedExportNotebookSnapshotHelp {
readonly kind: 'help';
}
export type ParsedExportNotebookSnapshotArgs =
| ParsedExportNotebookSnapshotRun
| ParsedExportNotebookSnapshotHelp;
export interface ExportNotebookSnapshotCliDeps {
readonly argv?: readonly string[];
readonly cwd?: string;
readonly env?: Readonly<Record<string, string | undefined>>;
readonly stdout?: ExportNotebookSnapshotStream;
readonly stderr?: ExportNotebookSnapshotStream;
readonly runner?: NotebookCommandRunner;
readonly fs?: NotebookSnapshotFs;
}
export class ExportNotebookSnapshotCliError extends Error {
constructor(message: string) {
super(message);
this.name = 'ExportNotebookSnapshotCliError';
Object.setPrototypeOf(this, new.target.prototype);
}
}
export const EXPORT_NOTEBOOK_SNAPSHOT_USAGE = [
'Usage: bun run notebook:snapshot --notebook <path.py> --out <path.html> [options]',
'',
'Options:',
' --notebook <path.py> Required marimo notebook file (.py)',
' --out <path.html> Required output HTML snapshot path (.html)',
` --marimo <cmd> marimo executable (default: $MARIMO_COMMAND or ${DEFAULT_MARIMO_COMMAND})`,
` --timeout-ms <positive-int> Per-command timeout in ms (default: ${DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS})`,
' --cwd <dir> Working directory passed to marimo subprocesses',
' --allowed-notebook-root <dir> Optional root directory bounding --notebook',
' --allowed-output-root <dir> Optional root directory bounding --out',
' -h, --help Show this help message',
'',
].join('\n');
const VALUE_FLAGS = new Set([
'--notebook',
'--out',
'--marimo',
'--timeout-ms',
'--cwd',
'--allowed-notebook-root',
'--allowed-output-root',
]);
function sanitizeSingleLine(message: string): string {
return message.replace(/\r?\n/g, ' ').trim();
}
function validateRawTokenValue(flag: string, rawValue: string): string {
if (rawValue.length === 0 || rawValue.trim().length === 0) {
throw new ExportNotebookSnapshotCliError(`Flag '${flag}' requires a non-empty value.`);
}
if (rawValue.includes('\0')) {
throw new ExportNotebookSnapshotCliError(`Flag '${flag}' value must not contain NUL bytes.`);
}
if (rawValue.startsWith('-')) {
throw new ExportNotebookSnapshotCliError(
`Flag '${flag}' value must not start with '-' (received '${rawValue}').`
);
}
return rawValue;
}
function parsePositiveIntFlag(flag: string, rawValue: string): number {
const validated = validateRawTokenValue(flag, rawValue);
if (!STRICT_POSITIVE_INT_RE.test(validated)) {
throw new ExportNotebookSnapshotCliError(
`Flag '${flag}' must be a positive integer (received '${validated}').`
);
}
const parsed = Number(validated);
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
throw new ExportNotebookSnapshotCliError(
`Flag '${flag}' must be a positive safe integer (received '${validated}').`
);
}
return parsed;
}
function resolveValidatedPath(baseCwd: string, flag: string, rawValue: string): string {
const validated = validateRawTokenValue(flag, rawValue);
return resolve(baseCwd, validated);
}
/**
* Parses and validates CLI arguments for `scripts/export-notebook-snapshot.ts`.
*
* Rejects missing required flags, duplicate flags, unknown flags, positional
* arguments, NUL bytes, and values starting with `-` prior to `path.resolve`.
*/
export function parseExportNotebookSnapshotArgs(
argv: readonly string[],
options?: ParseExportNotebookSnapshotArgsOptions
): ParsedExportNotebookSnapshotArgs {
const baseCwd = options?.cwd ?? process.cwd();
const env = options?.env ?? process.env;
const seen = new Map<string, string>();
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i] as string;
if (token === '--help' || token === '-h') {
return { kind: 'help' };
}
if (token === '--') {
throw new ExportNotebookSnapshotCliError('Unexpected positional argument separator "--".');
}
if (!token.startsWith('-')) {
throw new ExportNotebookSnapshotCliError(`Unexpected positional argument '${token}'.`);
}
const eqIndex = token.indexOf('=');
let flag: string;
let rawValue: string;
if (eqIndex !== -1) {
flag = token.slice(0, eqIndex);
rawValue = token.slice(eqIndex + 1);
if (!VALUE_FLAGS.has(flag)) {
throw new ExportNotebookSnapshotCliError(`Unknown flag '${flag}'.`);
}
} else {
flag = token;
if (!VALUE_FLAGS.has(flag)) {
throw new ExportNotebookSnapshotCliError(`Unknown flag '${flag}'.`);
}
if (i + 1 >= argv.length) {
throw new ExportNotebookSnapshotCliError(`Flag '${flag}' requires a value.`);
}
i += 1;
rawValue = argv[i] as string;
}
if (seen.has(flag)) {
throw new ExportNotebookSnapshotCliError(`Duplicate flag '${flag}'.`);
}
seen.set(flag, validateRawTokenValue(flag, rawValue));
}
const rawNotebook = seen.get('--notebook');
if (rawNotebook === undefined) {
throw new ExportNotebookSnapshotCliError('Missing required flag --notebook <path.py>.');
}
const rawOut = seen.get('--out');
if (rawOut === undefined) {
throw new ExportNotebookSnapshotCliError('Missing required flag --out <path.html>.');
}
const notebookPath = resolveValidatedPath(baseCwd, '--notebook', rawNotebook);
const outputPath = resolveValidatedPath(baseCwd, '--out', rawOut);
const rawMarimo = seen.get('--marimo');
let marimoCommand: string;
if (rawMarimo !== undefined) {
marimoCommand = rawMarimo;
} else {
const envMarimo = env.MARIMO_COMMAND;
marimoCommand =
typeof envMarimo === 'string' && envMarimo.trim().length > 0
? envMarimo
: DEFAULT_MARIMO_COMMAND;
}
const rawTimeoutMs = seen.get('--timeout-ms');
const timeoutMs =
rawTimeoutMs !== undefined
? parsePositiveIntFlag('--timeout-ms', rawTimeoutMs)
: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS;
const rawCwd = seen.get('--cwd');
const cwd = rawCwd !== undefined ? resolveValidatedPath(baseCwd, '--cwd', rawCwd) : undefined;
const rawAllowedNotebookRoot = seen.get('--allowed-notebook-root');
const allowedNotebookRoot =
rawAllowedNotebookRoot !== undefined
? resolveValidatedPath(baseCwd, '--allowed-notebook-root', rawAllowedNotebookRoot)
: undefined;
const rawAllowedOutputRoot = seen.get('--allowed-output-root');
const allowedOutputRoot =
rawAllowedOutputRoot !== undefined
? resolveValidatedPath(baseCwd, '--allowed-output-root', rawAllowedOutputRoot)
: undefined;
return {
kind: 'run',
notebookPath,
outputPath,
marimoCommand,
timeoutMs,
...(cwd !== undefined ? { cwd } : {}),
...(allowedNotebookRoot !== undefined ? { allowedNotebookRoot } : {}),
...(allowedOutputRoot !== undefined ? { allowedOutputRoot } : {}),
};
}
/**
* Executes the notebook snapshot CLI with injectable I/O, runner, and fs deps.
*/
export async function runExportNotebookSnapshotCli(
deps: ExportNotebookSnapshotCliDeps = {}
): Promise<number> {
const argv = deps.argv ?? process.argv.slice(2);
const stdout = deps.stdout ?? process.stdout;
const stderr = deps.stderr ?? process.stderr;
let parsed: ParsedExportNotebookSnapshotArgs;
try {
parsed = parseExportNotebookSnapshotArgs(argv, {
...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}),
...(deps.env !== undefined ? { env: deps.env } : {}),
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
stderr.write(`Invalid arguments: ${sanitizeSingleLine(message)}\n`);
return 1;
}
if (parsed.kind === 'help') {
stdout.write(EXPORT_NOTEBOOK_SNAPSHOT_USAGE);
return 0;
}
try {
const receipt = await exportNotebookSnapshot({
notebookPath: parsed.notebookPath,
outputPath: parsed.outputPath,
marimoCommand: parsed.marimoCommand,
timeoutMs: parsed.timeoutMs,
...(parsed.cwd !== undefined ? { cwd: parsed.cwd } : {}),
...(parsed.allowedNotebookRoot !== undefined
? { allowedNotebookRoot: parsed.allowedNotebookRoot }
: {}),
...(parsed.allowedOutputRoot !== undefined
? { allowedOutputRoot: parsed.allowedOutputRoot }
: {}),
runner: deps.runner ?? createNodeNotebookCommandRunner(),
fs: deps.fs ?? createNodeNotebookSnapshotFs(),
});
stdout.write(`${JSON.stringify(receipt)}\n`);
return 0;
} catch (err) {
if (err instanceof NotebookSnapshotError) {
stderr.write(
`Notebook snapshot export failed [${err.code}]: ${sanitizeSingleLine(err.message)}\n`
);
return 1;
}
const message = err instanceof Error ? err.message : String(err);
stderr.write(`Notebook snapshot export failed: ${sanitizeSingleLine(message)}\n`);
return 1;
}
}
if (import.meta.main) {
process.exitCode = await runExportNotebookSnapshotCli();
}