@jacebenson/jsn 5.5.7-dev.211.1 → 5.5.7-dev.213.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 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.211.1",
3
+ "version": "5.5.7-dev.213.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
- "lint": "npx eslint src/ bin/ test/",
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
- "@stryker-mutator/core": "^10.0.0",
34
+ "eslint": "^10.15.0",
36
35
  "globals": "^17.6.0"
37
36
  },
38
37
  "files": [
@@ -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.epilogueText,
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).
package/src/cli.js CHANGED
@@ -79,6 +79,7 @@ import { b4rulesCmd } from './commands/b4rules.js';
79
79
  import { atfCmd } from './commands/atf.js';
80
80
  import { scanCmd } from './commands/scan.js';
81
81
  import { storeCmd } from './commands/store.js';
82
+ import { subscriptionsCmd } from './commands/subscriptions.js';
82
83
  import { approvalsCmd } from './commands/approvals.js';
83
84
  import { perfCmd } from './commands/perf.js';
84
85
  import { customizationsCmd } from './commands/customizations.js';
@@ -444,6 +445,7 @@ export function buildCLI() {
444
445
  .command(atfCmd(wrap))
445
446
  .command(scanCmd(wrap))
446
447
  .command(storeCmd(wrap))
448
+ .command(subscriptionsCmd(wrap))
447
449
  .command(approvalsCmd(wrap))
448
450
  .command(skippedUpdatesCmd(wrap))
449
451
  .command(perfCmd(wrap))
@@ -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
 
@@ -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
- + 'one; scripts use explicit identifiers and manifests.');
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.';
@@ -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 (...args) => {
46
- const { createPrompt, useKeypress, usePagination, useState, isDownKey, isEnterKey, isUpKey } = await import('@inquirer/core');
47
- return createPrompt((config, done) => {
48
- const [active, setActive] = useState(0);
49
- const choices = config.choices;
50
-
51
- useKeypress((key) => {
52
- if (key.name === 'q' || key.name === 'escape') {
53
- done(undefined);
54
- return;
55
- }
56
- if (isEnterKey(key)) {
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 (isUpKey(key) && active > 0) setActive(active - 1);
61
- if (isDownKey(key) && active < choices.length - 1) setActive(active + 1);
62
- });
63
-
64
- const page = usePagination({
65
- items: choices,
66
- active,
67
- // Pagination budgets terminal lines, including the section headings.
68
- pageSize: choices.length + new Set(choices.map(choice => choice.section)).size * 2 - 1,
69
- loop: false,
70
- renderItem: ({ item, isActive }) => {
71
- const index = choices.indexOf(item);
72
- const heading = choices[index - 1]?.section !== item.section ? `${index ? '\n' : ''} ${item.section}\n` : '';
73
- return `${heading}${isActive ? '❯' : ' '} ${item.name}`;
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,47 @@
1
+ import { refreshSchedules } from '../schedule-cache.js';
2
+ import { declareCapabilities } from '../capabilities.js';
3
+ import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
+
5
+ declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
6
+ export function subscriptionsCmd(wrap) {
7
+ const local = (argv, app) => {
8
+ const snapshot = scheduleSnapshot();
9
+ const schedules = scheduleCatalog({ product: argv.product, sku: argv.sku, id: argv.id, snapshot });
10
+ const data = { provenance: snapshot.provenance, schedules, coverage: { index_documents: new Set(snapshot.schedules.map(s => s.source_url)).size, archive: 'unavailable', sku_mapping: 'only explicitly normalized codes; empty results do not establish absence of rights' } };
11
+ Object.defineProperty(data, '_formatted', { value: [
12
+ `Local catalog snapshot (${data.provenance.source}; ${data.provenance.freshness}; revision ${data.provenance.revision || 'bundled'}; retrieved ${data.provenance.retrieved_at || 'bundled'}; stale ${data.provenance.stale}); contractual applicability unverified. Archive unavailable.`,
13
+ ...schedules.flatMap(s => [
14
+ `${s.id} | ${s.product} | ${s.effective_date || s.source_version || 'date unverified'} | ${s.normalization_status || 'not specified'}`,
15
+ s.source_url,
16
+ `Measurement: ${s.measurement || 'not specified; inspection only'}. SKU mapping: ${(s.skus || []).join(', ') || 'unverified'}`,
17
+ ...(s.unknowns || s.limitations || []),
18
+ ...(argv.id ? [formatSchedule(s)] : []),
19
+ ]),
20
+ ].join('\n') });
21
+ app.ok(data, { summary: 'Local dated metering schedules, not purchased rights' });
22
+ };
23
+ return {
24
+ command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
25
+ builder: y => y.command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
26
+ const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
+ const manifest = argv.manifestUrl || process.env.JSN_SCHEDULES_MANIFEST_URL || app.config?.docs?.schedule_manifest_url || (origin ? new URL('/subscription-schedules/v1/manifest.json', origin).href : undefined);
28
+ const provenance = await refreshSchedules(manifest);
29
+ app.ok({ provenance }, { summary: 'Validated schedule cache refreshed' });
30
+ }) }).command({ command: 'schedules', describe: 'Inspect validated cache or bundled source-backed schedules offline', builder: b => b.option('product', { type: 'string' }).option('sku', { type: 'string' }).option('id', { type: 'string' }), handler: wrap(local) })
31
+ .command({ command: 'estimate <product>', describe: 'Read-only ITOM population comparison, not billing or a 90-day meter',
32
+ builder: b => b.positional('product', { type: 'string', describe: 'ITOM; arbitrary SKUs and HRSD unsupported' })
33
+ .option('schedule', { type: 'string', describe: 'Explicit dated schedule ID from subscriptions schedules' })
34
+ .option('assume-eligible', { type: 'boolean', default: false, describe: 'Hypothetically treat mapped populations as managed and component-eligible, exclusions unknown' }),
35
+ handler: wrap(async (argv, app) => {
36
+ // Validate unsupported selections before requesting an instance.
37
+ const selected = loadSchedule(argv.schedule);
38
+ if (String(argv.product).toUpperCase() !== 'ITOM' || selected.measurement !== 'illustrative-population') await estimateSubscription(null, argv.product, { schedule: argv.schedule });
39
+ app.requireInstance();
40
+ const report = await estimateSubscription(app.sdk, argv.product, { schedule: argv.schedule, assumeEligible: argv.assumeEligible });
41
+ Object.defineProperty(report, '_formatted', { value: formatEstimate(report) });
42
+ app.ok(report, { summary: 'Incomplete illustrative ITOM population comparison; no authoritative total' });
43
+ }),
44
+ }),
45
+ handler: wrap(local),
46
+ };
47
+ }
@@ -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.