@jacebenson/jsn 5.5.7-dev.211.1 → 5.5.7-dev.212.1
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 +16 -1
- package/package.json +5 -6
- package/src/cli-adapter.js +18 -1
- package/src/commands/codesearch.js +11 -2
- package/src/commands/docs/docs.js +2 -0
- package/src/commands/flows.js +7 -2
- package/src/commands/setup.js +28 -31
- package/src/docs-links.js +28 -0
- package/src/help.js +4 -0
- package/src/paginated-search.js +146 -178
- package/src/prompt-engine.js +169 -0
- package/src/prompts.js +304 -42
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ jsn setup
|
|
|
15
15
|
|
|
16
16
|
Setup connects a named profile to your instance. Its default preset allows writes, so enable read-only mode before exploring. See [setup and authentication](https://jsn.jace.pro/docs/setup/).
|
|
17
17
|
|
|
18
|
-
For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/docs/releases.md).
|
|
18
|
+
For unreleased changes, use `npm install -g @jacebenson/jsn@dev`; see [channels and updates](https://github.com/jacebenson/jsn/blob/main/site/docs/maintainers/releases.md).
|
|
19
19
|
|
|
20
20
|
## Read and discover
|
|
21
21
|
|
|
@@ -42,6 +42,21 @@ Writes are not universally dry-run operations or confirmation prompts. Inspect e
|
|
|
42
42
|
|
|
43
43
|
Inspect the bundled skill with `jsn skill show`, then use `jsn skill install` to select your agent or `jsn skill install --target hermes` for Hermes. Reinstall after upgrading JSN; reinstalling replaces recorded copies, including local edits. See [agent installation](https://jsn.jace.pro/docs/agents/).
|
|
44
44
|
|
|
45
|
+
## Local prompt experiment
|
|
46
|
+
|
|
47
|
+
From the repository root, run `node cli/scripts/prompt-demo.mjs` in a terminal.
|
|
48
|
+
It uses synthetic servers only. Nothing connects to ServiceNow or changes profiles.
|
|
49
|
+
Type to filter, use arrows to move and Enter to select. Down past the last loaded
|
|
50
|
+
server fetches another page. Escape cancels. Ctrl+C or Ctrl+D exits the prompt.
|
|
51
|
+
The forms menu includes masked input, confirmation and a checklist. The editor
|
|
52
|
+
menu uses your `$VISUAL` or `$EDITOR`, falling back to `vi`.
|
|
53
|
+
|
|
54
|
+
From `cli/`, `npm ci` installs lint and test dependencies without Inquirer.
|
|
55
|
+
Run `npm run test:pty` for the Linux Python 3 PTY checks. `npm test` also collects
|
|
56
|
+
them. Mutation tooling is not part of normal installs. `npm run test:mutation`
|
|
57
|
+
fetches pinned Stryker 10.1.1 on demand and uses `stryker.config.json`, retaining
|
|
58
|
+
the offline mutation-safety tests. Its execution is separate from normal tests.
|
|
59
|
+
|
|
45
60
|
## Go deeper
|
|
46
61
|
|
|
47
62
|
- [CLI guide and feature workflows](https://jsn.jace.pro/docs/cli-guide/)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jacebenson/jsn",
|
|
3
|
-
"version": "5.5.7-dev.
|
|
3
|
+
"version": "5.5.7-dev.212.1",
|
|
4
4
|
"description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
"main": "src/cli.js",
|
|
10
10
|
"scripts": {
|
|
11
11
|
"test": "node scripts/test.mjs",
|
|
12
|
-
"test:mutation": "stryker run",
|
|
13
|
-
"
|
|
12
|
+
"test:mutation": "npm exec --yes --package=@stryker-mutator/core@10.1.1 -- stryker run stryker.config.json",
|
|
13
|
+
"test:pty": "node --test test/pty/prompts-pty.test.js",
|
|
14
|
+
"lint": "eslint src/ bin/ test/",
|
|
14
15
|
"start": "node bin/jsn.js"
|
|
15
16
|
},
|
|
16
17
|
"keywords": [
|
|
@@ -23,8 +24,6 @@
|
|
|
23
24
|
"repository": "https://github.com/jacebenson/jsn",
|
|
24
25
|
"license": "MIT",
|
|
25
26
|
"dependencies": {
|
|
26
|
-
"@inquirer/core": "^10.3.2",
|
|
27
|
-
"@inquirer/prompts": "^7.10.1",
|
|
28
27
|
"commonmark": "^0.31.2",
|
|
29
28
|
"js-yaml": "^5.5.0",
|
|
30
29
|
"saxes": "^6.0.0",
|
|
@@ -32,7 +31,7 @@
|
|
|
32
31
|
},
|
|
33
32
|
"devDependencies": {
|
|
34
33
|
"@eslint/js": "^10.0.1",
|
|
35
|
-
"
|
|
34
|
+
"eslint": "^10.15.0",
|
|
36
35
|
"globals": "^17.6.0"
|
|
37
36
|
},
|
|
38
37
|
"files": [
|
package/src/cli-adapter.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parseArgs } from 'node:util';
|
|
2
2
|
import process from 'node:process';
|
|
3
3
|
import { renderSubcommandHelp } from './help.js';
|
|
4
|
+
import { resolveDocLink } from './docs-links.js';
|
|
4
5
|
|
|
5
6
|
const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
6
7
|
const names = (x) => typeof x === 'string' ? [x] : (x || []);
|
|
@@ -398,9 +399,25 @@ export class LocalCLI {
|
|
|
398
399
|
description: node.definition.describe,
|
|
399
400
|
commands,
|
|
400
401
|
options: this._optionRows(node),
|
|
401
|
-
epilogue: node
|
|
402
|
+
epilogue: this._docsEpilogue(node, path),
|
|
402
403
|
}));
|
|
403
404
|
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Every help page names the maintained documentation for its command family.
|
|
408
|
+
* The family comes from the parser's canonical resolved path, so aliases
|
|
409
|
+
* (`jsn flow`) and nested commands (`jsn records list`) reach the same
|
|
410
|
+
* registered topic without a per-subcommand footer. A page whose authored
|
|
411
|
+
* epilogue already prints that URL keeps its own wording rather than repeating
|
|
412
|
+
* it, and a family with no migrated guide gains no invented URL.
|
|
413
|
+
*/
|
|
414
|
+
_docsEpilogue(node, path) {
|
|
415
|
+
const base = node.epilogueText;
|
|
416
|
+
const link = path.length ? resolveDocLink(path[0]) : null;
|
|
417
|
+
if (!link || (base && base.includes(link))) return base;
|
|
418
|
+
const line = `Documentation: ${link}`;
|
|
419
|
+
return base ? `${base}\n${line}` : line;
|
|
420
|
+
}
|
|
404
421
|
async parse() {
|
|
405
422
|
// Reject stale installed shell snippets instead of dispatching their words
|
|
406
423
|
// as ordinary commands (for example the `r` alias).
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// GraphQL read-only queries; no sn_codesearch engine or Flow downloads.
|
|
2
2
|
import { searchGraphQL } from '../codesearch-graphql.js';
|
|
3
|
+
import { docLink } from '../docs-links.js';
|
|
3
4
|
|
|
4
5
|
export function renderCodeSearch(data) {
|
|
5
6
|
const out = [`${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}`];
|
|
@@ -35,13 +36,21 @@ export function codesearchCmd(wrap) {
|
|
|
35
36
|
.option('all-scopes', { type: 'boolean', default: true, describe: 'Search all scopes; false requires --scope' })
|
|
36
37
|
.option('page-size', { type: 'number', default: 250, describe: 'GraphQL page window size (max 1000)' })
|
|
37
38
|
.option('max-pages', { type: 'number', default: 20, describe: 'Maximum pages per table (max 1000)' })
|
|
38
|
-
.option('max-requests', { type: 'number', default: 1000, describe: 'Data-call budget including configuration, excluding SDK auth/bootstrap (max 10000)' })
|
|
39
|
+
.option('max-requests', { type: 'number', default: 1000, describe: 'Data-call budget including configuration, excluding SDK auth/bootstrap (max 10000)' })
|
|
40
|
+
.epilogue(`Code search is literal and read-only. Flow internals use "jsn flows search <term>".
|
|
41
|
+
Examples:
|
|
42
|
+
jsn codesearch search GlideAjax --limit 5
|
|
43
|
+
jsn codesearch search approval --scope x_my_app --limit 5
|
|
44
|
+
|
|
45
|
+
Full reference and coverage limits: ${docLink('codesearch')}`),
|
|
39
46
|
handler: wrap(async (argv, app) => {
|
|
40
47
|
const data = await searchGraphQL(app, argv);
|
|
41
48
|
Object.defineProperty(data, '_formatted', { value: renderCodeSearch(data), enumerable: false });
|
|
42
49
|
app.ok(data, { summary: `${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}` });
|
|
43
50
|
}),
|
|
44
|
-
}).demandCommand(1, 'Specify a subcommand: search')
|
|
51
|
+
}).demandCommand(1, 'Specify a subcommand: search')
|
|
52
|
+
.epilogue(`Code search is literal and read-only. Flow internals use "jsn flows search <term>".
|
|
53
|
+
Documentation: ${docLink('codesearch')}`),
|
|
45
54
|
handler: () => {},
|
|
46
55
|
};
|
|
47
56
|
}
|
|
@@ -3,6 +3,7 @@ import { searchHostedDocs, getHostedDoc, getHostedDocsStatus, configuredDocsServ
|
|
|
3
3
|
import { documentationService } from './local.js';
|
|
4
4
|
|
|
5
5
|
import { declareCapabilities } from '../../capabilities.js';
|
|
6
|
+
import { docLink } from '../../docs-links.js';
|
|
6
7
|
import { AppError } from '../../errors.js';
|
|
7
8
|
import { resolveDocsRelease } from './db.js';
|
|
8
9
|
import { listDocsReleases } from './releases.js';
|
|
@@ -62,6 +63,7 @@ export function docsCmd(wrapHandler) {
|
|
|
62
63
|
describe: 'Search ServiceNow documentation (hosted by default; configure your service in setup)',
|
|
63
64
|
builder: y => y
|
|
64
65
|
.usage('Usage: jsn docs "search terms" [options]')
|
|
66
|
+
.epilogue(`Documentation for this command: ${docLink('docs')}`)
|
|
65
67
|
.positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
|
|
66
68
|
.option('release', { type: 'string', describe: 'Documentation family (docs.release config, otherwise australia)' })
|
|
67
69
|
|
package/src/commands/flows.js
CHANGED
|
@@ -5,6 +5,7 @@ import { canUsePicker } from '../helpers.js';
|
|
|
5
5
|
import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
|
|
6
6
|
import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
|
|
7
7
|
import { declareCapabilities } from '../capabilities.js';
|
|
8
|
+
import { docLink } from '../docs-links.js';
|
|
8
9
|
import { inspectFlow } from '../flow-inspection.js';
|
|
9
10
|
import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
|
|
10
11
|
import { resolveRecord, unwrapSysId } from '../resolve-record.js';
|
|
@@ -96,7 +97,11 @@ export function flowsCmd(wrap) {
|
|
|
96
97
|
describe: 'Download/decode visible flows into a private cache and search literal text (first use can be slow)',
|
|
97
98
|
builder: y => y
|
|
98
99
|
.positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
|
|
99
|
-
.option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' })
|
|
100
|
+
.option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' })
|
|
101
|
+
.epilogue(`Example:
|
|
102
|
+
jsn flows search approval
|
|
103
|
+
Interactive use can pick a flow; scripts pass the term.
|
|
104
|
+
Documentation: ${docLink('flows')}`),
|
|
100
105
|
handler: wrap(async (argv, app) => {
|
|
101
106
|
app.requireInstance();
|
|
102
107
|
const session = app.session || {};
|
|
@@ -575,7 +580,7 @@ export function flowsCmd(wrap) {
|
|
|
575
580
|
}),
|
|
576
581
|
})
|
|
577
582
|
.epilogue('Run "jsn flows <command> --help" for details. In a terminal you can omit the target and pick\n'
|
|
578
|
-
+
|
|
583
|
+
+ `one; scripts use explicit identifiers and manifests.\nDocumentation: ${docLink('flows')}`);
|
|
579
584
|
},
|
|
580
585
|
handler: wrap(async (_argv, app) => {
|
|
581
586
|
const summary = 'Manage Flow Designer flows from the sys_hub_flow table. Flow structure comes from the ProcessFlow API, so V1, V2 and subflow definitions all render in full.';
|
package/src/commands/setup.js
CHANGED
|
@@ -42,39 +42,36 @@ const setupHelp = () => [
|
|
|
42
42
|
].join('\n');
|
|
43
43
|
|
|
44
44
|
/** The setup hub prompt; q and Escape resolve with no selected action. */
|
|
45
|
-
export const authHubPrompt = async (
|
|
46
|
-
const {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
done(choices[active].value);
|
|
45
|
+
export const authHubPrompt = async (config = {}, context = {}) => {
|
|
46
|
+
const { runPrompt, escapeResult } = await import('../prompt-engine.js');
|
|
47
|
+
const choices = config.choices || [];
|
|
48
|
+
const state = { active: 0 };
|
|
49
|
+
return runPrompt(config, context, {
|
|
50
|
+
escapeValue: escapeResult(undefined),
|
|
51
|
+
init: () => state,
|
|
52
|
+
key(_state, key, api) {
|
|
53
|
+
if (key.name === 'q') return { done: undefined };
|
|
54
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
55
|
+
const choice = choices[state.active];
|
|
56
|
+
if (choice) return { done: choice.value };
|
|
58
57
|
return;
|
|
59
58
|
}
|
|
60
|
-
if (
|
|
61
|
-
if (
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return `${config.message}\n${page}\n\n↑↓ navigate • ⏎ select • q/Esc exit`;
|
|
77
|
-
})(...args);
|
|
59
|
+
if (key.name === 'up' && state.active > 0) { state.active -= 1; api.redraw(); return; }
|
|
60
|
+
if (key.name === 'down' && state.active < choices.length - 1) { state.active += 1; api.redraw(); }
|
|
61
|
+
},
|
|
62
|
+
render() {
|
|
63
|
+
// Section headings are rendered inline; the pagination budget the
|
|
64
|
+
// Inquirer version needed no longer applies to a local renderer.
|
|
65
|
+
const lines = [config.message];
|
|
66
|
+
choices.forEach((choice, index) => {
|
|
67
|
+
const heading = choices[index - 1]?.section !== choice.section ? `${index ? '\n' : ''} ${choice.section}` : null;
|
|
68
|
+
if (heading) lines.push(heading);
|
|
69
|
+
lines.push(`${index === state.active ? '❯' : ' '} ${choice.name}`);
|
|
70
|
+
});
|
|
71
|
+
lines.push('', '↑↓ navigate • ⏎ select • q/Esc exit');
|
|
72
|
+
return lines;
|
|
73
|
+
},
|
|
74
|
+
});
|
|
78
75
|
};
|
|
79
76
|
|
|
80
77
|
/** Interactive hub: what do you want to do? Returns an action or undefined on exit. */
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// GENERATED FILENAME: keep in sync with site/config/docs-links.json.
|
|
2
|
+
// The npm package ships only cli/, so this projection is checked in and verified
|
|
3
|
+
// by site/test/docs_links_test.rb. Edit the registry, then regenerate this file.
|
|
4
|
+
export const SITE_ORIGIN = 'https://jsn.jace.pro';
|
|
5
|
+
export const ROOT_DOC_LINK = '/docs/';
|
|
6
|
+
export const DOC_LINKS = Object.freeze({
|
|
7
|
+
codesearch: '/features/servicenow-code-search-cli/',
|
|
8
|
+
docs: '/docs/cli-guide/#jsn-cli-guide',
|
|
9
|
+
flows: '/docs/flows/#flow-definition-search',
|
|
10
|
+
records: '/docs/records/#watching-a-servicenow-record',
|
|
11
|
+
updatesets: '/docs/updatesets/#transfer-an-update-set',
|
|
12
|
+
midservers: '/docs/midservers/#remote-mid-management-over-ssh',
|
|
13
|
+
setup: '/docs/setup/#connect-an-instance',
|
|
14
|
+
auth: '/docs/setup/#authentication-lifecycle-review',
|
|
15
|
+
skill: '/docs/agents/#use-jsn-with-ai-agents',
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/** Absolute documentation URL for one registered command family, or null when
|
|
19
|
+
* the family has no migrated guide. Callers decide how to render a miss. */
|
|
20
|
+
export function resolveDocLink(name) {
|
|
21
|
+
const path = DOC_LINKS[name];
|
|
22
|
+
return path ? `${SITE_ORIGIN}${path}` : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Absolute documentation URL for one registered command family. */
|
|
26
|
+
export function docLink(name) {
|
|
27
|
+
return resolveDocLink(name) || `${SITE_ORIGIN}${ROOT_DOC_LINK}`;
|
|
28
|
+
}
|
package/src/help.js
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
// (`approvals`, `cmdb`, `docs`, `perf`, `platform`, … were missing from the
|
|
11
11
|
// hand-written list while being fully registered).
|
|
12
12
|
|
|
13
|
+
import { SITE_ORIGIN, ROOT_DOC_LINK } from './docs-links.js';
|
|
14
|
+
|
|
13
15
|
const COMMON_COMMANDS = [
|
|
14
16
|
'incidents', 'requests', 'tasks', 'changes', 'approvals', 'knowledge', 'records', 'setup', 'discover',
|
|
15
17
|
];
|
|
@@ -23,6 +25,7 @@ const CONCISE_EXAMPLES = [
|
|
|
23
25
|
];
|
|
24
26
|
|
|
25
27
|
const CONCISE_MORE = [
|
|
28
|
+
{ label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides: install, setup, safety, output, agents and feature references' },
|
|
26
29
|
{ label: 'jsn <command> <action> --help', description: 'Options for one command or action' },
|
|
27
30
|
{ label: 'jsn discover <word>', description: 'Find commands by task words' },
|
|
28
31
|
{ label: 'jsn discover --table <table>', description: 'Find commands configured for a table' },
|
|
@@ -289,6 +292,7 @@ TIPS
|
|
|
289
292
|
"jsn --json" prints the registered command surface as JSON for scripts and agents
|
|
290
293
|
|
|
291
294
|
LEARN MORE
|
|
295
|
+
Documentation and feature references: https://jsn.jace.pro/docs/
|
|
292
296
|
Some list commands offer a picker in an interactive terminal with automatic output.
|
|
293
297
|
Arrow keys browse (10 visible items); type to search; scroll to load more; Enter selects; Esc cancels.
|
|
294
298
|
Picker eligibility and search fields vary by command. Explicit output formats (including --json) skip pickers.
|
package/src/paginated-search.js
CHANGED
|
@@ -1,195 +1,163 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Paginated
|
|
2
|
+
* Paginated, searchable record picker built on src/prompt-engine.js.
|
|
3
|
+
*
|
|
4
|
+
* Contract (unchanged from the Inquirer version):
|
|
5
|
+
* paginatedSearch({ message, pageSize, totalCount, source }, context?)
|
|
6
|
+
* source(term, offset, { signal }) -> [{ name, value }]
|
|
7
|
+
* Enter resolves the active choice object; Escape resolves undefined.
|
|
8
|
+
* Down at the last loaded row loads more while loaded < totalCount.
|
|
3
9
|
*/
|
|
4
10
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (!controller.signal.aborted) {
|
|
48
|
-
setStatus('done');
|
|
49
|
-
setChoices([]);
|
|
50
|
-
setLoaded(0);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
load();
|
|
55
|
-
return () => controller.abort();
|
|
56
|
-
}, []);
|
|
57
|
-
|
|
58
|
-
// Load more when scrolling past end
|
|
59
|
-
async function loadMore() {
|
|
60
|
-
if (loadedRef.current >= totalCountRef.current || searchModeRef.current) return;
|
|
61
|
-
setStatus('loading');
|
|
62
|
-
try {
|
|
63
|
-
const newItems = await source('', loadedRef.current, { signal: new AbortController().signal });
|
|
64
|
-
const updated = choicesRef.current.concat(newItems);
|
|
65
|
-
choicesRef.current = updated;
|
|
66
|
-
loadedRef.current = updated.length;
|
|
67
|
-
setChoices([...updated]);
|
|
68
|
-
setLoaded(updated.length);
|
|
69
|
-
} catch (err) {
|
|
70
|
-
console.error('Scroll load error:', err.message || err);
|
|
71
|
-
loadedRef.current = totalCountRef.current;
|
|
72
|
-
setLoaded(totalCountRef.current);
|
|
11
|
+
import { runPrompt, normalizeChoices, truncate, escapeResult } from './prompt-engine.js';
|
|
12
|
+
|
|
13
|
+
export const paginatedSearch = async (config = {}, context = {}) => {
|
|
14
|
+
const { message, pageSize = 10, totalCount = 0, source } = config;
|
|
15
|
+
let request;
|
|
16
|
+
const state = {
|
|
17
|
+
status: 'loading',
|
|
18
|
+
term: '',
|
|
19
|
+
choices: [],
|
|
20
|
+
active: 0,
|
|
21
|
+
loaded: 0,
|
|
22
|
+
searchMode: false,
|
|
23
|
+
token: 0,
|
|
24
|
+
error: '',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// Every request gets a token. A response may only be applied while its
|
|
28
|
+
// token is still current, so a stale (slower) search can never replace
|
|
29
|
+
// newer results or be selected by a later Enter.
|
|
30
|
+
const isCurrent = token => token === state.token && state.status !== 'cancelled';
|
|
31
|
+
|
|
32
|
+
async function load(term, offset, { append = false } = {}) {
|
|
33
|
+
request?.abort();
|
|
34
|
+
request = new AbortController();
|
|
35
|
+
const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
|
|
36
|
+
const token = ++state.token;
|
|
37
|
+
state.status = 'loading';
|
|
38
|
+
state.error = '';
|
|
39
|
+
try {
|
|
40
|
+
const items = normalizeChoices(await source(term || undefined, offset, { signal }) || []);
|
|
41
|
+
if (!isCurrent(token)) return;
|
|
42
|
+
state.choices = append ? state.choices.concat(items) : items;
|
|
43
|
+
state.loaded = state.choices.length;
|
|
44
|
+
state.active = Math.min(state.active, Math.max(0, state.choices.length - 1));
|
|
45
|
+
state.status = 'done';
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (!isCurrent(token)) return;
|
|
48
|
+
state.status = 'done';
|
|
49
|
+
state.error = error?.message || String(error);
|
|
50
|
+
if (!append) {
|
|
51
|
+
state.choices = [];
|
|
52
|
+
state.loaded = 0;
|
|
73
53
|
}
|
|
74
|
-
|
|
54
|
+
// A failed load-more keeps the rows already on screen.
|
|
75
55
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
setActive(0);
|
|
92
|
-
setStatus('done');
|
|
93
|
-
}
|
|
94
|
-
}).catch(() => {
|
|
95
|
-
if (!controller.signal.aborted) setStatus('done');
|
|
96
|
-
});
|
|
97
|
-
return () => controller.abort();
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const controller = new AbortController();
|
|
101
|
-
setStatus('loading');
|
|
102
|
-
setSearchMode(true);
|
|
103
|
-
searchModeRef.current = true;
|
|
104
|
-
|
|
105
|
-
source(searchTerm, undefined, { signal: controller.signal }).then(items => {
|
|
106
|
-
if (!controller.signal.aborted) {
|
|
107
|
-
choicesRef.current = items;
|
|
108
|
-
loadedRef.current = items.length;
|
|
109
|
-
activeRef.current = 0;
|
|
110
|
-
setChoices(items);
|
|
111
|
-
setLoaded(items.length);
|
|
112
|
-
setActive(0);
|
|
113
|
-
setStatus('done');
|
|
114
|
-
}
|
|
115
|
-
}).catch(() => {
|
|
116
|
-
if (!controller.signal.aborted) {
|
|
117
|
-
setStatus('done');
|
|
118
|
-
setChoices([]);
|
|
119
|
-
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let api;
|
|
59
|
+
const prompt = runPrompt({ ...config, message }, context, {
|
|
60
|
+
escapeValue: escapeResult(undefined),
|
|
61
|
+
init() {
|
|
62
|
+
// Kick off the first page. Enter is ignored while status is 'loading',
|
|
63
|
+
// so nothing is selectable until this resolves.
|
|
64
|
+
state.pending = load('', 0);
|
|
65
|
+
return state;
|
|
66
|
+
},
|
|
67
|
+
onReady(handle) {
|
|
68
|
+
api = handle;
|
|
69
|
+
state.pending.then(() => {
|
|
70
|
+
if (state.status !== 'cancelled') api.redraw();
|
|
120
71
|
});
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
done(choicesRef.current[activeRef.current]);
|
|
132
|
-
}
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
if (key.name === 'escape') {
|
|
137
|
-
done(undefined);
|
|
138
|
-
return;
|
|
72
|
+
},
|
|
73
|
+
key(_state, key, handle) {
|
|
74
|
+
api = handle;
|
|
75
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
76
|
+
// No selecting a row while a request is in flight: the list on
|
|
77
|
+
// screen may be about to change.
|
|
78
|
+
if (state.status === 'loading' || !state.choices.length) return;
|
|
79
|
+
const choice = state.choices[state.active];
|
|
80
|
+
if (!choice) return;
|
|
81
|
+
return { done: choice };
|
|
139
82
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
activeRef.current--;
|
|
144
|
-
setActive(activeRef.current);
|
|
145
|
-
}
|
|
83
|
+
if (key.name === 'up') {
|
|
84
|
+
if (state.active > 0) state.active -= 1;
|
|
85
|
+
api?.redraw();
|
|
146
86
|
return;
|
|
147
87
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
if (
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
} else if (!
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
88
|
+
if (key.name === 'down') {
|
|
89
|
+
if (state.status === 'loading') return;
|
|
90
|
+
if (state.active < state.choices.length - 1) {
|
|
91
|
+
state.active += 1;
|
|
92
|
+
api?.redraw();
|
|
93
|
+
} else if (!state.searchMode && state.loaded < totalCount) {
|
|
94
|
+
const before = state.loaded;
|
|
95
|
+
const pending = load('', state.loaded, { append: true });
|
|
96
|
+
const token = state.token;
|
|
97
|
+
void pending.then(() => {
|
|
98
|
+
if (!isCurrent(token)) return;
|
|
99
|
+
if (state.status === 'done' && state.loaded > before) state.active = before;
|
|
100
|
+
api?.redraw();
|
|
157
101
|
});
|
|
102
|
+
api?.redraw();
|
|
158
103
|
}
|
|
159
104
|
return;
|
|
160
105
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
if (
|
|
165
|
-
|
|
106
|
+
const previous = state.term;
|
|
107
|
+
if (key.name === 'backspace') state.term = state.term.slice(0, -1);
|
|
108
|
+
else if (key.name === 'space') state.term += ' ';
|
|
109
|
+
else if (key.text) state.term += key.text;
|
|
110
|
+
else return;
|
|
111
|
+
if (state.term === previous) return;
|
|
112
|
+
|
|
113
|
+
if (!state.term) {
|
|
114
|
+
state.searchMode = false;
|
|
115
|
+
state.active = 0;
|
|
116
|
+
void load('', 0).then(() => api?.redraw());
|
|
117
|
+
api?.redraw();
|
|
118
|
+
return;
|
|
166
119
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
pageSize
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
120
|
+
state.searchMode = true;
|
|
121
|
+
state.active = 0;
|
|
122
|
+
void load(state.term, undefined).then(() => api?.redraw());
|
|
123
|
+
api?.redraw();
|
|
124
|
+
},
|
|
125
|
+
render() {
|
|
126
|
+
const pages = Math.max(1, Math.ceil(state.choices.length / pageSize));
|
|
127
|
+
const current = Math.min(pages - 1, Math.floor(state.active / pageSize));
|
|
128
|
+
const start = current * pageSize;
|
|
129
|
+
const visible = state.choices.slice(start, start + pageSize);
|
|
130
|
+
const header = totalCount > 0 && !state.searchMode
|
|
131
|
+
? `${message} (${state.loaded} of ${totalCount} loaded)`
|
|
132
|
+
: message;
|
|
133
|
+
const lines = [`${header} Search: ${state.term}${state.status === 'loading' ? ' ...' : ''}`];
|
|
134
|
+
if (state.error) lines.push(` ${state.error}`);
|
|
135
|
+
else if (!state.choices.length) lines.push(state.status === 'loading' ? ' Loading...' : ' No matches');
|
|
136
|
+
visible.forEach((choice, index) => {
|
|
137
|
+
const absolute = start + index;
|
|
138
|
+
lines.push(`${absolute === state.active ? '>' : ' '} ${truncate(choice.name)}`);
|
|
139
|
+
});
|
|
140
|
+
const help = state.loaded < totalCount && !state.searchMode
|
|
141
|
+
? '(scroll to load more, type to search, Esc to cancel)'
|
|
142
|
+
: '(type to search, Esc to cancel)';
|
|
143
|
+
lines.push('', help);
|
|
144
|
+
return lines;
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
return prompt.then(value => {
|
|
149
|
+
// Mark the prompt so an in-flight source response cannot redraw or
|
|
150
|
+
// apply after the picker closed.
|
|
151
|
+
state.status = 'cancelled';
|
|
152
|
+
state.token += 1;
|
|
153
|
+
request?.abort();
|
|
154
|
+
return value;
|
|
155
|
+
}, error => {
|
|
156
|
+
state.status = 'cancelled';
|
|
157
|
+
state.token += 1;
|
|
158
|
+
request?.abort();
|
|
159
|
+
throw error;
|
|
160
|
+
}).then(value => value);
|
|
193
161
|
};
|
|
194
162
|
|
|
195
163
|
export default paginatedSearch;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small terminal prompt engine built on node:readline keypress events.
|
|
3
|
+
*
|
|
4
|
+
* This is deliberately not a general prompt library: it exists so JSN's
|
|
5
|
+
* observed prompt surface (input, password, confirm, select, search,
|
|
6
|
+
* checkbox, editor, paginated pickers) runs on Node built-ins with no
|
|
7
|
+
* runtime dependency, while keeping the existing caller contract
|
|
8
|
+
* `prompt(config, { input, output, signal })`.
|
|
9
|
+
*
|
|
10
|
+
* Every prompt restores raw mode and removes its listener in `finally`,
|
|
11
|
+
* on success, Escape, Ctrl+C and thrown errors alike.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import readline from 'node:readline';
|
|
15
|
+
|
|
16
|
+
export class PromptCancelled extends Error {
|
|
17
|
+
constructor() {
|
|
18
|
+
super('Cancelled.');
|
|
19
|
+
this.name = 'PromptCancelled';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Choices may be strings or { name, value, disabled }. */
|
|
24
|
+
export function normalizeChoices(choices = []) {
|
|
25
|
+
return choices.map(choice => {
|
|
26
|
+
if (choice && typeof choice === 'object') {
|
|
27
|
+
return {
|
|
28
|
+
name: String(choice.name ?? choice.value ?? ''),
|
|
29
|
+
value: 'value' in choice ? choice.value : choice.name,
|
|
30
|
+
disabled: Boolean(choice.disabled),
|
|
31
|
+
checked: Boolean(choice.checked),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
return { name: String(choice), value: choice, disabled: false };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function truncate(text, width = 70) {
|
|
39
|
+
const value = String(text ?? '');
|
|
40
|
+
return value.length > width ? `${value.slice(0, width - 3)}...` : value;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Run one interactive prompt.
|
|
45
|
+
*
|
|
46
|
+
* @param {object} config prompt config ({ message, ... })
|
|
47
|
+
* @param {object} context { input, output, signal }
|
|
48
|
+
* @param {object} spec
|
|
49
|
+
* init(config, context) -> state
|
|
50
|
+
* key(state, key, api) -> directive | undefined | Promise<...>
|
|
51
|
+
* directive: { done: value } finishes, { cancel: true } throws
|
|
52
|
+
* PromptCancelled, { escape: true } resolves undefined.
|
|
53
|
+
* render(config, state) -> string | string[]
|
|
54
|
+
* final(config, value, state) -> string | null — the settled answer line
|
|
55
|
+
* (Inquirer prints `✔ <message> <answer>`). Only written on a TTY after
|
|
56
|
+
* the live frame is erased, so one prompt yields exactly one final line
|
|
57
|
+
* and piped output keeps its existing byte contract.
|
|
58
|
+
* escapeValue — when the caller treats Escape as "leave this screen",
|
|
59
|
+
* pass a sentinel produced by `escapeResult(value)`.
|
|
60
|
+
*/
|
|
61
|
+
export async function runPrompt(config, context, spec) {
|
|
62
|
+
const input = context.input || process.stdin;
|
|
63
|
+
const output = context.output || process.stdout;
|
|
64
|
+
const canRaw = typeof input.setRawMode === 'function';
|
|
65
|
+
const previousRaw = canRaw ? Boolean(input.isRaw) : false;
|
|
66
|
+
|
|
67
|
+
let state;
|
|
68
|
+
let height = 0;
|
|
69
|
+
let settled = false;
|
|
70
|
+
let resolveDone;
|
|
71
|
+
let rejectDone;
|
|
72
|
+
|
|
73
|
+
const done = new Promise((resolve, reject) => { resolveDone = resolve; rejectDone = reject; });
|
|
74
|
+
|
|
75
|
+
const draw = () => {
|
|
76
|
+
if (settled) return;
|
|
77
|
+
const rendered = spec.render(state);
|
|
78
|
+
const text = Array.isArray(rendered) ? rendered.join('\n') : String(rendered ?? '');
|
|
79
|
+
if (output.isTTY && height > 0) output.write(`\x1b[${height}A\x1b[0J`);
|
|
80
|
+
output.write(`${text}\n`);
|
|
81
|
+
height = text.split('\n').length;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const finish = value => {
|
|
85
|
+
if (settled) return;
|
|
86
|
+
settled = true;
|
|
87
|
+
// The settled answer replaces the live frame rather than appending to it:
|
|
88
|
+
// rewind the frame height first so a terminal reader sees one final line.
|
|
89
|
+
if (spec.final && output.isTTY) {
|
|
90
|
+
const line = spec.final(config, value, state);
|
|
91
|
+
if (line) {
|
|
92
|
+
if (height > 0) output.write(`\x1b[${height}A\x1b[0J`);
|
|
93
|
+
output.write(`${line}\n`);
|
|
94
|
+
height = 0;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
resolveDone(value);
|
|
98
|
+
};
|
|
99
|
+
const fail = error => {
|
|
100
|
+
if (settled) return;
|
|
101
|
+
settled = true;
|
|
102
|
+
rejectDone(error);
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const api = { finish, fail, redraw: draw };
|
|
106
|
+
let queue = Promise.resolve();
|
|
107
|
+
const onKeypress = (_chunk, key) => {
|
|
108
|
+
if (!key || settled) return;
|
|
109
|
+
// Cancellation cannot wait behind validation or a source request.
|
|
110
|
+
if (key.name === 'escape') {
|
|
111
|
+
if (spec.escapeValue !== undefined) finish(spec.escapeValue.value);
|
|
112
|
+
else fail(new PromptCancelled());
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (key.ctrl && (key.name === 'c' || key.name === 'd')) {
|
|
116
|
+
fail(new PromptCancelled());
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
key = { ...key, text: !key.ctrl && !key.meta && typeof _chunk === 'string' && Array.from(_chunk).every(char => char.codePointAt(0) >= 32 && char.codePointAt(0) !== 127) ? _chunk : '' };
|
|
120
|
+
// Serialize handling: a chunk can carry several keys at once, and async
|
|
121
|
+
// handlers (search/load-more) must not reorder Enter ahead of arrows.
|
|
122
|
+
queue = queue.then(async () => {
|
|
123
|
+
if (settled) return;
|
|
124
|
+
|
|
125
|
+
const directive = await spec.key(state, key, api);
|
|
126
|
+
if (!directive || settled) return;
|
|
127
|
+
if ('done' in directive) finish(directive.done);
|
|
128
|
+
else if (directive.cancel) fail(new PromptCancelled());
|
|
129
|
+
else if (directive.escape) finish(undefined);
|
|
130
|
+
}).catch(error => fail(error));
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const onAbort = () => fail(context.signal.reason || new PromptCancelled());
|
|
134
|
+
const onEnd = () => fail(new PromptCancelled());
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
readline.emitKeypressEvents(input);
|
|
138
|
+
if (canRaw) input.setRawMode(true);
|
|
139
|
+
input.on('keypress', onKeypress);
|
|
140
|
+
input.on('end', onEnd);
|
|
141
|
+
input.on('close', onEnd);
|
|
142
|
+
input.on('error', fail);
|
|
143
|
+
if (context.signal) {
|
|
144
|
+
if (context.signal.aborted) onAbort();
|
|
145
|
+
else context.signal.addEventListener('abort', onAbort, { once: true });
|
|
146
|
+
}
|
|
147
|
+
state = spec.init(config, context);
|
|
148
|
+
if (input.readableEnded || input.destroyed) onEnd();
|
|
149
|
+
if (typeof input.resume === 'function') input.resume();
|
|
150
|
+
draw();
|
|
151
|
+
spec.onReady?.(api);
|
|
152
|
+
return await done;
|
|
153
|
+
} finally {
|
|
154
|
+
input.removeListener('keypress', onKeypress);
|
|
155
|
+
input.removeListener('end', onEnd);
|
|
156
|
+
input.removeListener('close', onEnd);
|
|
157
|
+
input.removeListener('error', fail);
|
|
158
|
+
if (context.signal) context.signal.removeEventListener('abort', onAbort);
|
|
159
|
+
if (canRaw) {
|
|
160
|
+
try { input.setRawMode(previousRaw); } catch { /* stream already closed */ }
|
|
161
|
+
}
|
|
162
|
+
if (typeof input.pause === 'function' && input.isTTY) input.pause();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Escape resolves `value` instead of cancelling (record pickers). */
|
|
167
|
+
export function escapeResult(value) {
|
|
168
|
+
return { value };
|
|
169
|
+
}
|
package/src/prompts.js
CHANGED
|
@@ -1,35 +1,86 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
/**
|
|
2
|
+
* JSN's interactive prompt surface, implemented on the local engine
|
|
3
|
+
* (src/prompt-engine.js) instead of @inquirer/prompts.
|
|
4
|
+
*
|
|
5
|
+
* Callers use `prompt(config, { input, output, signal })`. Escape cancels
|
|
6
|
+
* ordinary prompts with PromptCancelled; record pickers live in
|
|
7
|
+
* paginated-search.js and resolve undefined instead.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { runPrompt, normalizeChoices, truncate, PromptCancelled, escapeResult } from './prompt-engine.js';
|
|
11
|
+
export { PromptCancelled };
|
|
12
|
+
|
|
13
|
+
const ESC_HINT = ' (Esc to cancel)';
|
|
14
|
+
|
|
15
|
+
function withHint(config) {
|
|
16
|
+
const message = String(config.message ?? '');
|
|
17
|
+
return message.includes(ESC_HINT) ? message : `${message}${ESC_HINT}`;
|
|
6
18
|
}
|
|
7
19
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return await prompt({ ...config, message: `${config.message} (Esc to cancel)` }, {
|
|
19
|
-
...context,
|
|
20
|
-
signal: context.signal ? AbortSignal.any([context.signal, controller.signal]) : controller.signal,
|
|
21
|
-
});
|
|
22
|
-
} catch (error) {
|
|
23
|
-
if (controller.signal.aborted) throw controller.signal.reason;
|
|
24
|
-
throw error;
|
|
25
|
-
} finally {
|
|
26
|
-
input.removeListener('keypress', onKey);
|
|
27
|
-
}
|
|
28
|
-
};
|
|
20
|
+
function applyValidate(validate, value) {
|
|
21
|
+
if (typeof validate !== 'function') return null;
|
|
22
|
+
const result = validate(value);
|
|
23
|
+
return result instanceof Promise ? result : result;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function validateAnswer(validate, value) {
|
|
27
|
+
const result = await applyValidate(validate, value);
|
|
28
|
+
if (result === true || result === undefined || result === '') return null;
|
|
29
|
+
return typeof result === 'string' ? result : result === false ? 'Invalid value.' : null;
|
|
29
30
|
}
|
|
30
31
|
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
function textPrompt({ secret = false, defaultValue = null } = {}) {
|
|
33
|
+
return async (config = {}, context = {}) => runPrompt({ ...config, message: withHint(config) }, context, {
|
|
34
|
+
init: () => ({ buffer: '', error: '' }),
|
|
35
|
+
async key(state, key, api) {
|
|
36
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
37
|
+
const value = state.buffer.length ? state.buffer : (config.default ?? defaultValue ?? '');
|
|
38
|
+
const message = await validateAnswer(config.validate, value);
|
|
39
|
+
if (message) { state.error = message; api.redraw(); return; }
|
|
40
|
+
return { done: value };
|
|
41
|
+
}
|
|
42
|
+
if (key.name === 'backspace') {
|
|
43
|
+
state.buffer = state.buffer.slice(0, -1);
|
|
44
|
+
state.error = '';
|
|
45
|
+
api.redraw();
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (key.name === 'space') {
|
|
49
|
+
state.buffer += ' ';
|
|
50
|
+
state.error = '';
|
|
51
|
+
api.redraw();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (key.text) {
|
|
55
|
+
state.buffer += key.text;
|
|
56
|
+
state.error = '';
|
|
57
|
+
api.redraw();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (key.name === 'c' && key.ctrl) return { cancel: true };
|
|
61
|
+
api.redraw();
|
|
62
|
+
},
|
|
63
|
+
render(state) {
|
|
64
|
+
const label = withHint(config);
|
|
65
|
+
const suffix = config.default !== undefined && !secret ? ` (${config.default})` : '';
|
|
66
|
+
// Secrets are never echoed: the placeholder has a fixed width, so
|
|
67
|
+
// nothing about the typed value (characters or length) reaches stdout.
|
|
68
|
+
const shown = secret ? (state.buffer.length ? '******' : '') : state.buffer;
|
|
69
|
+
const error = state.error ? `\n ${state.error}` : '';
|
|
70
|
+
return `${label}${suffix}\n> ${shown}${error}`;
|
|
71
|
+
},
|
|
72
|
+
// Settled line keeps the prompt's own message (and hint) and never the
|
|
73
|
+
// secret value; Inquirer's `✔ message answer` shape.
|
|
74
|
+
final(cfg, value) {
|
|
75
|
+
const answer = secret || value === undefined || value === '' ? '' : ` ${value}`;
|
|
76
|
+
return `✔ ${withHint(cfg)}${answer}`;
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const input = textPrompt();
|
|
82
|
+
|
|
83
|
+
export const password = textPrompt({ secret: true });
|
|
33
84
|
|
|
34
85
|
// Use the shared Escape contract and a masked prompt; codes stay ephemeral.
|
|
35
86
|
export async function mfaCode(config = {}, context = {}) {
|
|
@@ -39,20 +90,231 @@ export async function mfaCode(config = {}, context = {}) {
|
|
|
39
90
|
|| 'Enter the 6-digit code from your authenticator app.',
|
|
40
91
|
}, context);
|
|
41
92
|
}
|
|
42
|
-
export const select = lazyPrompt('select');
|
|
43
|
-
export const search = lazyPrompt('search');
|
|
44
|
-
export const confirm = lazyPrompt('confirm');
|
|
45
|
-
export const checkbox = lazyPrompt('checkbox');
|
|
46
93
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
94
|
+
export async function confirm(config = {}, context = {}) {
|
|
95
|
+
const fallback = config.default === undefined ? true : Boolean(config.default);
|
|
96
|
+
return runPrompt({ ...config, message: withHint(config) }, context, {
|
|
97
|
+
init: () => ({ value: '', error: '' }),
|
|
98
|
+
key(state, key, api) {
|
|
99
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
100
|
+
const answer = /^y/i.test(state.value) ? true : /^n/i.test(state.value) ? false : fallback;
|
|
101
|
+
return { done: answer };
|
|
102
|
+
}
|
|
103
|
+
if (key.name === 'backspace') state.value = state.value.slice(0, -1);
|
|
104
|
+
else if (key.text) state.value += key.text;
|
|
105
|
+
api.redraw();
|
|
106
|
+
},
|
|
107
|
+
render(state) {
|
|
108
|
+
const hint = fallback ? '[Y/n]' : '[y/N]';
|
|
109
|
+
return `${withHint(config)} ${hint} ${state.value}`;
|
|
110
|
+
},
|
|
111
|
+
final: (cfg, value) => `✔ ${withHint(cfg)} ${value ? 'Yes' : 'No'}`,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
51
114
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
return
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
115
|
+
export async function select(config = {}, context = {}) {
|
|
116
|
+
const choices = normalizeChoices(config.choices || []);
|
|
117
|
+
return runPrompt({ ...config, message: withHint(config) }, context, {
|
|
118
|
+
init: () => ({ active: Math.max(firstEnabled(choices), choices.findIndex(choice => !choice.disabled && choice.value === config.default)) }),
|
|
119
|
+
key(state, key, api) {
|
|
120
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
121
|
+
const choice = choices[state.active];
|
|
122
|
+
if (!choice || choice.disabled) return;
|
|
123
|
+
return { done: choice.value };
|
|
124
|
+
}
|
|
125
|
+
if (key.name === 'up') { state.active = move(choices, state.active, -1); api.redraw(); return; }
|
|
126
|
+
if (key.name === 'down') { state.active = move(choices, state.active, 1); api.redraw(); return; }
|
|
127
|
+
if (key.name === 'k') { state.active = move(choices, state.active, -1); api.redraw(); return; }
|
|
128
|
+
if (key.name === 'j') { state.active = move(choices, state.active, 1); api.redraw(); return; }
|
|
129
|
+
},
|
|
130
|
+
render(state) {
|
|
131
|
+
const lines = [withHint(config)];
|
|
132
|
+
choices.forEach((choice, index) => {
|
|
133
|
+
const marker = index === state.active ? '>' : ' ';
|
|
134
|
+
lines.push(`${marker} ${choice.disabled ? `(disabled) ${choice.name}` : choice.name}`);
|
|
135
|
+
});
|
|
136
|
+
lines.push('', ' Use arrow keys, Enter to select.');
|
|
137
|
+
return lines;
|
|
138
|
+
},
|
|
139
|
+
final(cfg, value) {
|
|
140
|
+
const chosen = choices.find(choice => choice.value === value);
|
|
141
|
+
return `✔ ${withHint(cfg)} ${chosen ? chosen.name : value}`;
|
|
142
|
+
},
|
|
143
|
+
});
|
|
58
144
|
}
|
|
145
|
+
|
|
146
|
+
export async function search(config = {}, context = {}) {
|
|
147
|
+
let request;
|
|
148
|
+
const state = { term: '', choices: [], active: 0, loading: false, token: 0, error: '' };
|
|
149
|
+
async function load(api) {
|
|
150
|
+
request?.abort();
|
|
151
|
+
request = new AbortController();
|
|
152
|
+
const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
|
|
153
|
+
const token = ++state.token;
|
|
154
|
+
state.loading = true;
|
|
155
|
+
state.error = '';
|
|
156
|
+
state.active = 0;
|
|
157
|
+
api.redraw();
|
|
158
|
+
try {
|
|
159
|
+
const items = await config.source?.(state.term, { signal });
|
|
160
|
+
if (token !== state.token) return;
|
|
161
|
+
state.choices = normalizeChoices(items || []);
|
|
162
|
+
} catch (error) {
|
|
163
|
+
if (token !== state.token) return;
|
|
164
|
+
state.choices = [];
|
|
165
|
+
state.error = error?.message || String(error);
|
|
166
|
+
}
|
|
167
|
+
if (token !== state.token) return;
|
|
168
|
+
state.loading = false;
|
|
169
|
+
state.active = firstEnabled(state.choices);
|
|
170
|
+
api.redraw();
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
return await runPrompt({ ...config, message: withHint(config) }, context, {
|
|
174
|
+
init: () => state,
|
|
175
|
+
onReady: api => { void load(api); },
|
|
176
|
+
key(_state, key, api) {
|
|
177
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
178
|
+
const choice = state.choices[state.active];
|
|
179
|
+
if (!state.loading && choice && !choice.disabled) return { done: choice.value };
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (key.name === 'up' || key.name === 'down') {
|
|
183
|
+
state.active = move(state.choices, state.active, key.name === 'up' ? -1 : 1);
|
|
184
|
+
api.redraw();
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const previous = state.term;
|
|
188
|
+
if (key.name === 'backspace') state.term = state.term.slice(0, -1);
|
|
189
|
+
else if (key.text) state.term += key.text;
|
|
190
|
+
if (state.term !== previous) void load(api);
|
|
191
|
+
},
|
|
192
|
+
render() {
|
|
193
|
+
const lines = [`${withHint(config)} Search: ${state.term}${state.loading ? ' ...' : ''}`];
|
|
194
|
+
if (state.error) lines.push(` ${state.error}`);
|
|
195
|
+
else if (!state.choices.length) lines.push(state.loading ? ' Loading...' : ' No matches');
|
|
196
|
+
else state.choices.forEach((choice, index) => lines.push(`${index === state.active ? '>' : ' '} ${truncate(choice.name)}`));
|
|
197
|
+
lines.push('', ' Type to filter, arrows to move, Enter to select.');
|
|
198
|
+
return lines;
|
|
199
|
+
},
|
|
200
|
+
});
|
|
201
|
+
} finally {
|
|
202
|
+
state.token += 1;
|
|
203
|
+
request?.abort();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export async function checkbox(config = {}, context = {}) {
|
|
208
|
+
const choices = normalizeChoices(config.choices || []);
|
|
209
|
+
return runPrompt({ ...config, message: withHint(config) }, context, {
|
|
210
|
+
init: () => ({ active: firstEnabled(choices), picked: new Set(choices.flatMap((choice, index) => choice.checked && !choice.disabled ? [index] : [])), error: '' }),
|
|
211
|
+
key(state, key, api) {
|
|
212
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
213
|
+
const values = choices.filter((_choice, index) => state.picked.has(index)).map(choice => choice.value);
|
|
214
|
+
if (config.required && values.length === 0) {
|
|
215
|
+
state.error = 'Select at least one option.';
|
|
216
|
+
api.redraw();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
return { done: values };
|
|
220
|
+
}
|
|
221
|
+
if (key.name === 'space') {
|
|
222
|
+
if (choices[state.active] && !choices[state.active].disabled) {
|
|
223
|
+
if (state.picked.has(state.active)) state.picked.delete(state.active);
|
|
224
|
+
else state.picked.add(state.active);
|
|
225
|
+
state.error = '';
|
|
226
|
+
api.redraw();
|
|
227
|
+
}
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (key.name === 'a' && key.ctrl) {
|
|
231
|
+
choices.forEach((choice, index) => { if (!choice.disabled) state.picked.add(index); });
|
|
232
|
+
api.redraw();
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (key.name === 'up') { state.active = move(choices, state.active, -1); api.redraw(); return; }
|
|
236
|
+
if (key.name === 'down') { state.active = move(choices, state.active, 1); api.redraw(); return; }
|
|
237
|
+
},
|
|
238
|
+
render(state) {
|
|
239
|
+
const lines = [withHint(config)];
|
|
240
|
+
choices.forEach((choice, index) => {
|
|
241
|
+
lines.push(`${index === state.active ? '>' : ' '} [${state.picked.has(index) ? 'x' : ' '}] ${choice.name}`);
|
|
242
|
+
});
|
|
243
|
+
if (state.error) lines.push(` ${state.error}`);
|
|
244
|
+
lines.push('', ' Space toggles, arrows move, Enter confirms.');
|
|
245
|
+
return lines;
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function firstEnabled(choices) {
|
|
251
|
+
const index = choices.findIndex(choice => !choice.disabled);
|
|
252
|
+
return index < 0 ? 0 : index;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function move(choices, active, delta) {
|
|
256
|
+
let next = active + delta;
|
|
257
|
+
while (next >= 0 && next < choices.length && choices[next].disabled) next += delta;
|
|
258
|
+
if (next < 0 || next >= choices.length) return active;
|
|
259
|
+
return next;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Enter launches $EDITOR by default. Escape cancels before launch; once the
|
|
264
|
+
* editor owns the keyboard, its own controls apply.
|
|
265
|
+
*/
|
|
266
|
+
export async function editor(config = {}, context = {}) {
|
|
267
|
+
if (config.waitForUserInput !== false) {
|
|
268
|
+
await runPrompt(config, context, {
|
|
269
|
+
init: () => ({}),
|
|
270
|
+
key(_state, key) {
|
|
271
|
+
if (key.name === 'return' || key.name === 'enter') return { done: true };
|
|
272
|
+
},
|
|
273
|
+
render: () => [withHint(config), 'Press Enter to launch your preferred editor.'],
|
|
274
|
+
});
|
|
275
|
+
} else {
|
|
276
|
+
(context.output || process.stdout).write(`${withHint(config)}\n`);
|
|
277
|
+
}
|
|
278
|
+
const fs = await import('node:fs');
|
|
279
|
+
const os = await import('node:os');
|
|
280
|
+
const path = await import('node:path');
|
|
281
|
+
const { spawn } = await import('node:child_process');
|
|
282
|
+
|
|
283
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'jsn-editor-'));
|
|
284
|
+
const file = path.join(directory, 'draft.txt');
|
|
285
|
+
try {
|
|
286
|
+
fs.writeFileSync(file, config.default ?? '', 'utf8');
|
|
287
|
+
const [command, ...args] = editorCommand();
|
|
288
|
+
await new Promise((resolve, reject) => {
|
|
289
|
+
const child = spawn(command, [...args, file], {
|
|
290
|
+
stdio: 'inherit',
|
|
291
|
+
signal: context.signal,
|
|
292
|
+
env: process.env,
|
|
293
|
+
});
|
|
294
|
+
child.on('error', reject);
|
|
295
|
+
child.on('exit', (code, signal) => {
|
|
296
|
+
if (code === 0) resolve();
|
|
297
|
+
else reject(new Error(`Editor exited with ${signal ? `signal ${signal}` : `code ${code}`}`));
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
return fs.readFileSync(file, 'utf8');
|
|
301
|
+
} finally {
|
|
302
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function editorCommand() {
|
|
307
|
+
const spec = process.env.VISUAL || process.env.EDITOR || 'vi';
|
|
308
|
+
return spec.trim().split(/\s+/);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Kept for callers/tests that wrapped an Inquirer prompt with the Escape
|
|
313
|
+
* contract. The engine owns Escape now, so this is a pass-through that
|
|
314
|
+
* preserves the previous signature.
|
|
315
|
+
*/
|
|
316
|
+
export function cancellablePrompt(prompt) {
|
|
317
|
+
return async (config, context = {}) => prompt(config, context);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export { escapeResult };
|