@jacebenson/jsn 5.5.3 → 5.5.4-dev.185.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/package.json +2 -1
- package/src/capabilities.js +5 -0
- package/src/cli.js +11 -6
- package/src/codesearch-catalog.js +53 -0
- package/src/codesearch-graphql.js +177 -0
- package/src/commands/auth.js +9 -2
- package/src/commands/codesearch.js +35 -91
- package/src/commands/docs/client.js +18 -2
- package/src/commands/docs/docs.js +17 -3
- package/src/commands/docs/index.js +3 -2
- package/src/commands/docs/sections.js +59 -0
- package/src/commands/docs/server.js +4 -1
- package/src/commands/flows.js +22 -0
- package/src/commands/updatesets.js +11 -0
- package/src/flow-search.js +179 -0
- package/src/help.js +12 -3
- package/src/output.js +43 -13
- package/src/update-set-diff.js +228 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jacebenson/jsn",
|
|
3
|
-
"version": "5.5.
|
|
3
|
+
"version": "5.5.4-dev.185.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": {
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"@inquirer/core": "^10.3.2",
|
|
29
29
|
"@inquirer/prompts": "^7.10.1",
|
|
30
30
|
"better-sqlite3": "^13.1.1",
|
|
31
|
+
"commonmark": "^0.31.2",
|
|
31
32
|
"js-yaml": "^5.5.0",
|
|
32
33
|
"saxes": "^6.0.0",
|
|
33
34
|
"turndown": "^7.2.5"
|
package/src/capabilities.js
CHANGED
|
@@ -97,6 +97,11 @@ export function dailyCheckSkipCommands(caps = collectCapabilities()) {
|
|
|
97
97
|
return out;
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
+
export function skipsContextHeader(argv, caps = collectCapabilities()) {
|
|
101
|
+
return contextHeaderSkipCommands(caps).has(argv._?.[0])
|
|
102
|
+
|| caps.get(argv._?.[0])?.skipContextHeaderSubcommands?.includes(argv._?.[1]) === true;
|
|
103
|
+
}
|
|
104
|
+
|
|
100
105
|
export function contextHeaderSkipCommands(caps = collectCapabilities()) {
|
|
101
106
|
const out = dailyCheckSkipCommands(caps);
|
|
102
107
|
for (const [name, capability] of caps) {
|
package/src/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ import { renderHelp, renderTips } from './help.js';
|
|
|
12
12
|
import { isMutationCommand, refreshMutationCommands } from './mutations.js';
|
|
13
13
|
import { maybeShowHome } from './welcome.js';
|
|
14
14
|
import { skippedUpdatesCmd } from './commands/skipped-updates.js';
|
|
15
|
-
import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands,
|
|
15
|
+
import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, skipsContextHeader } from './capabilities.js';
|
|
16
16
|
import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
|
|
17
17
|
import { formatCommandList } from './helpers.js';
|
|
18
18
|
|
|
@@ -100,10 +100,11 @@ import { graphqlCmd } from './commands/graphql.js';
|
|
|
100
100
|
*
|
|
101
101
|
* Precedence is the middleware's, unchanged: the shortcut flags beat `--format`,
|
|
102
102
|
* and among the shortcuts the one applied last wins
|
|
103
|
-
* (csv > markdown > styled > quiet > json).
|
|
103
|
+
* (tsv > csv > markdown > styled > quiet > json).
|
|
104
104
|
*/
|
|
105
105
|
export function resolveRequestedFormat(argv) {
|
|
106
106
|
if (!argv) return '';
|
|
107
|
+
if (argv.tsv) return 'tsv';
|
|
107
108
|
if (argv.csv) return 'csv';
|
|
108
109
|
if (argv.markdown) return 'markdown';
|
|
109
110
|
if (argv.styled) return 'styled';
|
|
@@ -175,8 +176,8 @@ export function buildCLI() {
|
|
|
175
176
|
},
|
|
176
177
|
format: {
|
|
177
178
|
type: 'string',
|
|
178
|
-
description: 'Output format: auto, json, markdown, styled, quiet, csv',
|
|
179
|
-
choices: ['auto', 'json', 'markdown', 'styled', 'quiet', 'csv'],
|
|
179
|
+
description: 'Output format: auto, json, markdown, styled, quiet, csv, tsv',
|
|
180
|
+
choices: ['auto', 'json', 'markdown', 'styled', 'quiet', 'csv', 'tsv'],
|
|
180
181
|
},
|
|
181
182
|
json: {
|
|
182
183
|
type: 'boolean',
|
|
@@ -184,7 +185,11 @@ export function buildCLI() {
|
|
|
184
185
|
},
|
|
185
186
|
csv: {
|
|
186
187
|
type: 'boolean',
|
|
187
|
-
description: '
|
|
188
|
+
description: 'CSV output for compact, flat record lists',
|
|
189
|
+
},
|
|
190
|
+
tsv: {
|
|
191
|
+
type: 'boolean',
|
|
192
|
+
description: 'TSV output for compact, tab-separated record lists',
|
|
188
193
|
},
|
|
189
194
|
get: {
|
|
190
195
|
alias: 'select',
|
|
@@ -352,7 +357,7 @@ export function buildCLI() {
|
|
|
352
357
|
}
|
|
353
358
|
|
|
354
359
|
// Print context header for interactive terminals
|
|
355
|
-
if (!
|
|
360
|
+
if (!skipsContextHeader(argv)) {
|
|
356
361
|
await argv.app.printContextHeader(argv);
|
|
357
362
|
}
|
|
358
363
|
})
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Historical baseline: Jace Benson, https://github.com/arnoudkooi/SN-Utils/issues/91.
|
|
2
|
+
// Candidates, not assumed schema: each field is validated by GraphQL before use.
|
|
3
|
+
// No active-only filters: inactive artifacts are useful search results too.
|
|
4
|
+
export const CODESEARCH_CATALOG = Object.fromEntries(Object.entries({
|
|
5
|
+
bsm_action: 'name script',
|
|
6
|
+
cmn_map_page: 'name script',
|
|
7
|
+
content_block_programmatic: 'name programmatic_content',
|
|
8
|
+
ecc_agent_script_include: 'name script',
|
|
9
|
+
kb_navons: 'name script',
|
|
10
|
+
metric_definition: 'name script',
|
|
11
|
+
process_step_approval: 'name approver_script',
|
|
12
|
+
sc_cat_item_producer: 'name delivery_plan_script entitlement_script post_insert_script script',
|
|
13
|
+
sp_angular_provider: 'name script',
|
|
14
|
+
sp_search_source: 'name data_fetch_script facet_generation_script search_page_template typeahead_template',
|
|
15
|
+
sp_widget: 'name template script client_script link css',
|
|
16
|
+
sysauto_script: 'name script condition',
|
|
17
|
+
sysevent_email_action: 'name advanced_condition message message_html sms_alternate subject',
|
|
18
|
+
sysevent_email_template: 'name message message_html sms_alternate subject',
|
|
19
|
+
sysevent_in_email_action: 'name script filter_conditions condition_script',
|
|
20
|
+
sysevent_script_action: 'name script condition_script event_name',
|
|
21
|
+
sys_app_quota: 'query',
|
|
22
|
+
sys_dictionary: 'dynamic_ref_qual reference_qual attributes default_value calculation',
|
|
23
|
+
sys_dictionary_override: 'reference_qual attributes default_value calculation',
|
|
24
|
+
sys_filter_option_dynamic: 'name script_reference_id script',
|
|
25
|
+
sys_installation_exit: 'name script',
|
|
26
|
+
sys_processor: 'name script description path class_name',
|
|
27
|
+
sys_properties: 'name choices value',
|
|
28
|
+
sys_relationship: 'name apply_to query_from query_with',
|
|
29
|
+
sys_script: 'name script condition filter_condition',
|
|
30
|
+
sys_script_ajax: 'name script',
|
|
31
|
+
sys_script_client: 'name script',
|
|
32
|
+
sys_script_email: 'name script',
|
|
33
|
+
sys_script_fix: 'name script',
|
|
34
|
+
sys_script_include: 'name script description',
|
|
35
|
+
sys_script_validator: 'description validator',
|
|
36
|
+
sys_security_acl: 'name script condition',
|
|
37
|
+
sys_transform_entry: 'source_script',
|
|
38
|
+
sys_transform_map: 'name script',
|
|
39
|
+
sys_transform_script: 'script',
|
|
40
|
+
sys_trigger: 'name script job_context',
|
|
41
|
+
sys_ui_action: 'name script condition onclick',
|
|
42
|
+
sys_ui_context_menu: 'name action_script condition on_show_script',
|
|
43
|
+
sys_ui_list_control: 'columns_condition edit_condition empty_condition filter_condition link_condition new_condition',
|
|
44
|
+
sys_ui_macro: 'name xml',
|
|
45
|
+
sys_ui_page: 'name client_script html processing_script',
|
|
46
|
+
sys_ui_policy: 'short_description script_false script_true conditions',
|
|
47
|
+
sys_ui_script: 'name script',
|
|
48
|
+
sys_variable_value: 'value',
|
|
49
|
+
sys_web_service: 'name script',
|
|
50
|
+
sys_widgets: 'name script',
|
|
51
|
+
sys_ws_operation: 'name operation_script',
|
|
52
|
+
wf_activity_definition: 'name script',
|
|
53
|
+
}).map(([table, fields]) => [table, fields.split(' ')]));
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { AppError, errAuth, errForbidden, errUsage } from './errors.js';
|
|
2
|
+
import { CODESEARCH_CATALOG } from './codesearch-catalog.js';
|
|
3
|
+
|
|
4
|
+
const identifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
5
|
+
const value = (v) => v && typeof v === 'object' ? v.value : v;
|
|
6
|
+
const isAccessFailure = (error) => ['auth_error', 'forbidden', 'mfa_required', 'mfa_code_rejected'].includes(error.code)
|
|
7
|
+
|| /\b401\b|\b403\b|access denied|not authorized|\bforbidden\b|\bunauthorized\b|\bunauthenticated\b/i.test(`${error.status || ''} ${error.message}`);
|
|
8
|
+
function literal(text, label) {
|
|
9
|
+
// Glide encoded-query has no reliable literal escape for separators or eval.
|
|
10
|
+
if (/[\^\r\n\0]/.test(text) || /javascript:/i.test(text)) {
|
|
11
|
+
throw errUsage(`${label} cannot contain encoded-query separators or javascript:`);
|
|
12
|
+
}
|
|
13
|
+
return text;
|
|
14
|
+
}
|
|
15
|
+
function fail(message, code = 'api_error') {
|
|
16
|
+
return new AppError(code, message);
|
|
17
|
+
}
|
|
18
|
+
export function matchingRows(record, table, fields, term) {
|
|
19
|
+
if (!term) throw errUsage('A search term is required');
|
|
20
|
+
const rows = [];
|
|
21
|
+
const needle = term.toLowerCase();
|
|
22
|
+
for (const field of fields) {
|
|
23
|
+
const text = String(value(record[field]) ?? '');
|
|
24
|
+
let matches = 0;
|
|
25
|
+
const lines = [];
|
|
26
|
+
let context = '';
|
|
27
|
+
for (const [index, line] of text.split(/\r?\n/).entries()) {
|
|
28
|
+
const lower = line.toLowerCase();
|
|
29
|
+
let position = 0;
|
|
30
|
+
let count = 0;
|
|
31
|
+
while ((position = lower.indexOf(needle, position)) !== -1) {
|
|
32
|
+
count++;
|
|
33
|
+
position += needle.length;
|
|
34
|
+
}
|
|
35
|
+
if (count) {
|
|
36
|
+
matches += count;
|
|
37
|
+
lines.push(index + 1);
|
|
38
|
+
if (!context) context = line.trim().slice(0, 240);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (matches) rows.push({ table, name: String(value(record.name) ?? value(record.short_description) ?? value(record.sys_id)),
|
|
42
|
+
field, lines: lines.join(','), matches, context, sys_id: value(record.sys_id) });
|
|
43
|
+
}
|
|
44
|
+
return rows;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function searchGraphQL(app, options) {
|
|
48
|
+
const { term, table, scope, allScopes = true, searchGroup = 'sn_devstudio.Studio Search Group',
|
|
49
|
+
limit = 100, pageSize = 250, maxPages = 20, maxRequests = 1000 } = options;
|
|
50
|
+
if (!term?.trim()) throw errUsage('A search term is required');
|
|
51
|
+
literal(term, 'Search term');
|
|
52
|
+
if (scope) literal(scope, 'Scope');
|
|
53
|
+
if (table && !identifier.test(table)) throw errUsage('Invalid table identifier');
|
|
54
|
+
for (const [name, number, max] of [['limit', limit, 100000], ['page-size', pageSize, 1000],
|
|
55
|
+
['max-pages', maxPages, 1000], ['max-requests', maxRequests, 10000]]) {
|
|
56
|
+
if (!Number.isInteger(number) || number < 1 || number > max) throw errUsage(`${name} must be an integer from 1 to ${max}`);
|
|
57
|
+
}
|
|
58
|
+
if (!allScopes && !scope) throw errUsage('--no-all-scopes requires an explicit --scope');
|
|
59
|
+
const base = app.getEffectiveInstance();
|
|
60
|
+
let requests = 0;
|
|
61
|
+
const coverage = [];
|
|
62
|
+
const records = [];
|
|
63
|
+
const definitions = new Map(Object.entries(CODESEARCH_CATALOG).map(([name, fields]) => [name, { fields: [...fields], filters: [] }]));
|
|
64
|
+
// Search-group configuration is additive; never silently omit configured fields.
|
|
65
|
+
let configuration = { status: 'complete' };
|
|
66
|
+
try {
|
|
67
|
+
const params = new URLSearchParams({ sysparm_query: `search_group.name=${literal(searchGroup, 'Search group')}^ORDERBYsys_id`,
|
|
68
|
+
sysparm_limit: '1001', sysparm_fields: 'table,search_fields,additional_filter', sysparm_display_value: 'false' });
|
|
69
|
+
requests++;
|
|
70
|
+
const payload = await app.sdk.request(`${base}/api/now/table/sn_codesearch_table?${params}`);
|
|
71
|
+
if (!Array.isArray(payload?.result)) throw fail('Unreadable sn_codesearch_table response');
|
|
72
|
+
if (payload.result.length > 1000) throw fail('Search configuration exceeds 1000 rows');
|
|
73
|
+
for (const row of payload.result) {
|
|
74
|
+
const name = value(row.table);
|
|
75
|
+
const fields = String(value(row.search_fields) ?? '').split(/[,\s]+/).filter(Boolean);
|
|
76
|
+
if (!identifier.test(name) || !fields.length || fields.some((f) => !identifier.test(f)) || !Object.hasOwn(row, 'additional_filter')) {
|
|
77
|
+
throw fail('Invalid configured table or search fields');
|
|
78
|
+
}
|
|
79
|
+
const definition = definitions.get(name) || { fields: [], filters: [] };
|
|
80
|
+
definition.fields = [...new Set([...definition.fields, ...fields])];
|
|
81
|
+
const filter = String(value(row.additional_filter) ?? '').replace(/\^EQ$/, '');
|
|
82
|
+
if (/javascript:|(?:^|\^)ORDERBY|(?:^|\^)GROUPBY|(?:^|\^)EQ(?:\^|$)|[\r\n\0]/i.test(filter)) {
|
|
83
|
+
// Configuration is data, not permission to execute scripts or reorder.
|
|
84
|
+
definition.invalidFilter = 'Configured additional_filter contains script or query control directives';
|
|
85
|
+
}
|
|
86
|
+
if (filter) definition.filters.push(filter);
|
|
87
|
+
definitions.set(name, definition);
|
|
88
|
+
}
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (isAccessFailure(error)) throw error;
|
|
91
|
+
configuration = { status: 'partial', reason: error.message };
|
|
92
|
+
}
|
|
93
|
+
if (table && !definitions.has(table)) throw errUsage(`No curated or configured fields for ${table}`);
|
|
94
|
+
const targets = table ? [[table, definitions.get(table)]] : [...definitions];
|
|
95
|
+
let matchedRecords = 0;
|
|
96
|
+
for (const [name, definition] of targets) {
|
|
97
|
+
const status = { table: name, fields: definition.fields, status: 'partial', pages: 0, fetched: 0, reason: 'request budget' };
|
|
98
|
+
coverage.push(status);
|
|
99
|
+
if (definition.invalidFilter) { status.reason = definition.invalidFilter; continue; }
|
|
100
|
+
if (matchedRecords >= limit) { status.reason = 'record limit'; continue; }
|
|
101
|
+
const seen = new Set();
|
|
102
|
+
let fields = [...definition.fields];
|
|
103
|
+
let previous = '';
|
|
104
|
+
for (let page = 0; page < maxPages; page++) {
|
|
105
|
+
if (requests >= maxRequests) { status.reason = 'request budget'; break; }
|
|
106
|
+
// Distribute restrictions into every OR/NQ branch so filters cannot escape scope.
|
|
107
|
+
const branches = definition.filters.length ? definition.filters.flatMap((filter) => filter.split('^NQ')) : [''];
|
|
108
|
+
const query = branches.map((filter) => [filter, scope ? `sys_scope.scope=${scope}` : '',
|
|
109
|
+
fields.map((field) => `${field}LIKE${term}`).join('^OR')].filter(Boolean).join('^')).join('^NQ') + '^ORDERBYsys_id';
|
|
110
|
+
const selection = [...new Set(['sys_id', ...(scope ? ['sys_scope'] : []), ...fields])].map((field) => `${field} { value }`).join(' ');
|
|
111
|
+
const graphql = `query { GlideRecord_Query { ${name}(queryConditions: ${JSON.stringify(query)}, pagination: {limit: ${pageSize}, offset: ${page * pageSize}}) { _results { ${selection} } } } }`;
|
|
112
|
+
requests++;
|
|
113
|
+
let payload;
|
|
114
|
+
try {
|
|
115
|
+
payload = await app.sdk.request(`${base}/api/now/graphql`, { method: 'POST', body: JSON.stringify({ query: graphql }) });
|
|
116
|
+
const envelope = payload?.result ?? payload;
|
|
117
|
+
if (payload?.errors?.length || envelope?.errors?.length) {
|
|
118
|
+
const errors = payload.errors || envelope.errors;
|
|
119
|
+
if (errors.some((error) => /UNAUTHENTICATED/i.test(error.extensions?.code || ''))) {
|
|
120
|
+
throw errAuth(`GraphQL authentication rejected: ${errors.map((error) => error.message).join('; ')}`);
|
|
121
|
+
}
|
|
122
|
+
if (errors.some((error) => /FORBIDDEN|ACCESS_DENIED/i.test(error.extensions?.code || ''))) {
|
|
123
|
+
throw errForbidden(`GraphQL access denied: ${errors.map((error) => error.message).join('; ')}`);
|
|
124
|
+
}
|
|
125
|
+
throw fail(errors.map((e) => e.message || String(e)).join('; '), 'graphql_error');
|
|
126
|
+
}
|
|
127
|
+
if (payload?.ok === false || envelope?.error) throw fail(JSON.stringify(envelope.error || payload.error));
|
|
128
|
+
const rows = envelope?.data?.GlideRecord_Query?.[name]?._results;
|
|
129
|
+
if (!Array.isArray(rows)) throw fail('GraphQL response is missing _results');
|
|
130
|
+
status.pages++;
|
|
131
|
+
if (!rows.length) {
|
|
132
|
+
status.status = status.unsupportedFields?.length ? 'partial' : 'complete';
|
|
133
|
+
if (status.unsupportedFields?.length) status.reason = `Unsupported fields: ${status.unsupportedFields.join(', ')}`;
|
|
134
|
+
else delete status.reason;
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
for (const row of rows) {
|
|
138
|
+
const id = value(row.sys_id);
|
|
139
|
+
if (!id || seen.has(id) || (previous && id <= previous)) throw fail('Unstable pagination: missing, duplicate or unordered sys_id');
|
|
140
|
+
if ([...fields, ...(scope ? ['sys_scope'] : [])].some((field) => !Object.hasOwn(row, field) || row[field] == null)) throw fail('GraphQL omitted a requested field (schema or access restriction)');
|
|
141
|
+
previous = id;
|
|
142
|
+
seen.add(id);
|
|
143
|
+
status.fetched++;
|
|
144
|
+
const hits = matchingRows(row, name, fields, term);
|
|
145
|
+
if (hits.length) { records.push(...hits); matchedRecords++; }
|
|
146
|
+
if (matchedRecords >= limit) break;
|
|
147
|
+
}
|
|
148
|
+
if (matchedRecords >= limit) { status.reason = 'record limit'; break; }
|
|
149
|
+
status.reason = 'page budget';
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (isAccessFailure(error)) {
|
|
152
|
+
if (error.code === 'graphql_error') {
|
|
153
|
+
throw /\b401\b|unauthorized|unauthenticated/i.test(error.message) ? errAuth(error.message) : errForbidden(error.message);
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
// Only explicit schema-validation failures may narrow the selection.
|
|
158
|
+
// Never reinterpret ACL errors or missing data as nonexistent fields.
|
|
159
|
+
const missing = [...error.message.matchAll(/Cannot query field ["'](\w+)["']/g)]
|
|
160
|
+
.map((match) => match[1]).filter((field) => fields.includes(field));
|
|
161
|
+
if (missing.length && error.code === 'graphql_error') {
|
|
162
|
+
status.unsupportedFields = [...new Set([...(status.unsupportedFields || []), ...missing])];
|
|
163
|
+
fields = fields.filter((field) => !missing.includes(field));
|
|
164
|
+
if (fields.length) { page--; continue; }
|
|
165
|
+
}
|
|
166
|
+
status.reason = error.message;
|
|
167
|
+
status.status = /Cannot query field|Unknown field|Unknown type/i.test(error.message) ? 'unsupported' : 'partial';
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const state = configuration.status === 'complete' && coverage.every((item) => item.status === 'complete') ? 'complete' :
|
|
173
|
+
coverage.every((item) => item.status === 'unsupported') ? 'unsupported' : 'partial';
|
|
174
|
+
return { term, count: records.length, records, recordCount: matchedRecords, fieldCount: records.length,
|
|
175
|
+
matchCount: records.reduce((sum, row) => sum + row.matches, 0), status: state,
|
|
176
|
+
coverage, configuration, requests, hint: 'Flow internals require separate jsn flows search; no flow downloads are performed.' };
|
|
177
|
+
}
|
package/src/commands/auth.js
CHANGED
|
@@ -38,8 +38,8 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
|
|
|
38
38
|
methods[diagnostics.auth_method] || 'Not configured',
|
|
39
39
|
states[diagnostics.state] || (profile.authenticated ? 'Available' : 'Missing'),
|
|
40
40
|
connection,
|
|
41
|
-
profile.read_only ? 'Read-only' : 'Read/write',
|
|
42
|
-
profile.skip_confirmations ? 'No prompt' : 'Confirm',
|
|
41
|
+
profile.read_only === true ? 'Read-only' : 'Read/write',
|
|
42
|
+
profile.skip_confirmations === true ? 'No prompt' : 'Confirm',
|
|
43
43
|
profile.include_counts === false ? 'Off' : 'On',
|
|
44
44
|
];
|
|
45
45
|
if (details) {
|
|
@@ -60,6 +60,13 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
|
|
|
60
60
|
const formatRow = row => row.map((cell, column) => cell.padEnd(widths[column])).join(' ').trimEnd();
|
|
61
61
|
const lines = [summary || `${profiles.length} profiles`, '', formatRow(headings), ...rows.map(formatRow)];
|
|
62
62
|
if (profiles.some(profile => profile.active)) lines.push('', '* selected profile');
|
|
63
|
+
lines.push('', 'Profile protections (ACCESS / DELETES):');
|
|
64
|
+
if (profiles.some(profile => profile.read_only === true)) lines.push(' Read-only: blocks mutation commands, including writes, deletes and raw REST even with GET.');
|
|
65
|
+
if (profiles.some(profile => profile.read_only !== true)) lines.push(' Read/write: permits profile operations, subject to each command\'s guards.');
|
|
66
|
+
if (profiles.some(profile => profile.skip_confirmations !== true)) lines.push(' Confirm: guarded deletes require confirmation; --force bypasses this prompt, not read-only.');
|
|
67
|
+
if (profiles.some(profile => profile.skip_confirmations === true)) lines.push(' No prompt: profile skips standard delete confirmation; command-specific safeguards still apply.');
|
|
68
|
+
lines.push('ACCESS is a JSN profile setting, not ServiceNow ACL authorization.',
|
|
69
|
+
'CREDENTIALS describes local availability; only CONNECTION Verified confirms the status probe succeeded.');
|
|
63
70
|
if (profiles.some(profile => profile.diagnostics?.probe?.code === 'not_requested')) lines.push('', 'Connection not checked (--local).');
|
|
64
71
|
if (notes.length) lines.push('', ...notes);
|
|
65
72
|
if (!details) lines.push('', 'Show users and instance URLs: jsn auth status --details');
|
|
@@ -1,50 +1,20 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
// Flatten the API's nested shape into one row per record/field so the output
|
|
10
|
-
// controller can render it as a table / CSV / JSON.
|
|
11
|
-
//
|
|
12
|
-
// API shape:
|
|
13
|
-
// result: [ { recordType, hits: [ { name, className, tableLabel,
|
|
14
|
-
// matches: [ { field, fieldLabel,
|
|
15
|
-
// lineMatches: [ { line, context, escaped } ] } ] } ] } ] }
|
|
16
|
-
// NOTE: with ?table=<t> the API returns a single object, not an array.
|
|
17
|
-
export function flattenHits(result) {
|
|
18
|
-
const groups = Array.isArray(result) ? result : (result ? [result] : []);
|
|
19
|
-
const rows = [];
|
|
20
|
-
for (const group of groups) {
|
|
21
|
-
for (const hit of group.hits || []) {
|
|
22
|
-
for (const match of hit.matches || []) {
|
|
23
|
-
const lines = (match.lineMatches || []).filter((lm) => lm.context);
|
|
24
|
-
rows.push({
|
|
25
|
-
table: hit.className || group.recordType,
|
|
26
|
-
name: hit.name,
|
|
27
|
-
field: match.field,
|
|
28
|
-
lines: lines.map((lm) => lm.line).join(','),
|
|
29
|
-
matches: lines.length,
|
|
30
|
-
context: lines[0]?.context?.trim() || '',
|
|
31
|
-
sys_id: hit.sys_id || hit.sysId || '',
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
}
|
|
1
|
+
// GraphQL read-only queries; no sn_codesearch engine or Flow downloads.
|
|
2
|
+
import { searchGraphQL } from '../codesearch-graphql.js';
|
|
3
|
+
|
|
4
|
+
export function renderCodeSearch(data) {
|
|
5
|
+
const out = [`${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}`];
|
|
6
|
+
for (const row of data.records) {
|
|
7
|
+
out.push(`${row.table} ${row.name} .${row.field} (lines ${row.lines})`);
|
|
8
|
+
if (row.context) out.push(` ${row.context}`);
|
|
35
9
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
function renderFormatted(rows, term) {
|
|
42
|
-
if (rows.length === 0) return `No code matches for "${term}".\n`;
|
|
43
|
-
const out = [];
|
|
44
|
-
for (const r of rows) {
|
|
45
|
-
out.push(`${r.table} ${r.name} .${r.field} (lines ${r.lines})`);
|
|
46
|
-
if (r.context) out.push(` ${r.context}`);
|
|
10
|
+
if (!data.records.length) out.push(`No visible code matches for "${data.term}".`);
|
|
11
|
+
const gaps = data.coverage.filter((item) => item.status !== 'complete');
|
|
12
|
+
for (const gap of gaps) {
|
|
13
|
+
out.push(`${gap.table}: ${gap.status} (${gap.reason})`);
|
|
14
|
+
if (gap.unsupportedFields?.length) out.push(` Unsupported fields: ${gap.unsupportedFields.join(', ')}`);
|
|
47
15
|
}
|
|
16
|
+
if (data.configuration.status !== 'complete') out.push(`Search configuration: ${data.configuration.reason}`);
|
|
17
|
+
out.push(data.hint);
|
|
48
18
|
return out.join('\n') + '\n';
|
|
49
19
|
}
|
|
50
20
|
|
|
@@ -52,52 +22,26 @@ export function codesearchCmd(wrap) {
|
|
|
52
22
|
return {
|
|
53
23
|
command: 'codesearch [subcommand]',
|
|
54
24
|
aliases: ['codesearch'],
|
|
55
|
-
describe: 'Search code across ServiceNow artifacts
|
|
56
|
-
builder: (yargs) => yargs
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
params.set('search_group', argv.searchGroup);
|
|
76
|
-
params.set('search_all_scopes', String(argv.allScopes));
|
|
77
|
-
if (argv.table) params.set('table', argv.table);
|
|
78
|
-
if (argv.scope) params.set('scope', argv.scope);
|
|
79
|
-
|
|
80
|
-
const url = `${app.getEffectiveInstance()}/api/sn_codesearch/code_search/search?${params.toString()}`;
|
|
81
|
-
let payload;
|
|
82
|
-
try {
|
|
83
|
-
payload = await app.sdk.request(url);
|
|
84
|
-
} catch (err) {
|
|
85
|
-
if (err.code === 'api_error' && /404/.test(err.message)) {
|
|
86
|
-
err.message += '\n\nHint: the sn_codesearch plugin may not be active on this instance.';
|
|
87
|
-
}
|
|
88
|
-
throw err;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const result = payload?.result || [];
|
|
92
|
-
const rows = flattenHits(result);
|
|
93
|
-
|
|
94
|
-
app.ok(
|
|
95
|
-
{ term: argv.term, count: rows.length, records: rows, _formatted: renderFormatted(rows, argv.term) },
|
|
96
|
-
{ summary: `${rows.length} code match(es) for "${argv.term}"` },
|
|
97
|
-
);
|
|
98
|
-
}),
|
|
99
|
-
})
|
|
100
|
-
.demandCommand(1, 'Specify a subcommand: search'),
|
|
25
|
+
describe: 'Search code across ServiceNow artifacts with read-only GraphQL queries',
|
|
26
|
+
builder: (yargs) => yargs.command({
|
|
27
|
+
command: 'search <term>',
|
|
28
|
+
describe: 'Search code; Flow internals require separate jsn flows search',
|
|
29
|
+
builder: (y) => y
|
|
30
|
+
.positional('term', { type: 'string', describe: 'Literal case-insensitive search term (no encoded-query separators)' })
|
|
31
|
+
.option('limit', { alias: 'l', type: 'number', default: 100, describe: 'Max matching records (coverage is partial when reached)' })
|
|
32
|
+
.option('table', { alias: 't', type: 'string', describe: 'Restrict to a curated or configured source table' })
|
|
33
|
+
.option('scope', { alias: 's', type: 'string', describe: 'Restrict to an app scope (e.g. x_my_app)' })
|
|
34
|
+
.option('search-group', { type: 'string', default: 'sn_devstudio.Studio Search Group', describe: 'Layer configured fields and filters from this group over the curated catalog' })
|
|
35
|
+
.option('all-scopes', { type: 'boolean', default: true, describe: 'Search all scopes; false requires --scope' })
|
|
36
|
+
.option('page-size', { type: 'number', default: 250, describe: 'GraphQL page window size (max 1000)' })
|
|
37
|
+
.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
|
+
handler: wrap(async (argv, app) => {
|
|
40
|
+
const data = await searchGraphQL(app, argv);
|
|
41
|
+
Object.defineProperty(data, '_formatted', { value: renderCodeSearch(data), enumerable: false });
|
|
42
|
+
app.ok(data, { summary: `${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}` });
|
|
43
|
+
}),
|
|
44
|
+
}).demandCommand(1, 'Specify a subcommand: search'),
|
|
101
45
|
handler: () => {},
|
|
102
46
|
};
|
|
103
47
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Public documentation service. Deliberately independent of instance credentials.
|
|
2
2
|
import { AppError } from '../../errors.js';
|
|
3
|
+
import { selectDocument, SECTION_PROTOCOL } from './sections.js';
|
|
3
4
|
|
|
4
5
|
export const DEFAULT_DOCS_URL = 'https://jsn.jace.pro';
|
|
5
6
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
@@ -73,12 +74,27 @@ export async function searchHostedDocs(options = {}) {
|
|
|
73
74
|
export async function getHostedDoc(idOrPath, options = {}) {
|
|
74
75
|
const identifier = String(idOrPath || '');
|
|
75
76
|
if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
|
|
77
|
+
if ((options.outline && options.section !== undefined) || (options.section !== undefined && !String(options.section).trim())) throw new AppError('usage_error', 'Use either --outline or one nonempty --section.');
|
|
76
78
|
const numeric = /^\d+$/.test(identifier);
|
|
77
79
|
const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
|
|
78
80
|
...(numeric ? {} : { path: identifier }), revision: options.revision, release: options.release,
|
|
81
|
+
outline: options.outline || undefined, section: options.section,
|
|
79
82
|
}, options);
|
|
80
|
-
|
|
81
|
-
|
|
83
|
+
const targeted = options.outline || options.section !== undefined;
|
|
84
|
+
const native = data?.section_protocol === SECTION_PROTOCOL;
|
|
85
|
+
if (!data?.document || typeof data.document.path !== 'string' || typeof data.revision !== 'string' ||
|
|
86
|
+
(!(targeted && native && options.outline) && typeof data.document.body !== 'string')) throw invalidResponse();
|
|
87
|
+
if (options.revision && data.revision !== options.revision) throw new AppError('api_error', 'Documentation revision mismatch. Refresh the outline.');
|
|
88
|
+
if (options.release && data.document.release && data.document.release !== options.release) throw new AppError('api_error', `Documentation service returned release ${data.document.release}, expected ${options.release}.`);
|
|
89
|
+
let row = { ...data.document, release: options.release ?? data.release ?? data.document.release, revision: data.revision, service };
|
|
90
|
+
if (targeted) {
|
|
91
|
+
if (!native) row = selectDocument(row, options);
|
|
92
|
+
const mode = options.outline ? 'outline' : 'section';
|
|
93
|
+
if (row.retrieval?.protocol !== SECTION_PROTOCOL || row.retrieval?.mode !== mode ||
|
|
94
|
+
(options.outline ? !Array.isArray(row.outline) : !row.section || row.retrieval.subtree_complete !== true)) throw invalidResponse();
|
|
95
|
+
row.retrieval = { ...row.retrieval, execution: native ? 'service' : 'client-fallback', full_document_transferred: !native };
|
|
96
|
+
}
|
|
97
|
+
return row;
|
|
82
98
|
}
|
|
83
99
|
export async function getHostedDocsStatus(options = {}) {
|
|
84
100
|
const { data, service } = await request('api/docs/status', { release: options.release }, options);
|
|
@@ -9,6 +9,10 @@ import { listDocsReleases } from './releases.js';
|
|
|
9
9
|
|
|
10
10
|
declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
|
|
11
11
|
|
|
12
|
+
function presented(data, text) {
|
|
13
|
+
return Object.defineProperty(data, '_formatted', { value: text, enumerable: false });
|
|
14
|
+
}
|
|
15
|
+
|
|
12
16
|
async function search(argv, app) {
|
|
13
17
|
const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
|
|
14
18
|
const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
|
|
@@ -29,11 +33,18 @@ async function search(argv, app) {
|
|
|
29
33
|
async function read(argv, app) {
|
|
30
34
|
const maxLines = argv.lines ?? 80;
|
|
31
35
|
if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
|
|
32
|
-
const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
|
|
36
|
+
const row = await getHostedDoc(argv.path || argv['id-or-path'], { outline: argv.outline, section: argv.section, revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
|
|
33
37
|
const title = row.title || row.path;
|
|
38
|
+
const provenance = `${row.path}\nRelease: ${row.release} | Revision: ${row.revision}\nService: ${row.service}`;
|
|
39
|
+
if (row.outline) {
|
|
40
|
+
const text = row.outline.map(h => `${' '.repeat(h.ancestors.length)}${h.title} [lines ${h.start_line}–${h.end_line}]\n${' '.repeat(h.ancestors.length)} ${h.id}`).join('\n');
|
|
41
|
+
return app.ok(presented(row, `${title}\n${provenance}\n\n${text || 'No selectable headings.'}\n\nUse --section '<ID>' with this --path. Selection includes preamble and ancestor introductions.\nOther sections and linked prerequisites may still matter.\nRetrieval: ${row.retrieval.execution}; full document transferred: ${row.retrieval.full_document_transferred}\n`));
|
|
42
|
+
}
|
|
34
43
|
const lines = row.body.split('\n');
|
|
35
44
|
const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
|
|
36
|
-
|
|
45
|
+
const content = row.section ? row.body : lines.slice(0, maxLines).join('\n') + hint;
|
|
46
|
+
const context = row.section ? `\nComplete selected subtree: ${row.section.title}\n${row.retrieval.context_policy}\nOther sections to check: ${row.retrieval.context_sections.map(h => h.title).join('; ') || 'none'}.\nUse --outline to retrieve their IDs.\nSemantic answer completeness: unknown. Retrieval: ${row.retrieval.execution}.\n` : '';
|
|
47
|
+
app.ok(presented(row, `Doc ${row.id}: ${title} in ${row.release}\n${provenance}${context}\n${content}\n`), { summary: `Doc ${row.id}: ${title} in ${row.release}` });
|
|
37
48
|
}
|
|
38
49
|
|
|
39
50
|
export function docsCmd(wrap) {
|
|
@@ -53,7 +64,9 @@ export function docsCmd(wrap) {
|
|
|
53
64
|
.option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
|
|
54
65
|
.option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
|
|
55
66
|
.option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
|
|
56
|
-
.option('
|
|
67
|
+
.option('outline', { type: 'boolean', describe: 'List revision-bound section IDs for --path, without document body' })
|
|
68
|
+
.option('section', { type: 'string', describe: 'Read a complete subtree by outline ID or exact unique heading; includes ancestor introductions' })
|
|
69
|
+
.option('lines', { type: 'number', default: 80, describe: 'Full-document human preview lines; JSON and selected sections are not truncated' })
|
|
57
70
|
.command({ command: 'releases', describe: 'List locally installed documentation families', handler: wrap(async (_argv, app) => {
|
|
58
71
|
const releases = listDocsReleases();
|
|
59
72
|
app.ok({ releases, _formatted: releases.length ? releases.map(row => `${row.release}${row.default ? ' (default)' : ''} ${row.revision || 'unknown'} ${row.documents} documents ${row.indexPath}`).join('\n') + '\n' : 'No local documentation families installed.\n' }, { summary: `${releases.length} local documentation release(s)` });
|
|
@@ -90,6 +103,7 @@ export function docsCmd(wrap) {
|
|
|
90
103
|
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
|
|
91
104
|
return;
|
|
92
105
|
}
|
|
106
|
+
if ((argv.outline || argv.section !== undefined) && !argv.path) throw new AppError('usage_error', 'Use --path with --outline or --section.');
|
|
93
107
|
if (argv.path) return read(argv, app);
|
|
94
108
|
if (argv.query?.length) return search(argv, app);
|
|
95
109
|
const service = await documentationService(app.config, resolveDocsRelease(argv.release, app.config));
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// One search engine for the hosted website and the optional local service.
|
|
2
2
|
import fs from 'node:fs';
|
|
3
|
+
import { selectDocument } from './sections.js';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import Database from 'better-sqlite3';
|
|
5
6
|
import { resolveDocsDbPath } from './db.js';
|
|
@@ -72,11 +73,11 @@ export class DocumentationIndex {
|
|
|
72
73
|
.all(...binds, text, text, text, limit, offset).map(documentationSummary);
|
|
73
74
|
return { query: text, revision: this.revision(), total, count: results.length, limit, offset, results };
|
|
74
75
|
}
|
|
75
|
-
document({ id, path: docPath } = {}) {
|
|
76
|
+
document({ id, path: docPath, outline = false, section } = {}) {
|
|
76
77
|
const select = 'SELECT id, path, title, bundle, doc_type, release, body FROM docs WHERE';
|
|
77
78
|
const row = docPath ? this.db.prepare(`${select} path = ?`).get(docPath)
|
|
78
79
|
: /^\d{1,18}$/.test(String(id)) ? this.db.prepare(`${select} id = ?`).get(String(id)) : null;
|
|
79
80
|
if (!row) throw new DocumentationError('Document not found.', 404);
|
|
80
|
-
return row;
|
|
81
|
+
return outline || section !== undefined ? selectDocument({ ...row, revision: this.revision() }, { outline, section }) : row;
|
|
81
82
|
}
|
|
82
83
|
}
|