@jacebenson/jsn 5.5.3 → 5.5.4-dev.186.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.
@@ -0,0 +1,59 @@
1
+ // CommonMark source positions let us slice original text, never reserialize tables/code.
2
+ import * as commonmark from 'commonmark';
3
+ import { createHash } from 'node:crypto';
4
+ import { AppError } from '../../errors.js';
5
+
6
+ export const SECTION_PROTOCOL = 'sections-v1';
7
+ function failure(message) { return new AppError('usage_error', message, 'Use --outline for exact titles and revision-bound IDs.', 400); }
8
+ export function selectDocument(row, { outline = false, section } = {}) {
9
+ if (outline && section !== undefined) throw failure('Use either --outline or --section, not both.');
10
+ if (section !== undefined && !String(section).trim()) throw failure('Section must not be empty.');
11
+ if (!outline && section === undefined) return row;
12
+ const body = row.body;
13
+ const starts = [0];
14
+ for (const match of body.matchAll(/\r\n|\n|\r/g)) starts.push(match.index + match[0].length);
15
+ const ast = new commonmark.Parser().parse(body);
16
+ const headings = [];
17
+ for (let node = ast.firstChild; node; node = node.next) {
18
+ if (node.type !== 'heading') continue; // Never split lists, blockquotes or HTML blocks.
19
+ let title = '', walker = node.walker(), event;
20
+ while ((event = walker.next())) {
21
+ if (event.entering && ['text', 'code'].includes(event.node.type)) title += event.node.literal;
22
+ if (event.entering && ['softbreak', 'linebreak'].includes(event.node.type)) title += ' ';
23
+ }
24
+ headings.push({ title, depth: node.level, start_line: node.sourcepos[0][0], start: starts[node.sourcepos[0][0] - 1] });
25
+ }
26
+ const identity = createHash('sha256').update(JSON.stringify([SECTION_PROTOCOL, row.path, row.release, row.revision, body])).digest('hex').slice(0, 24);
27
+ const stack = [];
28
+ for (let i = 0; i < headings.length; i++) {
29
+ const h = headings[i];
30
+ while (stack.length && headings[stack.at(-1)].depth >= h.depth) stack.pop();
31
+ h.ancestors = stack.map(n => headings[n].id);
32
+ h.id = `s1:${identity}:${i + 1}`;
33
+ const next = headings.slice(i + 1).find(n => n.depth <= h.depth);
34
+ h.end = next?.start ?? body.length;
35
+ h.end_line = next ? next.start_line - 1 : starts.length;
36
+ h.introEnd = headings[i + 1]?.start ?? body.length;
37
+ stack.push(i);
38
+ }
39
+ const publicHeading = ({ start: _start, end: _end, introEnd: _introEnd, ...h }) => h; // Offsets remain an implementation detail.
40
+ const metadata = { protocol: SECTION_PROTOCOL, document_complete: false, semantic_completeness: 'unknown', truncated: false,
41
+ heading_policy: 'CommonMark top-level ATX/setext; container and HTML headings are not boundaries' };
42
+ const { body: _body, ...identityRow } = row;
43
+ if (outline) return { ...identityRow, outline: headings.map(publicHeading), retrieval: { ...metadata, mode: 'outline', total_lines: starts.length, context_policy: 'Selection includes preamble and ancestor introductions; other sections may contain relevant context.' } };
44
+ const matches = headings.filter(h => h.id === section || h.title === section);
45
+ if (!matches.length) throw failure('No matching section. IDs are document- and revision-bound; refresh the outline.');
46
+ if (matches.length !== 1) throw failure(`Ambiguous section ${JSON.stringify(section)}. Choose an ID: ${matches.map(h => `${h.id} (${h.title}, line ${h.start_line})`).join('; ')}`);
47
+ const h = matches[0];
48
+ const spans = [];
49
+ const add = (start, end, kind) => { if (end > start) spans.push({ start, end, kind }); };
50
+ add(0, headings[0]?.start ?? body.length, 'preamble');
51
+ for (const id of h.ancestors) { const a = headings.find(n => n.id === id); add(a.start, a.introEnd, 'ancestor-introduction'); }
52
+ add(h.start, h.end, 'section-subtree');
53
+ return { ...identityRow, body: spans.map(s => body.slice(s.start, s.end)).join(''), section: publicHeading(h), retrieval: {
54
+ ...metadata, mode: 'section', subtree_complete: true, document_complete: spans.reduce((n, s) => n + s.end - s.start, 0) === body.length,
55
+ context_policy: 'Preamble and ancestor introductions included. Sibling sections and linked prerequisites are not automatically included; read the full document when needed.',
56
+ context_sections: headings.filter(n => !spans.some(s => n.start >= s.start && n.start < s.end)).map(n => ({ id: n.id, title: n.title })),
57
+ included_spans: spans.map(s => ({ start_offset: s.start, end_offset: s.end, kind: s.kind })),
58
+ } };
59
+ }
@@ -1,4 +1,5 @@
1
1
  import http from 'node:http';
2
+ import { SECTION_PROTOCOL } from './sections.js';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import os from 'node:os';
@@ -27,7 +28,9 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
27
28
  if (url.pathname === '/api/docs/search') return send(200, { ...index.search({ query: params.q, limit: params.limit ?? 20, offset: params.offset ?? 0, bundle: params.bundle }), release });
28
29
  const revision = index.revision();
29
30
  if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
30
- return send(200, { release, revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
31
+ if (params.outline !== undefined && params.outline !== 'true') return send(400, { error: 'outline must be true.' });
32
+ const document = index.document({ path: params.path, id: url.pathname.split('/').at(-1), outline: params.outline === 'true', section: params.section });
33
+ return send(200, { release, revision, section_protocol: SECTION_PROTOCOL, document });
31
34
  } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
32
35
  finally { index?.close(); }
33
36
  });
@@ -1,3 +1,4 @@
1
+ import { searchFlows, formatFlowSearch } from '../flow-search.js';
1
2
  import fs from 'node:fs';
2
3
  import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
3
4
  import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
@@ -36,6 +37,7 @@ function describeOwned(counts) {
36
37
  const FLOW_COMMANDS = [
37
38
  { name: 'schemas', description: 'Read live trigger catalog and input schemas' },
38
39
  { name: 'catalog-variables [identifier]', description: 'List a catalog item\'s variables for a service_catalog trigger' },
40
+ { name: 'search <term>', description: 'Download, decode and search a private local flow cache (--refresh to rebuild)' },
39
41
  { name: 'list', description: 'List flows' },
40
42
  { name: 'executions', description: 'Show flow executions from sys_flow_context' },
41
43
  { name: 'show [identifier]', description: 'Show a flow: structure, inputs, steps and conditions' },
@@ -86,6 +88,26 @@ export function flowsCmd(wrap) {
86
88
  describe: 'Manage Flow Designer flows',
87
89
  builder: (yargs) => {
88
90
  return yargs
91
+ .command({
92
+ command: 'search <term>',
93
+ describe: 'Download/decode visible flows into a private cache and search literal text (first use can be slow)',
94
+ builder: y => y
95
+ .positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
96
+ .option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' }),
97
+ handler: wrap(async (argv, app) => {
98
+ app.requireInstance();
99
+ const session = app.session || {};
100
+ const result = await searchFlows({
101
+ sdk: app.sdk, term: argv.term, refresh: argv.refresh,
102
+ context: { profile: session.profileName, username: session.username, domain: session.domain, authMethod: session.profile?.auth_method },
103
+ progress: message => {
104
+ if (!argv.json && !argv.get && (!argv.format || ['auto', 'pretty', 'styled'].includes(argv.format))) process.stderr.write(`${message}\n`);
105
+ },
106
+ });
107
+ Object.defineProperty(result, '_formatted', { value: formatFlowSearch(result), enumerable: false });
108
+ app.ok(result, { summary: `${result.match_count} matching line(s) in ${result.matching_flows} flow(s); ${result.coverage.decoded}/${result.coverage.inventoried} definitions decoded${result.coverage.complete_visible_inventory ? '' : '; PARTIAL/UNKNOWN coverage'}` });
109
+ }),
110
+ })
89
111
  .command({
90
112
  command: 'schemas',
91
113
  describe: 'Read live trigger catalog and input schemas',
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { diffUpdateSets } from '../update-set-diff.js';
2
3
  import path from 'node:path';
3
4
  import { inspectUpdateSetXML, updateSetFilename, MAX_UPDATE_SET_BYTES } from '../update-set-xml.js';
4
5
  import { editor, confirm } from '../prompts.js';
@@ -15,6 +16,7 @@ import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../upd
15
16
  declareCapabilities('updatesets', {
16
17
  mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
17
18
  mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
19
+ skipContextHeaderSubcommands: ['diff'],
18
20
  localPreviewSubcommands: ['import'],
19
21
  });
20
22
 
@@ -548,6 +550,15 @@ export function updateSetsCmd(wrap) {
548
550
  describe: 'Manage update sets. Global + Default mutations require approval (--force only after user approval); create/set remain available to select a dedicated capture set. Scope mismatches warn; completed capture sets block writes.',
549
551
  builder: (yargs) => {
550
552
  return yargs
553
+ .command({
554
+ command: 'diff',
555
+ describe: 'Read-only captured-set comparison: jsn updatesets diff --source dev --target test [--from 2w|2026-10-01]. Not deployment readiness; bounded count-verified reads (20 x 200 rows/query).',
556
+ builder: y => y
557
+ .option('source', { type: 'string', demandOption: true, describe: 'Source profile' })
558
+ .option('target', { type: 'string', demandOption: true, describe: 'Target profile (all dates)' })
559
+ .option('from', { type: 'string', default: '2w', describe: 'Source sys_updated_on UTC window: 2w, 14d or YYYY-MM-DD; not completion history' }),
560
+ handler: wrap(diffUpdateSets),
561
+ })
551
562
  .command({
552
563
  command: 'list',
553
564
  aliases: ['ls'],
@@ -0,0 +1,179 @@
1
+ import { decodeGzipJson } from './sdk.js';
2
+ import fs from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+
8
+ const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
9
+ const field = value => String(value && typeof value === 'object' ? value.value ?? '' : value ?? '');
10
+ const TABLE = 'sys_hub_flow';
11
+
12
+ async function secureDirectory(directory) {
13
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
14
+ const stat = await fs.lstat(directory);
15
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid())) throw new Error('Unsafe flow cache directory');
16
+ await fs.chmod(directory, 0o700);
17
+ }
18
+
19
+ async function readCache(file) {
20
+ try {
21
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
22
+ try {
23
+ const stat = await handle.stat();
24
+ if (!stat.isFile() || (stat.mode & 0o077) || (process.getuid && stat.uid !== process.getuid())) throw new Error('Unsafe flow cache file permissions');
25
+ const cache = JSON.parse(await handle.readFile('utf8'));
26
+ return cache.schema === 1 && Array.isArray(cache.flows) ? cache : null;
27
+ } finally { await handle.close(); }
28
+ } catch (error) {
29
+ if (error.code === 'ENOENT' || error instanceof SyntaxError) return null;
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ async function writeCache(file, data) {
35
+ const temporary = `${file}.${randomUUID()}`;
36
+ try {
37
+ await fs.writeFile(temporary, JSON.stringify(data), { flag: 'wx', mode: 0o600 });
38
+ await fs.rename(temporary, file);
39
+ } finally { await fs.rm(temporary, { force: true }); }
40
+ }
41
+
42
+ export function formatFlowSearch(report) {
43
+ const { coverage: c, cache } = report;
44
+ return [
45
+ `${report.match_count} matching line(s) in ${report.matching_flows} flow(s)`,
46
+ ...(cache.disabled_reason ? [cache.disabled_reason] : []),
47
+ `Cache ${cache.state}; prior age ${cache.previous_age_seconds === null ? 'n/a' : `${Math.floor(cache.previous_age_seconds)}s`}; ${cache.reused_definitions} decoded definitions reused. Live source access revalidated.`,
48
+ `Visible inventory: provider ${c.provider_count ?? 'unknown'}, inventoried ${c.inventoried}, downloaded ${c.downloaded}, decoded ${c.decoded}. ${c.complete_visible_inventory ? 'Visible inventory accounted for.' : 'PARTIAL/UNKNOWN coverage.'}`,
49
+ c.scope,
50
+ ...report.matches.map(match => `${match.name} [${match.sys_id}] ${match.source} ${match.path}:${match.line}\n ${match.text}`),
51
+ ...report.failures.map(failure => `FAILED ${failure.stage}: ${failure.name || ''} ${failure.sys_id || ''} ${failure.message}`),
52
+ ].join('\n');
53
+ }
54
+
55
+ export async function searchFlows({ sdk, term, context = {}, refresh = false, cacheRoot, platform = process.platform, pageSize = 100, maxPages = 10000, progress = () => {} }) {
56
+ if (!String(term || '').trim()) throw new Error('A nonempty literal search term is required');
57
+ if (!Number.isInteger(pageSize) || pageSize < 1 || !Number.isInteger(maxPages) || maxPages < 1) throw new Error('Invalid flow pagination bounds');
58
+ const instance = new URL(sdk.baseURL).origin;
59
+ const directory = path.join(cacheRoot || process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'jsn', 'flow-search');
60
+ // Node's Windows mode bits cannot establish a private DACL. Do not touch
61
+ // cache paths (including existing files or reparse points) on that platform.
62
+ const diskCache = platform !== 'win32';
63
+ if (diskCache) await secureDirectory(directory);
64
+ const key = digest({ instance, profile: context.profile || '', username: context.username || '', authMethod: context.authMethod || '', domain: context.domain || '' });
65
+ const file = diskCache ? path.join(directory, `${key}.json`) : null;
66
+ const previous = !diskCache || refresh ? null : await readCache(file);
67
+ const previousById = new Map((previous?.flows || []).map(flow => [flow.sys_id, flow]));
68
+ if (!diskCache) progress('Disk cache disabled on Windows: private ACLs are not verified. Searching freshly downloaded definitions in memory only.');
69
+ if (diskCache) progress(previous ? 'Revalidating flow visibility and source permissions before reusing decoded cache.' : 'Downloading visible flow definitions and decoding a private local cache. First use can be slow; no instance records are changed.');
70
+ const failures = [];
71
+ const get = route => sdk.request(`${instance}${route}`, { method: 'GET' });
72
+ let expected;
73
+ try {
74
+ const response = await get(`/api/now/stats/${TABLE}?sysparm_count=true`);
75
+ const count = response?.result?.stats?.count;
76
+ if (!/^\d+$/.test(String(count))) throw new Error('Missing provider count');
77
+ expected = Number(count);
78
+ if (!Number.isSafeInteger(expected)) throw new Error('Invalid provider count');
79
+ } catch { expected = null; failures.push({ stage: 'inventory_count', message: 'Provider count unavailable; inventory completeness is unknown.' }); }
80
+ const rows = new Map();
81
+ let exhausted = false;
82
+ let offset = 0;
83
+ for (let page = 0; page < maxPages; page++) {
84
+ try {
85
+ const params = new URLSearchParams({ sysparm_query: 'ORDERBYsys_id', sysparm_fields: 'sys_id,name,type,sys_updated_on', sysparm_display_value: 'false', sysparm_limit: String(pageSize), sysparm_offset: String(offset) });
86
+ const response = await get(`/api/now/table/${TABLE}?${params}`);
87
+ if (!Array.isArray(response?.result)) throw new Error('Missing result array; source is unreadable');
88
+ const batch = response.result;
89
+ if (!batch.length) { exhausted = true; break; }
90
+ for (const row of batch) {
91
+ const id = field(row.sys_id);
92
+ if (!/^[0-9a-f]{32}$/i.test(id) || rows.has(id)) throw new Error('Missing/duplicate flow identity; unstable or ACL-filtered pagination');
93
+ rows.set(id, { sys_id: id, name: field(row.name), type: field(row.type), updated: field(row.sys_updated_on) });
94
+ }
95
+ offset += batch.length;
96
+ } catch (error) {
97
+ failures.push({ stage: 'inventory', message: error.message });
98
+ break;
99
+ }
100
+ }
101
+ if (expected !== null && exhausted && rows.size !== expected) failures.push({ stage: 'inventory', message: `Provider count ${expected} differs from ${rows.size} unique visible flow records; ACL filtering or concurrent changes may hide flows.` });
102
+ if (expected !== null) {
103
+ try {
104
+ const after = await get(`/api/now/stats/${TABLE}?sysparm_count=true`);
105
+ if (String(after?.result?.stats?.count) !== String(expected)) throw new Error('Provider count changed during inventory');
106
+ } catch { failures.push({ stage: 'inventory_count', message: 'Provider count changed or became unreadable during inventory; completeness is unknown.' }); }
107
+ }
108
+ if (!exhausted && !failures.some(f => f.stage === 'inventory')) failures.push({ stage: 'inventory', message: 'Pagination safety limit reached; inventory is partial.' });
109
+ const flows = [];
110
+ let downloaded = 0;
111
+ let reused = 0;
112
+ for (const row of rows.values()) {
113
+ let data;
114
+ try {
115
+ // A fresh source read is deliberately mandatory even on a cache hit. A
116
+ // profile/role fingerprint cannot detect field ACLs, impersonation or a
117
+ // revoked permission. Never release old source on a failed live read.
118
+ const response = await get(`/api/now/processflow/flow/${row.sys_id}`);
119
+ const code = response?.result?.errorCode;
120
+ if (response?.result?.errorMessage || (code != null && code !== '' && String(code) !== '0')) throw new Error('Provider refused the flow definition');
121
+ data = response?.result?.data;
122
+ if (data?.security?.can_read === false || data?.security?.can_read === 'false') throw new Error('403 Flow definition read denied');
123
+ if (!data || typeof data !== 'object') throw new Error('No readable ProcessFlow definition');
124
+ downloaded++;
125
+ } catch (error) {
126
+ failures.push({ ...row, stage: 'download', message: error.status === 403 || /403|forbidden/i.test(error.message) ? 'Access denied reading definition' : 'Definition download failed or unavailable', status: error.status || null });
127
+ continue;
128
+ }
129
+ try {
130
+ const sourceDigest = digest(data);
131
+ const cached = previousById.get(row.sys_id);
132
+ const entries = cached?.source_digest === sourceDigest && Array.isArray(cached.entries) ? cached.entries : decodeFlowSearchDefinition(data);
133
+ const unchanged = entries === cached?.entries;
134
+ if (unchanged) reused++;
135
+ flows.push({ ...row, source: `/api/now/processflow/flow/${row.sys_id}`, source_digest: sourceDigest, decoded_at: unchanged ? cached.decoded_at : new Date().toISOString(), entries });
136
+ } catch (error) { failures.push({ ...row, stage: 'decode', message: error.message }); }
137
+ }
138
+ const captured = new Date().toISOString();
139
+ if (diskCache) await writeCache(file, { schema: 1, captured_at: captured, flows });
140
+ const matches = [];
141
+ const needle = String(term).toLowerCase();
142
+ for (const flow of flows) for (const entry of flow.entries) {
143
+ entry.text.split(/\r?\n/).forEach((text, index) => {
144
+ if (text.toLowerCase().includes(needle)) matches.push({ sys_id: flow.sys_id, name: flow.name, source: flow.source, path: entry.path, line: index + 1, text });
145
+ });
146
+ }
147
+ const complete = exhausted && expected !== null && expected === rows.size && !failures.length;
148
+ return {
149
+ term, match_count: matches.length, matching_flows: new Set(matches.map(match => match.sys_id)).size, matches, failures,
150
+ cache: { state: !diskCache ? 'disabled' : refresh ? 'refreshed' : previous ? 'reused' : 'built', disabled_reason: diskCache ? null : 'Windows private cache ACLs are not verified; live in-memory search only', file, captured_at: captured, previous_age_seconds: previous ? Math.max(0, (Date.now() - Date.parse(previous.captured_at)) / 1000) : null, reused_definitions: reused, live_source_revalidation: true },
151
+ coverage: { provider_count: expected, inventoried: rows.size, downloaded, decoded: flows.length, complete_visible_inventory: complete, scope: 'ACL-visible sys_hub_flow ProcessFlow definitions only. Referenced custom action implementation scripts, inaccessible flows, and fields omitted by provider ACLs are not included. No instance-wide completeness claim.' },
152
+ };
153
+ }
154
+
155
+
156
+ // ProcessFlow returns the same definition graph used by flows show. Its values
157
+ // fields can contain the platform's base64-gzip JSON, not plain script text.
158
+ export function decodeFlowSearchDefinition(data) {
159
+ if (!data || typeof data !== 'object' || !['actionInstances', 'triggerInstances', 'flowLogicInstances', 'subFlowInstances'].some(key => Array.isArray(data[key]))) {
160
+ throw new Error('Unsupported definition: no ProcessFlow structure arrays');
161
+ }
162
+ const entries = [];
163
+ function walk(value, path, depth = 0) {
164
+ if (depth > 100) throw new Error(`Definition nesting exceeds decoder limit at ${path}`);
165
+ if (typeof value === 'string') {
166
+ if (value.trim().startsWith('H4sI')) {
167
+ const decoded = decodeGzipJson(value);
168
+ if (decoded === null) throw new Error(`Cannot decode gzip JSON at ${path}`);
169
+ walk(decoded, path, depth + 1);
170
+ } else if (value) entries.push({ path, text: value });
171
+ } else if (Array.isArray(value)) {
172
+ value.forEach((child, index) => walk(child, `${path}[${index}]`, depth + 1));
173
+ } else if (value && typeof value === 'object') {
174
+ for (const [key, child] of Object.entries(value)) walk(child, `${path}.${key}`, depth + 1);
175
+ }
176
+ }
177
+ walk(data, '$');
178
+ return entries;
179
+ }
package/src/help.js CHANGED
@@ -14,11 +14,11 @@ const COMMON_COMMANDS = [
14
14
  'incidents', 'requests', 'tasks', 'changes', 'approvals', 'knowledge', 'records', 'setup', 'discover',
15
15
  ];
16
16
 
17
- const CONCISE_FLAGS = ['instance', 'profile', 'json'];
17
+ const CONCISE_FLAGS = ['instance', 'profile', 'json', 'csv', 'tsv'];
18
18
 
19
19
  const CONCISE_EXAMPLES = [
20
20
  'jsn incidents list --query "active=true" --limit 5',
21
- 'jsn records list --table incident --limit 5 --json',
21
+ 'jsn records list --table incident --columns sys_id,number,state --limit 5 --csv',
22
22
  'jsn discover catalog',
23
23
  ];
24
24
 
@@ -242,6 +242,8 @@ function renderFlags(options, { full = false, width = helpWidth() } = {}) {
242
242
  * examples, and pointers to the exhaustive reference and local discovery.
243
243
  */
244
244
  function renderConciseHelp(config, registry, width) {
245
+ // Keep the short page consistent between ordinary 80-column terminals and pipes.
246
+ width = Math.min(width, 80);
245
247
  const commands = Array.isArray(registry?.commands) ? registry.commands : [];
246
248
  const byName = new Map(commands.map((command) => [command.name, command]));
247
249
  const common = COMMON_COMMANDS
@@ -259,9 +261,16 @@ function renderConciseHelp(config, registry, width) {
259
261
  renderGroup('COMMON COMMANDS', common, width),
260
262
  '',
261
263
  'EXAMPLES',
262
- ...CONCISE_EXAMPLES.map((example) => ` ${example}`),
264
+ ...CONCISE_EXAMPLES.map((example) => wrapText(example, { width: width - 2, firstIndent: 2 }).join(' \\\n')),
263
265
  renderFlags(Array.isArray(registry?.options) ? registry.options : [], { width }),
264
266
  '',
267
+ 'OUTPUT',
268
+ ...[
269
+ 'For smaller list responses, select fields with --columns and bound rows with --limit.',
270
+ 'CSV and TSV avoid repeated field names; JSON preserves metadata and nested structure.',
271
+ 'Use JSON for pagination metadata or both reference IDs and display labels.',
272
+ ].flatMap(text => wrapText(text, { width, firstIndent: 2 })),
273
+ '',
265
274
  'MORE',
266
275
  renderRows(CONCISE_MORE, { width, indent: 2 }),
267
276
  '',
package/src/output.js CHANGED
@@ -9,6 +9,7 @@ export const FormatMarkdown = 'markdown';
9
9
  export const FormatStyled = 'styled';
10
10
  export const FormatQuiet = 'quiet';
11
11
  export const FormatCSV = 'csv';
12
+ export const FormatTSV = 'tsv';
12
13
 
13
14
  /**
14
15
  * Resolve a dotpath (`.data[0].number`, `data.records.0.sys_id`) against an
@@ -93,6 +94,7 @@ export class OutputWriter {
93
94
  constructor(opts = {}) {
94
95
  this.format = opts.format || FormatAuto;
95
96
  this.writer = opts.writer || process.stdout;
97
+ this.errorWriter = opts.errorWriter || process.stderr;
96
98
  this.jqFilter = opts.jqFilter || '';
97
99
  this.verbose = opts.verbose === true;
98
100
  this.raw = opts.raw === true;
@@ -153,6 +155,8 @@ export class OutputWriter {
153
155
  return this.writeQuiet(data);
154
156
  case FormatCSV:
155
157
  return this.writeCSV(data, opts);
158
+ case FormatTSV:
159
+ return this.writeDelimited(data, '\t', tsvEscape, 'TSV');
156
160
  case FormatStyled:
157
161
  return this.writeStyled(data, opts);
158
162
  default:
@@ -289,38 +293,59 @@ export class OutputWriter {
289
293
  }
290
294
  }
291
295
 
292
- writeCSV(data, opts) {
293
- if (opts.summary && isTTY(this.writer)) {
294
- this.writer.write(opts.summary + '\n\n');
295
- }
296
+ writeCSV(data, _opts) {
297
+ return this.writeDelimited(data, ',', csvEscape, 'CSV');
298
+ }
299
+
300
+ writeDelimited(data, delimiter, escape, label) {
301
+ // Delimited stdout contains only the table, even on a terminal. Pagination is
302
+ // diagnostic output, not an extra row that spreadsheet readers must skip.
296
303
  if (Array.isArray(data)) {
297
- this.writeCSVTable(data);
304
+ this.writeDelimitedTable(data, delimiter, escape);
298
305
  } else if (data && typeof data === 'object' && Array.isArray(data.records)) {
299
- this.writeCSVTable(data.records);
306
+ this.writeDelimitedTable(data.records, delimiter, escape);
307
+ const page = data.pagination;
308
+ if (page?.hasMore === true) {
309
+ const count = data.records.length;
310
+ const total = Number.isSafeInteger(page.total) && page.total >= 0
311
+ ? ` of ${page.total}` : '';
312
+ const unknown = total ? '' : '; total unknown';
313
+ // List commands advance the requested window, including short pages.
314
+ // Do not guess an offset when the envelope lacks that context.
315
+ const nextOffset = Number.isSafeInteger(page.offset) && page.offset >= 0
316
+ && Number.isSafeInteger(page.limit) && page.limit > 0
317
+ && Number.isSafeInteger(page.offset + page.limit)
318
+ ? `; next offset ${page.offset + page.limit}` : '';
319
+ this.errorWriter.write(`${label} pagination: returned ${count}${total} records${unknown}; more available${nextOffset}.\n`);
320
+ }
300
321
  } else {
301
- this.writeCSVTable([data]);
322
+ this.writeDelimitedTable([data], delimiter, escape);
302
323
  }
303
324
  }
304
325
 
305
326
  writeCSVTable(rows) {
327
+ return this.writeDelimitedTable(rows, ',', csvEscape);
328
+ }
329
+
330
+ writeDelimitedTable(rows, delimiter, escape) {
306
331
  if (!Array.isArray(rows) || rows.length === 0) {
307
332
  this.writer.write('');
308
333
  return;
309
334
  }
310
335
  const columns = Object.keys(rows[0]);
311
- this.writer.write(columns.map(csvEscape).join(',') + '\n');
336
+ this.writer.write(columns.map(escape).join(delimiter) + '\n');
312
337
  for (const row of rows) {
313
338
  const cells = columns.map((col) => {
314
339
  const val = row[col];
315
340
  if (val == null) return '';
316
341
  if (typeof val === 'object') {
317
- if (val.display_value != null) return csvEscape(val.display_value);
318
- if (val.value != null) return csvEscape(val.value);
319
- return csvEscape(JSON.stringify(val));
342
+ if (val.display_value != null) return escape(val.display_value);
343
+ if (val.value != null) return escape(val.value);
344
+ return escape(JSON.stringify(val));
320
345
  }
321
- return csvEscape(val);
346
+ return escape(val);
322
347
  });
323
- this.writer.write(cells.join(',') + '\n');
348
+ this.writer.write(cells.join(delimiter) + '\n');
324
349
  }
325
350
  }
326
351
 
@@ -686,6 +711,11 @@ export function getDisplayValue(val) {
686
711
  return String(val);
687
712
  }
688
713
 
714
+ // Backslash escapes keep each TSV record on one physical line, including headers.
715
+ export function tsvEscape(val) {
716
+ return String(val ?? '').replace(/[\\\t\n\r]/g, ch => ({ '\\': '\\\\', '\t': '\\t', '\n': '\\n', '\r': '\\r' })[ch]);
717
+ }
718
+
689
719
  /** Escape a single CSV field: quote when it contains a delimiter, quote, or newline. */
690
720
  export function csvEscape(val) {
691
721
  if (val == null) return '';