@jacebenson/jsn 5.5.1 → 5.5.2-dev.173.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 +30 -2
- package/package.json +1 -1
- package/src/app.js +15 -2
- package/src/auth/mfa.js +85 -0
- package/src/cli-adapter.js +18 -4
- package/src/cli.js +26 -8
- package/src/commands/_generic.js +10 -2
- package/src/commands/_ticket.js +12 -4
- package/src/commands/approvals.js +1 -0
- package/src/commands/auth.js +15 -8
- package/src/commands/cases.js +1 -1
- package/src/commands/cmdb.js +1 -1
- package/src/commands/discover.js +1 -0
- package/src/commands/docs/client.js +17 -7
- package/src/commands/docs/community.js +4 -4
- package/src/commands/docs/db.js +26 -11
- package/src/commands/docs/docs.js +30 -13
- package/src/commands/docs/embed.js +2 -2
- package/src/commands/docs/index-worker.js +1 -1
- package/src/commands/docs/index.js +4 -3
- package/src/commands/docs/ingest.js +4 -4
- package/src/commands/docs/install.js +19 -17
- package/src/commands/docs/local.js +6 -4
- package/src/commands/docs/refresh.js +3 -3
- package/src/commands/docs/releases.js +27 -0
- package/src/commands/docs/search.js +3 -3
- package/src/commands/docs/serve.js +3 -3
- package/src/commands/docs/server.js +13 -10
- package/src/commands/docs/service-snapshot.js +3 -3
- package/src/commands/docs/snapshot.js +32 -11
- package/src/commands/docs/sync-service.js +8 -6
- package/src/commands/docs/sync.js +24 -15
- package/src/commands/flows.js +70 -5
- package/src/commands/knowledge.js +1 -0
- package/src/commands/records.js +12 -3
- package/src/commands/setup.js +20 -8
- package/src/commands/tickets.js +11 -3
- package/src/errors.js +23 -1
- package/src/flow-create.js +1237 -57
- package/src/flow-inspection.js +26 -2
- package/src/help.js +95 -21
- package/src/helpers.js +20 -1
- package/src/output.js +19 -5
- package/src/prompts.js +9 -0
- package/src/record-command-profiles.js +8 -4
- package/src/record-profiles.js +1 -0
- package/src/records-engine.js +2 -1
- package/src/sdk.js +157 -15
- package/src/setup-preferences.js +3 -3
- package/src/table-read-params.js +9 -0
- package/src/welcome.js +34 -36
package/README.md
CHANGED
|
@@ -121,7 +121,7 @@ jsn records list --table incident --limit 10 --json
|
|
|
121
121
|
jsn flows list
|
|
122
122
|
```
|
|
123
123
|
|
|
124
|
-
Run `jsn --help` for the command
|
|
124
|
+
Run `jsn --help` for a concise command overview, or `jsn --all-commands --help` for the complete command and flag reference. See the [CLI guide](https://github.com/jacebenson/jsn/blob/main/docs/cli-guide.md) for authentication, output formats, development, and examples. The [docs site](https://jacebenson.github.io/jsn/) has feature guides.
|
|
125
125
|
|
|
126
126
|
## AI agents
|
|
127
127
|
|
|
@@ -289,13 +289,41 @@ Local mode downloads the public documentation on first use and checks for update
|
|
|
289
289
|
daily while running. The server starts again automatically when needed. A first
|
|
290
290
|
search can report that the index is still being prepared; later updates preserve
|
|
291
291
|
the last working index if offline. Local storage lives under
|
|
292
|
-
`~/.jsn/docs
|
|
292
|
+
`~/.jsn/docs/docs.db` for the default family. Other families use
|
|
293
|
+
`~/.jsn/docs/releases/NAME/docs.db`. `JSN_DATA_HOME` overrides the parent directory.
|
|
294
|
+
Existing default-family installs keep their original index path.
|
|
293
295
|
|
|
294
296
|
To host the same service yourself, run `jsn docs --serve --host 0.0.0.0 --port 3000`.
|
|
295
297
|
It manages its own index; expose it through your normal HTTPS proxy. The hosted
|
|
296
298
|
website and this server share one search engine. `JSN_DOCS_URL` temporarily
|
|
297
299
|
overrides the saved choice without starting a local server.
|
|
298
300
|
|
|
301
|
+
Choose a family with `jsn docs "GlideRecord" --release brazil`. The same option
|
|
302
|
+
applies to `--path`, `docs show <ID>`, `docs status`, `docs sync`, `docs install`
|
|
303
|
+
and `--serve`. Resolution is `--release` first, then the optional `docs.release`
|
|
304
|
+
preference, then `australia`. Release names contain 1–40 lowercase letters,
|
|
305
|
+
digits or dashes. The service decides which families exist.
|
|
306
|
+
|
|
307
|
+
Documentation preferences are saved in the global profile config at
|
|
308
|
+
`$XDG_CONFIG_HOME/servicenow/config.json`, normally
|
|
309
|
+
`~/.config/servicenow/config.json`. Alongside `docs.source` and `docs.url`, set
|
|
310
|
+
`docs.release` without changing the service URL:
|
|
311
|
+
|
|
312
|
+
```json
|
|
313
|
+
{ "docs": { "source": "hosted", "url": "https://jsn.jace.pro", "release": "brazil" } }
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
`jsn docs releases` lists installed families, revisions, document counts, index
|
|
317
|
+
paths and the default marker without contacting the network. To install an
|
|
318
|
+
optional local index, use `jsn docs install --source snapshot --release brazil`,
|
|
319
|
+
or `jsn docs sync --release brazil --no-embed`. Sync downloads the named Git
|
|
320
|
+
branch; `--no-ingest` downloads only the source. Snapshot installs use
|
|
321
|
+
`/docs-index/releases/NAME/manifest.json` and verify the declared release. Only
|
|
322
|
+
the default family can fall back to the old `/docs-index/manifest.json` when
|
|
323
|
+
the family manifest returns 404. That legacy manifest may omit `release`.
|
|
324
|
+
`jsn docs --serve --release brazil` serves only Brazil and rejects requests
|
|
325
|
+
for other families. Search, read and status JSON include the selected `release`.
|
|
326
|
+
|
|
299
327
|
Exact paths remain stable across revisions. Numeric IDs can be pinned with
|
|
300
328
|
`--revision <search-revision>`. Older `docs search`, `docs show` and `docs status`
|
|
301
329
|
spellings remain compatible but are omitted from the everyday help menu.
|
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -16,7 +16,7 @@ import { saveConfig } from './config.js';
|
|
|
16
16
|
import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
|
|
17
17
|
import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
|
|
18
18
|
import { errUsage, errAuth } from './errors.js';
|
|
19
|
-
import { canPrompt } from './helpers.js';
|
|
19
|
+
import { canPrompt, canUsePicker } from './helpers.js';
|
|
20
20
|
import { guardMutationContext } from './mutation-context.js';
|
|
21
21
|
import process from 'node:process';
|
|
22
22
|
|
|
@@ -59,9 +59,11 @@ export class App {
|
|
|
59
59
|
username: session?.username, authMethod: session?.profile?.auth_method,
|
|
60
60
|
}), {
|
|
61
61
|
domain: session?.domain || '',
|
|
62
|
+
includeReferenceLinks: this._authArgv?.includeReferenceLinks === true,
|
|
62
63
|
username: session?.username || '',
|
|
63
64
|
recovery: createAuthRecovery({ app: this, session }),
|
|
64
65
|
onMutation: event => this.recordMutation(instance, session?.profileName, event),
|
|
66
|
+
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
65
67
|
});
|
|
66
68
|
}
|
|
67
69
|
|
|
@@ -72,6 +74,7 @@ export class App {
|
|
|
72
74
|
domain: options.domain ?? profile.domain ?? '',
|
|
73
75
|
username: options.username || '',
|
|
74
76
|
onMutation: event => this.recordMutation(instance, options.profileName || null, event),
|
|
77
|
+
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
75
78
|
});
|
|
76
79
|
}
|
|
77
80
|
|
|
@@ -94,11 +97,21 @@ export class App {
|
|
|
94
97
|
return this.session?.instance || '';
|
|
95
98
|
}
|
|
96
99
|
|
|
97
|
-
async printContextHeader(
|
|
100
|
+
async printContextHeader(argv = {}) {
|
|
98
101
|
if (!this.getEffectiveInstance() || !this.sdk) return;
|
|
99
102
|
if (process.env.JSN_NO_HEADER) return;
|
|
100
103
|
if (this.output.getFormat() === FormatJSON || this.output.getFormat() === FormatQuiet) return;
|
|
101
104
|
|
|
105
|
+
// The banner is a terminal affordance, never data. `--get`/`--select`
|
|
106
|
+
// prints an extracted JSON value while the format still reports pretty, so
|
|
107
|
+
// a banner on stderr merged with `2>&1` landed in front of the JSON and
|
|
108
|
+
// broke `jsn ... 2>&1 | jq` / `json.load(sys.stdin)` at character 0. Skip
|
|
109
|
+
// it whenever an extraction was requested or stderr is not a terminal
|
|
110
|
+
// (nobody reads it there, and it costs five HTTP requests per command:
|
|
111
|
+
// user, application preference, update-set preference, scope, update set).
|
|
112
|
+
if (argv.get !== undefined && argv.get !== null && argv.get !== false) return;
|
|
113
|
+
if (process.stderr.isTTY !== true) return;
|
|
114
|
+
|
|
102
115
|
let userDisplayName = 'Unknown';
|
|
103
116
|
let userSysID = '';
|
|
104
117
|
|
package/src/auth/mfa.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// ServiceNow TOTP challenge helpers for Basic authentication (issue #402).
|
|
2
|
+
//
|
|
3
|
+
// The flow mirrors the platform's own login page, as implemented by
|
|
4
|
+
// @servicenow/sdk-cli 4.13.0's UISession:
|
|
5
|
+
//
|
|
6
|
+
// 1. POST /angular.do?sysparm_type=view_form.login → JSON { status:
|
|
7
|
+
// 'mfa_code_required' } with a session cookie but no authenticated user.
|
|
8
|
+
// 2. GET /validate_multifactor_auth_code.do → HTML form holding
|
|
9
|
+
// sysparm_ck and sysparm_process_nonce.
|
|
10
|
+
// 3. POST /validate_mfa_code.do → 302 on success; 200 with
|
|
11
|
+
// x-mfa_token: invalid when the code is rejected.
|
|
12
|
+
// 4. POST /angular.do?sysparm_type=get_user → session user token.
|
|
13
|
+
//
|
|
14
|
+
// The wire shape is observed from that reference client, not verified here
|
|
15
|
+
// against a live MFA-enabled instance (none is available in this workspace).
|
|
16
|
+
// Only the exact challenge marker enters MFA. Once recognized, failures
|
|
17
|
+
// must remain terminal; callers may not fall back to Basic headers.
|
|
18
|
+
//
|
|
19
|
+
// Codes are ephemeral: these helpers return them only to the caller's request
|
|
20
|
+
// body. Nothing in this module logs, caches, or persists a code.
|
|
21
|
+
|
|
22
|
+
export const MFA_REQUIRED_STATUS = 'mfa_code_required';
|
|
23
|
+
export const MFA_INVALID_TOKEN_HEADER_VALUE = 'invalid';
|
|
24
|
+
|
|
25
|
+
/** Read the login endpoint's JSON body without trusting its content type. */
|
|
26
|
+
export function parseLoginStatus(body) {
|
|
27
|
+
if (typeof body !== 'string' || body.trim() === '') return null;
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(body);
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
35
|
+
const status = typeof parsed.status === 'string' ? parsed.status : '';
|
|
36
|
+
const message = typeof parsed.message === 'string' ? parsed.message : '';
|
|
37
|
+
return { status, message };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Extract the hidden anti-CSRF and nonce fields from the MFA validation page.
|
|
42
|
+
* Accepts either attribute order so a form-layout change does not break login.
|
|
43
|
+
*/
|
|
44
|
+
export function extractMfaFormTokens(html) {
|
|
45
|
+
const text = String(html ?? '');
|
|
46
|
+
const read = (name) => {
|
|
47
|
+
const pattern = new RegExp(
|
|
48
|
+
`name=["']${name}["'][^>]*value=["']([^"']+)["']|value=["']([^"']+)["'][^>]*name=["']${name}["']`,
|
|
49
|
+
'i',
|
|
50
|
+
);
|
|
51
|
+
const match = text.match(pattern);
|
|
52
|
+
return match ? (match[1] ?? match[2] ?? '') : '';
|
|
53
|
+
};
|
|
54
|
+
return { csrf: read('sysparm_ck'), processNonce: read('sysparm_process_nonce') };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The TOTP verification form body the platform page posts. */
|
|
58
|
+
export function buildMfaVerificationBody({ csrf, processNonce, code }) {
|
|
59
|
+
return new URLSearchParams({
|
|
60
|
+
sysparm_ck: csrf,
|
|
61
|
+
sysparm_process_nonce: processNonce,
|
|
62
|
+
sys_action: 'sysverb_validate_mfa_code',
|
|
63
|
+
sys_mfa_check_remembered_browser: 'false',
|
|
64
|
+
// Browser-fingerprint fields are only used for "remember this device";
|
|
65
|
+
// JSN authenticates one session at a time, so they stay empty.
|
|
66
|
+
bfp: '',
|
|
67
|
+
bfp_hash: '',
|
|
68
|
+
sys_web_authentication_successful: 'false',
|
|
69
|
+
sys_web_authentication_response: '',
|
|
70
|
+
sys_web_authn_registration_successful: 'false',
|
|
71
|
+
sys_web_authn_registration_skipped: 'false',
|
|
72
|
+
sys_mfa_factor_validate: 'TOTP',
|
|
73
|
+
sys_show_works_with_sn_enabled: 'true',
|
|
74
|
+
mfa_factor: 'mfa_TOTP_div',
|
|
75
|
+
txtResponse: code,
|
|
76
|
+
txtResponse_email: '',
|
|
77
|
+
txtResponse_sms: '',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Trim human separators and require six decimal digits. */
|
|
82
|
+
export function normalizeTotpCode(value) {
|
|
83
|
+
const digits = String(value ?? '').replace(/[\s-]/g, '');
|
|
84
|
+
return /^\d{6}$/.test(digits) ? digits : '';
|
|
85
|
+
}
|
package/src/cli-adapter.js
CHANGED
|
@@ -4,6 +4,10 @@ import { renderSubcommandHelp } from './help.js';
|
|
|
4
4
|
|
|
5
5
|
const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
6
6
|
const names = (x) => typeof x === 'string' ? [x] : (x || []);
|
|
7
|
+
// Query shorthand belongs only to commands that declare the query option.
|
|
8
|
+
const optionSpec = (name, config = {}) => ({ ...config, name,
|
|
9
|
+
...(name === 'query' ? { alias: [...new Set([...names(config.alias), 'q'])] } : {}),
|
|
10
|
+
});
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
13
|
* A repeatable option may be declared either way: `type: 'array'` (this
|
|
@@ -89,7 +93,7 @@ class CommandNode {
|
|
|
89
93
|
node.register(new CommandNode(typeof definition === 'string' ? { command: definition, builder, handler } : definition));
|
|
90
94
|
return this;
|
|
91
95
|
},
|
|
92
|
-
option(name, config = {}) { node.options.set(name,
|
|
96
|
+
option(name, config = {}) { node.options.set(name, optionSpec(name, config)); return this; },
|
|
93
97
|
options(config = {}) { for (const [name, value] of Object.entries(config)) this.option(name, value); return this; },
|
|
94
98
|
positional(name, config = {}) { node.positionals.set(name, { ...config, name }); return this; },
|
|
95
99
|
demandCommand(count, message) { node.demand = { count, message }; return this; },
|
|
@@ -119,7 +123,7 @@ export class LocalCLI {
|
|
|
119
123
|
usage(value) { this.root.usageText = value; return this; }
|
|
120
124
|
epilogue(value) { this.root.epilogueText = value; return this; }
|
|
121
125
|
middleware(fn) { this.middlewares.push(...(Array.isArray(fn) ? fn : [fn])); return this; }
|
|
122
|
-
option(name, config) { this.root.options.set(name,
|
|
126
|
+
option(name, config) { this.root.options.set(name, optionSpec(name, config)); return this; }
|
|
123
127
|
options(config) { for (const [name, value] of Object.entries(config)) this.option(name, value); return this; }
|
|
124
128
|
command(definition, builder, handler) {
|
|
125
129
|
this.root.register(new CommandNode(typeof definition === 'string' ? { command: definition, builder, handler } : definition));
|
|
@@ -238,6 +242,10 @@ export class LocalCLI {
|
|
|
238
242
|
catch (err) { this._fail(err.message, err); return { values: {}, positionals: [] }; }
|
|
239
243
|
const argv = { _: path.map((n) => n.name) };
|
|
240
244
|
for (const [key, value] of Object.entries(parsed.values)) {
|
|
245
|
+
if (opts.validate !== false && key === 'q' && !options.has('q')) {
|
|
246
|
+
this._fail('Option -q (--query) is not supported by this command.');
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
241
249
|
const spec = this._specFor(options, key, value);
|
|
242
250
|
if (this._assign(argv, key, value, spec, opts) === false) return null;
|
|
243
251
|
}
|
|
@@ -285,12 +293,16 @@ export class LocalCLI {
|
|
|
285
293
|
* discovery output are generated from, so neither can drift away from the
|
|
286
294
|
* commands that actually exist. Builders run here (idempotently) because a
|
|
287
295
|
* parent's children are only registered when its builder is invoked.
|
|
296
|
+
*
|
|
297
|
+
* `summaries: true` adds the command's short summary for the concise human
|
|
298
|
+
* help page. Machine discovery leaves it out, so the JSON schema and bytes
|
|
299
|
+
* stay unchanged.
|
|
288
300
|
*/
|
|
289
|
-
commandRegistry() {
|
|
301
|
+
commandRegistry({ summaries = false } = {}) {
|
|
290
302
|
const visible = (node) => node.name !== this.completionCommand && !node.definition.hidden;
|
|
291
303
|
const serialize = (node) => {
|
|
292
304
|
node.build();
|
|
293
|
-
|
|
305
|
+
const entry = {
|
|
294
306
|
name: node.name,
|
|
295
307
|
command: node.definition.command || node.name,
|
|
296
308
|
aliases: [...node.aliases],
|
|
@@ -304,6 +316,8 @@ export class LocalCLI {
|
|
|
304
316
|
help: `jsn ${node.name} ${child.name} --help`,
|
|
305
317
|
})),
|
|
306
318
|
};
|
|
319
|
+
if (summaries) entry.summary = node.definition.summary || '';
|
|
320
|
+
return entry;
|
|
307
321
|
};
|
|
308
322
|
return {
|
|
309
323
|
commands: this.root.children.filter(visible).map(serialize),
|
package/src/cli.js
CHANGED
|
@@ -10,7 +10,7 @@ import { App } from './app.js';
|
|
|
10
10
|
import { resolveSession, applySession } from './session.js';
|
|
11
11
|
import { renderHelp, renderTips } from './help.js';
|
|
12
12
|
import { isMutationCommand, refreshMutationCommands } from './mutations.js';
|
|
13
|
-
import {
|
|
13
|
+
import { maybeShowHome } from './welcome.js';
|
|
14
14
|
import { skippedUpdatesCmd } from './commands/skipped-updates.js';
|
|
15
15
|
import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, contextHeaderSkipCommands } from './capabilities.js';
|
|
16
16
|
import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
|
|
@@ -187,14 +187,18 @@ export function buildCLI() {
|
|
|
187
187
|
description: 'Output in CSV format (shortcut for --format=csv)',
|
|
188
188
|
},
|
|
189
189
|
get: {
|
|
190
|
+
alias: 'select',
|
|
190
191
|
type: 'string',
|
|
191
192
|
description: 'Extract a JSON path from the output envelope (e.g. --get "data.records.0.number"); no jq needed',
|
|
192
193
|
},
|
|
193
194
|
quiet: {
|
|
194
195
|
type: 'boolean',
|
|
195
196
|
description: 'Output only data, no envelope (shortcut for --format=quiet)',
|
|
196
|
-
alias: '
|
|
197
|
+
alias: 'S',
|
|
197
198
|
},
|
|
199
|
+
verbose: { type: 'boolean', description: 'Keep machine-output coaching and pretty-print JSON' },
|
|
200
|
+
raw: { type: 'boolean', description: 'Print extracted strings without JSON quotes' },
|
|
201
|
+
'include-reference-links': { type: 'boolean', description: 'Include Table API reference links on reads' },
|
|
198
202
|
styled: {
|
|
199
203
|
type: 'boolean',
|
|
200
204
|
description: 'Force styled output even when piped',
|
|
@@ -209,6 +213,8 @@ export function buildCLI() {
|
|
|
209
213
|
// resolveRequestedFormat so the parse-time failure path applies the
|
|
210
214
|
// identical policy instead of approximating it from raw tokens.
|
|
211
215
|
(argv) => {
|
|
216
|
+
app.output.verbose = argv.verbose === true;
|
|
217
|
+
app.output.raw = argv.raw === true;
|
|
212
218
|
const requested = resolveRequestedFormat(argv);
|
|
213
219
|
if (requested) {
|
|
214
220
|
argv.format = requested;
|
|
@@ -216,6 +222,10 @@ export function buildCLI() {
|
|
|
216
222
|
}
|
|
217
223
|
if (argv.get) {
|
|
218
224
|
app.output.setJqFilter(argv.get);
|
|
225
|
+
if (!requested || requested === 'auto') {
|
|
226
|
+
app.output.setFormat('json');
|
|
227
|
+
argv.format = 'json';
|
|
228
|
+
}
|
|
219
229
|
}
|
|
220
230
|
},
|
|
221
231
|
// --profile / --instance resolve through the SESSION (src/session.js).
|
|
@@ -234,6 +244,7 @@ export function buildCLI() {
|
|
|
234
244
|
}
|
|
235
245
|
app._authArgv = argv;
|
|
236
246
|
applySession(app, session);
|
|
247
|
+
if (app.sdk) app.sdk.includeReferenceLinks = argv.includeReferenceLinks === true;
|
|
237
248
|
} catch (err) {
|
|
238
249
|
guardExit(argv, { code: err.code || 'usage', message: err.message, hint: err.hint });
|
|
239
250
|
}
|
|
@@ -548,6 +559,8 @@ export function buildCLI() {
|
|
|
548
559
|
// negation) instead of re-scanning raw argv — one policy, one answer for
|
|
549
560
|
// this command line no matter which layer rejects it.
|
|
550
561
|
const formatArgv = cliInstance.parseGlobalOptions(raw);
|
|
562
|
+
app.output.verbose = formatArgv?.verbose === true;
|
|
563
|
+
app.output.raw = formatArgv?.raw === true;
|
|
551
564
|
const requestedFormat = resolveRequestedFormat(formatArgv);
|
|
552
565
|
if (msg === 'You must specify a command') {
|
|
553
566
|
const hasLoneProfile = raw.some((a, i, arr) => {
|
|
@@ -588,12 +601,15 @@ export function buildCLI() {
|
|
|
588
601
|
}
|
|
589
602
|
process.exit(0);
|
|
590
603
|
}
|
|
591
|
-
//
|
|
592
|
-
//
|
|
593
|
-
// format, no configured profile, and not shown before.
|
|
604
|
+
// Human terminals always get the compact local home. Machine and
|
|
605
|
+
// non-interactive discovery retain their existing reference output.
|
|
594
606
|
const config = loadConfig(formatArgv);
|
|
595
|
-
|
|
596
|
-
|
|
607
|
+
const welcome = maybeShowHome({ argv: formatArgv, requestedFormat, cfg: config });
|
|
608
|
+
if (!welcome) {
|
|
609
|
+
const registry = visibleCommandRegistry(
|
|
610
|
+
cliInstance.commandRegistry({ summaries: true }), config, formatArgv);
|
|
611
|
+
process.stdout.write(renderHelp(config, registry, { full: formatArgv?.allCommands === true }) + '\n');
|
|
612
|
+
}
|
|
597
613
|
process.exit(0);
|
|
598
614
|
}
|
|
599
615
|
// Every other failure here (unknown command, missing required argument,
|
|
@@ -616,7 +632,9 @@ export function buildCLI() {
|
|
|
616
632
|
cliInstance.rootHelpRenderer = () => {
|
|
617
633
|
const options = cliInstance.parseGlobalOptions(process.argv.slice(2));
|
|
618
634
|
const config = loadConfig(options);
|
|
619
|
-
|
|
635
|
+
const registry = visibleCommandRegistry(
|
|
636
|
+
cliInstance.commandRegistry({ summaries: true }), config, options);
|
|
637
|
+
return renderHelp(config, registry, { full: options?.allCommands === true });
|
|
620
638
|
};
|
|
621
639
|
|
|
622
640
|
// Snapshot the root command names (plus aliases) for the completion
|
package/src/commands/_generic.js
CHANGED
|
@@ -2,7 +2,7 @@ import { constrainQuery, constrainedQueryHelp } from '../constrained-query.js';
|
|
|
2
2
|
import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
|
|
3
3
|
// Generic table-based CRUD command builder
|
|
4
4
|
|
|
5
|
-
import { formatRecordForDisplay, getStringField, buildRecordPayload, confirmDelete, interactiveList, canPrompt } from '../helpers.js';
|
|
5
|
+
import { formatRecordForDisplay, findOmittedColumns, getStringField, buildRecordPayload, confirmDelete, interactiveList, canPrompt } from '../helpers.js';
|
|
6
6
|
import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
|
|
7
7
|
import { unwrapSysId } from '../resolve-record.js';
|
|
8
8
|
import { getCurrentUser, getCurrentApplication } from '../context.js';
|
|
@@ -171,11 +171,19 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
|
|
|
171
171
|
const q = `${constrainedQuery}${constrainedQuery ? '^' : ''}ORDERBYDESCsys_updated_on`;
|
|
172
172
|
const params = recordListParams({ limit, fields: ['sys_id', ...columns], query: q });
|
|
173
173
|
const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues ?? opts.referenceMode });
|
|
174
|
+
const missingColumns = findOmittedColumns(records, columns);
|
|
175
|
+
const presentColumns = missingColumns.length ? columns.filter(c => !missingColumns.includes(c)) : columns;
|
|
174
176
|
app.ok({
|
|
175
177
|
table,
|
|
176
178
|
count: records.length,
|
|
177
179
|
columns,
|
|
178
|
-
|
|
180
|
+
...(missingColumns.length ? {
|
|
181
|
+
missing_columns: missingColumns,
|
|
182
|
+
warnings: [
|
|
183
|
+
`Column(s) not returned by ServiceNow (non-existent or restricted on ${table}): ${missingColumns.join(', ')}. Run \`jsn columns --table ${table}\` to inspect valid fields.`,
|
|
184
|
+
],
|
|
185
|
+
} : {}),
|
|
186
|
+
records: argv.displayValues || opts.listProjection === 'full' ? records : records.map(r => formatRecordForDisplay(r, presentColumns)),
|
|
179
187
|
context: { instance_url: app.getEffectiveInstance() },
|
|
180
188
|
}, {
|
|
181
189
|
summary: `${records.length} ${name}(s)`,
|
package/src/commands/_ticket.js
CHANGED
|
@@ -2,7 +2,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
|
|
|
2
2
|
// Generic command builder for CRUD operations on a ServiceNow table
|
|
3
3
|
// Used by incidents, changes, requests, tasks, and most dev subcommands
|
|
4
4
|
|
|
5
|
-
import { getStringField, formatRecordForDisplay, buildQuerySuffix, resolveFieldsParam, confirmDelete, interactiveList, canPrompt, buildRecordPayload } from '../helpers.js';
|
|
5
|
+
import { getStringField, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, resolveFieldsParam, confirmDelete, interactiveList, canPrompt, buildRecordPayload } from '../helpers.js';
|
|
6
6
|
import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
|
|
7
7
|
import { resolveSysId } from '../resolve-record.js';
|
|
8
8
|
import { FormatAuto } from '../output.js';
|
|
@@ -56,7 +56,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
|
|
|
56
56
|
count: 0,
|
|
57
57
|
columns: pickerColumns,
|
|
58
58
|
records: [],
|
|
59
|
-
pagination: { limit, offset: 0 },
|
|
59
|
+
pagination: { limit, offset: 0, hasMore: false },
|
|
60
60
|
context: { instance_url: app.getEffectiveInstance() },
|
|
61
61
|
}, {
|
|
62
62
|
summary: `0 ${table}(s)`,
|
|
@@ -88,7 +88,9 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
|
|
|
88
88
|
const params = recordListParams({ limit, offset, fields, query: q });
|
|
89
89
|
|
|
90
90
|
const records = await listRecords(app.sdk, { table, params, displayValues: argv.displayValues ?? opts.referenceMode });
|
|
91
|
-
const
|
|
91
|
+
const missingColumns = fields ? findOmittedColumns(records, columns) : [];
|
|
92
|
+
const presentColumns = missingColumns.length ? columns.filter(c => !missingColumns.includes(c)) : columns;
|
|
93
|
+
const displayRecords = fields && !argv.displayValues && opts.listProjection !== 'full' ? records.map(r => formatRecordForDisplay(r, presentColumns)) : records;
|
|
92
94
|
|
|
93
95
|
const breadcrumbs = [
|
|
94
96
|
{ action: 'create', cmd: `jsn ${alias} create --description "..."`, description: `Create a new ${displayName}` },
|
|
@@ -114,8 +116,14 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
|
|
|
114
116
|
table,
|
|
115
117
|
count: records.length,
|
|
116
118
|
columns,
|
|
119
|
+
...(missingColumns.length ? {
|
|
120
|
+
missing_columns: missingColumns,
|
|
121
|
+
warnings: [
|
|
122
|
+
`Column(s) not returned by ServiceNow (non-existent or restricted on ${table}): ${missingColumns.join(', ')}. Run \`jsn columns --table ${table}\` to inspect valid fields.`,
|
|
123
|
+
],
|
|
124
|
+
} : {}),
|
|
117
125
|
records: displayRecords,
|
|
118
|
-
pagination: { limit, offset },
|
|
126
|
+
pagination: { limit, offset, hasMore: records.length === limit },
|
|
119
127
|
context: { instance_url: app.getEffectiveInstance() },
|
|
120
128
|
}, {
|
|
121
129
|
summary: `${records.length} ${table}(s)`,
|
|
@@ -173,6 +173,7 @@ export function approvalsCmd(wrap) {
|
|
|
173
173
|
return {
|
|
174
174
|
command: 'approvals [subcommand]',
|
|
175
175
|
describe: 'Manage approval requests (list, approve, reject, submit, history)',
|
|
176
|
+
summary: 'List, approve, or reject approval requests',
|
|
176
177
|
builder: (yargs) => {
|
|
177
178
|
return yargs
|
|
178
179
|
.command({
|
package/src/commands/auth.js
CHANGED
|
@@ -299,7 +299,7 @@ async function readBrowserSessionFile(file) {
|
|
|
299
299
|
}
|
|
300
300
|
|
|
301
301
|
/** Collect human answers, then call the same login operation as auth login. */
|
|
302
|
-
export async function loginWizard(app, argv = {}) {
|
|
302
|
+
export async function loginWizard(app, argv = {}, { concise = false } = {}) {
|
|
303
303
|
const { input, select, confirm, password } = await import('../prompts.js');
|
|
304
304
|
const explicitInstance = resolveWizardInstance(app, argv);
|
|
305
305
|
const instance = resolveInstanceArg(explicitInstance || await input({
|
|
@@ -322,19 +322,21 @@ export async function loginWizard(app, argv = {}) {
|
|
|
322
322
|
const request = { ...argv, profile: undefined, instance, name: name.trim() };
|
|
323
323
|
if (method === 'browser') request.browser = true;
|
|
324
324
|
if (method === 'oauth') request.oauth = true;
|
|
325
|
+
const settings = await chooseConnectionPreferences(app.config, profileSettingValues(argv), { confirm });
|
|
325
326
|
if (method === 'basic') {
|
|
326
327
|
request.basic = true;
|
|
327
328
|
const username = await input({ message: 'Username:', validate: value => value.trim() ? true : 'A username is required' });
|
|
328
329
|
request._basicCredentials = { username: username.trim(), password: await password({ message: 'Password:' }) };
|
|
329
330
|
}
|
|
330
|
-
const settings = await chooseConnectionPreferences(app.config, profileSettingValues(argv), { confirm });
|
|
331
331
|
request['read-only'] = settings.read_only;
|
|
332
332
|
request['skip-confirmations'] = settings.skip_confirmations;
|
|
333
333
|
request['include-counts'] = settings.include_counts;
|
|
334
|
-
request.makeDefault = argv.makeDefault ??
|
|
335
|
-
message: 'Use this profile by default?', default: !app.config.defaultProfile
|
|
336
|
-
});
|
|
337
|
-
|
|
334
|
+
request.makeDefault = argv.makeDefault ?? (Object.keys(app.config.profiles || {}).length === 0 && !app.config.defaultProfile
|
|
335
|
+
? true : await confirm({ message: 'Use this profile by default?', default: !app.config.defaultProfile }));
|
|
336
|
+
const result = await loginProfile(request, app, { concise });
|
|
337
|
+
if (result.authenticated && !concise) {
|
|
338
|
+
process.stdout.write(`Connection preset: ${settings.read_only ? 'read-only' : 'writes allowed'} · deletes ${settings.skip_confirmations ? 'without confirmation' : 'ask first'} · totals ${settings.include_counts ? 'on' : 'off'}\nChange with: jsn auth modify ${result.profile} --read-only\n`);
|
|
339
|
+
}
|
|
338
340
|
return { instanceURL: instance, profileName: result.profile, loggedIn: result.authenticated };
|
|
339
341
|
}
|
|
340
342
|
|
|
@@ -550,7 +552,7 @@ function canLogoutBareProfile(app, instance, target, explicitlySelected) {
|
|
|
550
552
|
return sameInstance.length <= 1;
|
|
551
553
|
}
|
|
552
554
|
|
|
553
|
-
export async function loginProfile(argv, app) {
|
|
555
|
+
export async function loginProfile(argv, app, { concise = false } = {}) {
|
|
554
556
|
argv = profileSettingValues(argv);
|
|
555
557
|
validateLoginSelectors(argv);
|
|
556
558
|
if (argv.name !== undefined) {
|
|
@@ -808,7 +810,12 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
|
|
|
808
810
|
description: 'Set these at login; --skip-confirmations disables delete prompts',
|
|
809
811
|
},
|
|
810
812
|
] : [];
|
|
811
|
-
|
|
813
|
+
if (concise && canUsePicker(app, argv)) {
|
|
814
|
+
const next = setDefault ? 'jsn incidents list' : `jsn --profile ${quoteShellArg(profileName)} incidents list`;
|
|
815
|
+
app.ok(result, { summary: `${summary}\nNext: ${next}`, breadcrumbs: [] });
|
|
816
|
+
} else {
|
|
817
|
+
app.ok(result, { summary, breadcrumbs });
|
|
818
|
+
}
|
|
812
819
|
return result;
|
|
813
820
|
}
|
|
814
821
|
|
package/src/commands/cases.js
CHANGED
|
@@ -112,7 +112,7 @@ async function listCases(app, argv, resolved, query) {
|
|
|
112
112
|
count: records.length,
|
|
113
113
|
columns,
|
|
114
114
|
records: displayRecords,
|
|
115
|
-
pagination: { limit: argv.limit, offset: argv.offset },
|
|
115
|
+
pagination: { limit: argv.limit, offset: argv.offset, hasMore: records.length === argv.limit },
|
|
116
116
|
context: { instance_url: app.getEffectiveInstance() },
|
|
117
117
|
}, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
|
|
118
118
|
}
|
package/src/commands/cmdb.js
CHANGED
|
@@ -454,7 +454,7 @@ export function cmdbCmd(wrap) {
|
|
|
454
454
|
count: records.length,
|
|
455
455
|
columns,
|
|
456
456
|
records: displayRecords,
|
|
457
|
-
pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total } : {}) },
|
|
457
|
+
pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total, hasMore: argv.offset + argv.limit < total } : {}) },
|
|
458
458
|
context: { instance_url: app.getEffectiveInstance() },
|
|
459
459
|
}, {
|
|
460
460
|
summary: `${records.length} CI(s) from cmdb_ci${total != null ? ` of ${total}` : ''}`,
|
package/src/commands/discover.js
CHANGED
|
@@ -20,6 +20,7 @@ export function discoverCmd(wrap, getRegistry) {
|
|
|
20
20
|
return {
|
|
21
21
|
command: 'discover [query]',
|
|
22
22
|
describe: 'Find commands by words in their names, aliases, descriptions, or configured table',
|
|
23
|
+
summary: 'Find commands by task word or table',
|
|
23
24
|
builder: y => y
|
|
24
25
|
.positional('query', { type: 'string', describe: 'Search words (quote multiple words)' })
|
|
25
26
|
.option('table', { type: 'string', describe: 'Find specialized commands configured for this exact table' })
|
|
@@ -39,9 +39,10 @@ async function request(endpoint, params, options = {}) {
|
|
|
39
39
|
const code = response.status === 404 ? 'not_found' : response.status === 429 ? 'rate_limited' : response.status === 400 ? 'usage_error' : 'api_error';
|
|
40
40
|
const message = typeof data?.error === 'string' ? data.error.slice(0, 300) : `Documentation service returned HTTP ${response.status}.`;
|
|
41
41
|
const hint = response.status === 409 ? 'Search again for the current revision, or retrieve the document by its exact path.'
|
|
42
|
-
: response.status === 429 ? 'Wait before retrying.' : response.status >= 500 ? 'Try again later; the documentation service may be updating or unavailable.' : '';
|
|
42
|
+
: response.status === 429 ? 'Wait before retrying.' : response.status >= 500 ? 'Try again later; the documentation service may be updating or unavailable.' : typeof data?.hint === 'string' ? data.hint : '';
|
|
43
43
|
throw new AppError(code, message, hint, response.status);
|
|
44
44
|
}
|
|
45
|
+
if (options.release && data?.release !== undefined && data.release !== options.release) throw new AppError('api_error', `Documentation service returned release ${data.release}, expected ${options.release}.`);
|
|
45
46
|
return { data, service };
|
|
46
47
|
}
|
|
47
48
|
function invalidResponse() {
|
|
@@ -54,24 +55,33 @@ export async function searchHostedDocs(options = {}) {
|
|
|
54
55
|
if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0 || offset > 10000) {
|
|
55
56
|
throw new AppError('usage_error', 'Use --limit 1–50 and --offset 0–10000.');
|
|
56
57
|
}
|
|
57
|
-
const { data, service } = await request('api/docs/search', { q: query, limit, offset, bundle: options.bundle }, options);
|
|
58
|
+
const { data, service } = await request('api/docs/search', { q: query, limit, offset, bundle: options.bundle, release: options.release }, options);
|
|
58
59
|
if (!data || !Array.isArray(data.results) || data.results.length > limit || data.count !== data.results.length ||
|
|
59
60
|
!Number.isInteger(data.total) || data.total < data.count || typeof data.revision !== 'string' ||
|
|
60
61
|
!data.results.every(row => row && Number.isInteger(row.id) && typeof row.path === 'string')) throw invalidResponse();
|
|
61
|
-
|
|
62
|
+
// A service that predates release selection echoes no release of its own; when every
|
|
63
|
+
// row it returned is stamped with a different family, say so instead of relabelling it.
|
|
64
|
+
if (options.release && data.release === undefined) {
|
|
65
|
+
const stamped = new Set(data.results.map(row => row.release).filter(value => typeof value === 'string' && value));
|
|
66
|
+
if (stamped.size === 1 && !stamped.has(options.release)) {
|
|
67
|
+
throw new AppError('api_error', `Documentation service answered with ${[...stamped][0]} documents, expected ${options.release}.`,
|
|
68
|
+
'Update the documentation service to serve multiple releases, or omit --release.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { ...data, release: options.release ?? data.release, query, limit, offset, service };
|
|
62
72
|
}
|
|
63
73
|
export async function getHostedDoc(idOrPath, options = {}) {
|
|
64
74
|
const identifier = String(idOrPath || '');
|
|
65
75
|
if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
|
|
66
76
|
const numeric = /^\d+$/.test(identifier);
|
|
67
77
|
const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
|
|
68
|
-
...(numeric ? {} : { path: identifier }), revision: options.revision,
|
|
78
|
+
...(numeric ? {} : { path: identifier }), revision: options.revision, release: options.release,
|
|
69
79
|
}, options);
|
|
70
80
|
if (!data || !data.document || typeof data.document.body !== 'string' || typeof data.document.path !== 'string' || typeof data.revision !== 'string') throw invalidResponse();
|
|
71
|
-
return { ...data.document, revision: data.revision, service };
|
|
81
|
+
return { ...data.document, release: options.release ?? data.release, revision: data.revision, service };
|
|
72
82
|
}
|
|
73
83
|
export async function getHostedDocsStatus(options = {}) {
|
|
74
|
-
const { data, service } = await request('api/docs/status', {}, options);
|
|
84
|
+
const { data, service } = await request('api/docs/status', { release: options.release }, options);
|
|
75
85
|
if (!data || typeof data.state !== 'string') throw invalidResponse();
|
|
76
|
-
return { ...data, service };
|
|
86
|
+
return { ...data, release: options.release ?? data.release, service };
|
|
77
87
|
}
|
|
@@ -10,7 +10,7 @@ import process from 'node:process';
|
|
|
10
10
|
import TurndownService from 'turndown';
|
|
11
11
|
import { parseFrontmatter, stringifyFrontmatter } from '../../frontmatter.js';
|
|
12
12
|
import Database from 'better-sqlite3';
|
|
13
|
-
import { getDocsCommunityDir,
|
|
13
|
+
import { getDocsCommunityDir, resolveDocsDbPath, docsDbExists } from './db.js';
|
|
14
14
|
import { refreshDocs } from './refresh.js';
|
|
15
15
|
import { ingestDocs } from './ingest.js';
|
|
16
16
|
|
|
@@ -216,7 +216,7 @@ export async function syncCommunity(opts = {}) {
|
|
|
216
216
|
const expand = opts.expand === true;
|
|
217
217
|
const force = opts.force === true;
|
|
218
218
|
const delayMs = opts.delayMs != null ? opts.delayMs : 500;
|
|
219
|
-
const dbPath = opts.dbPath ||
|
|
219
|
+
const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
|
|
220
220
|
|
|
221
221
|
const results = { hubs: [], articles: [], skipped: [], errors: [] };
|
|
222
222
|
|
|
@@ -326,8 +326,8 @@ function findExisting(url, urlIndex) {
|
|
|
326
326
|
return urlIndex.get(url) || null;
|
|
327
327
|
}
|
|
328
328
|
|
|
329
|
-
export function listCommunityDocs({ dbPath } = {}) {
|
|
330
|
-
const dbFile = dbPath ||
|
|
329
|
+
export function listCommunityDocs({ dbPath, release } = {}) {
|
|
330
|
+
const dbFile = dbPath || resolveDocsDbPath(release);
|
|
331
331
|
if (!fs.existsSync(dbFile)) return { total: 0, docs: [] };
|
|
332
332
|
const db = new Database(dbFile, { readonly: true });
|
|
333
333
|
const rows = db
|