@headwall/websnapper-cli 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,54 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [1.0.0] - 2026-12-02
10
+
11
+ First release, published to npm as `@headwall/websnapper-cli`:
12
+ `npm install -g @headwall/websnapper-cli@latest`.
13
+
14
+ ### Added
15
+
16
+ - Project scaffold: `wsnap help` and `wsnap version`, `--json` output, option parsing that
17
+ reports every problem at once, and settings read from `WSNAP_*` environment variables
18
+ - `wsnap host add <host>`: stores a host and its API key, read from a hidden prompt or, with
19
+ `--key-stdin`, from stdin. `--no-key` for a host in open auth mode. Adding a host again
20
+ replaces its key and keeps its place in the failover order. The key is checked against the
21
+ host's `/v1/viewports` first; a host that rejects it or can't be reached is not saved (exit 4)
22
+ unless `--no-verify` is given
23
+ - `wsnap host list`: hosts in failover order, keys masked (`wsk_…a1b2`)
24
+ - `wsnap host remove <host>`: by URL or bare host name
25
+ - The host store is written atomically, mode `0600` in a `0700` directory, and is refused if
26
+ other users can access it or change its directory, if it belongs to another user, or if it
27
+ is a symbolic link
28
+ - A key is not sent over plain `http://` (other than to this machine) unless the host was
29
+ added with `--allow-insecure-key`. `/health` is always asked without the key
30
+ - Each command rejects options that don't apply to it
31
+ - `wsnap capture <url>`: takes a screenshot with the first working host, passing through every
32
+ `/v1/snapshot` option. Fails over to the next host only when a host is down, busy, rate
33
+ limited, rejects the key or cuts the image off; a failed or refused target stops at once
34
+ (exit 2 or 3). Writes to a new temporary file beside the output and renames it on success, so
35
+ a failed or interrupted capture never leaves a partial file. An empty image counts as a
36
+ failed host. Without `--output`, names the file
37
+ `wsnap-<host>-<date>-<time>.<ext>` and never overwrites one. `--output -` writes to stdout
38
+ - Combinations the server would refuse (`--quality` with `--format png`, `--width` alone,
39
+ `--viewport` with a size) are caught before any request is made
40
+ - `wsnap status`: every host's state, checking readiness with `/health` and the key with
41
+ `/v1/viewports`
42
+ - `wsnap test`: one line, exit 0 when any host works
43
+ - `wsnap viewports`: the presets of the first working host
44
+ - `--host <host>` on `capture`, `status` and `viewports` to use one host only
45
+ - Ctrl-C stops requests in flight, deletes any `.part` file and exits 130
46
+ - Documentation in `docs/`: getting started, command reference with exit codes, configuration,
47
+ JSON output for scripts and agents, development
48
+ - Control characters in text from a server are shown escaped, so they can't affect the
49
+ terminal
50
+ - `--json` still writes one object if `wsnap` hits a bug (`unexpected_error`, details on
51
+ stderr), and a failed `host add` check always has a `message`
52
+
53
+ [Unreleased]: https://github.com/headwalluk/websnapper-cli/compare/v1.0.0...HEAD
54
+ [1.0.0]: https://github.com/headwalluk/websnapper-cli/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Faulkner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # websnapper-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@headwall/websnapper-cli)](https://www.npmjs.com/package/@headwall/websnapper-cli) ![Node 22+](https://img.shields.io/badge/node-%3E%3D22-brightgreen) ![MIT](https://img.shields.io/badge/licence-MIT-blue)
4
+
5
+ `wsnap` is a command-line client for [websnapper](https://github.com/headwalluk/websnapper)
6
+ screenshot servers. It stores your servers and API keys, takes screenshots, and moves on to
7
+ the next server when one is down or busy.
8
+
9
+ It is built for scripts and AI agents first: every command takes `--json` and writes one
10
+ JSON object, exit codes say exactly what failed, and a capture that fails never leaves a
11
+ partial file behind. It is just as usable by hand.
12
+
13
+ ```sh
14
+ npm install -g @headwall/websnapper-cli@latest
15
+ ```
16
+
17
+ Needs Node 22 or later. The same command upgrades it.
18
+
19
+ ```
20
+ $ wsnap host add snap.example.com
21
+ Enter your API key (not shown):
22
+ Configured
23
+
24
+ $ wsnap capture https://example.com/
25
+ Screenshot saved as wsnap-example.com-20261202-150419.png 895 KB
26
+ ```
27
+
28
+ ## Documentation
29
+
30
+ Using wsnap:
31
+
32
+ - [Getting started](docs/getting-started.md): install, add a host, take a screenshot
33
+ - [Command reference](docs/cli.md): every command and option, and the exit codes
34
+ - [Configuration](docs/configuration.md): the host store and environment variables
35
+
36
+ Scripts and AI agents:
37
+
38
+ - [JSON output](docs/json-output.md): the `--json` object for every command, error codes and
39
+ outcomes
40
+
41
+ Developers:
42
+
43
+ - [Development](docs/development.md): setup, layout, how responses are classified, tests
44
+ - [Changelog](CHANGELOG.md)
45
+
46
+ ## Licence
47
+
48
+ MIT. See [LICENSE](LICENSE).
package/bin/wsnap ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Production entry point: runs the compiled CLI from dist/. In development use `npm run wsnap --`.
3
+ import('../dist/cli.js');
package/dist/args.js ADDED
@@ -0,0 +1,85 @@
1
+ import { parseArgs as parseArgsTokens } from 'node:util';
2
+ /** Every option wsnap accepts. All are accepted before or after the command. */
3
+ const OPTIONS = {
4
+ 'json': { type: 'boolean' },
5
+ 'quiet': { type: 'boolean', short: 'q' },
6
+ 'help': { type: 'boolean', short: 'h' },
7
+ 'host': { type: 'string' },
8
+ 'output': { type: 'string', short: 'o' },
9
+ 'connect-timeout': { type: 'string' },
10
+ 'timeout': { type: 'string' },
11
+ 'viewport': { type: 'string' },
12
+ 'width': { type: 'string' },
13
+ 'height': { type: 'string' },
14
+ 'full': { type: 'boolean' },
15
+ 'format': { type: 'string' },
16
+ 'quality': { type: 'string' },
17
+ 'wait': { type: 'string' },
18
+ 'delay': { type: 'string' },
19
+ 'key-stdin': { type: 'boolean' },
20
+ 'no-key': { type: 'boolean' },
21
+ 'no-verify': { type: 'boolean' },
22
+ 'allow-insecure-key': { type: 'boolean' },
23
+ };
24
+ /** Options every command accepts. */
25
+ export const GLOBAL_OPTIONS = ['json', 'quiet', 'help', 'connect-timeout', 'timeout'];
26
+ /** Narrows a token name to a known option. */
27
+ function isOptionName(name) {
28
+ return Object.hasOwn(OPTIONS, name);
29
+ }
30
+ /** Option names by their one-letter forms. */
31
+ const SHORT_NAMES = Object.fromEntries(Object.entries(OPTIONS).flatMap(([name, definition]) => ('short' in definition ? [[definition.short, name]] : [])));
32
+ /** The boolean option a swallowed value names (--json, -q), so it still takes effect. */
33
+ function swallowedFlag(value) {
34
+ const name = value.startsWith('--') ? value.slice(2).split('=')[0] ?? '' : SHORT_NAMES[value.slice(1)] ?? '';
35
+ return isOptionName(name) && OPTIONS[name].type === 'boolean' ? name : undefined;
36
+ }
37
+ /** Splits argv into words and options, collecting every problem rather than stopping at the first. */
38
+ export function parseArgs(argv) {
39
+ const parsed = { words: [], strings: {}, flags: new Set(), problems: [] };
40
+ const { tokens } = parseArgsTokens({ args: argv, options: OPTIONS, strict: false, allowPositionals: true, tokens: true });
41
+ for (const token of tokens) {
42
+ if (token.kind === 'positional') {
43
+ parsed.words.push(token.value);
44
+ continue;
45
+ }
46
+ if (token.kind !== 'option') {
47
+ // The "--" terminator: what follows arrives as positionals.
48
+ continue;
49
+ }
50
+ const { name, rawName, value, inlineValue } = token;
51
+ if (!isOptionName(name)) {
52
+ parsed.problems.push(`Unknown option ${rawName}.`);
53
+ }
54
+ else if (OPTIONS[name].type === 'boolean') {
55
+ if (inlineValue === true) {
56
+ parsed.problems.push(`${rawName} takes no value.`);
57
+ }
58
+ parsed.flags.add(name);
59
+ }
60
+ else if (value === undefined) {
61
+ parsed.problems.push(`${rawName} needs a value.`);
62
+ }
63
+ else if (inlineValue !== true && value.length > 1 && value.startsWith('-')) {
64
+ // Non-strict parsing hands the next option over as this one's value.
65
+ parsed.problems.push(`${rawName} needs a value; got option ${value}. Use ${rawName}=${value} if that is the value.`);
66
+ // Non-strict parsing consumed it as a value; honour it as well, so --json still gets JSON.
67
+ const flag = swallowedFlag(value);
68
+ if (flag !== undefined) {
69
+ parsed.flags.add(flag);
70
+ }
71
+ }
72
+ else if (parsed.strings[name] !== undefined) {
73
+ parsed.problems.push(`${rawName} is given more than once.`);
74
+ }
75
+ else {
76
+ parsed.strings[name] = value;
77
+ }
78
+ }
79
+ return parsed;
80
+ }
81
+ /** Every option given on the line, as typed names, for checking against what a command accepts. */
82
+ export function givenOptions(args) {
83
+ return [...Object.keys(args.strings), ...args.flags];
84
+ }
85
+ //# sourceMappingURL=args.js.map
package/dist/cli.js ADDED
@@ -0,0 +1,189 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { GLOBAL_OPTIONS, givenOptions, parseArgs } from './args.js';
3
+ import { captureCommand } from './commands/capture.js';
4
+ import { hostAddCommand, hostListCommand, hostRemoveCommand } from './commands/host.js';
5
+ import { statusCommand, testCommand } from './commands/status.js';
6
+ import { viewportsCommand } from './commands/viewports.js';
7
+ import { loadSettingsFromEnvironment, SettingsError } from './config/env.js';
8
+ import { StoreError } from './config/store.js';
9
+ import { ExitCode } from './exit-codes.js';
10
+ import { createLogger } from './logger.js';
11
+ import { escapeControlCharacters } from './output.js';
12
+ import { InputTooLongError, InterruptedError } from './prompt.js';
13
+ import { CLI_NAME, ClientError, interruptedResult, localError, usageError } from './results.js';
14
+ const COMMANDS = [
15
+ captureCommand, statusCommand, testCommand, viewportsCommand, hostAddCommand, hostListCommand, hostRemoveCommand,
16
+ ];
17
+ const INTERRUPTED_MESSAGE = 'Interrupted.';
18
+ /** Aborted by the first Ctrl-C; requests in flight stop and the command reports exit 130. */
19
+ const interruption = new AbortController();
20
+ const BUILT_IN_COMMANDS = [
21
+ { name: 'help', summary: 'Show this help, or a command\'s usage.' },
22
+ { name: 'version', summary: 'Show the version.' },
23
+ ];
24
+ /** Reads the package version from package.json, one level above src/ and dist/. */
25
+ function packageVersion() {
26
+ const packageJson = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
27
+ return packageJson.version;
28
+ }
29
+ /** Finds the command whose path matches the leading words. */
30
+ function findCommand(words) {
31
+ return COMMANDS.find((command) => command.path.every((word, position) => words[position] === word));
32
+ }
33
+ /** Lists the commands and global options. */
34
+ function helpText() {
35
+ const entries = [
36
+ ...COMMANDS.map((command) => ({ name: command.path.join(' '), summary: command.summary })),
37
+ ...BUILT_IN_COMMANDS,
38
+ ];
39
+ const width = Math.max(...entries.map((entry) => entry.name.length));
40
+ return [
41
+ `${CLI_NAME} ${packageVersion()}: a command-line client for websnapper servers.`,
42
+ '',
43
+ `Usage: ${CLI_NAME} [options] <command>`,
44
+ '',
45
+ 'Commands:',
46
+ ...entries.map((entry) => ` ${entry.name.padEnd(width)} ${entry.summary}`),
47
+ '',
48
+ 'Options for every command: --json, -q/--quiet, -h/--help, --connect-timeout <ms>, --timeout <ms>.',
49
+ ].join('\n');
50
+ }
51
+ /** Shows help: for one command when words name one, otherwise the full list. */
52
+ function showHelp(words) {
53
+ const command = findCommand(words);
54
+ const text = command === undefined ? helpText() : `${command.summary}\n\nUsage: ${command.usage}`;
55
+ return { exitCode: ExitCode.success, data: { usage: text }, text };
56
+ }
57
+ /** Explains an unmatched command line, naming the subcommands when the first word is a command group. */
58
+ function unknownCommandProblem(words) {
59
+ const [groupName, subcommandName] = words;
60
+ const subcommands = COMMANDS.filter((command) => command.path.length > 1 && command.path[0] === groupName).map((command) => command.path[1]);
61
+ let problem = `Unknown command: ${words.join(' ')}.`;
62
+ if (subcommands.length > 0) {
63
+ const given = subcommandName === undefined ? 'none' : `"${subcommandName}"`;
64
+ problem = `"${groupName}" needs a subcommand: ${subcommands.join(', ')}; got ${given}.`;
65
+ }
66
+ return problem;
67
+ }
68
+ /** Options given that the command doesn't accept. */
69
+ function inapplicableOptions(command, args) {
70
+ return givenOptions(args)
71
+ .filter((option) => !GLOBAL_OPTIONS.includes(option) && !command.options.includes(option))
72
+ .map((option) => `--${option} does not apply to "${command.path.join(' ')}".`);
73
+ }
74
+ /** Writes unexpected errors, with their stack, to stderr. */
75
+ const crashLogger = createLogger({ level: 'warn', tag: CLI_NAME });
76
+ /** Maps an error thrown by a command to its result; an unexpected one is logged and becomes unexpected_error. */
77
+ function errorResult(error) {
78
+ let result;
79
+ if (error instanceof SettingsError) {
80
+ result = localError(ClientError.configError, error.problems);
81
+ }
82
+ else if (error instanceof StoreError) {
83
+ result = localError(error.code, error.problems);
84
+ }
85
+ else if (error instanceof InputTooLongError) {
86
+ result = usageError([error.message]);
87
+ }
88
+ else if (error instanceof InterruptedError) {
89
+ result = interruptedResult(error.message);
90
+ }
91
+ else {
92
+ crashLogger.error('Unexpected error', { error });
93
+ result = localError(ClientError.unexpectedError, [`Unexpected error: ${error.message}`]);
94
+ }
95
+ return result;
96
+ }
97
+ /** Loads settings and runs one command, turning expected errors into results. */
98
+ async function runCommand(command, args) {
99
+ let result;
100
+ try {
101
+ const settings = loadSettingsFromEnvironment({ connectTimeoutMs: args.strings['connect-timeout'], timeoutMs: args.strings.timeout });
102
+ result = await command.run({
103
+ operands: args.words.slice(command.path.length),
104
+ args,
105
+ settings,
106
+ client: {
107
+ connectTimeoutMs: settings.connectTimeoutMs,
108
+ timeoutMs: settings.timeoutMs,
109
+ userAgent: `${CLI_NAME}/${packageVersion()}`,
110
+ signal: interruption.signal,
111
+ },
112
+ stdin: process.stdin,
113
+ stdout: process.stdout,
114
+ stderr: process.stderr,
115
+ signal: interruption.signal,
116
+ logger: createLogger({ level: settings.logLevel, tag: CLI_NAME }),
117
+ now: () => new Date(),
118
+ currentUid: process.getuid?.(),
119
+ });
120
+ }
121
+ catch (error) {
122
+ result = errorResult(error);
123
+ }
124
+ // Whatever an interrupted command made of its aborted requests, Ctrl-C is what happened.
125
+ if (interruption.signal.aborted && result.exitCode !== ExitCode.success) {
126
+ result = interruptedResult(INTERRUPTED_MESSAGE);
127
+ }
128
+ return result;
129
+ }
130
+ /** Runs the CLI and resolves to the process exit code. */
131
+ async function main(argv) {
132
+ const args = parseArgs(argv);
133
+ const json = args.flags.has('json');
134
+ const quiet = args.flags.has('quiet');
135
+ const [commandName] = args.words;
136
+ const command = findCommand(args.words);
137
+ let result;
138
+ if (args.problems.length > 0) {
139
+ result = usageError(args.problems);
140
+ }
141
+ else if (commandName === undefined || commandName === 'help') {
142
+ result = showHelp(args.words.slice(1));
143
+ }
144
+ else if (commandName === 'version') {
145
+ result = { exitCode: ExitCode.success, data: { version: packageVersion() }, text: packageVersion() };
146
+ }
147
+ else if (command === undefined) {
148
+ result = usageError([unknownCommandProblem(args.words)]);
149
+ }
150
+ else if (args.flags.has('help')) {
151
+ result = showHelp(command.path);
152
+ }
153
+ else if (inapplicableOptions(command, args).length > 0) {
154
+ result = usageError(inapplicableOptions(command, args));
155
+ }
156
+ else {
157
+ result = await runCommand(command, args);
158
+ }
159
+ const succeeded = result.exitCode === ExitCode.success;
160
+ if (json) {
161
+ console.log(JSON.stringify({ ok: succeeded, exitCode: result.exitCode, ...result.data }));
162
+ }
163
+ else if (result.text !== '' && !(succeeded && quiet)) {
164
+ const write = succeeded ? console.log : console.error;
165
+ write(escapeControlCharacters(result.text));
166
+ }
167
+ return result.exitCode;
168
+ }
169
+ process.stdout.on('error', (error) => {
170
+ if (error.code === 'EPIPE') {
171
+ // stdout's reader has gone (| head): nothing more can be delivered, so exit at once.
172
+ process.exit(ExitCode.brokenPipe);
173
+ }
174
+ throw error;
175
+ });
176
+ // once: a second Ctrl-C gets the default behaviour and ends the process, should a command not stop.
177
+ process.once('SIGINT', () => {
178
+ interruption.abort();
179
+ });
180
+ // Never process.exit() here: it drops output still queued for a pipe.
181
+ main(process.argv.slice(2))
182
+ .then((exitCode) => {
183
+ process.exitCode = exitCode;
184
+ })
185
+ .catch((error) => {
186
+ console.error(error);
187
+ process.exitCode = ExitCode.localError;
188
+ });
189
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=command.js.map