Refactor prompt timeout plugin to reduce nesting
This commit is contained in:
parent
69282c63d5
commit
37ffd09545
1 changed files with 16 additions and 13 deletions
27
src/util.js
27
src/util.js
|
|
@ -92,19 +92,22 @@ export const stealth = async context => {
|
||||||
// alternative inquirer is big (node_modules 29MB, enquirer 9.7MB, prompts 9.8MB, none 9.4MB) and slower
|
// alternative inquirer is big (node_modules 29MB, enquirer 9.7MB, prompts 9.8MB, none 9.4MB) and slower
|
||||||
// open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372
|
// open issue: prevents handleSIGINT() to work if prompt is cancelled with Ctrl-C instead of Escape: https://github.com/enquirer/enquirer/issues/372
|
||||||
import Enquirer from 'enquirer'; const enquirer = new Enquirer();
|
import Enquirer from 'enquirer'; const enquirer = new Enquirer();
|
||||||
const timeoutPlugin = defaultTimeout => enquirer => { // cancel prompt after timeout ms; can be disabled per prompt via options.timeout = 0
|
const timeoutHint = () => 'timeout';
|
||||||
const onPrompt = prompt => {
|
const cancelPromptWithHint = prompt => {
|
||||||
const effectiveTimeout = prompt.options?.timeout ?? defaultTimeout;
|
prompt.hint = timeoutHint;
|
||||||
if (!effectiveTimeout) return;
|
|
||||||
const t = setTimeout(() => {
|
|
||||||
prompt.hint = () => 'timeout';
|
|
||||||
prompt.cancel();
|
prompt.cancel();
|
||||||
}, effectiveTimeout);
|
};
|
||||||
const clear = () => clearTimeout(t);
|
const applyPromptTimeout = (prompt, timeout) => {
|
||||||
prompt.on('submit', clear);
|
if (!timeout) return;
|
||||||
prompt.on('cancel', clear);
|
const timer = setTimeout(cancelPromptWithHint, timeout, prompt);
|
||||||
};
|
const clearTimer = () => clearTimeout(timer);
|
||||||
enquirer.on('prompt', onPrompt);
|
prompt.on('submit', clearTimer);
|
||||||
|
prompt.on('cancel', clearTimer);
|
||||||
|
};
|
||||||
|
// cancel prompt after timeout ms; can be disabled per prompt via options.timeout = 0
|
||||||
|
const timeoutPlugin = defaultTimeout => enquirerInstance => {
|
||||||
|
const onPrompt = prompt => applyPromptTimeout(prompt, prompt.options?.timeout ?? defaultTimeout);
|
||||||
|
enquirerInstance.on('prompt', onPrompt);
|
||||||
};
|
};
|
||||||
enquirer.use(timeoutPlugin(cfg.login_timeout));
|
enquirer.use(timeoutPlugin(cfg.login_timeout));
|
||||||
// single prompt that just returns the non-empty value instead of an object
|
// single prompt that just returns the non-empty value instead of an object
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue