@basementuniverse/jsonpad-cli 1.0.0 → 1.2.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.
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Shell completion
3
+ *
4
+ * `jsonpad completion <shell>` outputs a small script for the shell, which
5
+ * asks `jsonpad __complete <words...>` for candidates every time Tab is
6
+ * pressed. The candidates come from the command definitions, so they always
7
+ * match the installed version
8
+ */
9
+ import { Argument } from 'commander';
10
+ export const COMPLETE_COMMAND = '__complete';
11
+ export const SHELLS = ['bash', 'zsh', 'fish'];
12
+ function isHidden(item) {
13
+ return 'hidden' in item ? !!item.hidden : !!item._hidden;
14
+ }
15
+ /**
16
+ * A command's options, and those of the commands above it (e.g. the global
17
+ * options), which commander accepts anywhere
18
+ */
19
+ function optionsFor(command) {
20
+ const options = [];
21
+ for (let current = command; current; current = current.parent) {
22
+ options.push(...current.options.filter(option => !isHidden(option)));
23
+ }
24
+ return options;
25
+ }
26
+ function findOption(command, flag) {
27
+ return optionsFor(command).find(option => option.long === flag || option.short === flag);
28
+ }
29
+ function findSubcommand(command, name) {
30
+ return command.commands.find(child => child.name() === name || child.aliases().includes(name));
31
+ }
32
+ /**
33
+ * The subcommand that runs when a command group is given no subcommand, e.g.
34
+ * `list` for `jsonpad items`
35
+ */
36
+ function defaultSubcommand(command) {
37
+ const name = command._defaultCommandName;
38
+ return name ? findSubcommand(command, name) : undefined;
39
+ }
40
+ /**
41
+ * The candidates for the word being completed, given the words before it
42
+ *
43
+ * `words` is everything after `jsonpad`, with the (possibly empty) word being
44
+ * completed last. No candidates means the shell should complete file names,
45
+ * which suits arguments like `items import <file>` and options like `--out`
46
+ */
47
+ export function completions(program, words) {
48
+ const current = words.length > 0 ? words[words.length - 1] : '';
49
+ let command = program;
50
+ let positionals = 0;
51
+ let optionTakingValue;
52
+ for (const word of words.slice(0, -1)) {
53
+ if (optionTakingValue) {
54
+ optionTakingValue = undefined;
55
+ continue;
56
+ }
57
+ if (word.startsWith('-') && word !== '-') {
58
+ // An option a group doesn't have belongs to its default subcommand
59
+ if (!word.includes('=') && !findOption(command, word)) {
60
+ command = defaultSubcommand(command) ?? command;
61
+ }
62
+ const option = word.includes('=') ? undefined : findOption(command, word);
63
+ if (option && (option.required || option.optional)) {
64
+ optionTakingValue = option;
65
+ }
66
+ continue;
67
+ }
68
+ const subcommand = positionals === 0 ? findSubcommand(command, word) : undefined;
69
+ if (subcommand) {
70
+ command = subcommand;
71
+ continue;
72
+ }
73
+ // Anything else is an argument, which a group passes to its default
74
+ // subcommand
75
+ if (positionals === 0 && command.commands.length > 0) {
76
+ command = defaultSubcommand(command) ?? command;
77
+ }
78
+ positionals++;
79
+ }
80
+ if (optionTakingValue) {
81
+ return (optionTakingValue.argChoices ?? []).filter(choice => choice.startsWith(current));
82
+ }
83
+ if (current.startsWith('-')) {
84
+ const withDefault = [command, defaultSubcommand(command)].filter((candidate) => !!candidate);
85
+ return [
86
+ ...new Set([
87
+ ...withDefault.flatMap(candidate => optionsFor(candidate)
88
+ .map(option => option.long)
89
+ .filter((flag) => !!flag && flag.startsWith(current))),
90
+ ...('--help'.startsWith(current) ? ['--help'] : []),
91
+ ]),
92
+ ];
93
+ }
94
+ if (positionals === 0 && command.commands.length > 0) {
95
+ return command.commands
96
+ .filter(child => !isHidden(child))
97
+ .map(child => child.name())
98
+ .filter(name => name.startsWith(current));
99
+ }
100
+ const argument = command.registeredArguments[positionals];
101
+ return (argument?.argChoices ?? []).filter(choice => choice.startsWith(current));
102
+ }
103
+ /**
104
+ * The completion script for a shell
105
+ */
106
+ export function completionScript(shell) {
107
+ switch (shell) {
108
+ case 'bash':
109
+ return `# jsonpad completion for bash
110
+ # Add this to ~/.bashrc:
111
+ # eval "$(jsonpad completion bash)"
112
+
113
+ _jsonpad_completion() {
114
+ local IFS=$'\\n'
115
+ COMPREPLY=($(jsonpad ${COMPLETE_COMMAND} "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
116
+ }
117
+
118
+ complete -o default -F _jsonpad_completion jsonpad
119
+ `;
120
+ case 'zsh':
121
+ return `#compdef jsonpad
122
+ # jsonpad completion for zsh
123
+ # Add this to ~/.zshrc, after compinit:
124
+ # eval "$(jsonpad completion zsh)"
125
+
126
+ _jsonpad() {
127
+ local -a candidates
128
+ candidates=("\${(@f)$(jsonpad ${COMPLETE_COMMAND} "\${(@)words[2,CURRENT]}" 2>/dev/null)}")
129
+
130
+ if [[ -n "\${candidates[1]}" ]]; then
131
+ compadd -- "\${candidates[@]}"
132
+ else
133
+ _files
134
+ fi
135
+ }
136
+
137
+ compdef _jsonpad jsonpad
138
+ `;
139
+ case 'fish':
140
+ return `# jsonpad completion for fish
141
+ # Save this as ~/.config/fish/completions/jsonpad.fish:
142
+ # jsonpad completion fish > ~/.config/fish/completions/jsonpad.fish
143
+
144
+ function __jsonpad_complete
145
+ set -l candidates (jsonpad ${COMPLETE_COMMAND} (commandline -opc)[2..-1] (commandline -ct) 2>/dev/null)
146
+ if test (count $candidates) -gt 0
147
+ printf '%s\\n' $candidates
148
+ else
149
+ __fish_complete_path (commandline -ct)
150
+ end
151
+ end
152
+
153
+ complete -c jsonpad -e
154
+ complete -c jsonpad -f -a '(__jsonpad_complete)'
155
+ `;
156
+ }
157
+ }
158
+ export function defineCompletion(command, context) {
159
+ return command
160
+ .description('Output a script that completes jsonpad commands and options when you press Tab')
161
+ .addArgument(new Argument('<shell>', 'The shell').choices(SHELLS))
162
+ .addHelpText('after', `
163
+ Setup:
164
+ bash Add to ~/.bashrc: eval "$(jsonpad completion bash)"
165
+ zsh Add to ~/.zshrc, after compinit: eval "$(jsonpad completion zsh)"
166
+ fish Run: jsonpad completion fish > ~/.config/fish/completions/jsonpad.fish`)
167
+ .action((shell) => {
168
+ context.stdout.write(completionScript(shell));
169
+ });
170
+ }
@@ -0,0 +1,158 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CliError, EXIT_NOT_FOUND } from './errors.js';
4
+ export const DEFAULT_API_URL = 'https://api.jsonpad.io';
5
+ const PROFILE_NAME = /^[a-z0-9][a-z0-9_-]*$/i;
6
+ export function validateProfileName(name) {
7
+ if (!PROFILE_NAME.test(name)) {
8
+ throw new CliError(`"${name}" isn't a valid profile name. Use letters, numbers, - and _`);
9
+ }
10
+ }
11
+ /**
12
+ * The config file's path: JSONPAD_CONFIG if it's set, otherwise
13
+ * jsonpad/config.json in the platform's config directory
14
+ */
15
+ export function configPath(context) {
16
+ const { env } = context;
17
+ if (env.JSONPAD_CONFIG) {
18
+ return path.resolve(context.cwd, env.JSONPAD_CONFIG);
19
+ }
20
+ if (context.platform === 'win32') {
21
+ const appData = env.APPDATA || path.join(context.homedir(), 'AppData', 'Roaming');
22
+ return path.join(appData, 'jsonpad', 'config.json');
23
+ }
24
+ const configHome = env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME)
25
+ ? env.XDG_CONFIG_HOME
26
+ : path.join(context.homedir(), '.config');
27
+ return path.join(configHome, 'jsonpad', 'config.json');
28
+ }
29
+ /**
30
+ * Read the config file. A missing file is an empty config
31
+ */
32
+ export function readConfig(context) {
33
+ const file = configPath(context);
34
+ let text;
35
+ try {
36
+ text = fs.readFileSync(file, 'utf8');
37
+ }
38
+ catch (error) {
39
+ if (error.code === 'ENOENT') {
40
+ return { profiles: {} };
41
+ }
42
+ throw new CliError(`Can't read ${file}: ${error.message}`);
43
+ }
44
+ if (context.platform !== 'win32') {
45
+ const mode = fs.statSync(file).mode;
46
+ if ((mode & 0o077) !== 0) {
47
+ context.error(`${context.colours.yellow('warning')}: ${file} can be read by other users, and it contains API tokens. Run chmod 600 ${file}`);
48
+ }
49
+ }
50
+ let config;
51
+ try {
52
+ config = JSON.parse(text);
53
+ }
54
+ catch (error) {
55
+ throw new CliError(`Can't parse ${file}: ${error.message}`);
56
+ }
57
+ const profiles = config?.profiles;
58
+ const validProfiles = profiles &&
59
+ typeof profiles === 'object' &&
60
+ !Array.isArray(profiles) &&
61
+ Object.values(profiles).every((profile) => profile &&
62
+ typeof profile.token === 'string' &&
63
+ (profile.apiUrl === undefined || typeof profile.apiUrl === 'string'));
64
+ if (!config ||
65
+ typeof config !== 'object' ||
66
+ !validProfiles ||
67
+ (config.defaultProfile !== undefined &&
68
+ typeof config.defaultProfile !== 'string')) {
69
+ throw new CliError(`${file} isn't a valid config file. Fix it, or delete it and add your profiles again`);
70
+ }
71
+ return config;
72
+ }
73
+ /**
74
+ * Write the config file, readable only by the current user
75
+ */
76
+ export function writeConfig(context, config) {
77
+ const file = configPath(context);
78
+ const temporaryFile = `${file}.${process.pid}.tmp`;
79
+ try {
80
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
81
+ // Write a new file and move it into place, so that a failed write can't
82
+ // leave a half-written config behind
83
+ fs.writeFileSync(temporaryFile, `${JSON.stringify(config, null, 2)}\n`, {
84
+ mode: 0o600,
85
+ });
86
+ fs.chmodSync(temporaryFile, 0o600);
87
+ fs.renameSync(temporaryFile, file);
88
+ }
89
+ catch (error) {
90
+ fs.rmSync(temporaryFile, { force: true });
91
+ throw new CliError(`Can't write ${file}: ${error.message}`);
92
+ }
93
+ return file;
94
+ }
95
+ /**
96
+ * Work out which token and API URL a command uses
97
+ *
98
+ * In order:
99
+ * 1. a profile chosen with --profile, or JSONPAD_PROFILE
100
+ * 2. JSONPAD_TOKEN (and JSONPAD_API_URL)
101
+ * 3. the default profile
102
+ *
103
+ * --api-url overrides the API URL from any of these. A profile's own API URL
104
+ * takes precedence over JSONPAD_API_URL, because a profile's token and URL
105
+ * belong together
106
+ */
107
+ export function resolveAuth(context) {
108
+ const { env, globalOptions } = context;
109
+ const chosenProfile = globalOptions.profile || env.JSONPAD_PROFILE;
110
+ const apiUrl = (url) => globalOptions.apiUrl || url || env.JSONPAD_API_URL || DEFAULT_API_URL;
111
+ if (!chosenProfile && env.JSONPAD_TOKEN) {
112
+ return {
113
+ token: env.JSONPAD_TOKEN,
114
+ apiUrl: apiUrl(undefined),
115
+ source: { type: 'environment' },
116
+ };
117
+ }
118
+ // The config file is only read when it's needed, so a command run with
119
+ // JSONPAD_TOKEN (e.g. in CI) doesn't depend on it
120
+ const config = readConfig(context);
121
+ const name = chosenProfile || config.defaultProfile;
122
+ if (!name) {
123
+ throw new CliError('Set the JSONPAD_TOKEN environment variable to an API token');
124
+ }
125
+ const profile = config.profiles[name];
126
+ if (!profile) {
127
+ throw new CliError(chosenProfile
128
+ ? `There's no profile named "${name}". Run jsonpad config list to see your profiles`
129
+ : `The default profile "${name}" doesn't exist. Run jsonpad config use <profile> to choose another one`, EXIT_NOT_FOUND);
130
+ }
131
+ return {
132
+ token: profile.token,
133
+ apiUrl: apiUrl(profile.apiUrl),
134
+ source: { type: 'profile', name },
135
+ };
136
+ }
137
+ /**
138
+ * Show enough of a token to recognise it
139
+ */
140
+ export function maskToken(token) {
141
+ return token.length > 8 ? `••••${token.slice(-4)}` : '••••';
142
+ }
143
+ /**
144
+ * Work out which identity requests are made as, if any: the identity token is
145
+ * JSONPAD_IDENTITY_TOKEN (never an option, since it's a secret), and its group
146
+ * is --identity-group or JSONPAD_IDENTITY_GROUP
147
+ */
148
+ export function resolveIdentity(context) {
149
+ const token = context.env.JSONPAD_IDENTITY_TOKEN;
150
+ const group = context.globalOptions.identityGroup ?? context.env.JSONPAD_IDENTITY_GROUP;
151
+ if (!token) {
152
+ if (context.globalOptions.identityGroup !== undefined) {
153
+ throw new CliError('--identity-group needs an identity token in JSONPAD_IDENTITY_TOKEN. Log in with jsonpad identities login');
154
+ }
155
+ return null;
156
+ }
157
+ return { token, group: group || null };
158
+ }
package/build/context.js CHANGED
@@ -1,26 +1,42 @@
1
- import { CliError } from './errors.js';
1
+ import os from 'node:os';
2
+ import { createRetryingClient, installVerboseFetch } from './client.js';
3
+ import { resolveAuth, resolveIdentity } from './config.js';
2
4
  import { createColours } from './output.js';
3
5
  import { JSONPad } from './sdk.js';
4
6
  export function createContext(options = {}) {
5
7
  const env = options.env ?? process.env;
6
8
  const stdout = options.stdout ?? process.stdout;
7
9
  const stderr = options.stderr ?? process.stderr;
8
- return {
10
+ const context = {
9
11
  env,
10
12
  cwd: options.cwd ?? process.cwd(),
13
+ platform: options.platform ?? process.platform,
14
+ homedir: options.homedir ?? os.homedir,
15
+ stdin: options.stdin ?? process.stdin,
11
16
  stdout,
12
17
  stderr,
13
18
  colours: createColours(!!stdout.isTTY && !('NO_COLOR' in env)),
19
+ globalOptions: {},
20
+ auth: null,
21
+ client: null,
22
+ identity: null,
14
23
  log: (text = '') => void stdout.write(`${text}\n`),
15
24
  error: (text = '') => void stderr.write(`${text}\n`),
25
+ sleep: options.sleep ??
26
+ (milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))),
16
27
  createClient() {
17
- const token = env.JSONPAD_TOKEN;
18
- if (!token) {
19
- throw new CliError('Set the JSONPAD_TOKEN environment variable to an API token');
28
+ const auth = resolveAuth(context);
29
+ if (context.globalOptions.verbose) {
30
+ installVerboseFetch(context);
20
31
  }
21
- return new JSONPad(token, undefined, undefined, {
22
- apiUrl: env.JSONPAD_API_URL || undefined,
23
- });
32
+ const identity = resolveIdentity(context);
33
+ context.auth = auth;
34
+ context.identity = identity;
35
+ context.client = createRetryingClient(context, new JSONPad(auth.token, identity?.group ?? undefined, identity?.token, {
36
+ apiUrl: auth.apiUrl,
37
+ }));
38
+ return context.client;
24
39
  },
25
40
  };
41
+ return context;
26
42
  }
package/build/errors.js CHANGED
@@ -4,6 +4,23 @@ export const EXIT_ERROR = 1;
4
4
  export const EXIT_REBUILD_NOT_ALLOWED = 2;
5
5
  export const EXIT_BUILD_FAILED = 3;
6
6
  export const EXIT_DESTRUCTIVE_NOT_ALLOWED = 4;
7
+ export const EXIT_CONFIRMATION_NEEDED = 5;
8
+ export const EXIT_NOT_FOUND = 6;
9
+ export const EXIT_PERMISSION_DENIED = 7;
10
+ export const EXIT_LIMIT_REACHED = 8;
11
+ export const EXIT_INTERRUPTED = 130;
12
+ /**
13
+ * API errors (403s) that mean a plan limit was reached, rather than that the
14
+ * token isn't allowed to do something
15
+ */
16
+ const PLAN_LIMIT_ERRORS = new Set([
17
+ 'MAX_LISTS_EXCEEDED',
18
+ 'MAX_ITEMS_EXCEEDED',
19
+ 'MAX_INDEXES_EXCEEDED',
20
+ 'MAX_TOKENS_EXCEEDED',
21
+ 'MAX_IDENTITIES_EXCEEDED',
22
+ 'STORAGE_LIMIT_EXCEEDED',
23
+ ]);
7
24
  /**
8
25
  * An error with a message for the user, and the exit code to finish with
9
26
  */
@@ -31,3 +48,42 @@ export function describeApiError(error) {
31
48
  ? error.message
32
49
  : String(error);
33
50
  }
51
+ /**
52
+ * Turn an error thrown by the SDK into a CliError, with an exit code that says
53
+ * what kind of failure it was
54
+ *
55
+ * The commands ported from the SDK's jsonpad command don't use this: they
56
+ * exit with 1 for every API error, as they always have
57
+ */
58
+ export function apiError(error, apiUrl) {
59
+ if (error instanceof CliError) {
60
+ return error;
61
+ }
62
+ // fetch rejects with a TypeError when it can't reach the server, with the
63
+ // reason (e.g. ECONNREFUSED) as its cause
64
+ if (error instanceof TypeError && error.message === 'fetch failed') {
65
+ const cause = error.cause;
66
+ const reason = cause?.code || cause?.message || error.message;
67
+ return new CliError(`Can't connect to ${apiUrl ?? 'the API'} (${reason})`, EXIT_ERROR);
68
+ }
69
+ return new CliError(describeApiError(error), apiErrorExitCode(error));
70
+ }
71
+ export function apiErrorExitCode(error) {
72
+ if (!(error instanceof JSONPadError)) {
73
+ return EXIT_ERROR;
74
+ }
75
+ switch (error.status) {
76
+ case 404:
77
+ return EXIT_NOT_FOUND;
78
+ case 401:
79
+ return EXIT_PERMISSION_DENIED;
80
+ case 403:
81
+ return error.errorName && PLAN_LIMIT_ERRORS.has(error.errorName)
82
+ ? EXIT_LIMIT_REACHED
83
+ : EXIT_PERMISSION_DENIED;
84
+ case 429:
85
+ return EXIT_LIMIT_REACHED;
86
+ default:
87
+ return EXIT_ERROR;
88
+ }
89
+ }
package/build/indexes.js CHANGED
@@ -1,4 +1,4 @@
1
- import { CliError, describeApiError, EXIT_BUILD_FAILED } from './errors.js';
1
+ import { apiError, CliError, describeApiError, EXIT_BUILD_FAILED, } from './errors.js';
2
2
  import { IndexBuildError } from './sdk.js';
3
3
  /**
4
4
  * Parse a --timeout option (in seconds) into milliseconds
@@ -38,3 +38,26 @@ export async function waitForIndexes(context, jsonpad, indexes, timeout) {
38
38
  throw new CliError('One or more indexes did not build. Fix the problem, then run jsonpad rebuild-index <list> <index>', EXIT_BUILD_FAILED);
39
39
  }
40
40
  }
41
+ /**
42
+ * Wait for one index to be built, describing progress on stderr, and return it
43
+ * once it's ready. For the new commands, which keep stdout for data
44
+ */
45
+ export async function waitForIndex(context, jsonpad, list, index, timeout) {
46
+ const { green, red } = context.colours;
47
+ context.stderr.write(`Waiting for index ${list}/${index} to build... `);
48
+ try {
49
+ const ready = await jsonpad.waitForIndex(list, index, { timeout });
50
+ context.stderr.write(`${green('ready')}\n`);
51
+ return ready;
52
+ }
53
+ catch (error) {
54
+ if (error instanceof IndexBuildError) {
55
+ context.stderr.write(`${red(error.reason === 'failed' ? 'failed' : 'timed out')}\n`);
56
+ throw new CliError(error.reason === 'failed'
57
+ ? `The index didn't build. Fix the problem, then run jsonpad indexes rebuild ${list} ${index}`
58
+ : `The index didn't finish building in time. Run jsonpad indexes wait ${list} ${index} to keep waiting`, EXIT_BUILD_FAILED);
59
+ }
60
+ context.stderr.write(`${red('error')}\n`);
61
+ throw apiError(error, context.auth?.apiUrl);
62
+ }
63
+ }
package/build/input.js ADDED
@@ -0,0 +1,167 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import readline from 'node:readline';
4
+ import { CliError, EXIT_CONFIRMATION_NEEDED, EXIT_ERROR, EXIT_INTERRUPTED, } from './errors.js';
5
+ const CTRL_C = String.fromCharCode(3);
6
+ const CTRL_D = String.fromCharCode(4);
7
+ const BACKSPACE = String.fromCharCode(8);
8
+ const DELETE = String.fromCharCode(127);
9
+ const ESCAPE = String.fromCharCode(27);
10
+ /**
11
+ * Read everything from stdin
12
+ */
13
+ export async function readStdin(context) {
14
+ let text = '';
15
+ context.stdin.setEncoding('utf8');
16
+ for await (const chunk of context.stdin) {
17
+ text += chunk;
18
+ }
19
+ return text;
20
+ }
21
+ /**
22
+ * Read a JSON option value, which can be:
23
+ * - JSON, e.g. --data '{"name":"Pancakes"}'
24
+ * - @ and a file name, e.g. --data @pancakes.json
25
+ * - a dash to read from stdin, e.g. --data -
26
+ */
27
+ export async function readJsonInput(context, option, value) {
28
+ let text;
29
+ let source;
30
+ if (value === '-') {
31
+ text = await readStdin(context);
32
+ source = `${option} (from stdin)`;
33
+ }
34
+ else if (value.startsWith('@')) {
35
+ const file = value.slice(1);
36
+ try {
37
+ text = fs.readFileSync(path.resolve(context.cwd, file), 'utf8');
38
+ }
39
+ catch (error) {
40
+ throw new CliError(error.code === 'ENOENT'
41
+ ? `Can't find ${file} (for ${option})`
42
+ : `Can't read ${file} (for ${option}): ${error.message}`);
43
+ }
44
+ source = `${option} (from ${file})`;
45
+ }
46
+ else {
47
+ text = value;
48
+ source = option;
49
+ }
50
+ try {
51
+ return JSON.parse(text);
52
+ }
53
+ catch (error) {
54
+ throw new CliError(`${source} isn't valid JSON: ${error.message}`);
55
+ }
56
+ }
57
+ /**
58
+ * Collect a repeatable option whose values can also be comma-separated, e.g.
59
+ * --tags a,b --tags c gives ['a', 'b', 'c']
60
+ */
61
+ export function collectList(value, previous = []) {
62
+ return [
63
+ ...previous,
64
+ ...value
65
+ .split(',')
66
+ .map(part => part.trim())
67
+ .filter(Boolean),
68
+ ];
69
+ }
70
+ /**
71
+ * Whether the user can be asked something: stdin and stderr (where questions
72
+ * are written) are both a terminal
73
+ */
74
+ export function canPrompt(context) {
75
+ return !!context.stdin.isTTY && !!context.stderr.isTTY;
76
+ }
77
+ async function askYesNo(context, question) {
78
+ context.stderr.write(`${question} [y/N] `);
79
+ const lines = readline.createInterface({
80
+ input: context.stdin,
81
+ terminal: false,
82
+ });
83
+ try {
84
+ const answer = await new Promise(resolve => {
85
+ lines.once('line', resolve);
86
+ lines.once('close', () => resolve(null));
87
+ });
88
+ if (answer === null) {
89
+ context.stderr.write('\n');
90
+ }
91
+ return /^y(es)?$/i.test((answer ?? '').trim());
92
+ }
93
+ finally {
94
+ lines.close();
95
+ }
96
+ }
97
+ /**
98
+ * Check that the user wants to go ahead with something that can't be undone
99
+ *
100
+ * With --yes, there's nothing to check. Otherwise the user is asked on a
101
+ * terminal, and anywhere else (a script, CI) the command is refused, rather
102
+ * than waiting for an answer that will never come
103
+ */
104
+ export async function confirm(context, options) {
105
+ if (options.yes) {
106
+ return;
107
+ }
108
+ if (!canPrompt(context)) {
109
+ throw new CliError(`${options.question} Run again with --yes to confirm`, EXIT_CONFIRMATION_NEEDED);
110
+ }
111
+ if (!(await askYesNo(context, options.question))) {
112
+ throw new CliError('Cancelled', EXIT_ERROR);
113
+ }
114
+ }
115
+ /**
116
+ * Ask for a secret (e.g. a token) on a terminal, without showing what's typed
117
+ */
118
+ export function promptSecret(context, question) {
119
+ const { stdin, stderr } = context;
120
+ if (!canPrompt(context) || !stdin.setRawMode) {
121
+ return Promise.reject(new CliError("Can't ask for input, because this isn't a terminal"));
122
+ }
123
+ stderr.write(question);
124
+ stdin.setRawMode(true);
125
+ stdin.setEncoding('utf8');
126
+ stdin.resume();
127
+ return new Promise((resolve, reject) => {
128
+ let value = '';
129
+ const finish = () => {
130
+ stdin.off('data', onData);
131
+ stdin.setRawMode(false);
132
+ stdin.pause();
133
+ stderr.write('\n');
134
+ };
135
+ const onData = (chunk) => {
136
+ // Arrow keys and the like arrive as escape sequences, which aren't part
137
+ // of the secret
138
+ if (String(chunk).startsWith(ESCAPE)) {
139
+ return;
140
+ }
141
+ for (const character of String(chunk)) {
142
+ switch (character) {
143
+ case '\r':
144
+ case '\n':
145
+ case CTRL_D:
146
+ finish();
147
+ resolve(value);
148
+ return;
149
+ case CTRL_C:
150
+ finish();
151
+ reject(new CliError('Cancelled', EXIT_INTERRUPTED));
152
+ return;
153
+ case BACKSPACE:
154
+ case DELETE:
155
+ value = value.slice(0, -1);
156
+ break;
157
+ default:
158
+ // Ignore other control characters, e.g. from arrow keys
159
+ if (character >= ' ') {
160
+ value += character;
161
+ }
162
+ }
163
+ }
164
+ };
165
+ stdin.on('data', onData);
166
+ });
167
+ }