### Install snapshot-review with npm Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md Install snapshot-review as a dev dependency. Requires Node >= 20.6 and has no runtime dependencies. ```sh npm install --save-dev snapshot-review ``` -------------------------------- ### writeAccepted basic example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Basic usage of writeAccepted. Pass a file path and a Map of keys to values. The example writes a single accepted snapshot entry. ```ts import { writeAccepted } from 'snapshot-review'; writeAccepted('./test/api.test.snapshot', new Map([ ['GET /users 1', JSON.stringify({ id: 'usr_1', name: 'Priya' }, null, 2)], ])); ``` -------------------------------- ### Run tests and build Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md Commands for running the test suite and example. The first command runs the full suite with Node's test runner, requiring Node 24+ for type stripping. The second runs the diff demo example. The third builds and runs the distribution tests, which is what CI runs against Node 20 and 22. ```sh node --test "test/*.test.ts" # full suite, needs node 24+ for type stripping node examples/diff-demo.ts npm run build && npm run test:dist # what CI runs against node 20 and 22 ``` -------------------------------- ### pruneKeys basic example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Basic usage of pruneKeys. Pass a file path and a Set of keys to delete. The example removes two keys from a snapshot file. ```ts import { pruneKeys } from 'snapshot-review'; pruneKeys('./test/legacy.test.snapshot', new Set(['deleted test 1', 'deleted test 2'])); ``` -------------------------------- ### Round-trip example: parse, edit blocks, serialize Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/parser.md Example showing a round-trip: parse a snapshot file, edit the blocks in place (replacing the value for a specific key), and serialize back. The `apply.md` module's `writeAccepted`/`pruneKeys` use this exact pattern and always re-parse an existing file before writing. ```ts import { parseSnapshotFile, serializeSnapshotFile } from 'snapshot-review'; const file = parseSnapshotFile(oldSource, 'test.snapshot'); // Replace the value of one key, in place: file.blocks = file.blocks.map((b) => b.key === 'GET /users 1' ? { ...b, value: JSON.stringify(newBody, null, 2) } : b ); const nextSource = serializeSnapshotFile(file); ``` -------------------------------- ### pruneKeys with reviewSnapshots Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Example showing how to prune all stale entries from a review. Filters entries with status 'stale' and calls pruneKeys per file. ```ts import { reviewSnapshots, pruneKeys } from 'snapshot-review'; const { files } = reviewSnapshots({ cwd: '.', cmd: 'node --test' }); for (const file of files) { const stale = file.entries.filter((e) => e.status === 'stale').map((e) => e.key); if (stale.length > 0) { pruneKeys(file.relPath, new Set(stale)); } } ``` -------------------------------- ### diffLines large input fallback example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/diff.md Example triggering the coarse fallback path when the line-product exceeds 4 million cells, and iterating over the result to print added lines. ```ts import { diffLines } from 'snapshot-review'; // >4M cells of line-product: e.g. 3000 lines each. Takes the coarse path. const big = diffLines('line\n'.repeat(3000), 'line\n'.repeat(3000) + 'extra\n'); for (const line of big) { if (line.type === 'add') console.log(`new: ${line.text}`); } ``` -------------------------------- ### formatDiff basic example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/diff.md Basic usage of formatDiff with default options and with context 1 and color disabled. ```ts import { formatDiff } from 'snapshot-review'; const oldValue = JSON.stringify({ seats: 12, sms: false }, null, 2); const newValue = JSON.stringify({ seats: 15, sms: true }, null, 2); console.log(formatDiff(oldValue, newValue)); // color auto console.log(formatDiff(oldValue, newValue, { context: 1, color: false })); // plain ``` -------------------------------- ### diffLines basic example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/diff.md Basic usage of diffLines showing the returned array of DiffLine objects for a simple change. ```ts import { diffLines } from 'snapshot-review'; const delta = diffLines('a\nb\nc\n', 'a\nx\nc\n'); // [{ type: 'equal', text: 'a' }, { type: 'remove', text: 'b' }, { type: 'add', text: 'x' }, { type: 'equal', text: 'c' }] ``` -------------------------------- ### parseArgs usage example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/cli.md Example of parsing CLI arguments with parseArgs. The comment shows the resulting object. The import path is module-level, not from the package exports. ```ts import { parseArgs } from './src/cli.ts'; // module-level; not in the package exports const args = parseArgs(['--prune', '-y', '--cmd', 'node --test --test-name-pattern=api']); // { mode: 'prune', cmd: 'node --test --test-name-pattern=api', cwd: process.cwd(), yes: true, help: false, version: false } ``` -------------------------------- ### writeAccepted with reviewSnapshots Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Example showing how to accept only entries that were actually reviewed. Iterates over reviewSnapshots results, collects changed entries that pass a custom check, and calls writeAccepted per file. Includes a helper function looksCorrectToMe that filters out values containing 'undefined'. ```ts import { reviewSnapshots, writeAccepted } from 'snapshot-review'; const { files } = reviewSnapshots({ cwd: '.', cmd: 'node --test' }); const accepted = new Map(); for (const file of files) { for (const entry of file.entries) { if (entry.status === 'changed' && looksCorrectToMe(entry)) { accepted.set(entry.key, entry.newValue ?? ''); } } if (accepted.size > 0) { writeAccepted(file.relPath, accepted); // per-file, like the CLI does accepted.clear(); } } function looksCorrectToMe(entry: { key: string; newValue?: string }): boolean { return Boolean(entry.newValue) && !entry.newValue!.includes('undefined'); } ``` -------------------------------- ### removeFile with reviewSnapshots Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Example showing how to remove orphaned snapshot files. Iterates over orphanedFiles from reviewSnapshots and calls removeFile for each. ```ts import { reviewSnapshots, removeFile } from 'snapshot-review'; const { orphanedFiles } = reviewSnapshots({ cwd: '.', cmd: 'node --test' }); for (const orphan of orphanedFiles) { removeFile(orphan.relPath); } ``` -------------------------------- ### snapshot-review CLI usage Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md CLI usage examples for snapshot-review. The --ci flag exits with code 1 if any snapshot needs attention. The --prune -y flag skips the confirmation prompt. ```sh npx snapshot-review # walk changed/new snapshots one at a time npx snapshot-review --list # print status for every snapshot, no prompts npx snapshot-review --prune # remove stale entries and orphaned files npx snapshot-review --prune -y # same, no confirmation prompt npx snapshot-review --ci # like --list, but exits 1 if anything needs attention ``` -------------------------------- ### Catching all library errors Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/errors.md Example showing how to catch TestRunFailedError, SnapshotReviewError, and UnparsableSnapshotFileError when calling reviewSnapshots and parseSnapshotFile. ```TypeScript import { reviewSnapshots, SnapshotReviewError, TestRunFailedError, parseSnapshotFile, UnparsableSnapshotFileError, } from 'snapshot-review'; try { reviewSnapshots({ cwd: '.', cmd: 'node --test' }); } catch (err) { if (err instanceof TestRunFailedError) { console.error(`tests could not run: code=${err.exitCode}`); } else if (err instanceof SnapshotReviewError) { console.error(`snapshot-review error: ${err.message}`); } else { throw err; } } try { parseSnapshotFile(source, 'x.snapshot'); } catch (err) { if (err instanceof UnparsableSnapshotFileError) { console.error(`${err.filePath}@${err.offset}: ${err.message}`); } } ``` -------------------------------- ### Scripted piped input example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/prompt.md Shows the scripted (piped) input case this module exists for: two answers are pushed before the second ask() call. Unlike readline/promises' question(), this prompter delivers the buffered line. The first ask returns 'yes', the second returns 'no' (already buffered). ```typescript import { Readable, Writable } from 'node:stream'; import { createPrompter } from './src/prompt.ts'; // Two answers piped in before the second ask() call — readline/promises' // question() would hang here; this prompter delivers the buffered line. const lines = new Readable({ read() {} }); lines.push('yes\n'); lines.push('no\n'); lines.push(null); const prompter = createPrompter(lines, process.stdout); const first = await prompter.ask('Delete these? [y/N] '); // 'yes' const second = await prompter.ask('Delete orphan? [y/N] '); // 'no' (was already buffered) prompter.close(); ``` -------------------------------- ### Error handling with TestRunFailedError Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/runner.md Error handling for reviewSnapshots. Catches TestRunFailedError when the command fails to start or is signal-killed, printing the command, exit code, and stderr. Other errors are rethrown. ```ts import { reviewSnapshots, TestRunFailedError } from 'snapshot-review'; try { reviewSnapshots({ cmd: 'nonexistent-binary' }); } catch (err) { if (err instanceof TestRunFailedError) { console.error(`command "${err.command}" exited with code ${err.exitCode}`); console.error(err.stderr); } else { throw err; } } ``` -------------------------------- ### CLI shell usage examples Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/cli.md Shell commands to invoke the CLI in different modes. --prune -y skips the prompt. Use --ci to check status; it returns non-zero if changes are needed. ```sh npx snapshot-review # interactive review npx snapshot-review --list # report only npx snapshot-review --prune -y # delete stale + orphaned, no prompt npx snapshot-review --ci && echo "snapshots clean" ``` -------------------------------- ### Catch and handle snapshot-review errors Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/errors.md Shows how to catch and handle errors thrown by the snapshot-review library. Use the catch-all SnapshotReviewError for general handling, or distinguish between TestRunFailedError, UnparsableSnapshotFileError, and UnrecognizedEscapeError for specific cases. The example includes a narrow catch around parseSnapshotFile to diagnose parsing failures without writing the file back. ```ts import { SnapshotReviewError, UnparsableSnapshotFileError, UnrecognizedEscapeError, TestRunFailedError, reviewSnapshots, parseSnapshotFile, } from 'snapshot-review'; // 1) Single catch-all for the whole library: try { reviewSnapshots({ cwd: '.', cmd: 'node --test' }); } catch (err) { if (err instanceof SnapshotReviewError) { console.error(`snapshot-review: ${err.message}`); } throw err; } // 2) Distinguishing the three concrete cases: function handle(err: unknown): void { if (err instanceof TestRunFailedError) { // The isolated run never happened: command, exitCode (null = killed), stderr. console.error(`command ${err.command} failed (${err.exitCode})`); } else if (err instanceof UnparsableSnapshotFileError) { console.error(`file ${err.filePath} is not a parseable node:test .snapshot file (offset ${err.offset})`); } else if (err instanceof UnrecognizedEscapeError) { console.error('unrecognized escape — file was probably not written by node:test'); } } // 3) Narrow catching around parsing: try { const parsed = parseSnapshotFile(source, 'a.test.snapshot'); // ... use parsed ... } catch (err) { if (err instanceof UnparsableSnapshotFileError) { // Diagnose: read `err.filePath`, `err.offset`, and inspect the source // around that byte offset. Do not write the file back. } } ``` -------------------------------- ### Error handling for parseSnapshotFile Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/parser.md Demonstrates catching the two error types thrown by parseSnapshotFile: UnparsableSnapshotFileError and UnrecognizedEscapeError, with example error messages. ```ts import { parseSnapshotFile, UnparsableSnapshotFileError, UnrecognizedEscapeError } from 'snapshot-review'; try { parseSnapshotFile('// a comment\n', 'x.snapshot'); } catch (err) { if (err instanceof UnparsableSnapshotFileError) { console.error(`cannot safely parse ${err.filePath} at offset ${err.offset}`); } else if (err instanceof UnrecognizedEscapeError) { console.error('file contains an escape sequence node:test never emits'); } } ``` -------------------------------- ### Generate random suffix with randomSuffix Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/runner.md Example usage of randomSuffix to generate a random suffix string. The output is an 8-character hex string. ```ts import { randomSuffix } from 'snapshot-review'; console.log(randomSuffix()); // e.g. "9f2c1a4b" ``` -------------------------------- ### formatDiff suppress color for log file Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/diff.md Example of writing a color-suppressed diff to a file using formatDiff with color: false. ```ts import fs from 'node:fs'; import { formatDiff } from 'snapshot-review'; const patch = formatDiff(before, after, { color: false }); fs.writeFileSync('snapshot.diff', patch + '\n', 'utf8'); ``` -------------------------------- ### writeAccepted function signature Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Signature of writeAccepted. Writes accepted values into a real .snapshot file, replacing existing blocks and inserting new ones. Creates the file if it doesn't exist, sorts blocks by key.localeCompare, and assigns start: -1, end: -1 to new blocks. ```ts export function writeAccepted(filePath: string, accepted: Map): void ``` -------------------------------- ### main() Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/cli.md Main entry point that parses arguments, handles help/version, and dispatches to review, list, prune, or CI modes. Returns a process exit code. ```APIDOC ## main() ### Description Main entry point that parses arguments, handles help/version, and dispatches to review, list, prune, or CI modes. Returns a process exit code. ### Method FUNCTION ### Endpoint main(): Promise ### Parameters None ### Return Value - **Promise** - Process exit code: 0 for success (including nothing to do), 1 for CI failures or errors. ### Exit Codes | Code | Meaning | |------|---------| | 0 | Success (including "Nothing to prune", "Nothing to review", list/version/help). | | 1 | `--ci` mode with anything changed/new/stale/orphaned; or reviewSnapshots threw. | ### Behavior - **--help**: Prints HELP text and returns 0. - **--version**: Reads package.json version and prints it. - **review (default)**: Interactive review of changed/new snapshots, prompts for accept/reject/skip/quit, handles stale/orphaned deletion. - **list**: Prints snapshot status report. - **prune**: Deletes stale and orphaned snapshots (with confirmation unless --yes). - **ci**: Prints summary and returns 1 if any changes exist, otherwise 0. ### Request Example ```sh npx snapshot-review # interactive review npx snapshot-review --list # report only npx snapshot-review --prune -y # delete stale + orphaned, no prompt npx snapshot-review --ci && echo "snapshots clean" ``` ### Response #### Success Response (200) - **number** - Exit code. #### Response Example ```json 0 ``` ### Error Handling - **Unrecognized argument**: Writes message to stderr and exits with code 1. - **Piped stdin**: Pending prompts resolve to '' (skip) to avoid deadlock. ``` -------------------------------- ### Unknown flag error example Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/cli.md Example of error handling for an unknown flag. The error message is written to stderr and the process exits with code 1. ```sh $ npx snapshot-review --nope # Unrecognized argument: --nope. Run with --help for usage. # (Message is written to stderr; process exits 1.) ``` -------------------------------- ### Basic parse and read keys/values Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/parser.md Shows how to read a snapshot file and iterate over its blocks, printing each key and value, and the leading whitespace. ```ts import fs from 'node:fs'; import { parseSnapshotFile } from 'snapshot-review'; const source = fs.readFileSync('./test/example.test.snapshot', 'utf8'); const file = parseSnapshotFile(source, './test/example.test.snapshot'); for (const block of file.blocks) { console.log(`${block.key}: ${block.value}`); } console.log(`leading whitespace: ${JSON.stringify(file.leading)}`); ``` -------------------------------- ### Basic review with reviewSnapshots Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/runner.md Basic usage of reviewSnapshots to run tests and print snapshot entries, orphaned files, and the tail of the run output. Requires a project with a package.json and a test command. ```ts import { reviewSnapshots } from 'snapshot-review'; const result = reviewSnapshots({ cwd: '.', cmd: 'node --test' }); for (const file of result.files) { for (const entry of file.entries) { console.log(`${file.relPath} :: ${entry.key} = ${entry.status}`); } } for (const orphan of result.orphanedFiles) { console.log(`orphaned file: ${orphan.relPath}`); } console.log(`run output tail:\n${result.runOutput}`); ``` -------------------------------- ### createPrompter(input, output) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/prompt.md Creates a Prompter instance that writes prompts to the given output stream and reads answers from the given input stream. It handles piped, non-interactive stdin correctly by buffering lines. ```APIDOC ## createPrompter(input, output) ### Description Creates a `Prompter` instance. Prompts are written with `output.write(promptText)` (no newline); answers are delivered exactly as read. The `'close'` event flushes all pending waiters with `''` so callers never hang waiting on a closed stream. ### Signature ```ts export function createPrompter(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Prompter ``` ### Parameters - `input` (NodeJS.ReadableStream) - Required - Usually `process.stdin`. - `output` (NodeJS.WritableStream) - Required - Usually `process.stdout`. ### Returns `Prompter` - A prompter instance. ### Source `src/prompt.ts:22` ### Example — basic (as the CLI uses it) ```ts import { createPrompter } from './src/prompt.ts'; // internal module const prompter = createPrompter(process.stdin, process.stdout); try { const answer = (await prompter.ask('Accept? [a]ccept / [r]eject / [s]kip / [q]uit ')).trim().toLowerCase(); if (answer === 'a' || answer === 'accept') accept(); } finally { prompter.close(); } ``` ### Example — scripted (piped) input ```ts import { Readable, Writable } from 'node:stream'; import { createPrompter } from './src/prompt.ts'; // Two answers piped in before the second ask() call — readline/promises' // question() would hang here; this prompter delivers the buffered line. const lines = new Readable({ read() {} }); lines.push('yes\n'); lines.push('no\n'); lines.push(null); const prompter = createPrompter(lines, process.stdout); const first = await prompter.ask('Delete these? [y/N] '); // 'yes' const second = await prompter.ask('Delete orphan? [y/N] '); // 'no' (was already buffered) prompter.close(); ``` ``` -------------------------------- ### ReviewOptions interface Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/types.md Options for `reviewSnapshots(options?: ReviewOptions)`. `cwd` sets the project root, defaulting to `process.cwd()`. `cmd` is the test command as typed in a shell (default `"node --test"`); `--test-update-snapshots` is appended automatically when the library runs it inside an isolated copy. `ignore` lists extra directory basenames to exclude when copying; `node_modules`, `.git`, `dist`, and `.DS_Store` are always excluded. Mapped from CLI flags `--cmd` and `--cwd`. ```typescript export interface ReviewOptions { /** Project root to review. Default `process.cwd()`. */ cwd?: string; /** * The test command to run, as it would be typed in a shell, e.g. * `"node --test"`. `--test-update-snapshots` is appended automatically * when this library runs it (always inside an isolated copy — see * {@link reviewSnapshots}). Default `"node --test"`. */ cmd?: string; /** Extra directory names to exclude when copying the project. Always excludes `node_modules`, `.git`, `dist`. */ ignore?: string[]; } ``` -------------------------------- ### CLI usage text (HELP constant) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/configuration.md Usage text printed by the CLI's --help flag. Lists the four modes (interactive, --list, --prune, --ci) and the available options with their defaults. ```text Usage: npx snapshot-review Interactive: review each changed/new snapshot, accept/reject/skip npx snapshot-review --list Report what snapshots exist and which are stale, non-interactively npx snapshot-review --prune Delete snapshots no test references any more npx snapshot-review --ci Non-interactive report; exits 1 if anything needs review Options: --cmd Test command to run (default "node --test") --cwd Project root (default: current directory) -y, --yes Don't prompt for confirmation (use with --prune) -h, --help Show this help --version Show the installed version ``` -------------------------------- ### Accept/reject loop with formatDiff and writeAccepted Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/runner.md Interactive accept/reject loop for changed snapshot entries. Uses formatDiff to display changes and writeAccepted to persist accepted values. Requires a prompt implementation and the snapshot-review package. ```ts import { reviewSnapshots, formatDiff, writeAccepted } from 'snapshot-review'; const result = reviewSnapshots({ cmd: 'node --test', cwd: '.' }); for (const file of result.files) { const accepted = new Map(); for (const entry of file.entries) { if (entry.status !== 'changed') continue; console.log(formatDiff(entry.oldValue ?? '', entry.newValue ?? '')); const answer = await prompt(); // your own input logic if (answer === 'a') accepted.set(entry.key, entry.newValue ?? ''); } if (accepted.size > 0) writeAccepted(file.relPath, accepted); } ``` -------------------------------- ### SnapshotBlock interface Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/parser.md Defines the shape of a parsed snapshot block: the decoded test name, the decoded value, and byte offsets marking the start and end of the block in the source file. ```ts export interface SnapshotBlock { /** The decoded test name, e.g. `"outer suite > inner case 1"`. */ key: string; /** The decoded value — exactly what Node compares with `strictEqual`. */ value: string; /** Byte offset of `exports[` in the source. */ start: number; /** Byte offset just past this block's trailing blank line(s), i.e. where the next block (or EOF) begins. */ end: number; } ``` -------------------------------- ### writeAccepted(filePath, accepted) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/apply.md Writes accepted snapshot values to a file, replacing or inserting blocks as needed. ```APIDOC ## `writeAccepted(filePath, accepted)` ### Description Writes accepted values into a real `.snapshot` file, replacing blocks for existing keys and inserting new ones. Creates the file if it doesn't exist. ### Method Function ### Signature `writeAccepted(filePath: string, accepted: Map): void` ### Parameters - `filePath` (string) - Required - Path to the real `.snapshot` file to write. - `accepted` (Map) - Required - Keys to (new) values to accept. Existing keys are replaced; new keys inserted. ### Return `void`. Creates the file if it does not exist (starting from `leading: ''` and no blocks). Blocks are written sorted by `key.localeCompare`. Newly inserted blocks are given `start: -1, end: -1` since they have no source offsets. ### Throws `UnparsableSnapshotFileError` / `UnrecognizedEscapeError` if the existing file does not match Node's writer format. ### Example ```ts import { writeAccepted } from 'snapshot-review'; writeAccepted('./test/api.test.snapshot', new Map([ ['GET /users 1', JSON.stringify({ id: 'usr_1', name: 'Priya' }, null, 2)], ])); ``` ``` -------------------------------- ### snapshot-review CLI usage Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md Shows the four CLI modes of snapshot-review: interactive review, listing snapshots, pruning stale ones, and a CI-friendly non-interactive report that exits 1 when attention is needed. ```bash npx snapshot-review # interactive: show each failing snapshot, accept/reject/skip npx snapshot-review --list # what snapshots exist, which are stale npx snapshot-review --prune # delete snapshots no test references any more npx snapshot-review --ci # non-interactive report; exits 1 if anything needs attention ``` -------------------------------- ### CLI Commands Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md Command-line interface for reviewing, listing, pruning, and checking snapshots. ```APIDOC ## CLI Commands ### Description Command-line interface for reviewing, listing, pruning, and checking snapshots. ### Usage ```sh npx snapshot-review # walk changed/new snapshots one at a time npx snapshot-review --list # print status for every snapshot, no prompts npx snapshot-review --prune # remove stale entries and orphaned files npx snapshot-review --prune -y # same, no confirmation prompt npx snapshot-review --ci # like --list, but exits 1 if anything needs attention ``` ### Options - `--list` - Print status for every snapshot, no prompts. - `--prune` - Remove stale entries and orphaned files. - `-y` - Skip confirmation prompt when used with `--prune`. - `--ci` - Like `--list`, but exits 1 if anything needs attention. ### Interactive Mode Shows a line-level diff for each changed or new snapshot and asks `[a]ccept / [r]eject / [s]kip / [q]uit`. Accepting writes only that entry back to the real `.snapshot` file. After changed/new entries, if any snapshots are stale or orphaned, asks once per file whether to delete them. ``` -------------------------------- ### ReviewOptions Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/runner.md Options for configuring the snapshot review process. ```APIDOC ## ReviewOptions ### Description Configuration options for the `reviewSnapshots` function. ### Fields - **cwd** (string) - Optional - Project root to review. Default `process.cwd()`. - **cmd** (string) - Optional - The test command to run, e.g. `"node --test"`. `--test-update-snapshots` is appended automatically. Default `"node --test"`. - **ignore** (string[]) - Optional - Extra directory names to exclude when copying the project. Always excludes `node_modules`, `.git`, `dist`. ### Example ```ts const options: ReviewOptions = { cwd: '/path/to/project', cmd: 'node --test', ignore: ['build'] }; ``` ``` -------------------------------- ### Basic prompter usage Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/prompt.md Basic usage as the CLI does: create a prompter on stdin/stdout, ask a question, trim and lowercase the answer, then close in a finally block. The prompt is written without a newline. ```typescript import { createPrompter } from './src/prompt.ts'; // internal module const prompter = createPrompter(process.stdin, process.stdout); try { const answer = (await prompter.ask('Accept? [a]ccept / [r]eject / [s]kip / [q]uit ')).trim().toLowerCase(); if (answer === 'a' || answer === 'accept') accept(); } finally { prompter.close(); } ``` -------------------------------- ### serializeSnapshotFile function signature and parameter type Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/parser.md Function signature for serializing a full snapshot file. The parameter type is `Pick`, with the inline expansion showing the shape: `leading` as a string and `blocks` as an array of `SnapshotBlock` objects. Returns the full source text matching Node's writer: `leading` verbatim, then each block with one blank line between entries and none after the last. ```ts export function serializeSnapshotFile(file: Pick): string ``` ```ts { leading: string; blocks: SnapshotBlock[]; // { key: string; value: string; start: number; end: number } } ``` -------------------------------- ### reviewSnapshots(options) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/runner.md Function that runs the test command with snapshot update flag in a temporary copy and returns a review result. ```APIDOC ## reviewSnapshots(options) ### Description Runs the test command with `--test-update-snapshots` in a temporary copy of the project and returns a `ReviewResult` describing which snapshot files changed, which are new, and which are orphaned. The real project is never modified. ### Method Function ### Signature `reviewSnapshots(options: ReviewOptions = {}): ReviewResult` ### Parameters - `options` (ReviewOptions) - Optional - Default `{}` - See `ReviewOptions` for details. ### Return `ReviewResult` — one `SnapshotFileDiff` per `.snapshot` path that exists in either the real project or the fresh run, one `OrphanedFile` per real `.snapshot` file with no counterpart at all in the fresh run, and the raw run output. ### Throws `TestRunFailedError` when the spawned command fails to start or is signal-killed (`result.error` set). If the command runs and merely has failing tests, no error is thrown — a non-zero exit alone does **not** throw; only a spawn-level failure does. ### Mechanics and side effects - Creates a temp dir `snapshot-review-*` under `os.tmpdir()` and deletes it in `finally` — always, including on error. The real project is never written to. - `copyProject` uses `fs.cpSync` with a filter that excludes every basename in the ignore set **and every `*.snapshot` file**. Existing `.snapshot` files are deliberately not copied — a file's presence after the update-flag run is exactly how "this test ran" is told apart from "this test never ran". - `linkNodeModules` symlinks the project's `node_modules` into the copy (`'junction'`); if the symlink fails, falls back to a real recursive copy. - The command is run via `spawnSync(`${cmd} --test-update-snapshots`, { cwd, shell: true, encoding: 'utf8', env })`. The env is a copy of `process.env` with `NODE_TEST_CONTEXT` and `NODE_TEST_WORKER_ID` deleted so that invoking this from inside a `node --test` process doesn't make the child think it's a recursive `run()` call and skip all files. - `stale` is relative to *this* run of `cmd`: a filtered command (`--test-name-pattern`, a narrower glob, `.only`) makes untouched-but-real snapshots look identical to deleted ones. - The suite really executes (in the copy) — any side effects the tests have (network calls, writes outside the project) happen for real. ### Example — basic review ```ts import { reviewSnapshots } from 'snapshot-review'; const result = reviewSnapshots({ cwd: '.', cmd: 'node --test' }); for (const file of result.files) { for (const entry of file.entries) { console.log(`${file.relPath} :: ${entry.key} = ${entry.status}`); } } for (const orphan of result.orphanedFiles) { console.log(`orphaned file: ${orphan.relPath}`); } console.log(`run output tail:\n${result.runOutput}`); ``` ### Example — accept/reject loop (changed entries only) ```ts import { reviewSnapshots, formatDiff, writeAccepted } from 'snapshot-review'; const result = reviewSnapshots({ cmd: 'node --test', cwd: '.' }); for (const file of result.files) { const accepted = new Map(); for (const entry of file.entries) { if (entry.status !== 'changed') continue; console.log(formatDiff(entry.oldValue ?? '', entry.newValue ?? '')); const answer = await prompt(); // your own input logic if (answer === 'a') accepted.set(entry.key, entry.newValue ?? ''); } if (accepted.size > 0) writeAccepted(file.relPath, accepted); } ``` ### Example — error handling ```ts import { reviewSnapshots, TestRunFailedError } from 'snapshot-review'; try { reviewSnapshots({ cmd: 'nonexistent-binary' }); } catch (err) { if (err instanceof TestRunFailedError) { console.error(`command "${err.command}" exited with code ${err.exitCode}`); console.error(err.stderr); } else { throw err; } } ``` ``` -------------------------------- ### Check direct invocation and run main with error handling Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/cli.md Guard that runs the snapshot-review CLI only when invoked directly via `npx snapshot-review`, not when imported. Compares `process.argv[1]` with `import.meta.url`; on failure writes the error message to stderr and exits with code 1. ```typescript // Only run when invoked directly (`npx snapshot-review`), not when imported for tests. const invokedDirectly = process.argv[1] && import.meta.url === `file://${process.argv[1]}`; if (invokedDirectly) { main().then( (code) => process.exit(code), (err) => { process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`); process.exit(1); }, ); } ``` -------------------------------- ### snapshot-review diff output Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md snapshot-review's diff for the same two values as Node's output, showing only changed lines with context. Run `node examples/diff-demo.ts` to reproduce. ```text … 4 unchanged lines … "email": "priya@example.com", "role": "admin", "plan": "team", - "seats": 12, + "seats": 15, "createdAt": "2024-01-15T00:00:00.000Z", "settings": { "theme": "dark", "notifications": { "email": true, - "sms": false, + "sms": true, "push": true }, "locale": "en-US" … 7 unchanged lines … ``` -------------------------------- ### reviewSnapshots Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md Programmatic API to review snapshots. ```APIDOC ## reviewSnapshots ### Description Programmatic API to review snapshots. Returns a result object with files and entries. ### Signature ```ts reviewSnapshots(options: { cwd: string; cmd: string }): { files: Array<{ entries: Array<{ status: string; oldValue?: any; newValue?: any }> }> } ``` ### Parameters - `options.cwd` (string) - Required - Working directory. - `options.cmd` (string) - Required - Command to run tests. ### Returns - `result.files` - Array of files, each with `entries` array. Each entry has `status` (e.g., 'changed') and optional `oldValue`/`newValue`. ``` -------------------------------- ### ReviewResult interface (src/runner.ts:49) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/types.md Returned from `reviewSnapshots` and consumed by all four CLI modes. `files` contains per-`.snapshot`-file entry comparisons, `orphanedFiles` lists real files with no counterpart after the fresh run, and `runOutput` holds the raw stdout+stderr tail for diagnostics. ```typescript export interface ReviewResult { files: SnapshotFileDiff[]; orphanedFiles: OrphanedFile[]; /** Raw stdout+stderr tail from the isolated test run, for diagnostics. */ runOutput: string; } ``` -------------------------------- ### parseSnapshotFile(source, filePath) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/parser.md Parses the full text of a Node `.snapshot` file into a `ParsedSnapshotFile` object containing the leading whitespace and all snapshot blocks. Throws errors for any unrecognized syntax instead of guessing. ```APIDOC ## parseSnapshotFile(source, filePath) ### Description Parses the full text of a Node `.snapshot` file into a `ParsedSnapshotFile` object containing the leading whitespace and all snapshot blocks. Throws errors for any unrecognized syntax instead of guessing. ### Signature ```ts export function parseSnapshotFile(source: string, filePath = ''): ParsedSnapshotFile ``` ### Parameters - `source` (string) - Required - Full text of the `.snapshot` file. - `filePath` (string) - Optional - Default: `''` - Used only in error messages; the path to the file being parsed. ### Return Value `ParsedSnapshotFile` - The `leading` whitespace plus every `SnapshotBlock` (decoded key and value, with byte-offset `start`/`end`). ### Throws - `UnparsableSnapshotFileError` - If the text before the first `exports[` is not blank (offset 0); if a position where a block should start does not begin with `exports[`; if a token `]`, `=`, `;` or an opening backtick is missing; or a backtick string runs to end of file without closing. - `UnrecognizedEscapeError` - If a `\` is followed by anything other than `\`, `` ` ``, `$`, or `"`. ### Example ```ts import fs from 'node:fs'; import { parseSnapshotFile } from 'snapshot-review'; const source = fs.readFileSync('./test/example.test.snapshot', 'utf8'); const file = parseSnapshotFile(source, './test/example.test.snapshot'); for (const block of file.blocks) { console.log(`${block.key}: ${block.value}`); } console.log(`leading whitespace: ${JSON.stringify(file.leading)}`); ``` ### Error Handling Example ```ts import { parseSnapshotFile, UnparsableSnapshotFileError, UnrecognizedEscapeError } from 'snapshot-review'; try { parseSnapshotFile('// a comment\n', 'x.snapshot'); } catch (err) { if (err instanceof UnparsableSnapshotFileError) { console.error(`cannot safely parse ${err.filePath} at offset ${err.offset}`); } else if (err instanceof UnrecognizedEscapeError) { console.error('file contains an escape sequence node:test never emits'); } } ``` ``` -------------------------------- ### parseArgs(argv) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/cli.md Parses raw command-line arguments into an Args object with mode, command, working directory, and boolean flags. Throws SnapshotReviewError on unrecognized arguments. ```APIDOC ## parseArgs(argv) ### Description Parses raw command-line arguments into an Args object with mode, command, working directory, and boolean flags. Throws SnapshotReviewError on unrecognized arguments. ### Method FUNCTION ### Endpoint parseArgs(argv: string[]): Args ### Parameters #### Parameters - **argv** (string[]) - Required - Raw argument list, typically process.argv.slice(2). ### Return Value - **Args** - An object with properties: mode ('review' | 'list' | 'prune' | 'ci'), cmd (string), cwd (string), yes (boolean), help (boolean), version (boolean). Defaults: mode='review', cmd='node --test', cwd=process.cwd(), all booleans false. ### Throws - **SnapshotReviewError** - Unrecognized argument: . Run with --help for usage. ### Flag Reference | Flag | Effect | |------|--------| | `--list` | mode = 'list' | | `--prune` | mode = 'prune' | | `--ci` | mode = 'ci' | | `-y`, `--yes` | yes = true | | `-h`, `--help` | help = true | | `--version` | version = true | | `--cmd ` | cmd = next argv item (keeps default if missing) | | `--cwd ` | cwd = next argv item (keeps default if missing) | ### Request Example ```ts import { parseArgs } from './src/cli.ts'; // module-level; not in the package exports const args = parseArgs(['--prune', '-y', '--cmd', 'node --test --test-name-pattern=api']); // { mode: 'prune', cmd: 'node --test --test-name-pattern=api', cwd: process.cwd(), yes: true, help: false, version: false } ``` ### Response #### Success Response (200) - **Args** - Parsed arguments object. #### Response Example ```json { "mode": "prune", "cmd": "node --test --test-name-pattern=api", "cwd": "/current/working/directory", "yes": true, "help": false, "version": false } ``` ``` -------------------------------- ### SnapshotReviewError Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/errors.md Base class for every error this library throws. It is also thrown directly by the CLI's argument parser for unknown flags. ```APIDOC ## SnapshotReviewError ### Description Base class for every error this library throws. It is also thrown directly by the CLI's argument parser for unknown flags. ### Constructor `constructor(message: string)` ### Parameters - **message** (string) - Required - The error message. ### Properties - **name** (string) - The concrete error class name, not "Error". - **message** (string) - The formatted message. ### Usage Catching `SnapshotReviewError` catches every error this library throws. ``` -------------------------------- ### Programmatic API usage Source: https://github.com/agentscope-java/snapshot-review/blob/main/README.md Programmatic API usage for snapshot-review. `parseSnapshotFile` and `serializeSnapshotFile` are also exported for direct `.snapshot` file access without the CLI's accept/reject flow. ```ts import { reviewSnapshots, parseSnapshotFile, diffLines, formatDiff } from 'snapshot-review'; const result = reviewSnapshots({ cwd: '.', cmd: 'node --test' }); for (const file of result.files) { for (const entry of file.entries) { if (entry.status === 'changed') { console.log(formatDiff(entry.oldValue!, entry.newValue!)); } } } ``` -------------------------------- ### formatDiff(oldText, newText, options) Source: https://github.com/agentscope-java/snapshot-review/blob/main/_autodocs/api-reference/diff.md Renders a diff between two strings in unified-diff-style text with context trimming and optional ANSI color. Returns a string with lines prefixed by spaces, plus signs, or minus signs, and collapses runs of unchanged context lines. ```APIDOC ## formatDiff(oldText, newText, options) ### Description Renders a diff between two strings in unified-diff-style text with context trimming and optional ANSI color. Returns a string with lines prefixed by spaces, plus signs, or minus signs, and collapses runs of unchanged context lines. ### Method Function ### Signature ```ts export function formatDiff(oldText: string, newText: string, options: FormatDiffOptions = {}): string ``` ### Parameters - **oldText** (string) - Required - Previous snapshot value. - **newText** (string) - Required - New snapshot value. - **options** (FormatDiffOptions) - Optional - Configuration options. Default `{}`. ### Options - **context** (number) - Optional - Lines of unchanged context to keep around each change. Default 3. - **color** (boolean) - Optional - ANSI color on/off. Default auto: `Boolean(process.stdout?.isTTY) && !process.env['NO_COLOR']`. ### Return `string` — unified-diff-style text: - ` ` for equal context lines (two-space indent), - `+ ` green (add), - `- ` red (remove), - ` … N unchanged line(s) …` (dim) where a run of non-kept context lines is collapsed. If every line is equal it returns the dim literal ` (no differences)` instead of an empty string. ### Example — basic ```ts import { formatDiff } from 'snapshot-review'; const oldValue = JSON.stringify({ seats: 12, sms: false }, null, 2); const newValue = JSON.stringify({ seats: 15, sms: true }, null, 2); console.log(formatDiff(oldValue, newValue)); // color auto console.log(formatDiff(oldValue, newValue, { context: 1, color: false })); // plain ``` ### Example — suppressing color for a log file ```ts import fs from 'node:fs'; import { formatDiff } from 'snapshot-review'; const patch = formatDiff(before, after, { color: false }); fs.writeFileSync('snapshot.diff', patch + '\n', 'utf8'); ``` ```