codepen-commander 1.3.0 → 1.4.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/README.md +103 -11
- package/api/client.js +129 -106
- package/cli.js +34 -29
- package/commands/auth/default.js +40 -0
- package/commands/auth/index.js +83 -0
- package/commands/auth/list.js +78 -0
- package/commands/auth/login.js +136 -0
- package/commands/auth/logout.js +186 -0
- package/commands/auth/status.js +212 -0
- package/commands/build.js +256 -0
- package/commands/clone.js +13 -581
- package/commands/delete.js +548 -80
- package/commands/deploy.js +164 -169
- package/commands/domains.js +83 -39
- package/commands/fork.js +13 -317
- package/commands/info.js +152 -0
- package/commands/init.js +375 -0
- package/commands/list.js +95 -78
- package/commands/new.js +155 -83
- package/commands/open.js +29 -19
- package/commands/privacy.js +52 -36
- package/commands/pull.js +123 -110
- package/commands/push.js +221 -376
- package/commands/restore.js +251 -0
- package/commands/rollback.js +141 -0
- package/commands/serve.js +119 -0
- package/commands/settings.js +126 -0
- package/commands/shell.js +305 -0
- package/commands/status.js +133 -39
- package/commands/sync.js +330 -0
- package/commands/undeploy.js +102 -0
- package/commands/unlink.js +191 -0
- package/commands/versions.js +100 -163
- package/config/auth.js +4 -374
- package/config/pen-blocks.js +166 -0
- package/config/project.js +103 -231
- package/config/user-store.js +364 -0
- package/constants.js +42 -0
- package/errors.js +17 -0
- package/package.json +1 -1
- package/shell/index.html +79 -0
- package/shell/scripts.js +276 -0
- package/shell/styles.css +492 -0
- package/site/blocks/classic.js +270 -0
- package/site/blocks/context.js +63 -0
- package/site/blocks/index.js +4 -0
- package/site/blocks/packages.js +242 -0
- package/site/blocks/unsupported-page.js +328 -0
- package/site/builder.js +475 -0
- package/site/detect.js +65 -0
- package/site/ignore-files.js +90 -0
- package/site/manifest.js +227 -0
- package/site/server.js +483 -0
- package/site/shell.js +363 -0
- package/sync/fs.js +19 -17
- package/sync/info.js +6 -81
- package/utils/browser.js +17 -10
- package/utils/cli-options.js +79 -0
- package/utils/codepen-url.js +183 -0
- package/utils/format.js +39 -30
- package/utils/fs-safe.js +95 -0
- package/utils/html.js +40 -1
- package/utils/json.js +4 -19
- package/utils/output.js +37 -0
- package/utils/package-paths.js +51 -0
- package/utils/prompts/index.js +5 -0
- package/utils/prompts/multi-select.js +185 -0
- package/utils/prompts/secret.js +65 -0
- package/utils/prompts/select.js +141 -0
- package/utils/prompts/text.js +99 -0
- package/utils/prompts/tty-list.js +165 -0
- package/utils/prompts/types.js +35 -0
- package/utils/strings.js +98 -0
- package/utils/watcher.js +82 -0
- package/{commands → workflows}/auth-context.js +13 -7
- package/workflows/batch-pens.js +1647 -0
- package/workflows/batch-target.js +184 -0
- package/workflows/classic-convert.js +241 -0
- package/workflows/clone-pen.js +381 -0
- package/{commands → workflows}/create-pen.js +59 -84
- package/workflows/discover-pens.js +91 -0
- package/workflows/fork-pen.js +314 -0
- package/workflows/missing-pen.js +212 -0
- package/workflows/pull-pen.js +204 -0
- package/workflows/push-pen.js +318 -0
- package/{commands → workflows}/scaffold.js +4 -3
- package/workflows/sync-pen.js +227 -0
- package/{commands → workflows}/unowned-pen.js +16 -12
- package/commands/auth.js +0 -593
- package/commands/meta.js +0 -184
- package/utils/prompts.js +0 -316
- /package/{types.js → api/types.js} +0 -0
package/commands/meta.js
DELETED
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
import { CodePenClient } from '../api/client.js';
|
|
2
|
-
import { requireProject, writeProjectConfig } from '../config/project.js';
|
|
3
|
-
import { mergeUpdatedPenInfoIntoConfig } from '../sync/info.js';
|
|
4
|
-
import { fmt, formatDate, shortId } from '../utils/format.js';
|
|
5
|
-
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
6
|
-
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
7
|
-
const VALID_ACCESS = new Set(['public', 'private', 'protected', 'collaborators']);
|
|
8
|
-
function parseBooleanOption(raw, flagName) {
|
|
9
|
-
const lower = raw.trim().toLowerCase();
|
|
10
|
-
if (lower === 'true' || lower === '1' || lower === 'yes' || lower === 'on')
|
|
11
|
-
return true;
|
|
12
|
-
if (lower === 'false' || lower === '0' || lower === 'no' || lower === 'off')
|
|
13
|
-
return false;
|
|
14
|
-
throw new CliError(400, `Invalid boolean value "${raw}" for ${flagName}. Use true or false.`);
|
|
15
|
-
}
|
|
16
|
-
function renderPenInfo(pen, profile) {
|
|
17
|
-
console.log(`${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
|
|
18
|
-
if (profile) {
|
|
19
|
-
console.log(`Profile: ${fmt.cyan(profile)}`);
|
|
20
|
-
}
|
|
21
|
-
if (pen.description) {
|
|
22
|
-
console.log(`Description: ${pen.description}`);
|
|
23
|
-
}
|
|
24
|
-
console.log(`Editor: ${pen.editor}`);
|
|
25
|
-
console.log(`Access: ${pen.access}${pen.template ? fmt.dim(' · Template') : ''}`);
|
|
26
|
-
console.log(`Tags: ${pen.tags.length > 0 ? pen.tags.join(', ') : fmt.dim('none')}`);
|
|
27
|
-
console.log(`Stats: ${pen.views_count} views · ${pen.loves_count} loves`);
|
|
28
|
-
console.log(`Editor URL: ${fmt.cyan(pen.urls.editor)}`);
|
|
29
|
-
console.log(`Preview URL: ${fmt.cyan(pen.urls.preview)}`);
|
|
30
|
-
if (pen.deployment) {
|
|
31
|
-
console.log(`Deployed: ${fmt.cyan(pen.deployment.url)} ${fmt.dim(`(v ${shortId(pen.deployment.version_id)})`)}`);
|
|
32
|
-
if (pen.deployment.custom_domains.length > 0) {
|
|
33
|
-
console.log(`Domains: ${pen.deployment.custom_domains.join(', ')}`);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
console.log(`Deployed: ${fmt.dim('not deployed')}`);
|
|
38
|
-
}
|
|
39
|
-
console.log(`Created: ${fmt.dim(formatDate(pen.created_at))}`);
|
|
40
|
-
console.log(`Updated: ${fmt.dim(formatDate(pen.updated_at))}`);
|
|
41
|
-
}
|
|
42
|
-
function renderPenSettings(settings) {
|
|
43
|
-
const boolText = (b) => (b ? fmt.green('true') : fmt.dim('false'));
|
|
44
|
-
console.log(`auto_deploy: ${boolText(settings.auto_deploy)}`);
|
|
45
|
-
console.log(`auto_run: ${boolText(settings.auto_run)}`);
|
|
46
|
-
console.log(`auto_save: ${boolText(settings.auto_save)}`);
|
|
47
|
-
console.log(`indent_with: ${fmt.cyan(settings.indent_with)}`);
|
|
48
|
-
console.log(`tab_size: ${fmt.cyan(String(settings.tab_size))}`);
|
|
49
|
-
}
|
|
50
|
-
export async function infoPenCommand(options = {}) {
|
|
51
|
-
const project = await requireProject(options.cwd ?? process.cwd());
|
|
52
|
-
const auth = await resolveCommandAuth({
|
|
53
|
-
explicitProfile: options.explicitProfile,
|
|
54
|
-
project,
|
|
55
|
-
interactive: options.json ? false : options.interactive,
|
|
56
|
-
persistProfileToProject: !options.json,
|
|
57
|
-
env: options.env,
|
|
58
|
-
homeDir: options.homeDir,
|
|
59
|
-
selectProfile: options.selectProfile,
|
|
60
|
-
});
|
|
61
|
-
const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
|
|
62
|
-
const patch = {};
|
|
63
|
-
if (options.title !== undefined)
|
|
64
|
-
patch.title = options.title;
|
|
65
|
-
if (options.description !== undefined)
|
|
66
|
-
patch.description = options.description;
|
|
67
|
-
if (options.tags !== undefined) {
|
|
68
|
-
const parsedTags = options.tags
|
|
69
|
-
.split(',')
|
|
70
|
-
.map((t) => t.trim())
|
|
71
|
-
.filter(Boolean);
|
|
72
|
-
if (parsedTags.length > 5) {
|
|
73
|
-
throw new CliError(400, 'CodePen allows at most 5 tags per Pen.');
|
|
74
|
-
}
|
|
75
|
-
patch.tags = parsedTags;
|
|
76
|
-
}
|
|
77
|
-
if (options.access !== undefined) {
|
|
78
|
-
const lower = options.access.trim().toLowerCase();
|
|
79
|
-
if (!VALID_ACCESS.has(lower)) {
|
|
80
|
-
throw new CliError(400, `Invalid --access "${options.access}". Use: Public, Private, Protected, or Collaborators.`);
|
|
81
|
-
}
|
|
82
|
-
patch.access = (lower[0].toUpperCase() + lower.slice(1));
|
|
83
|
-
}
|
|
84
|
-
if (options.password !== undefined) {
|
|
85
|
-
if (options.password.length < 8) {
|
|
86
|
-
throw new CliError(400, 'Password must be at least 8 characters.');
|
|
87
|
-
}
|
|
88
|
-
patch.password = options.password;
|
|
89
|
-
}
|
|
90
|
-
if (options.template !== undefined) {
|
|
91
|
-
patch.template = parseBooleanOption(options.template, '--template');
|
|
92
|
-
}
|
|
93
|
-
const hasUpdates = Object.keys(patch).length > 0;
|
|
94
|
-
const pen = hasUpdates
|
|
95
|
-
? await client.updatePen(project.config.pen_id, patch)
|
|
96
|
-
: await client.getPen(project.config.pen_id);
|
|
97
|
-
if (hasUpdates) {
|
|
98
|
-
const nextConfig = mergeUpdatedPenInfoIntoConfig(project.config, pen, patch);
|
|
99
|
-
await writeProjectConfig(project.rootDir, nextConfig);
|
|
100
|
-
project.config = nextConfig;
|
|
101
|
-
}
|
|
102
|
-
if (options.json) {
|
|
103
|
-
printJsonResponse(200, hasUpdates ? 'Updated Pen metadata.' : 'Fetched Pen metadata.', pen);
|
|
104
|
-
return { pen, updated: hasUpdates, auth, project };
|
|
105
|
-
}
|
|
106
|
-
if (hasUpdates) {
|
|
107
|
-
console.log(`${fmt.green('✓')} Updated Pen metadata.\n`);
|
|
108
|
-
}
|
|
109
|
-
renderPenInfo(pen, auth.profile);
|
|
110
|
-
return { pen, updated: hasUpdates, auth, project };
|
|
111
|
-
}
|
|
112
|
-
export function registerMetaCommands(program) {
|
|
113
|
-
program
|
|
114
|
-
.command('info')
|
|
115
|
-
.description('Show or update Pen metadata (title, description, tags, access, template)')
|
|
116
|
-
.option('-t, --title <title>', 'Update Pen title')
|
|
117
|
-
.option('-d, --description <text>', 'Update Pen description')
|
|
118
|
-
.option('--tags <tags>', 'Replace tags with comma-separated list (pass "" to clear)')
|
|
119
|
-
.option('--access <level>', 'Update access: Public, Private, Protected, or Collaborators')
|
|
120
|
-
.option('--password <password>', 'Set/replace password (min 8 chars; for Protected Pens)')
|
|
121
|
-
.option('--template <bool>', 'Set template flag (true/false)')
|
|
122
|
-
.option('--json', 'Output Pen metadata as JSON')
|
|
123
|
-
.action(async (options, command) => {
|
|
124
|
-
await infoPenCommand({
|
|
125
|
-
...options,
|
|
126
|
-
explicitProfile: getGlobalProfileOption(command),
|
|
127
|
-
});
|
|
128
|
-
});
|
|
129
|
-
program
|
|
130
|
-
.command('settings')
|
|
131
|
-
.description('View or update Pen editor & deploy settings')
|
|
132
|
-
.option('--auto-deploy <bool>', 'Auto-deploy on save (true/false)')
|
|
133
|
-
.option('--auto-run <bool>', 'Auto-run preview (true/false)')
|
|
134
|
-
.option('--auto-save <bool>', 'Auto-save in editor (true/false)')
|
|
135
|
-
.option('--indent-with <mode>', 'Indentation style: tabs or spaces')
|
|
136
|
-
.option('--tab-size <n>', 'Tab size (integer between 1 and 6)')
|
|
137
|
-
.option('--json', 'Output settings as JSON')
|
|
138
|
-
.action(async (options, command) => {
|
|
139
|
-
const project = await requireProject();
|
|
140
|
-
const auth = await resolveCommandAuth({
|
|
141
|
-
explicitProfile: getGlobalProfileOption(command),
|
|
142
|
-
project,
|
|
143
|
-
interactive: options.json ? false : undefined,
|
|
144
|
-
persistProfileToProject: !options.json,
|
|
145
|
-
});
|
|
146
|
-
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
147
|
-
const patch = {};
|
|
148
|
-
if (options.autoDeploy !== undefined) {
|
|
149
|
-
patch.auto_deploy = parseBooleanOption(options.autoDeploy, '--auto-deploy');
|
|
150
|
-
}
|
|
151
|
-
if (options.autoRun !== undefined) {
|
|
152
|
-
patch.auto_run = parseBooleanOption(options.autoRun, '--auto-run');
|
|
153
|
-
}
|
|
154
|
-
if (options.autoSave !== undefined) {
|
|
155
|
-
patch.auto_save = parseBooleanOption(options.autoSave, '--auto-save');
|
|
156
|
-
}
|
|
157
|
-
if (options.indentWith !== undefined) {
|
|
158
|
-
const lower = options.indentWith.trim().toLowerCase();
|
|
159
|
-
if (lower !== 'tabs' && lower !== 'spaces') {
|
|
160
|
-
throw new CliError(400, 'Invalid --indent-with value. Use "tabs" or "spaces".');
|
|
161
|
-
}
|
|
162
|
-
patch.indent_with = lower;
|
|
163
|
-
}
|
|
164
|
-
if (options.tabSize !== undefined) {
|
|
165
|
-
const parsed = Number.parseInt(options.tabSize, 10);
|
|
166
|
-
if (Number.isNaN(parsed) || parsed < 1 || parsed > 6) {
|
|
167
|
-
throw new CliError(400, '--tab-size must be an integer between 1 and 6.');
|
|
168
|
-
}
|
|
169
|
-
patch.tab_size = parsed;
|
|
170
|
-
}
|
|
171
|
-
const hasUpdates = Object.keys(patch).length > 0;
|
|
172
|
-
const settings = hasUpdates
|
|
173
|
-
? await client.updateSettings(project.config.pen_id, patch)
|
|
174
|
-
: (await client.getPen(project.config.pen_id)).settings;
|
|
175
|
-
if (options.json) {
|
|
176
|
-
printJsonResponse(200, hasUpdates ? 'Updated Pen settings.' : 'Fetched Pen settings.', settings);
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
if (hasUpdates) {
|
|
180
|
-
console.log(`${fmt.green('✓')} Updated Pen settings.\n`);
|
|
181
|
-
}
|
|
182
|
-
renderPenSettings(settings);
|
|
183
|
-
});
|
|
184
|
-
}
|
package/utils/prompts.js
DELETED
|
@@ -1,316 +0,0 @@
|
|
|
1
|
-
import readline from 'node:readline';
|
|
2
|
-
import readlinePromises from 'node:readline/promises';
|
|
3
|
-
import { stdin as defaultInput, stdout as defaultOutput } from 'node:process';
|
|
4
|
-
import { fmt, stripAnsi } from './format.js';
|
|
5
|
-
export function isInteractive() {
|
|
6
|
-
return Boolean(defaultInput.isTTY && defaultOutput.isTTY);
|
|
7
|
-
}
|
|
8
|
-
export async function promptText(question, defaultValue) {
|
|
9
|
-
const rl = readlinePromises.createInterface({ input: defaultInput, output: defaultOutput });
|
|
10
|
-
try {
|
|
11
|
-
const suffix = defaultValue ? ` ${fmt.dim(`(${defaultValue})`)}` : '';
|
|
12
|
-
const answer = await rl.question(`${question}${suffix}: `);
|
|
13
|
-
const trimmed = answer.trim();
|
|
14
|
-
return trimmed || defaultValue || '';
|
|
15
|
-
}
|
|
16
|
-
finally {
|
|
17
|
-
rl.close();
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
export async function promptConfirm(question, defaultYes = false) {
|
|
21
|
-
const rl = readlinePromises.createInterface({ input: defaultInput, output: defaultOutput });
|
|
22
|
-
try {
|
|
23
|
-
const hint = defaultYes ? 'Y/n' : 'y/N';
|
|
24
|
-
const answer = (await rl.question(`${question} ${fmt.dim(`[${hint}]`)} `)).trim().toLowerCase();
|
|
25
|
-
if (!answer)
|
|
26
|
-
return defaultYes;
|
|
27
|
-
return answer === 'y' || answer === 'yes';
|
|
28
|
-
}
|
|
29
|
-
finally {
|
|
30
|
-
rl.close();
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function countTerminalRows(lines, columns) {
|
|
34
|
-
const safeCols = Math.max(1, columns);
|
|
35
|
-
let total = 0;
|
|
36
|
-
for (const rawLine of lines) {
|
|
37
|
-
for (const subLine of rawLine.split('\n')) {
|
|
38
|
-
const visibleLength = stripAnsi(subLine).length;
|
|
39
|
-
total += visibleLength === 0 ? 1 : Math.ceil(visibleLength / safeCols);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
return total;
|
|
43
|
-
}
|
|
44
|
-
async function promptSelectFallback(question, options, defaultIndex, input, output) {
|
|
45
|
-
output.write(`${question}\n`);
|
|
46
|
-
options.forEach((opt, idx) => {
|
|
47
|
-
const num = fmt.cyan(`${idx + 1})`);
|
|
48
|
-
const desc = opt.description ? ` ${fmt.dim(`— ${opt.description}`)}` : '';
|
|
49
|
-
output.write(` ${num} ${opt.label}${desc}\n`);
|
|
50
|
-
});
|
|
51
|
-
const rl = readlinePromises.createInterface({ input, output });
|
|
52
|
-
try {
|
|
53
|
-
for (;;) {
|
|
54
|
-
const answer = (await rl.question(`Choose [1-${options.length}] ${fmt.dim(`(default ${defaultIndex + 1})`)}: `)).trim();
|
|
55
|
-
if (!answer) {
|
|
56
|
-
return options[defaultIndex].value;
|
|
57
|
-
}
|
|
58
|
-
const num = Number.parseInt(answer, 10);
|
|
59
|
-
if (!Number.isNaN(num) && num >= 1 && num <= options.length && String(num) === answer) {
|
|
60
|
-
return options[num - 1].value;
|
|
61
|
-
}
|
|
62
|
-
const byValue = options.find((opt) => opt.value.toLowerCase() === answer.toLowerCase());
|
|
63
|
-
if (byValue) {
|
|
64
|
-
return byValue.value;
|
|
65
|
-
}
|
|
66
|
-
output.write(`${fmt.yellow(`Please enter a number between 1 and ${options.length} (or an option name).`)}\n`);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
finally {
|
|
70
|
-
rl.close();
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
async function promptSelectInteractive(question, options, defaultIndex, input, output) {
|
|
74
|
-
readline.emitKeypressEvents(input);
|
|
75
|
-
let selectedIndex = defaultIndex;
|
|
76
|
-
let windowStart = 0;
|
|
77
|
-
let lastRenderedRows = 0;
|
|
78
|
-
let settled = false;
|
|
79
|
-
const getColumns = () => Math.max(20, output.columns || 80);
|
|
80
|
-
const getMaxVisible = () => {
|
|
81
|
-
const termRows = output.rows || 24;
|
|
82
|
-
const available = Math.max(3, termRows - 5);
|
|
83
|
-
return Math.min(options.length, available, 12);
|
|
84
|
-
};
|
|
85
|
-
const syncWindow = (maxVisible) => {
|
|
86
|
-
if (options.length <= maxVisible) {
|
|
87
|
-
windowStart = 0;
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (selectedIndex < windowStart) {
|
|
91
|
-
windowStart = selectedIndex;
|
|
92
|
-
}
|
|
93
|
-
else if (selectedIndex >= windowStart + maxVisible) {
|
|
94
|
-
windowStart = selectedIndex - maxVisible + 1;
|
|
95
|
-
}
|
|
96
|
-
const maxStart = Math.max(0, options.length - maxVisible);
|
|
97
|
-
if (windowStart > maxStart) {
|
|
98
|
-
windowStart = maxStart;
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
const erasePrevious = () => {
|
|
102
|
-
if (lastRenderedRows <= 0)
|
|
103
|
-
return '';
|
|
104
|
-
return `\x1b[${lastRenderedRows}A\r\x1b[J`;
|
|
105
|
-
};
|
|
106
|
-
const renderActive = (hideCursor) => {
|
|
107
|
-
const columns = getColumns();
|
|
108
|
-
const maxVisible = getMaxVisible();
|
|
109
|
-
syncWindow(maxVisible);
|
|
110
|
-
const lines = [`${fmt.bold(question)} ${fmt.dim('(↑/↓, Enter)')}`];
|
|
111
|
-
if (windowStart > 0) {
|
|
112
|
-
lines.push(` ${fmt.dim(`↑ ${windowStart} more`)}`);
|
|
113
|
-
}
|
|
114
|
-
const windowEnd = Math.min(options.length, windowStart + maxVisible);
|
|
115
|
-
for (let i = windowStart; i < windowEnd; i++) {
|
|
116
|
-
const opt = options[i];
|
|
117
|
-
const isSelected = i === selectedIndex;
|
|
118
|
-
if (isSelected) {
|
|
119
|
-
const desc = opt.description ? ` ${fmt.cyan(`— ${opt.description}`)}` : '';
|
|
120
|
-
lines.push(` ${fmt.bold(fmt.cyan('→'))} ${fmt.bold(fmt.cyan(opt.label))}${desc}`);
|
|
121
|
-
}
|
|
122
|
-
else {
|
|
123
|
-
const desc = opt.description ? ` ${fmt.dim(`— ${opt.description}`)}` : '';
|
|
124
|
-
lines.push(` ${opt.label}${desc}`);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
const hiddenBelow = options.length - windowEnd;
|
|
128
|
-
if (hiddenBelow > 0) {
|
|
129
|
-
lines.push(` ${fmt.dim(`↓ ${hiddenBelow} more`)}`);
|
|
130
|
-
}
|
|
131
|
-
const prefix = `${hideCursor ? '\x1b[?25l' : ''}${erasePrevious()}`;
|
|
132
|
-
output.write(`${prefix}${lines.join('\n')}\n`);
|
|
133
|
-
lastRenderedRows = countTerminalRows(lines, columns);
|
|
134
|
-
};
|
|
135
|
-
const renderFinal = (lines) => {
|
|
136
|
-
const prefix = erasePrevious();
|
|
137
|
-
output.write(`${prefix}${lines.join('\n')}\n\x1b[?25h`);
|
|
138
|
-
lastRenderedRows = 0;
|
|
139
|
-
};
|
|
140
|
-
const wasRaw = Boolean(input.isRaw);
|
|
141
|
-
input.setRawMode?.(true);
|
|
142
|
-
input.resume();
|
|
143
|
-
return new Promise((resolve, reject) => {
|
|
144
|
-
const cleanup = () => {
|
|
145
|
-
input.removeListener('keypress', onKeypress);
|
|
146
|
-
input.removeListener('end', onEnd);
|
|
147
|
-
output.removeListener('resize', onResize);
|
|
148
|
-
process.removeListener('SIGINT', onSigint);
|
|
149
|
-
try {
|
|
150
|
-
input.setRawMode?.(wasRaw);
|
|
151
|
-
}
|
|
152
|
-
catch {
|
|
153
|
-
// Ignore if stream already closed
|
|
154
|
-
}
|
|
155
|
-
input.pause();
|
|
156
|
-
};
|
|
157
|
-
const cancel = () => {
|
|
158
|
-
if (settled)
|
|
159
|
-
return;
|
|
160
|
-
settled = true;
|
|
161
|
-
cleanup();
|
|
162
|
-
renderFinal([fmt.bold(question), ` ${fmt.red('×')} ${fmt.dim('Canceled')}`]);
|
|
163
|
-
reject(new Error('Prompt canceled by user.'));
|
|
164
|
-
};
|
|
165
|
-
const confirm = () => {
|
|
166
|
-
if (settled)
|
|
167
|
-
return;
|
|
168
|
-
settled = true;
|
|
169
|
-
cleanup();
|
|
170
|
-
const chosen = options[selectedIndex];
|
|
171
|
-
const desc = chosen.description ? ` ${fmt.dim(`— ${chosen.description}`)}` : '';
|
|
172
|
-
renderFinal([
|
|
173
|
-
fmt.bold(question),
|
|
174
|
-
` ${fmt.bold(fmt.green('→'))} ${fmt.bold(fmt.green(chosen.label))}${desc}`,
|
|
175
|
-
]);
|
|
176
|
-
resolve(chosen.value);
|
|
177
|
-
};
|
|
178
|
-
const onResize = () => {
|
|
179
|
-
if (settled)
|
|
180
|
-
return;
|
|
181
|
-
renderActive(false);
|
|
182
|
-
};
|
|
183
|
-
const onSigint = () => {
|
|
184
|
-
cancel();
|
|
185
|
-
};
|
|
186
|
-
const onEnd = () => {
|
|
187
|
-
cancel();
|
|
188
|
-
};
|
|
189
|
-
const onKeypress = (str, key) => {
|
|
190
|
-
if (settled)
|
|
191
|
-
return;
|
|
192
|
-
if (str === '\u0003' || (key?.ctrl && key.name === 'c') || key?.name === 'escape') {
|
|
193
|
-
cancel();
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
if (key?.name === 'return' || key?.name === 'enter') {
|
|
197
|
-
confirm();
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
if (key?.name === 'up' || (!key?.ctrl && !key?.meta && key?.name === 'k')) {
|
|
201
|
-
selectedIndex = (selectedIndex - 1 + options.length) % options.length;
|
|
202
|
-
renderActive(false);
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
if (key?.name === 'down' || (!key?.ctrl && !key?.meta && key?.name === 'j')) {
|
|
206
|
-
selectedIndex = (selectedIndex + 1) % options.length;
|
|
207
|
-
renderActive(false);
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
if (key?.name === 'home' || key?.name === 'pageup') {
|
|
211
|
-
if (selectedIndex !== 0) {
|
|
212
|
-
selectedIndex = 0;
|
|
213
|
-
renderActive(false);
|
|
214
|
-
}
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
if (key?.name === 'end' || key?.name === 'pagedown') {
|
|
218
|
-
if (selectedIndex !== options.length - 1) {
|
|
219
|
-
selectedIndex = options.length - 1;
|
|
220
|
-
renderActive(false);
|
|
221
|
-
}
|
|
222
|
-
return;
|
|
223
|
-
}
|
|
224
|
-
if (str && /^[1-9]$/.test(str) && !key?.ctrl && !key?.meta) {
|
|
225
|
-
const idx = Number.parseInt(str, 10) - 1;
|
|
226
|
-
if (idx >= 0 && idx < options.length && idx !== selectedIndex) {
|
|
227
|
-
selectedIndex = idx;
|
|
228
|
-
renderActive(false);
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
input.on('keypress', onKeypress);
|
|
233
|
-
input.once('end', onEnd);
|
|
234
|
-
output.on('resize', onResize);
|
|
235
|
-
process.on('SIGINT', onSigint);
|
|
236
|
-
renderActive(true);
|
|
237
|
-
});
|
|
238
|
-
}
|
|
239
|
-
export async function promptSelectWithIO(question, options, defaultIndex = 0, io = {}) {
|
|
240
|
-
if (options.length === 0) {
|
|
241
|
-
throw new Error('promptSelect requires at least one option.');
|
|
242
|
-
}
|
|
243
|
-
const clampedDefault = Math.min(Math.max(0, Math.trunc(defaultIndex)), options.length - 1);
|
|
244
|
-
const input = io.input ?? defaultInput;
|
|
245
|
-
const output = io.output ?? defaultOutput;
|
|
246
|
-
const term = io.term ?? process.env.TERM;
|
|
247
|
-
const canUseInteractive = Boolean(input.isTTY) &&
|
|
248
|
-
Boolean(output.isTTY) &&
|
|
249
|
-
typeof input.setRawMode === 'function' &&
|
|
250
|
-
term !== 'dumb';
|
|
251
|
-
if (canUseInteractive) {
|
|
252
|
-
return promptSelectInteractive(question, options, clampedDefault, input, output);
|
|
253
|
-
}
|
|
254
|
-
return promptSelectFallback(question, options, clampedDefault, input, output);
|
|
255
|
-
}
|
|
256
|
-
export async function promptSelect(question, options, defaultIndex = 0) {
|
|
257
|
-
return promptSelectWithIO(question, options, defaultIndex);
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Prompts for a secret (such as an API key) without echoing the raw characters to the terminal.
|
|
261
|
-
*/
|
|
262
|
-
export async function promptSecret(question) {
|
|
263
|
-
if (!defaultInput.isTTY) {
|
|
264
|
-
const rl = readlinePromises.createInterface({ input: defaultInput, output: defaultOutput });
|
|
265
|
-
try {
|
|
266
|
-
return (await rl.question(`${question}: `)).trim();
|
|
267
|
-
}
|
|
268
|
-
finally {
|
|
269
|
-
rl.close();
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
return new Promise((resolve, reject) => {
|
|
273
|
-
defaultOutput.write(`${question}: `);
|
|
274
|
-
let value = '';
|
|
275
|
-
const wasRaw = defaultInput.isRaw;
|
|
276
|
-
defaultInput.setRawMode(true);
|
|
277
|
-
defaultInput.resume();
|
|
278
|
-
defaultInput.setEncoding('utf8');
|
|
279
|
-
const cleanup = () => {
|
|
280
|
-
defaultInput.removeListener('data', onData);
|
|
281
|
-
defaultInput.setRawMode(Boolean(wasRaw));
|
|
282
|
-
defaultInput.pause();
|
|
283
|
-
};
|
|
284
|
-
const onData = (chunk) => {
|
|
285
|
-
for (const ch of chunk) {
|
|
286
|
-
if (ch === '\r' || ch === '\n') {
|
|
287
|
-
cleanup();
|
|
288
|
-
defaultOutput.write('\n');
|
|
289
|
-
resolve(value.trim());
|
|
290
|
-
return;
|
|
291
|
-
}
|
|
292
|
-
if (ch === '\u0003') {
|
|
293
|
-
// Ctrl+C
|
|
294
|
-
cleanup();
|
|
295
|
-
defaultOutput.write('\n');
|
|
296
|
-
reject(new Error('Prompt canceled by user.'));
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
if (ch === '\u007f' || ch === '\b') {
|
|
300
|
-
if (value.length > 0) {
|
|
301
|
-
value = value.slice(0, -1);
|
|
302
|
-
defaultOutput.write('\b \b');
|
|
303
|
-
}
|
|
304
|
-
continue;
|
|
305
|
-
}
|
|
306
|
-
// Ignore non-printable escape sequences
|
|
307
|
-
if (ch.charCodeAt(0) < 32) {
|
|
308
|
-
continue;
|
|
309
|
-
}
|
|
310
|
-
value += ch;
|
|
311
|
-
defaultOutput.write('•');
|
|
312
|
-
}
|
|
313
|
-
};
|
|
314
|
-
defaultInput.on('data', onData);
|
|
315
|
-
});
|
|
316
|
-
}
|
|
File without changes
|