@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 +54 -0
- package/LICENSE +21 -0
- package/README.md +47 -2
- package/bin/wsnap +3 -0
- package/dist/args.js +85 -0
- package/dist/cli.js +189 -0
- package/dist/command.js +2 -0
- package/dist/commands/capture.js +357 -0
- package/dist/commands/host.js +173 -0
- package/dist/commands/status.js +90 -0
- package/dist/commands/viewports.js +39 -0
- package/dist/config/env.js +102 -0
- package/dist/config/store.js +267 -0
- package/dist/exit-codes.js +17 -0
- package/dist/failover.js +91 -0
- package/dist/hosts.js +84 -0
- package/dist/http/classify.js +120 -0
- package/dist/http/request.js +99 -0
- package/dist/http/websnapper.js +152 -0
- package/dist/logger.js +24 -0
- package/dist/output.js +38 -0
- package/dist/prompt.js +101 -0
- package/dist/results.js +35 -0
- package/package.json +54 -4
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { copyFile, link, open, rename, rm } from 'node:fs/promises';
|
|
4
|
+
import { ExitCode } from '../exit-codes.js';
|
|
5
|
+
import { failureResult, selectHosts, tryHosts } from '../failover.js';
|
|
6
|
+
import { classifyNetworkError } from '../http/classify.js';
|
|
7
|
+
import { toNetworkError } from '../http/request.js';
|
|
8
|
+
import { openSnapshot, snapshotMetadata } from '../http/websnapper.js';
|
|
9
|
+
import { formatBytes } from '../output.js';
|
|
10
|
+
import { ClientError, localError, usageError } from '../results.js';
|
|
11
|
+
const STDOUT_PATH = '-';
|
|
12
|
+
const EMPTY_IMAGE_DETAIL = '200 with an empty image';
|
|
13
|
+
const PART_NAME_RANDOM_BYTES = 6;
|
|
14
|
+
const PART_SUFFIX = '.part';
|
|
15
|
+
const GENERATED_PREFIX = 'wsnap';
|
|
16
|
+
const LAST_NAME_SUFFIX = 1000;
|
|
17
|
+
const INTEGER_PATTERN = /^\d+$/;
|
|
18
|
+
const UNSAFE_NAME_CHARACTERS = /[^a-z0-9.-]+/gi;
|
|
19
|
+
const FORMATS = ['png', 'jpeg', 'webp'];
|
|
20
|
+
const WAIT_MODES = ['load', 'networkidle'];
|
|
21
|
+
const FILE_EXTENSIONS = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };
|
|
22
|
+
const FALLBACK_EXTENSION = 'img';
|
|
23
|
+
/** Errors from link() on filesystems without hard links; the name is then claimed with an exclusive copy. */
|
|
24
|
+
const HARD_LINK_UNSUPPORTED_CODES = ['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS'];
|
|
25
|
+
/** Whole-number options and their /v1/snapshot parameters. */
|
|
26
|
+
const INTEGER_OPTIONS = [
|
|
27
|
+
{ option: 'width', parameter: 'width', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
|
|
28
|
+
{ option: 'height', parameter: 'height', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
|
|
29
|
+
{ option: 'quality', parameter: 'quality', minimum: 1, maximum: 100 },
|
|
30
|
+
{ option: 'delay', parameter: 'delay_ms', minimum: 0, maximum: Number.MAX_SAFE_INTEGER },
|
|
31
|
+
];
|
|
32
|
+
/** Problems with the target URL operand, or the parsed URL. */
|
|
33
|
+
function parseTarget(operands) {
|
|
34
|
+
const [operand] = operands;
|
|
35
|
+
let result;
|
|
36
|
+
if (operand === undefined || operands.length > 1) {
|
|
37
|
+
result = { problem: operand === undefined ? `Give a URL: ${captureCommand.usage}` : `Give one URL; got ${operands.length}: ${operands.join(' ')}.` };
|
|
38
|
+
}
|
|
39
|
+
else if (!URL.canParse(operand) || !['http:', 'https:'].includes(new URL(operand).protocol)) {
|
|
40
|
+
const hint = URL.canParse(`https://${operand}`) && !operand.includes('://') ? ` Did you mean https://${operand}?` : '';
|
|
41
|
+
result = { problem: `"${operand}" is not an http:// or https:// URL.${hint}` };
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
result = { target: new URL(operand) };
|
|
45
|
+
}
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
/** Builds the /v1/snapshot query from the options, collecting every problem the client can see. */
|
|
49
|
+
function buildQuery(context, target, problems) {
|
|
50
|
+
const { strings, flags } = context.args;
|
|
51
|
+
const query = new URLSearchParams(target === undefined ? {} : { url: target.href });
|
|
52
|
+
if (strings.viewport !== undefined) {
|
|
53
|
+
if (strings.viewport.trim() === '') {
|
|
54
|
+
problems.push('--viewport needs a preset name. "wsnap viewports" lists them.');
|
|
55
|
+
}
|
|
56
|
+
query.set('viewport', strings.viewport);
|
|
57
|
+
}
|
|
58
|
+
for (const { option, parameter, minimum, maximum } of INTEGER_OPTIONS) {
|
|
59
|
+
const value = strings[option];
|
|
60
|
+
if (value === undefined) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!INTEGER_PATTERN.test(value) || Number(value) < minimum || Number(value) > maximum) {
|
|
64
|
+
const range = maximum === Number.MAX_SAFE_INTEGER ? `${minimum} or more` : `${minimum} to ${maximum}`;
|
|
65
|
+
problems.push(`--${option} must be a whole number, ${range}; got "${value}".`);
|
|
66
|
+
}
|
|
67
|
+
query.set(parameter, String(Number(value)));
|
|
68
|
+
}
|
|
69
|
+
if (flags.has('full')) {
|
|
70
|
+
query.set('full', '1');
|
|
71
|
+
}
|
|
72
|
+
for (const [option, allowed] of [['format', FORMATS], ['wait', WAIT_MODES]]) {
|
|
73
|
+
const value = strings[option];
|
|
74
|
+
if (value !== undefined && !allowed.includes(value)) {
|
|
75
|
+
problems.push(`--${option} must be ${allowed.join(', ')}; got "${value}".`);
|
|
76
|
+
}
|
|
77
|
+
if (value !== undefined) {
|
|
78
|
+
query.set(option, value);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// The server refuses these combinations with a 400, which counts as a ban strike.
|
|
82
|
+
const { viewport, width, height, format, quality } = strings;
|
|
83
|
+
if (viewport !== undefined && (width !== undefined || height !== undefined)) {
|
|
84
|
+
problems.push('Use --viewport, or --width with --height or --full; not both.');
|
|
85
|
+
}
|
|
86
|
+
else if (height !== undefined && width === undefined) {
|
|
87
|
+
problems.push('--height needs --width.');
|
|
88
|
+
}
|
|
89
|
+
else if (width !== undefined && height === undefined && !flags.has('full')) {
|
|
90
|
+
problems.push('--width needs --height or --full.');
|
|
91
|
+
}
|
|
92
|
+
if (format === 'png' && quality !== undefined) {
|
|
93
|
+
problems.push('--quality applies to jpeg and webp only.');
|
|
94
|
+
}
|
|
95
|
+
return query;
|
|
96
|
+
}
|
|
97
|
+
/** Problems with --output: empty, or stdout when stdout can't take an image. */
|
|
98
|
+
function outputProblems(context) {
|
|
99
|
+
const output = context.args.strings.output;
|
|
100
|
+
const problems = [];
|
|
101
|
+
if (output === '') {
|
|
102
|
+
problems.push('--output needs a path, or - for stdout.');
|
|
103
|
+
}
|
|
104
|
+
else if (output === STDOUT_PATH && context.args.flags.has('json')) {
|
|
105
|
+
problems.push('--json and --output - both write to stdout. Use one.');
|
|
106
|
+
}
|
|
107
|
+
else if (output === STDOUT_PATH && context.stdout.isTTY === true) {
|
|
108
|
+
problems.push('Not writing an image to a terminal. Redirect stdout, or use --output <file>.');
|
|
109
|
+
}
|
|
110
|
+
return problems;
|
|
111
|
+
}
|
|
112
|
+
/** Checks the arguments and builds the plan, or lists every problem. */
|
|
113
|
+
function planCapture(context) {
|
|
114
|
+
const parsed = parseTarget(context.operands);
|
|
115
|
+
const problems = 'problem' in parsed ? [parsed.problem] : [];
|
|
116
|
+
const query = buildQuery(context, 'target' in parsed ? parsed.target : undefined, problems);
|
|
117
|
+
problems.push(...outputProblems(context));
|
|
118
|
+
return problems.length > 0 || !('target' in parsed)
|
|
119
|
+
? { problems }
|
|
120
|
+
: { target: parsed.target, query, output: context.args.strings.output };
|
|
121
|
+
}
|
|
122
|
+
/** wsnap-<target host>-<YYYYMMDD-HHMMSS>, in local time, without an extension. */
|
|
123
|
+
export function generatedBaseName(target, now) {
|
|
124
|
+
const host = target.hostname.replace(UNSAFE_NAME_CHARACTERS, '-').replace(/^-+|-+$/g, '');
|
|
125
|
+
const twoDigits = (value) => String(value).padStart(2, '0');
|
|
126
|
+
const date = `${now.getFullYear()}${twoDigits(now.getMonth() + 1)}${twoDigits(now.getDate())}`;
|
|
127
|
+
const time = `${twoDigits(now.getHours())}${twoDigits(now.getMinutes())}${twoDigits(now.getSeconds())}`;
|
|
128
|
+
return `${GENERATED_PREFIX}-${host}-${date}-${time}`;
|
|
129
|
+
}
|
|
130
|
+
/** A sink writing to the .part file from its start. */
|
|
131
|
+
function fileSink(handle) {
|
|
132
|
+
let position = 0;
|
|
133
|
+
return {
|
|
134
|
+
toStdout: false,
|
|
135
|
+
begin: async () => {
|
|
136
|
+
position = 0;
|
|
137
|
+
await handle.truncate(0);
|
|
138
|
+
},
|
|
139
|
+
write: async (chunk) => {
|
|
140
|
+
// A write may take only part of the buffer (a nearly full disk); carry on until it is all written.
|
|
141
|
+
let offset = 0;
|
|
142
|
+
while (offset < chunk.length) {
|
|
143
|
+
const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset, position);
|
|
144
|
+
if (bytesWritten === 0) {
|
|
145
|
+
throw new Error('The disk accepted no more data.');
|
|
146
|
+
}
|
|
147
|
+
offset += bytesWritten;
|
|
148
|
+
position += bytesWritten;
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/** A sink writing to a stream, waiting for each chunk to be taken. */
|
|
154
|
+
function streamSink(stream) {
|
|
155
|
+
return {
|
|
156
|
+
toStdout: true,
|
|
157
|
+
begin: () => Promise.resolve(),
|
|
158
|
+
write: (chunk) => new Promise((resolve, reject) => {
|
|
159
|
+
stream.write(chunk, (error) => (error ? reject(error) : resolve()));
|
|
160
|
+
}),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/** Copies a response body into a sink, keeping a failure on either side apart from the other. */
|
|
164
|
+
async function copyBody(body, sink) {
|
|
165
|
+
let bytes = 0;
|
|
166
|
+
let writeError;
|
|
167
|
+
let networkError;
|
|
168
|
+
try {
|
|
169
|
+
for await (const chunk of body) {
|
|
170
|
+
const buffer = chunk;
|
|
171
|
+
try {
|
|
172
|
+
await sink.write(buffer);
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
writeError = error;
|
|
176
|
+
// Leaving the loop destroys the body, so the download stops too.
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
bytes += buffer.length;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
networkError = toNetworkError(error);
|
|
184
|
+
}
|
|
185
|
+
return { bytes, ...(networkError === undefined ? {} : { networkError }), ...(writeError === undefined ? {} : { writeError }) };
|
|
186
|
+
}
|
|
187
|
+
/** Asks one host for the screenshot and streams it into the sink. */
|
|
188
|
+
async function captureFrom(host, query, sink, context) {
|
|
189
|
+
await sink.begin();
|
|
190
|
+
const opened = await openSnapshot(host, query, context.client);
|
|
191
|
+
let attempt = { outcome: opened.outcome, bytes: 0 };
|
|
192
|
+
if (opened.response !== undefined) {
|
|
193
|
+
const copied = await copyBody(opened.response.body, sink);
|
|
194
|
+
if (copied.writeError !== undefined) {
|
|
195
|
+
attempt = { outcome: opened.outcome, bytes: copied.bytes, writeError: copied.writeError, stop: true };
|
|
196
|
+
}
|
|
197
|
+
else if (copied.networkError !== undefined) {
|
|
198
|
+
attempt = { outcome: classifyNetworkError(copied.networkError, true), bytes: copied.bytes, stop: sink.toStdout && copied.bytes > 0 };
|
|
199
|
+
}
|
|
200
|
+
else if (copied.bytes === 0) {
|
|
201
|
+
attempt = { outcome: { kind: 'unhealthy', detail: EMPTY_IMAGE_DETAIL }, bytes: 0 };
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
attempt = { outcome: opened.outcome, bytes: copied.bytes, metadata: snapshotMetadata(opened.response.headers) };
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return attempt;
|
|
208
|
+
}
|
|
209
|
+
/** Exit 1, write_error. */
|
|
210
|
+
function writeFailure(error) {
|
|
211
|
+
return localError(ClientError.writeError, [`Cannot save the screenshot: ${error.message}`]);
|
|
212
|
+
}
|
|
213
|
+
/** Creates this run's own .part file before any request, so an unwritable path costs no request. */
|
|
214
|
+
async function openPart(partPath) {
|
|
215
|
+
let opened;
|
|
216
|
+
try {
|
|
217
|
+
// 'wx' (O_CREAT | O_EXCL): never truncates an existing file or follows a symlink planted at the name.
|
|
218
|
+
opened = { handle: await open(partPath, 'wx') };
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
opened = { result: writeFailure(error) };
|
|
222
|
+
}
|
|
223
|
+
return opened;
|
|
224
|
+
}
|
|
225
|
+
/** Gives the finished .part file a name with an exclusive copy; false when the name is taken. */
|
|
226
|
+
async function copyWithoutOverwrite(partPath, candidate) {
|
|
227
|
+
let copied = true;
|
|
228
|
+
try {
|
|
229
|
+
await copyFile(partPath, candidate, constants.COPYFILE_EXCL);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (error.code !== 'EEXIST') {
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
copied = false;
|
|
236
|
+
}
|
|
237
|
+
return copied;
|
|
238
|
+
}
|
|
239
|
+
/** Gives the finished .part file a second name, never replacing a file; false when the name is taken. */
|
|
240
|
+
async function linkWithoutOverwrite(partPath, candidate) {
|
|
241
|
+
let linked = true;
|
|
242
|
+
try {
|
|
243
|
+
await link(partPath, candidate);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
const code = error.code ?? '';
|
|
247
|
+
if (code === 'EEXIST') {
|
|
248
|
+
linked = false;
|
|
249
|
+
}
|
|
250
|
+
else if (HARD_LINK_UNSUPPORTED_CODES.includes(code)) {
|
|
251
|
+
linked = await copyWithoutOverwrite(partPath, candidate);
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return linked;
|
|
258
|
+
}
|
|
259
|
+
/** Names the finished file <base>.<ext>, or <base>-2.<ext>, -3 and so on when taken. The .part is left for the caller. */
|
|
260
|
+
async function placeAtFreeName(partPath, base, extension) {
|
|
261
|
+
let placed;
|
|
262
|
+
for (let suffix = 1; suffix <= LAST_NAME_SUFFIX; suffix += 1) {
|
|
263
|
+
const candidate = suffix === 1 ? `${base}.${extension}` : `${base}-${suffix}.${extension}`;
|
|
264
|
+
if (await linkWithoutOverwrite(partPath, candidate)) {
|
|
265
|
+
placed = candidate;
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (placed === undefined) {
|
|
270
|
+
throw new Error(`${base}.${extension} and ${LAST_NAME_SUFFIX - 1} numbered names after it are all taken.`);
|
|
271
|
+
}
|
|
272
|
+
return placed;
|
|
273
|
+
}
|
|
274
|
+
/** Exit 0: the --json fields and the human line. */
|
|
275
|
+
function successResult(host, path, bytes, metadata, toStdout) {
|
|
276
|
+
return {
|
|
277
|
+
exitCode: ExitCode.success,
|
|
278
|
+
data: { host: host.url, path, bytes, ...metadata },
|
|
279
|
+
text: toStdout ? '' : `Screenshot saved as ${path} ${formatBytes(bytes)}`,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** Captures into a .part file, trying hosts in order, then gives it its final name. The .part never survives. */
|
|
283
|
+
async function captureToFile(context, plan, hosts) {
|
|
284
|
+
const base = generatedBaseName(plan.target, context.now());
|
|
285
|
+
const partPath = `${plan.output ?? base}.${randomBytes(PART_NAME_RANDOM_BYTES).toString('hex')}${PART_SUFFIX}`;
|
|
286
|
+
const opened = await openPart(partPath);
|
|
287
|
+
if ('result' in opened) {
|
|
288
|
+
return opened.result;
|
|
289
|
+
}
|
|
290
|
+
const { handle } = opened;
|
|
291
|
+
let result;
|
|
292
|
+
try {
|
|
293
|
+
const sink = fileSink(handle);
|
|
294
|
+
const { last, attempts } = await tryHosts(hosts, context, (host) => captureFrom(host, plan.query, sink, context));
|
|
295
|
+
if (last.writeError !== undefined) {
|
|
296
|
+
result = writeFailure(last.writeError);
|
|
297
|
+
}
|
|
298
|
+
else if (last.outcome.kind === 'success' && last.metadata !== undefined) {
|
|
299
|
+
const extension = FILE_EXTENSIONS[last.metadata.contentType] ?? FALLBACK_EXTENSION;
|
|
300
|
+
try {
|
|
301
|
+
const path = plan.output ?? await placeAtFreeName(partPath, base, extension);
|
|
302
|
+
if (plan.output !== undefined) {
|
|
303
|
+
await rename(partPath, plan.output);
|
|
304
|
+
}
|
|
305
|
+
result = successResult(last.host, path, last.bytes, last.metadata, false);
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
result = writeFailure(error);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
result = failureResult(last, attempts);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
finally {
|
|
316
|
+
await handle.close();
|
|
317
|
+
await rm(partPath, { force: true });
|
|
318
|
+
}
|
|
319
|
+
return result;
|
|
320
|
+
}
|
|
321
|
+
/** Captures straight to stdout. Once bytes are out, a cut-off body is not retried elsewhere. */
|
|
322
|
+
async function captureToStdout(context, plan, hosts) {
|
|
323
|
+
const sink = streamSink(context.stdout);
|
|
324
|
+
const { last, attempts } = await tryHosts(hosts, context, (host) => captureFrom(host, plan.query, sink, context));
|
|
325
|
+
let result;
|
|
326
|
+
if (last.writeError !== undefined) {
|
|
327
|
+
result = writeFailure(last.writeError);
|
|
328
|
+
}
|
|
329
|
+
else if (last.outcome.kind === 'success' && last.metadata !== undefined) {
|
|
330
|
+
result = successResult(last.host, STDOUT_PATH, last.bytes, last.metadata, true);
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
result = failureResult(last, attempts);
|
|
334
|
+
}
|
|
335
|
+
return result;
|
|
336
|
+
}
|
|
337
|
+
/** Takes a screenshot of a URL with the first working host. */
|
|
338
|
+
async function runCapture(context) {
|
|
339
|
+
const plan = planCapture(context);
|
|
340
|
+
if ('problems' in plan) {
|
|
341
|
+
return usageError(plan.problems);
|
|
342
|
+
}
|
|
343
|
+
const selection = await selectHosts(context);
|
|
344
|
+
if ('result' in selection) {
|
|
345
|
+
return selection.result;
|
|
346
|
+
}
|
|
347
|
+
return plan.output === STDOUT_PATH ? captureToStdout(context, plan, selection.hosts) : captureToFile(context, plan, selection.hosts);
|
|
348
|
+
}
|
|
349
|
+
export const captureCommand = {
|
|
350
|
+
path: ['capture'],
|
|
351
|
+
summary: 'Take a screenshot of a URL.',
|
|
352
|
+
usage: 'wsnap capture <url> [-o <file> | -o -] [--viewport <slug> | --width <px> (--height <px> | --full)] [--full]'
|
|
353
|
+
+ ' [--format png|jpeg|webp] [--quality 1-100] [--wait load|networkidle] [--delay <ms>] [--host <host>]',
|
|
354
|
+
options: ['host', 'output', 'viewport', 'width', 'height', 'full', 'format', 'quality', 'wait', 'delay'],
|
|
355
|
+
run: runCapture,
|
|
356
|
+
};
|
|
357
|
+
//# sourceMappingURL=capture.js.map
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { keyProblem, loadStore, saveStore } from '../config/store.js';
|
|
2
|
+
import { ExitCode } from '../exit-codes.js';
|
|
3
|
+
import { displayHost, findHost, maskKey, normaliseHostUrl, sendsKeyInClear } from '../hosts.js';
|
|
4
|
+
import { describeOutcome, outcomeFields } from '../http/classify.js';
|
|
5
|
+
import { checkOptions, fetchViewports } from '../http/websnapper.js';
|
|
6
|
+
import { columns, hostCountHeading } from '../output.js';
|
|
7
|
+
import { readAllInput, readHiddenLine } from '../prompt.js';
|
|
8
|
+
import { ClientError, localError, usageError } from '../results.js';
|
|
9
|
+
const KEY_PROMPT = 'Enter your API key (not shown): ';
|
|
10
|
+
const NO_KEY_LABEL = '(no key)';
|
|
11
|
+
/** Checks there is exactly one host operand; returns a problem otherwise. */
|
|
12
|
+
function singleHostProblem(operands, usage) {
|
|
13
|
+
let problem;
|
|
14
|
+
if (operands.length === 0) {
|
|
15
|
+
problem = `Give a host: ${usage}`;
|
|
16
|
+
}
|
|
17
|
+
else if (operands.length > 1) {
|
|
18
|
+
problem = `Give one host; got ${operands.length}: ${operands.join(' ')}.`;
|
|
19
|
+
}
|
|
20
|
+
return problem;
|
|
21
|
+
}
|
|
22
|
+
/** Reads the key the way the flags ask: none, all of stdin, or a hidden prompt. Empty means none. */
|
|
23
|
+
async function readKey(context) {
|
|
24
|
+
let key = '';
|
|
25
|
+
if (context.args.flags.has('key-stdin')) {
|
|
26
|
+
key = await readAllInput(context.stdin);
|
|
27
|
+
}
|
|
28
|
+
else if (!context.args.flags.has('no-key')) {
|
|
29
|
+
key = await readHiddenLine(KEY_PROMPT, context.stdin, context.stderr);
|
|
30
|
+
}
|
|
31
|
+
return key === '' ? undefined : key;
|
|
32
|
+
}
|
|
33
|
+
/** Problems with host add's arguments, found before anything is read or prompted for. */
|
|
34
|
+
function hostAddProblems(context) {
|
|
35
|
+
const problems = [];
|
|
36
|
+
const operandProblem = singleHostProblem(context.operands, hostAddCommand.usage);
|
|
37
|
+
const keyStdin = context.args.flags.has('key-stdin');
|
|
38
|
+
const noKey = context.args.flags.has('no-key');
|
|
39
|
+
const allowInsecureKey = context.args.flags.has('allow-insecure-key');
|
|
40
|
+
const normalised = operandProblem === undefined ? normaliseHostUrl(context.operands[0] ?? '') : undefined;
|
|
41
|
+
const inClear = normalised !== undefined && 'url' in normalised && sendsKeyInClear(normalised.url);
|
|
42
|
+
if (operandProblem !== undefined) {
|
|
43
|
+
problems.push(operandProblem);
|
|
44
|
+
}
|
|
45
|
+
else if (normalised !== undefined && 'problem' in normalised) {
|
|
46
|
+
problems.push(normalised.problem);
|
|
47
|
+
}
|
|
48
|
+
if (inClear && !noKey && !allowInsecureKey) {
|
|
49
|
+
problems.push('That is a plain http:// address, so the API key would cross the network unencrypted. '
|
|
50
|
+
+ 'Use https://, --no-key for a host without a key, or --allow-insecure-key to send it anyway.');
|
|
51
|
+
}
|
|
52
|
+
else if (allowInsecureKey && (noKey || (normalised !== undefined && 'url' in normalised && !inClear))) {
|
|
53
|
+
problems.push('--allow-insecure-key applies only to a key for a plain http:// host other than this machine.');
|
|
54
|
+
}
|
|
55
|
+
if (keyStdin && noKey) {
|
|
56
|
+
problems.push('Use --key-stdin or --no-key, not both.');
|
|
57
|
+
}
|
|
58
|
+
else if (!keyStdin && !noKey && context.stdin.isTTY !== true) {
|
|
59
|
+
problems.push('No terminal to prompt for the API key. Use --key-stdin to read it from stdin, or --no-key for a host without one.');
|
|
60
|
+
}
|
|
61
|
+
return problems;
|
|
62
|
+
}
|
|
63
|
+
/** Adds a host, or replaces the key of one already configured, keeping its place in the order. */
|
|
64
|
+
async function runHostAdd(context) {
|
|
65
|
+
const problems = hostAddProblems(context);
|
|
66
|
+
if (problems.length > 0) {
|
|
67
|
+
return usageError(problems);
|
|
68
|
+
}
|
|
69
|
+
const normalised = normaliseHostUrl(context.operands[0] ?? '');
|
|
70
|
+
const url = 'url' in normalised ? normalised.url : '';
|
|
71
|
+
// Loaded up front so a broken store is reported before the prompt.
|
|
72
|
+
await loadStore(context.settings.configPath, context.currentUid);
|
|
73
|
+
const key = await readKey(context);
|
|
74
|
+
const badKey = key === undefined ? undefined : keyProblem(key);
|
|
75
|
+
const entry = {
|
|
76
|
+
url,
|
|
77
|
+
...(key === undefined ? {} : { key }),
|
|
78
|
+
addedAt: context.now().toISOString(),
|
|
79
|
+
...(key !== undefined && context.args.flags.has('allow-insecure-key') ? { allowInsecureKey: true } : {}),
|
|
80
|
+
};
|
|
81
|
+
const verify = !context.args.flags.has('no-verify');
|
|
82
|
+
const verification = badKey === undefined && verify ? (await fetchViewports(entry, checkOptions(context.client))).outcome : undefined;
|
|
83
|
+
let result;
|
|
84
|
+
if (badKey !== undefined) {
|
|
85
|
+
result = usageError([badKey]);
|
|
86
|
+
}
|
|
87
|
+
else if (verification !== undefined && verification.kind !== 'success') {
|
|
88
|
+
result = verifyFailure(url, verification);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
const replaced = await saveHost(context, entry);
|
|
92
|
+
result = { exitCode: ExitCode.success, data: { host: url, verified: verify, replaced }, text: 'Configured' };
|
|
93
|
+
}
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
/** Re-reads the store and adds the entry, or replaces the host in place keeping its addedAt; true when replaced. */
|
|
97
|
+
async function saveHost(context, entry) {
|
|
98
|
+
// Read again after the prompt and the check, so a host command that ran meanwhile isn't undone.
|
|
99
|
+
const store = await loadStore(context.settings.configPath, context.currentUid);
|
|
100
|
+
const existing = store.hosts.find((host) => host.url === entry.url);
|
|
101
|
+
const saved = existing === undefined ? entry : { ...entry, addedAt: existing.addedAt };
|
|
102
|
+
const hosts = existing === undefined ? [...store.hosts, saved] : store.hosts.map((host) => (host === existing ? saved : host));
|
|
103
|
+
await saveStore(context.settings.configPath, { ...store, hosts });
|
|
104
|
+
return existing !== undefined;
|
|
105
|
+
}
|
|
106
|
+
/** The result when the host fails the /v1/viewports check: nothing saved, exit 4. */
|
|
107
|
+
function verifyFailure(url, outcome) {
|
|
108
|
+
const lines = [`Not saved. ${displayHost(url)}: ${describeOutcome(outcome)}`];
|
|
109
|
+
if ('message' in outcome && outcome.message !== undefined) {
|
|
110
|
+
lines.push(`The server said: ${outcome.message}`);
|
|
111
|
+
}
|
|
112
|
+
if (outcome.kind !== 'bad_key') {
|
|
113
|
+
lines.push('Use --no-verify to save it anyway.');
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
exitCode: ExitCode.noHost,
|
|
117
|
+
data: { error: ClientError.verifyFailed, host: url, outcome: outcome.kind, ...outcomeFields(outcome), message: 'message' in outcome && outcome.message !== undefined ? outcome.message : lines[0] },
|
|
118
|
+
text: lines.join('\n'),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/** Lists configured hosts in failover order, with keys masked. */
|
|
122
|
+
async function runHostList(context) {
|
|
123
|
+
if (context.operands.length > 0) {
|
|
124
|
+
return usageError([`host list takes no arguments; got: ${context.operands.join(' ')}.`]);
|
|
125
|
+
}
|
|
126
|
+
const { hosts } = await loadStore(context.settings.configPath, context.currentUid);
|
|
127
|
+
const lines = columns(hosts.map((host) => [displayHost(host.url), host.key === undefined ? NO_KEY_LABEL : maskKey(host.key)]));
|
|
128
|
+
return {
|
|
129
|
+
exitCode: ExitCode.success,
|
|
130
|
+
data: { hosts: hosts.map((host) => ({ url: host.url, key: host.key === undefined ? null : maskKey(host.key), addedAt: host.addedAt })) },
|
|
131
|
+
text: [hostCountHeading(hosts.length), ...lines].join('\n'),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** Removes one configured host, matched by URL or bare host name. */
|
|
135
|
+
async function runHostRemove(context) {
|
|
136
|
+
const operandProblem = singleHostProblem(context.operands, hostRemoveCommand.usage);
|
|
137
|
+
if (operandProblem !== undefined) {
|
|
138
|
+
return usageError([operandProblem]);
|
|
139
|
+
}
|
|
140
|
+
const store = await loadStore(context.settings.configPath, context.currentUid);
|
|
141
|
+
const found = findHost(store.hosts, context.operands[0] ?? '');
|
|
142
|
+
let result;
|
|
143
|
+
if ('problem' in found) {
|
|
144
|
+
result = localError(ClientError.unknownHost, [found.problem]);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
await saveStore(context.settings.configPath, { ...store, hosts: store.hosts.filter((host) => host !== found.host) });
|
|
148
|
+
result = { exitCode: ExitCode.success, data: { host: found.host.url }, text: `Removed ${displayHost(found.host.url)}` };
|
|
149
|
+
}
|
|
150
|
+
return result;
|
|
151
|
+
}
|
|
152
|
+
export const hostAddCommand = {
|
|
153
|
+
path: ['host', 'add'],
|
|
154
|
+
summary: 'Add a host, or replace its key. Checks the key first.',
|
|
155
|
+
usage: 'wsnap host add <host> [--key-stdin | --no-key] [--allow-insecure-key] [--no-verify]',
|
|
156
|
+
options: ['key-stdin', 'no-key', 'allow-insecure-key', 'no-verify'],
|
|
157
|
+
run: runHostAdd,
|
|
158
|
+
};
|
|
159
|
+
export const hostListCommand = {
|
|
160
|
+
path: ['host', 'list'],
|
|
161
|
+
summary: 'List hosts in failover order.',
|
|
162
|
+
usage: 'wsnap host list',
|
|
163
|
+
options: [],
|
|
164
|
+
run: runHostList,
|
|
165
|
+
};
|
|
166
|
+
export const hostRemoveCommand = {
|
|
167
|
+
path: ['host', 'remove'],
|
|
168
|
+
summary: 'Remove a host.',
|
|
169
|
+
usage: 'wsnap host remove <host>',
|
|
170
|
+
options: [],
|
|
171
|
+
run: runHostRemove,
|
|
172
|
+
};
|
|
173
|
+
//# sourceMappingURL=host.js.map
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { ExitCode } from '../exit-codes.js';
|
|
2
|
+
import { attemptData, selectHosts } from '../failover.js';
|
|
3
|
+
import { displayHost } from '../hosts.js';
|
|
4
|
+
import { describeOutcome, outcomeFields } from '../http/classify.js';
|
|
5
|
+
import { checkHealth, checkOptions, fetchViewports } from '../http/websnapper.js';
|
|
6
|
+
import { columns, hostCountHeading } from '../output.js';
|
|
7
|
+
import { ClientError, usageError } from '../results.js';
|
|
8
|
+
const ONLINE_STATE = 'online';
|
|
9
|
+
const NO_HOST_MESSAGE = 'No working host';
|
|
10
|
+
/** Checks one host: /health for readiness, then /v1/viewports for the key. */
|
|
11
|
+
async function checkHost(host, options) {
|
|
12
|
+
const health = await checkHealth(host, options);
|
|
13
|
+
return health.kind === 'success' ? (await fetchViewports(host, options)).outcome : health;
|
|
14
|
+
}
|
|
15
|
+
/** The problem when a command that takes no arguments is given some. */
|
|
16
|
+
function noOperandsProblem(context, name) {
|
|
17
|
+
return context.operands.length === 0 ? undefined : `${name} takes no arguments; got: ${context.operands.join(' ')}.`;
|
|
18
|
+
}
|
|
19
|
+
/** Checks every selected host at once and reports each one's state. */
|
|
20
|
+
async function runStatus(context) {
|
|
21
|
+
const problem = noOperandsProblem(context, 'status');
|
|
22
|
+
if (problem !== undefined) {
|
|
23
|
+
return usageError([problem]);
|
|
24
|
+
}
|
|
25
|
+
const selection = await selectHosts(context);
|
|
26
|
+
if ('result' in selection) {
|
|
27
|
+
return selection.result;
|
|
28
|
+
}
|
|
29
|
+
const options = checkOptions(context.client);
|
|
30
|
+
const checked = await Promise.all(selection.hosts.map(async (host) => ({ host, outcome: await checkHost(host, options) })));
|
|
31
|
+
const anyOnline = checked.some((attempt) => attempt.outcome.kind === 'success');
|
|
32
|
+
const lines = columns(checked.map((attempt) => [displayHost(attempt.host.url), describeOutcome(attempt.outcome)]));
|
|
33
|
+
const heading = context.args.strings.host === undefined ? [hostCountHeading(checked.length)] : [];
|
|
34
|
+
return {
|
|
35
|
+
exitCode: anyOnline ? ExitCode.success : ExitCode.noHost,
|
|
36
|
+
data: {
|
|
37
|
+
...(anyOnline ? {} : { error: ClientError.noHost, message: `${NO_HOST_MESSAGE}.` }),
|
|
38
|
+
hosts: checked.map((attempt) => ({
|
|
39
|
+
host: attempt.host.url,
|
|
40
|
+
state: attempt.outcome.kind === 'success' ? ONLINE_STATE : attempt.outcome.kind,
|
|
41
|
+
...outcomeFields(attempt.outcome),
|
|
42
|
+
})),
|
|
43
|
+
},
|
|
44
|
+
text: [...heading, ...lines].join('\n'),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Checks every host at once, settling on the first online one and cancelling the rest. */
|
|
48
|
+
async function runTest(context) {
|
|
49
|
+
const problem = noOperandsProblem(context, 'test');
|
|
50
|
+
if (problem !== undefined) {
|
|
51
|
+
return usageError([problem]);
|
|
52
|
+
}
|
|
53
|
+
const selection = await selectHosts(context);
|
|
54
|
+
if ('result' in selection) {
|
|
55
|
+
return selection.result;
|
|
56
|
+
}
|
|
57
|
+
const settled = new AbortController();
|
|
58
|
+
const options = { ...checkOptions(context.client), signal: AbortSignal.any([context.signal, settled.signal]) };
|
|
59
|
+
let online;
|
|
60
|
+
const checked = await Promise.all(selection.hosts.map(async (host) => {
|
|
61
|
+
const outcome = await checkHost(host, options);
|
|
62
|
+
if (outcome.kind === 'success' && online === undefined) {
|
|
63
|
+
online = host;
|
|
64
|
+
settled.abort();
|
|
65
|
+
}
|
|
66
|
+
return { host, outcome };
|
|
67
|
+
}));
|
|
68
|
+
return online === undefined
|
|
69
|
+
? {
|
|
70
|
+
exitCode: ExitCode.noHost,
|
|
71
|
+
data: { error: ClientError.noHost, message: `${NO_HOST_MESSAGE}.`, attempts: checked.map(attemptData) },
|
|
72
|
+
text: NO_HOST_MESSAGE,
|
|
73
|
+
}
|
|
74
|
+
: { exitCode: ExitCode.success, data: { host: online.url }, text: `OK: ${displayHost(online.url)}` };
|
|
75
|
+
}
|
|
76
|
+
export const statusCommand = {
|
|
77
|
+
path: ['status'],
|
|
78
|
+
summary: 'Check every host and show its state.',
|
|
79
|
+
usage: 'wsnap status [--host <host>]',
|
|
80
|
+
options: ['host'],
|
|
81
|
+
run: runStatus,
|
|
82
|
+
};
|
|
83
|
+
export const testCommand = {
|
|
84
|
+
path: ['test'],
|
|
85
|
+
summary: 'Check that at least one host works. One line; the exit code says it all.',
|
|
86
|
+
usage: 'wsnap test',
|
|
87
|
+
options: [],
|
|
88
|
+
run: runTest,
|
|
89
|
+
};
|
|
90
|
+
//# sourceMappingURL=status.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ExitCode } from '../exit-codes.js';
|
|
2
|
+
import { failureResult, selectHosts, tryHosts } from '../failover.js';
|
|
3
|
+
import { displayHost } from '../hosts.js';
|
|
4
|
+
import { checkOptions, fetchViewports } from '../http/websnapper.js';
|
|
5
|
+
import { columns } from '../output.js';
|
|
6
|
+
import { usageError } from '../results.js';
|
|
7
|
+
/** Lists the viewport presets offered by the first working host. */
|
|
8
|
+
async function runViewports(context) {
|
|
9
|
+
if (context.operands.length > 0) {
|
|
10
|
+
return usageError([`viewports takes no arguments; got: ${context.operands.join(' ')}.`]);
|
|
11
|
+
}
|
|
12
|
+
const selection = await selectHosts(context);
|
|
13
|
+
if ('result' in selection) {
|
|
14
|
+
return selection.result;
|
|
15
|
+
}
|
|
16
|
+
const options = checkOptions(context.client);
|
|
17
|
+
const { last, attempts } = await tryHosts(selection.hosts, context, (host) => fetchViewports(host, options));
|
|
18
|
+
let result;
|
|
19
|
+
if (last.outcome.kind === 'success' && last.viewports !== undefined) {
|
|
20
|
+
const rows = last.viewports.map((viewport) => [viewport.slug, viewport.label, `${viewport.width}×${viewport.height}`]);
|
|
21
|
+
result = {
|
|
22
|
+
exitCode: ExitCode.success,
|
|
23
|
+
data: { host: last.host.url, viewports: last.viewports },
|
|
24
|
+
text: [`Viewports on ${displayHost(last.host.url)}:`, ...columns(rows)].join('\n'),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
result = failureResult(last, attempts);
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
export const viewportsCommand = {
|
|
33
|
+
path: ['viewports'],
|
|
34
|
+
summary: 'List the viewport presets of the first working host.',
|
|
35
|
+
usage: 'wsnap viewports [--host <host>]',
|
|
36
|
+
options: ['host'],
|
|
37
|
+
run: runViewports,
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=viewports.js.map
|