#!/usr/bin/env node import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { runAudit, writeAuditReport } from './audit.ts'; import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts'; import { fetchSpec, verifyCache } from './fetch.ts'; import { renderReport, renderSpec } from './render.ts'; import { buildRelease } from './release.ts'; import { resolveProfiles } from './resolve.ts'; import { specList, specShow, validateManifest } from './spec.ts'; import { validateReport } from './report.ts'; import { validateSpec } from './validate.ts'; const USAGE_MESSAGE = 'Usage: bhl [args]; ' + 'spec list [--spec-root ] [--domain ] [--capability ]; ' + 'spec show [--spec-root ]; ' + 'spec render --spec-root --out ; ' + 'profile resolve [--profile ] [--preset ]; ' + 'report validate [--spec-root ]; ' + 'report render --out ; ' + 'manifest validate [--spec-root ]; ' + 'fetch --version --cache ; ' + 'verify --version --cache ; ' + 'audit --out [--spec-root ] [--spec-version ] ' + '[--profile ] [--preset ] [--generated-at ]; ' + 'release --version --out ; ' + 'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' + '3 not implemented, 4 internal.'; function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } function readPackageInfo(): { name: string; version: string } { const raw = readFileSync(new URL('../package.json', import.meta.url), 'utf8'); const parsed: unknown = JSON.parse(raw); if ( !isRecord(parsed) || typeof parsed['name'] !== 'string' || typeof parsed['version'] !== 'string' ) { throw new Error('package.json is malformed'); } return { name: parsed['name'], version: parsed['version'] }; } interface ParsedArgs { root: string; profiles: string[]; presets: string[]; } type FlagName = 'profile' | 'preset'; const FLAG_TARGETS: Readonly> = { '--profile': 'profile', '--preset': 'preset', }; interface SplitState { positional: string[]; collected: Record; cursor: number; } function parseFlagAt(args: readonly string[], state: SplitState, arg: string): string { const flag = FLAG_TARGETS[arg]; const value = args[state.cursor + 1]; if (flag === undefined || value === undefined) { return `missing value for ${arg}`; } state.collected[flag].push(value); state.cursor += 2; return ''; } function splitArgs(args: readonly string[]): { ok: SplitState } | { error: string } { const state: SplitState = { positional: [], collected: { profile: [], preset: [] }, cursor: 0, }; while (state.cursor < args.length) { const arg = args[state.cursor] ?? ''; if (FLAG_TARGETS[arg] !== undefined) { const error = parseFlagAt(args, state, arg); if (error !== '') { return { error }; } continue; } if (arg.startsWith('--')) { return { error: `unknown flag ${arg}` }; } state.positional.push(arg); state.cursor += 1; } return { ok: state }; } function toParsedArgs(state: SplitState): ParsedArgs | { error: string } { if (state.positional.length !== 1) { const extra = state.positional[1]; const message = state.positional.length === 0 ? 'resolve requires a spec root path' : `unexpected argument ${extra ?? ''}`; return { error: message }; } return { root: state.positional[0] ?? '', profiles: state.collected.profile, presets: state.collected.preset, }; } function parseArgs(args: readonly string[]): ParsedArgs | { error: string } { const split = splitArgs(args); if ('error' in split) { return split; } return toParsedArgs(split.ok); } function runProfile(command: string, rest: readonly string[]): number { const [sub, ...args] = rest; if (sub !== 'resolve') { emit(failEnvelope(command, 'USAGE', 'profile requires the subcommand resolve')); return ExitCode.Usage; } const parsed = parseArgs(args); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } const result = resolveProfiles(parsed.root, parsed.profiles, parsed.presets); const data = { root: parsed.root, profiles: result.profiles, effective: result.effective, errors: result.diagnostics, }; if (result.ok) { emit(okEnvelope(command, data)); return ExitCode.Ok; } emit({ ok: false, command, data, error: { code: 'VALIDATION_FAILED', message: `${String(result.diagnostics.length)} diagnostic(s)`, }, }); return ExitCode.ValidationFailed; } const REPORT_FLAGS: Readonly> = { '--spec-root': 'spec-root', '--out': 'out', }; function takeReportFlag( args: readonly string[], cursor: number, target: { specRoot: string; out: string | undefined }, arg: string, ): { next: number } | { error: string } { const flag = REPORT_FLAGS[arg]; const value = args[cursor + 1]; if (flag === undefined || value === undefined) { return { error: `missing value for ${arg}` }; } if (flag === 'spec-root') { target.specRoot = value; } else { target.out = value; } return { next: cursor + 2 }; } function parseReportArgs( args: readonly string[], ): { file: string; specRoot: string; out: string | undefined } | { error: string } { const target: { specRoot: string; out: string | undefined } = { specRoot: 'spec', out: undefined, }; const positional: string[] = []; let cursor = 0; while (cursor < args.length) { const arg = args[cursor] ?? ''; if (REPORT_FLAGS[arg] !== undefined) { const taken = takeReportFlag(args, cursor, target, arg); if ('error' in taken) { return taken; } cursor = taken.next; continue; } if (arg.startsWith('--')) { return { error: `unknown flag ${arg}` }; } positional.push(arg); cursor += 1; } if (positional.length !== 1) { return { error: 'report requires exactly one report file' }; } return { file: positional[0] ?? '', specRoot: target.specRoot, out: target.out }; } interface SpecFlags { root: string; domain?: string; capability?: string; out?: string; positional: string[]; } function takeNamedFlag( args: readonly string[], cursor: number, target: SpecFlags, arg: string, ): { next: number } | { error: string } { const value = args[cursor + 1]; if (value === undefined) { return { error: `missing value for ${arg}` }; } if (arg === '--spec-root') { target.root = value; } else if (arg === '--domain') { target.domain = value; } else if (arg === '--capability') { target.capability = value; } else { target.out = value; } return { next: cursor + 2 }; } function parseSpecArgs(args: readonly string[]): SpecFlags | { error: string } { const target: SpecFlags = { root: 'spec', positional: [] }; let cursor = 0; while (cursor < args.length) { const arg = args[cursor] ?? ''; if (arg === '--spec-root' || arg === '--domain' || arg === '--capability' || arg === '--out') { const taken = takeNamedFlag(args, cursor, target, arg); if ('error' in taken) { return taken; } cursor = taken.next; continue; } if (arg.startsWith('--')) { return { error: `unknown flag ${arg}` }; } target.positional.push(arg); cursor += 1; } return target; } function emitValidationFailure( command: string, data: Record, count: number, code = 'VALIDATION_FAILED', ): number { emit({ ok: false, command, data, error: { code, message: `${String(count)} diagnostic(s)` }, }); return ExitCode.ValidationFailed; } function emitSpecList(parsed: SpecFlags): number { const result = specList(parsed.root, parsed.domain, parsed.capability); const data = { root: parsed.root, requirements: result.requirements, errors: result.diagnostics }; if (!result.ok) { return emitValidationFailure('spec', data, result.diagnostics.length); } emit(okEnvelope('spec', data)); return ExitCode.Ok; } function emitSpecShow(parsed: SpecFlags): number { const id = parsed.positional[0]; if (id === undefined || parsed.positional.length !== 1) { emit(failEnvelope('spec', 'USAGE', 'spec show requires exactly one requirement id')); return ExitCode.Usage; } const result = specShow(parsed.root, id); if (!result.ok) { const code = result.diagnostics[0]?.code === 'unknown-requirement' ? 'NOT_FOUND' : 'VALIDATION_FAILED'; return emitValidationFailure( 'spec', { root: parsed.root, errors: result.diagnostics }, result.diagnostics.length, code, ); } emit(okEnvelope('spec', { root: parsed.root, requirement: result.requirement })); return ExitCode.Ok; } function emitSpecRender(parsed: SpecFlags): number { const out = parsed.out; if (out === undefined) { emit(failEnvelope('spec', 'USAGE', 'spec render requires --out ')); return ExitCode.Usage; } const result = renderSpec(parsed.root); if (!result.ok) { return emitValidationFailure( 'spec', { root: parsed.root, errors: result.diagnostics }, result.diagnostics.length, ); } for (const file of result.files) { const target = path.join(out, file.path); mkdirSync(path.dirname(target), { recursive: true }); writeFileSync(target, file.content, 'utf8'); } emit( okEnvelope('spec', { root: parsed.root, out, files: result.files.map((file) => file.path) }), ); return ExitCode.Ok; } function runSpec(command: string, rest: readonly string[]): number { const [sub, ...args] = rest; if (sub !== 'list' && sub !== 'show' && sub !== 'render') { emit(failEnvelope(command, 'USAGE', 'spec requires the subcommand list, show or render')); return ExitCode.Usage; } const parsed = parseSpecArgs(args); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } if (sub === 'list') { return emitSpecList(parsed); } if (sub === 'render') { return emitSpecRender(parsed); } return emitSpecShow(parsed); } interface FetchFlags { version?: string; cache?: string; positional: string[]; } const FETCH_FLAGS: Readonly> = { '--version': 'version', '--cache': 'cache', }; function takeFetchFlag( args: readonly string[], cursor: number, target: FetchFlags, arg: string, ): { next: number } | { error: string } { const flag = FETCH_FLAGS[arg]; const value = args[cursor + 1]; if (flag === undefined || value === undefined) { return { error: `missing value for ${arg}` }; } target[flag] = value; return { next: cursor + 2 }; } function parseFetchArgs(args: readonly string[]): FetchFlags | { error: string } { const target: FetchFlags = { positional: [] }; let cursor = 0; while (cursor < args.length) { const arg = args[cursor] ?? ''; if (FETCH_FLAGS[arg] !== undefined) { const taken = takeFetchFlag(args, cursor, target, arg); if ('error' in taken) { return taken; } cursor = taken.next; continue; } if (arg.startsWith('--')) { return { error: `unknown flag ${arg}` }; } target.positional.push(arg); cursor += 1; } return target; } function fetchUsage(parsed: FetchFlags): string { if (parsed.positional.length !== 1) { return 'fetch requires exactly one '; } if (parsed.version === undefined) { return 'fetch requires --version '; } if (parsed.cache === undefined) { return 'fetch requires --cache '; } return ''; } function runFetch(command: string, rest: readonly string[]): number { const parsed = parseFetchArgs(rest); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } const usageError = fetchUsage(parsed); if (usageError !== '') { emit(failEnvelope(command, 'USAGE', usageError)); return ExitCode.Usage; } const source = parsed.positional[0] ?? ''; const version = parsed.version ?? ''; const cache = parsed.cache ?? ''; const result = fetchSpec(source, cache, version); const data = { source, version, cache, files: result.files, errors: result.diagnostics }; if (!result.ok) { return emitValidationFailure(command, data, result.diagnostics.length); } emit(okEnvelope(command, data)); return ExitCode.Ok; } function runVerify(command: string, rest: readonly string[]): number { const parsed = parseFetchArgs(rest); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } if ( parsed.version === undefined || parsed.cache === undefined || parsed.positional.length !== 0 ) { emit(failEnvelope(command, 'USAGE', 'verify requires --version --cache ')); return ExitCode.Usage; } const result = verifyCache(parsed.cache, parsed.version); const data = { version: parsed.version, cache: parsed.cache, files: result.files, errors: result.diagnostics, }; if (!result.ok) { return emitValidationFailure(command, data, result.diagnostics.length); } emit(okEnvelope(command, data)); return ExitCode.Ok; } const AUDIT_FLAGS: Readonly< Record > = { '--spec-root': 'spec-root', '--out': 'out', '--generated-at': 'generated-at', '--profile': 'profile', '--preset': 'preset', '--spec-version': 'spec-version', }; interface AuditFlags { root: string; out?: string; generatedAt?: string; specVersion?: string; profiles: string[]; presets: string[]; positional: string[]; } function takeAuditFlag( args: readonly string[], cursor: number, target: AuditFlags, arg: string, ): { next: number } | { error: string } { const flag = AUDIT_FLAGS[arg]; const value = args[cursor + 1]; if (flag === undefined || value === undefined) { return { error: `missing value for ${arg}` }; } if (flag === 'spec-root') { target.root = value; } else if (flag === 'out') { target.out = value; } else if (flag === 'generated-at') { target.generatedAt = value; } else if (flag === 'spec-version') { target.specVersion = value; } else if (flag === 'profile') { target.profiles.push(value); } else { target.presets.push(value); } return { next: cursor + 2 }; } function parseAuditArgs(args: readonly string[]): AuditFlags | { error: string } { const target: AuditFlags = { root: 'spec', profiles: [], presets: [], positional: [] }; let cursor = 0; while (cursor < args.length) { const arg = args[cursor] ?? ''; if (AUDIT_FLAGS[arg] !== undefined) { const taken = takeAuditFlag(args, cursor, target, arg); if ('error' in taken) { return taken; } cursor = taken.next; continue; } if (arg.startsWith('--')) { return { error: `unknown flag ${arg}` }; } target.positional.push(arg); cursor += 1; } return target; } const RELEASE_FLAGS: Readonly> = { '--version': 'version', '--out': 'out', }; interface ReleaseFlags { version?: string; out?: string; positional: string[]; } function takeReleaseFlag( args: readonly string[], cursor: number, target: ReleaseFlags, arg: string, ): { next: number } | { error: string } { const flag = RELEASE_FLAGS[arg]; const value = args[cursor + 1]; if (flag === undefined || value === undefined) { return { error: `missing value for ${arg}` }; } target[flag] = value; return { next: cursor + 2 }; } function parseReleaseArgs(args: readonly string[]): ReleaseFlags | { error: string } { const target: ReleaseFlags = { positional: [] }; let cursor = 0; while (cursor < args.length) { const arg = args[cursor] ?? ''; if (RELEASE_FLAGS[arg] !== undefined) { const taken = takeReleaseFlag(args, cursor, target, arg); if ('error' in taken) { return taken; } cursor = taken.next; continue; } if (arg.startsWith('--')) { return { error: `unknown flag ${arg}` }; } target.positional.push(arg); cursor += 1; } return target; } function runRelease(command: string, rest: readonly string[]): number { const parsed = parseReleaseArgs(rest); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } const specRoot = parsed.positional[0]; const version = parsed.version; const out = parsed.out; if ( specRoot === undefined || parsed.positional.length !== 1 || version === undefined || out === undefined ) { emit( failEnvelope(command, 'USAGE', 'release requires --version --out '), ); return ExitCode.Usage; } const result = buildRelease(specRoot, version, out); const data = { spec_root: specRoot, version, out, files: result.files, errors: result.diagnostics, }; if (!result.ok) { return emitValidationFailure(command, data, result.diagnostics.length); } emit(okEnvelope(command, data)); return ExitCode.Ok; } function runAuditCommand(command: string, rest: readonly string[]): number { const parsed = parseAuditArgs(rest); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } const projectDir = parsed.positional[0]; const out = parsed.out; if (projectDir === undefined || parsed.positional.length !== 1 || out === undefined) { emit(failEnvelope(command, 'USAGE', 'audit requires and --out ')); return ExitCode.Usage; } const generatedAt = parsed.generatedAt ?? new Date().toISOString().slice(0, 10); const result = runAudit({ projectDir, specRoot: parsed.root, profileIds: parsed.profiles, presetIds: parsed.presets, generatedAt, specVersion: parsed.specVersion, }); if (!result.ok || result.report === undefined) { return emitValidationFailure( command, { project: projectDir, errors: result.diagnostics }, result.diagnostics.length, ); } mkdirSync(path.dirname(out), { recursive: true }); writeAuditReport(result, out); emit( okEnvelope(command, { project: projectDir, out, summary: result.report['summary'], }), ); return ExitCode.Ok; } function runManifest(command: string, rest: readonly string[]): number { const [sub, ...args] = rest; if (sub !== 'validate') { emit(failEnvelope(command, 'USAGE', 'manifest requires the subcommand validate')); return ExitCode.Usage; } const parsed = parseSpecArgs(args); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } const file = parsed.positional[0]; if (file === undefined || parsed.positional.length !== 1) { emit(failEnvelope(command, 'USAGE', 'manifest validate requires exactly one manifest file')); return ExitCode.Usage; } const result = validateManifest(file, parsed.root); const data = { file, spec_root: parsed.root, errors: result.diagnostics }; if (result.ok) { emit(okEnvelope(command, data)); return ExitCode.Ok; } emit({ ok: false, command, data, error: { code: 'VALIDATION_FAILED', message: `${String(result.diagnostics.length)} diagnostic(s)`, }, }); return ExitCode.ValidationFailed; } function runReportRender(parsed: { file: string; out: string | undefined }): number { const out = parsed.out; if (out === undefined) { emit(failEnvelope('report', 'USAGE', 'report render requires --out ')); return ExitCode.Usage; } let report: unknown; try { report = JSON.parse(readFileSync(parsed.file, 'utf8')); } catch { emit(failEnvelope('report', 'READ_ERROR', `report file ${parsed.file} is not readable JSON`)); return ExitCode.ValidationFailed; } if (!isRecord(report)) { emit(failEnvelope('report', 'READ_ERROR', 'report must be a JSON object')); return ExitCode.ValidationFailed; } mkdirSync(path.dirname(out), { recursive: true }); writeFileSync(out, renderReport(report), 'utf8'); emit(okEnvelope('report', { file: parsed.file, out })); return ExitCode.Ok; } function runReport(command: string, rest: readonly string[]): number { const [sub, ...args] = rest; if (sub !== 'validate' && sub !== 'render') { emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate or render')); return ExitCode.Usage; } const parsed = parseReportArgs(args); if ('error' in parsed) { emit(failEnvelope(command, 'USAGE', parsed.error)); return ExitCode.Usage; } if (sub === 'render') { return runReportRender(parsed); } const result = validateReport(parsed.file, parsed.specRoot); const data = { file: parsed.file, spec_root: parsed.specRoot, errors: result.diagnostics }; if (result.ok) { emit(okEnvelope(command, data)); return ExitCode.Ok; } emit({ ok: false, command, data, error: { code: 'VALIDATION_FAILED', message: `${String(result.diagnostics.length)} diagnostic(s)`, }, }); return ExitCode.ValidationFailed; } function runValidate(command: string, rest: readonly string[]): number { const [root] = rest; if (root === undefined || root.startsWith('--')) { emit(failEnvelope(command, 'USAGE', 'validate requires a spec root path')); return ExitCode.Usage; } const result = validateSpec(root); const data = { root, files: result.files, errors: result.diagnostics }; if (result.ok) { emit(okEnvelope(command, data)); return ExitCode.Ok; } emit({ ok: false, command, data, error: { code: 'VALIDATION_FAILED', message: `${String(result.diagnostics.length)} diagnostic(s)`, }, }); return ExitCode.ValidationFailed; } const COMMAND_HANDLERS: Readonly number>> = { version: () => { const info = readPackageInfo(); emit(okEnvelope('version', { name: info.name, version: info.version })); return ExitCode.Ok; }, profile: (rest) => runProfile('profile', rest), validate: (rest) => runValidate('validate', rest), spec: (rest) => runSpec('spec', rest), manifest: (rest) => runManifest('manifest', rest), report: (rest) => runReport('report', rest), fetch: (rest) => runFetch('fetch', rest), verify: (rest) => runVerify('verify', rest), audit: (rest) => runAuditCommand('audit', rest), release: (rest) => runRelease('release', rest), }; export function run(argv: readonly string[]): number { const [command, ...rest] = argv; if (command === undefined) { emit(failEnvelope('none', 'USAGE', USAGE_MESSAGE)); return ExitCode.Usage; } const handler = COMMAND_HANDLERS[command]; if (handler !== undefined) { return handler(rest); } emit(failEnvelope(command, 'USAGE', USAGE_MESSAGE)); return ExitCode.Usage; } export function main(argv: readonly string[] = process.argv.slice(2)): void { process.exitCode = run(argv); } main();