@jacebenson/jsn 4.5.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -4
- package/bin/jsn.js +0 -14
- package/package.json +3 -6
- package/skills/servicenow/SKILL.md +3 -0
- package/src/cli-adapter.js +15 -7
- package/src/commands/auth.js +6 -4
- package/src/commands/docs/client.js +77 -0
- package/src/commands/docs/db.js +0 -1
- package/src/commands/docs/docs.js +72 -288
- package/src/commands/docs/index-worker.js +15 -0
- package/src/commands/docs/index.js +81 -0
- package/src/commands/docs/local.js +68 -0
- package/src/commands/docs/server.js +60 -0
- package/src/commands/docs/service-snapshot.js +43 -0
- package/src/commands/docs/sync-service.js +162 -0
- package/src/commands/setup.js +36 -26
- package/src/config.js +9 -0
- package/src/setup-preferences.js +57 -0
package/README.md
CHANGED
|
@@ -4,14 +4,14 @@ A command-line interface for ServiceNow. Read and update records, manage flows,
|
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Supports the current Node.js LTS release. Supports macOS, Linux, and Windows.
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
npm install -g @jacebenson/jsn
|
|
11
11
|
jsn setup
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
See the [setup guide](docs/docs-setup.md) to connect an instance safely.
|
|
14
|
+
See the [setup guide](https://github.com/jacebenson/jsn/blob/main/docs/docs-setup.md) to connect an instance safely.
|
|
15
15
|
|
|
16
16
|
### Dev channel
|
|
17
17
|
|
|
@@ -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 list. See the [CLI guide](docs/cli-guide.md) for authentication, output formats, development, and examples. The [docs site](https://jacebenson.github.io/jsn/) has feature guides.
|
|
124
|
+
Run `jsn --help` for the command list. 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
|
|
|
@@ -130,7 +130,8 @@ JSN includes a skill for Claude Code, OpenCode, Hermes, Cursor, Copilot, and oth
|
|
|
130
130
|
## Development
|
|
131
131
|
|
|
132
132
|
```bash
|
|
133
|
-
|
|
133
|
+
cd cli
|
|
134
|
+
npm ci
|
|
134
135
|
npm test
|
|
135
136
|
```
|
|
136
137
|
|
|
@@ -206,3 +207,32 @@ requests. Save the original domain ID from `session-current` if you intend to
|
|
|
206
207
|
restore it afterward. A failed readback can leave the session changed; inspect
|
|
207
208
|
`session-current` before retrying. These commands do not call `touch-session`.
|
|
208
209
|
Other authentication methods retain the existing profile configuration flow.
|
|
210
|
+
|
|
211
|
+
## Documentation search
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
jsn docs "GlideRecord" --limit 5
|
|
215
|
+
jsn docs --path "api-reference/c_GlideRecordClientSideAPI.md"
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
No ServiceNow connection is required. Hosted docs at `https://jsn.jace.pro` are
|
|
219
|
+
the default and download no database. `jsn setup` asks once for defaults for new
|
|
220
|
+
connections and whether to use hosted documentation. Decline hosted docs to let
|
|
221
|
+
JSN start a local server, or decline that too and enter your own service base URL.
|
|
222
|
+
Later changes live under **Defaults and documentation** in setup. Existing connections
|
|
223
|
+
keep their saved settings.
|
|
224
|
+
|
|
225
|
+
Local mode downloads the public documentation on first use and checks for updates
|
|
226
|
+
daily while running. The server starts again automatically when needed. A first
|
|
227
|
+
search can report that the index is still being prepared; later updates preserve
|
|
228
|
+
the last working index if offline. Local storage lives under
|
|
229
|
+
`~/.jsn/docs-service` (`JSN_DATA_HOME` overrides the parent directory).
|
|
230
|
+
|
|
231
|
+
To host the same service yourself, run `jsn docs --serve --host 0.0.0.0 --port 3000`.
|
|
232
|
+
It manages its own index; expose it through your normal HTTPS proxy. The hosted
|
|
233
|
+
website and this server share one search engine. `JSN_DOCS_URL` temporarily
|
|
234
|
+
overrides the saved choice without starting a local server.
|
|
235
|
+
|
|
236
|
+
Exact paths remain stable across revisions. Numeric IDs can be pinned with
|
|
237
|
+
`--revision <search-revision>`. Older `docs search`, `docs show` and `docs status`
|
|
238
|
+
spellings remain compatible but are omitted from the everyday help menu.
|
package/bin/jsn.js
CHANGED
|
@@ -7,20 +7,6 @@ process.stdout.on('error', (err) => {
|
|
|
7
7
|
throw err;
|
|
8
8
|
});
|
|
9
9
|
|
|
10
|
-
// Suppress the node:sqlite experimental warning on Node 22.x.
|
|
11
|
-
// SQLite is stable in Node 24+. The patch must be applied before any
|
|
12
|
-
// module imports node:sqlite, so we use a dynamic import after patching.
|
|
13
|
-
const originalEmitWarning = process.emitWarning;
|
|
14
|
-
process.emitWarning = function emitWarning(warning, ...args) {
|
|
15
|
-
const message = typeof warning === 'string'
|
|
16
|
-
? warning
|
|
17
|
-
: (warning?.message || '');
|
|
18
|
-
if (message.includes('SQLite')) {
|
|
19
|
-
return;
|
|
20
|
-
}
|
|
21
|
-
return originalEmitWarning.apply(this, [warning, ...args]);
|
|
22
|
-
};
|
|
23
|
-
|
|
24
10
|
import('../src/cli.js').then(async (m) => {
|
|
25
11
|
try {
|
|
26
12
|
await m.cli.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jacebenson/jsn",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.0",
|
|
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": {
|
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
"test:mutation": "stryker run",
|
|
13
13
|
"lint": "npx eslint src/ bin/ test/",
|
|
14
14
|
"start": "node bin/jsn.js",
|
|
15
|
-
"docs": "npm --prefix docs run build",
|
|
16
|
-
"docs:serve": "npm --prefix docs run serve"
|
|
15
|
+
"docs": "npm --prefix ../docs run build",
|
|
16
|
+
"docs:serve": "npm --prefix ../docs run serve"
|
|
17
17
|
},
|
|
18
18
|
"keywords": [
|
|
19
19
|
"servicenow",
|
|
@@ -24,9 +24,6 @@
|
|
|
24
24
|
"author": "Jace Benson",
|
|
25
25
|
"repository": "https://github.com/jacebenson/jsn",
|
|
26
26
|
"license": "MIT",
|
|
27
|
-
"engines": {
|
|
28
|
-
"node": ">=22.5.0"
|
|
29
|
-
},
|
|
30
27
|
"dependencies": {
|
|
31
28
|
"@inquirer/core": "^10.3.2",
|
|
32
29
|
"@inquirer/prompts": "^7.10.1",
|
|
@@ -31,3 +31,6 @@ For development:
|
|
|
31
31
|
For incoming update sets: import the XML, preview the set, and resolve preview
|
|
32
32
|
errors with the human where needed. Once the preview is clear, commit the set
|
|
33
33
|
and verify the results.
|
|
34
|
+
|
|
35
|
+
Search documentation with `jsn docs "query"` or read with `jsn docs --path <path>`.
|
|
36
|
+
Documentation source and defaults for future connections are configured in `jsn setup`.
|
package/src/cli-adapter.js
CHANGED
|
@@ -12,7 +12,7 @@ const names = (x) => typeof x === 'string' ? [x] : (x || []);
|
|
|
12
12
|
*/
|
|
13
13
|
const isArrayOption = (spec) => spec?.type === 'array' || spec?.array === true;
|
|
14
14
|
const commandName = (command) => command.trim().split(/\s+/)[0];
|
|
15
|
-
const positionSpec = (command) => [...command.matchAll(/([<[])([^>\]]+)[>\]]/g)].map((m) => ({ name: m[2], required: m[1] === '<' }));
|
|
15
|
+
const positionSpec = (command) => [...command.matchAll(/([<[])([^>\]]+)[>\]]/g)].map((m) => ({ name: m[2].replace(/\.\.$/, ''), array: m[2].endsWith('..'), required: m[1] === '<' }));
|
|
16
16
|
|
|
17
17
|
class CommandNode {
|
|
18
18
|
constructor(definition) {
|
|
@@ -286,7 +286,7 @@ export class LocalCLI {
|
|
|
286
286
|
* parent's children are only registered when its builder is invoked.
|
|
287
287
|
*/
|
|
288
288
|
commandRegistry() {
|
|
289
|
-
const visible = (node) => node.name !== this.completionCommand;
|
|
289
|
+
const visible = (node) => node.name !== this.completionCommand && !node.definition.hidden;
|
|
290
290
|
const serialize = (node) => {
|
|
291
291
|
node.build();
|
|
292
292
|
return {
|
|
@@ -319,7 +319,7 @@ export class LocalCLI {
|
|
|
319
319
|
/** Structured child signatures for a parent node, built on demand. */
|
|
320
320
|
subcommandsOf(node) {
|
|
321
321
|
return node.children
|
|
322
|
-
.filter((child) => child.name !== this.completionCommand)
|
|
322
|
+
.filter((child) => child.name !== this.completionCommand && !child.definition.hidden)
|
|
323
323
|
.map((child) => {
|
|
324
324
|
child.build();
|
|
325
325
|
return {
|
|
@@ -338,7 +338,8 @@ export class LocalCLI {
|
|
|
338
338
|
}
|
|
339
339
|
const lines = [node.usageText || `Usage: ${this.script} ${path.join(' ') || '<command>'}`];
|
|
340
340
|
if (node.definition.describe) lines.push(`\n${node.definition.describe}`);
|
|
341
|
-
|
|
341
|
+
const children = node.children.filter(n => n.name !== this.completionCommand && !n.definition.hidden);
|
|
342
|
+
if (children.length) lines.push('\nCommands:\n' + children.map((n) => ` ${n.definition.command} ${n.definition.describe || ''}`).join('\n'));
|
|
342
343
|
if (node.options.size) lines.push('\nOptions:\n' + [...node.options].map(([name, s]) => ` --${name}${s.alias ? `, -${names(s.alias).join(', -')}` : ''} ${s.describe || s.description || ''}`).join('\n'));
|
|
343
344
|
if (node.epilogueText) lines.push(`\n${node.epilogueText}`);
|
|
344
345
|
process.stdout.write(lines.join('\n') + '\n');
|
|
@@ -353,7 +354,7 @@ export class LocalCLI {
|
|
|
353
354
|
node.build();
|
|
354
355
|
const argv = { _: path.map((n) => n.name) };
|
|
355
356
|
const completionFilter = (callback) => {
|
|
356
|
-
const values = [...node.children].filter((n) => n.name !== this.completionCommand)
|
|
357
|
+
const values = [...node.children].filter((n) => n.name !== this.completionCommand && !n.definition.hidden)
|
|
357
358
|
.flatMap((n) => path.length ? [n.name] : [n.name, ...n.aliases]);
|
|
358
359
|
const opts = [...this._optionConfig(path)].map(([name]) => `--${name}`);
|
|
359
360
|
callback(null, [...new Set([...values, ...opts])]);
|
|
@@ -385,7 +386,7 @@ export class LocalCLI {
|
|
|
385
386
|
return this._fail(`Unknown command: ${firstWord}`);
|
|
386
387
|
}
|
|
387
388
|
if (this.strictCmd && path.length && node.children.length && firstWord
|
|
388
|
-
&& !this._lookup(node.children, firstWord)) {
|
|
389
|
+
&& !node.definition.defaultPositionals && !this._lookup(node.children, firstWord)) {
|
|
389
390
|
return this._fail(`Unknown command: ${firstWord}`);
|
|
390
391
|
}
|
|
391
392
|
if (!path.length && this.root.demand) return this._fail(this.root.demand.message);
|
|
@@ -401,7 +402,14 @@ export class LocalCLI {
|
|
|
401
402
|
const positions = positionSpec(node.definition.command || '').map((position) => ({
|
|
402
403
|
...position, ...node.positionals.get(position.name), name: position.name,
|
|
403
404
|
}));
|
|
404
|
-
|
|
405
|
+
let positionalIndex = 0;
|
|
406
|
+
for (const position of positions) {
|
|
407
|
+
if (position.array) {
|
|
408
|
+
const values = parsed.positionals.slice(positionalIndex);
|
|
409
|
+
if (values.length) argv[position.name] = values;
|
|
410
|
+
positionalIndex = parsed.positionals.length;
|
|
411
|
+
} else if (parsed.positionals[positionalIndex] !== undefined) argv[position.name] = parsed.positionals[positionalIndex++];
|
|
412
|
+
}
|
|
405
413
|
for (const spec of specs) if (spec.demandOption && argv[spec.name] === undefined) return this._fail(`Missing required argument: --${spec.name}`);
|
|
406
414
|
for (const pos of positions) if (pos.required && argv[pos.name] === undefined) return this._fail(`Missing required argument: ${pos.name}`);
|
|
407
415
|
for (const middleware of this.middlewares) await middleware(argv);
|
package/src/commands/auth.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { connectionPreferences, chooseConnectionPreferences } from '../setup-preferences.js';
|
|
1
2
|
import { detectCommandAudience } from '../command-audience.js';
|
|
2
3
|
import { getEffectiveInstance, normalizeInstanceURL, saveConfig, setActiveProfile } from '../config.js';
|
|
3
4
|
import { errUsage, errUsageHint, errConfirmationRequired } from '../errors.js';
|
|
@@ -326,7 +327,7 @@ export async function loginWizard(app, argv = {}) {
|
|
|
326
327
|
const username = await input({ message: 'Username:', validate: value => value.trim() ? true : 'A username is required' });
|
|
327
328
|
request._basicCredentials = { username: username.trim(), password: await password({ message: 'Password:' }) };
|
|
328
329
|
}
|
|
329
|
-
const settings = await
|
|
330
|
+
const settings = await chooseConnectionPreferences(app.config, profileSettingValues(argv), { confirm });
|
|
330
331
|
request['read-only'] = settings.read_only;
|
|
331
332
|
request['skip-confirmations'] = settings.skip_confirmations;
|
|
332
333
|
request['include-counts'] = settings.include_counts;
|
|
@@ -620,9 +621,10 @@ Find your instance URL in your browser's address bar when logged into ServiceNow
|
|
|
620
621
|
throw errUsage('OAuth login requires --print-url followed by --code <code> when noninteractive.');
|
|
621
622
|
}
|
|
622
623
|
const preliminary = argv.printUrl && !argv.waitFile;
|
|
623
|
-
const
|
|
624
|
-
|
|
625
|
-
|
|
624
|
+
const explicitPreferences = ['read-only', 'skip-confirmations', 'include-counts'].every(flag => typeof argv[flag] === 'boolean');
|
|
625
|
+
const preferences = !targetProfile && interactive && !preliminary && !explicitPreferences
|
|
626
|
+
? await chooseConnectionPreferences(app.config, argv, { confirm: (await import('../prompts.js')).confirm })
|
|
627
|
+
: await configureProfileOptions({ ...targetProfile, ...connectionPreferences(app.config, targetProfile || {}, argv) }, argv);
|
|
626
628
|
let setDefault = argv.makeDefault === true;
|
|
627
629
|
if (!targetProfile && argv.makeDefault === undefined && interactive && !preliminary) {
|
|
628
630
|
const { confirm } = await import('../prompts.js');
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Public documentation service. Deliberately independent of instance credentials.
|
|
2
|
+
import { AppError } from '../../errors.js';
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_DOCS_URL = 'https://jsn.jace.pro';
|
|
5
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
6
|
+
export function docsServiceUrl(value = process.env.JSN_DOCS_URL || DEFAULT_DOCS_URL) {
|
|
7
|
+
let url;
|
|
8
|
+
try { url = new URL(value); } catch { throw new AppError('usage_error', 'Invalid documentation service URL.'); }
|
|
9
|
+
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
10
|
+
throw new AppError('usage_error', 'Documentation service URL must be HTTP(S), without credentials, a query, or a fragment.');
|
|
11
|
+
}
|
|
12
|
+
url.pathname = url.pathname.replace(/\/+$/, '') + '/';
|
|
13
|
+
return url.toString();
|
|
14
|
+
}
|
|
15
|
+
export function configuredDocsService(config = {}) {
|
|
16
|
+
return docsServiceUrl(process.env.JSN_DOCS_URL || config.docs?.url || DEFAULT_DOCS_URL);
|
|
17
|
+
}
|
|
18
|
+
async function request(endpoint, params, options = {}) {
|
|
19
|
+
const service = docsServiceUrl(options.serviceUrl);
|
|
20
|
+
const url = new URL(endpoint, service);
|
|
21
|
+
for (const [key, value] of Object.entries(params)) if (value !== undefined && value !== null && value !== '') url.searchParams.set(key, String(value));
|
|
22
|
+
let response, data;
|
|
23
|
+
try {
|
|
24
|
+
response = await fetch(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });
|
|
25
|
+
let bytes = 0;
|
|
26
|
+
const chunks = [];
|
|
27
|
+
for await (const chunk of response.body) {
|
|
28
|
+
bytes += chunk.length;
|
|
29
|
+
if (bytes > MAX_RESPONSE_BYTES) throw new AppError('api_error', 'Documentation service response is too large.');
|
|
30
|
+
chunks.push(chunk);
|
|
31
|
+
}
|
|
32
|
+
try { data = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
33
|
+
catch { throw new AppError('api_error', 'Documentation service did not return JSON.', 'Check JSN_DOCS_URL points to a JSN documentation service.'); }
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (error instanceof AppError) throw error;
|
|
36
|
+
throw new AppError('network_error', 'Could not reach the documentation service.', `Check your connection and JSN_DOCS_URL (${service}).`, 0, error);
|
|
37
|
+
}
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
const code = response.status === 404 ? 'not_found' : response.status === 429 ? 'rate_limited' : response.status === 400 ? 'usage_error' : 'api_error';
|
|
40
|
+
const message = typeof data?.error === 'string' ? data.error.slice(0, 300) : `Documentation service returned HTTP ${response.status}.`;
|
|
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.' : '';
|
|
43
|
+
throw new AppError(code, message, hint, response.status);
|
|
44
|
+
}
|
|
45
|
+
return { data, service };
|
|
46
|
+
}
|
|
47
|
+
function invalidResponse() {
|
|
48
|
+
return new AppError('api_error', 'Unexpected documentation service response.', 'Check JSN_DOCS_URL and the documentation service version.');
|
|
49
|
+
}
|
|
50
|
+
export async function searchHostedDocs(options = {}) {
|
|
51
|
+
const query = String(options.query || '').trim();
|
|
52
|
+
const limit = options.limit ?? 20, offset = options.offset ?? 0;
|
|
53
|
+
if (!query || query.length > 200) throw new AppError('usage_error', 'Search query must contain 1–200 characters.');
|
|
54
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0 || offset > 10000) {
|
|
55
|
+
throw new AppError('usage_error', 'Use --limit 1–50 and --offset 0–10000.');
|
|
56
|
+
}
|
|
57
|
+
const { data, service } = await request('api/docs/search', { q: query, limit, offset, bundle: options.bundle }, options);
|
|
58
|
+
if (!data || !Array.isArray(data.results) || data.results.length > limit || data.count !== data.results.length ||
|
|
59
|
+
!Number.isInteger(data.total) || data.total < data.count || typeof data.revision !== 'string' ||
|
|
60
|
+
!data.results.every(row => row && Number.isInteger(row.id) && typeof row.path === 'string')) throw invalidResponse();
|
|
61
|
+
return { ...data, query, limit, offset, service };
|
|
62
|
+
}
|
|
63
|
+
export async function getHostedDoc(idOrPath, options = {}) {
|
|
64
|
+
const identifier = String(idOrPath || '');
|
|
65
|
+
if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
|
|
66
|
+
const numeric = /^\d+$/.test(identifier);
|
|
67
|
+
const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
|
|
68
|
+
...(numeric ? {} : { path: identifier }), revision: options.revision,
|
|
69
|
+
}, options);
|
|
70
|
+
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 };
|
|
72
|
+
}
|
|
73
|
+
export async function getHostedDocsStatus(options = {}) {
|
|
74
|
+
const { data, service } = await request('api/docs/status', {}, options);
|
|
75
|
+
if (!data || typeof data.state !== 'string') throw invalidResponse();
|
|
76
|
+
return { ...data, service };
|
|
77
|
+
}
|
package/src/commands/docs/db.js
CHANGED
|
@@ -131,7 +131,6 @@ export function defaultDocsRoots(opts = {}) {
|
|
|
131
131
|
|
|
132
132
|
export function openDocsDb(opts = {}) {
|
|
133
133
|
const dbPath = opts.dbPath || getDocsDbPath();
|
|
134
|
-
ensureDocsCacheDir();
|
|
135
134
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
136
135
|
const release = docsReaderLease(dbPath);
|
|
137
136
|
let db;
|