@jacebenson/jsn 5.2.0 → 5.3.0-dev.135.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 +72 -9
- package/package.json +1 -1
- package/skills/servicenow/SKILL.md +11 -1
- package/src/amb.js +370 -0
- package/src/app.js +8 -4
- package/src/cli.js +11 -1
- package/src/command-audience.js +1 -1
- package/src/commands/cases.js +218 -0
- package/src/commands/catalog/enrich.js +151 -56
- package/src/commands/catalog-order.js +99 -23
- package/src/commands/catalog.js +6 -5
- package/src/commands/records.js +110 -1
- package/src/commands/store.js +312 -0
- package/src/commands/updatesets.js +253 -11
- package/src/errors.js +10 -3
- package/src/output.js +28 -1
- package/src/record-command-profiles.js +1 -1
- package/src/record-watch.js +206 -0
- package/src/sdk.js +66 -1
- package/src/store.js +588 -0
- package/src/update-set-apply.js +287 -0
- package/src/welcome.js +324 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// Preview and commit a *retrieved* update set, and read its preview problems.
|
|
2
|
+
//
|
|
3
|
+
// These are the platform's own steps: retrieving (import) only loads the XML,
|
|
4
|
+
// previewing compares it with the target, and committing applies it. ServiceNow
|
|
5
|
+
// exposes all three through the CICD Update Set API (sn_cicd):
|
|
6
|
+
//
|
|
7
|
+
// POST /api/sn_cicd/update_set/preview/{remote_update_set_id}
|
|
8
|
+
// POST /api/sn_cicd/update_set/commit/{remote_update_set_id}
|
|
9
|
+
// GET /api/sn_cicd/progress/{progress_id}
|
|
10
|
+
//
|
|
11
|
+
// The alternate path — calling hidden Ajax processors or scripting
|
|
12
|
+
// GlideUpdateManager2 from a background script — is deliberately not used: it
|
|
13
|
+
// bypasses the platform's own validation and is not a public contract.
|
|
14
|
+
//
|
|
15
|
+
// Nothing here resolves, ignores, or skips a preview problem. A human decides
|
|
16
|
+
// those in ServiceNow; jsn reports them and refuses to commit while unresolved
|
|
17
|
+
// problems remain.
|
|
18
|
+
import { AppError, CodeAPI, CodeUsage, errUsage } from './errors.js';
|
|
19
|
+
|
|
20
|
+
// sn_cicd progress statuses (same vocabulary as commands/atf.js).
|
|
21
|
+
const PROGRESS_PENDING = '0';
|
|
22
|
+
const PROGRESS_RUNNING = '1';
|
|
23
|
+
const PROGRESS_SUCCESSFUL = '2';
|
|
24
|
+
const PROGRESS_ERROR = '3';
|
|
25
|
+
const PROGRESS_CANCELED = '4';
|
|
26
|
+
const TERMINAL_STATUSES = new Set([PROGRESS_SUCCESSFUL, PROGRESS_ERROR, PROGRESS_CANCELED]);
|
|
27
|
+
|
|
28
|
+
// sys_update_preview_problem.status values that mean a human already decided.
|
|
29
|
+
const RESOLVED_PROBLEM_STATUSES = new Set(['ignored', 'skipped', 'skip_collision', 'accepted', 'resolved']);
|
|
30
|
+
|
|
31
|
+
export const PREVIEW_PROBLEM_TABLE = 'sys_update_preview_problem';
|
|
32
|
+
export const DEFAULT_OPERATION_TIMEOUT_MS = 10 * 60 * 1000;
|
|
33
|
+
const DEFAULT_POLL_MS = 2000;
|
|
34
|
+
|
|
35
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
36
|
+
|
|
37
|
+
function text(value) {
|
|
38
|
+
if (value == null) return '';
|
|
39
|
+
if (typeof value === 'string') return value;
|
|
40
|
+
if (typeof value === 'object') {
|
|
41
|
+
if (value.display_value != null) return String(value.display_value);
|
|
42
|
+
if (value.value != null) return String(value.value);
|
|
43
|
+
}
|
|
44
|
+
return String(value);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function statusWord(status) {
|
|
48
|
+
switch (status) {
|
|
49
|
+
case PROGRESS_PENDING: return 'pending';
|
|
50
|
+
case PROGRESS_RUNNING: return 'running';
|
|
51
|
+
case PROGRESS_SUCCESSFUL: return 'successful';
|
|
52
|
+
case PROGRESS_ERROR: return 'failed';
|
|
53
|
+
case PROGRESS_CANCELED: return 'canceled';
|
|
54
|
+
default: return 'unknown';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Normalize a sn_cicd operation/progress response into one shape. */
|
|
59
|
+
export function normalizeProgress(response) {
|
|
60
|
+
const inner = response?.result && typeof response.result === 'object' ? response.result : (response ?? {});
|
|
61
|
+
const status = inner.status == null ? '' : String(inner.status);
|
|
62
|
+
const percent = Number(inner.percent_complete ?? 0);
|
|
63
|
+
// Live progress bodies carry status_message:"" and put the reason in error.
|
|
64
|
+
// An empty string must not mask the real failure text.
|
|
65
|
+
const message = [inner.status_message, inner.status_detail, inner.error]
|
|
66
|
+
.map((value) => text(value).trim())
|
|
67
|
+
.find((value) => value) || '';
|
|
68
|
+
return {
|
|
69
|
+
status,
|
|
70
|
+
label: String(inner.status_label ?? '') || statusWord(status),
|
|
71
|
+
percent_complete: Number.isFinite(percent) ? percent : 0,
|
|
72
|
+
message,
|
|
73
|
+
progress_id: text(inner?.links?.progress?.id ?? inner.progress_id ?? ''),
|
|
74
|
+
result_id: text(inner?.links?.results?.id ?? inner.result_id ?? ''),
|
|
75
|
+
raw: inner,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function isTerminalProgress(progress) {
|
|
80
|
+
if (TERMINAL_STATUSES.has(progress.status)) return true;
|
|
81
|
+
return /^(successful|success|complete|completed|failed|failure|error|canceled|cancelled)$/i.test(progress.label);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function isSuccessfulProgress(progress) {
|
|
85
|
+
if (progress.status === PROGRESS_SUCCESSFUL) return true;
|
|
86
|
+
return /^(successful|success|complete|completed)$/i.test(progress.label);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Follow GET /api/sn_cicd/progress/{id} until the operation reaches a terminal
|
|
91
|
+
* status or the deadline passes.
|
|
92
|
+
*
|
|
93
|
+
* A response without a progress link cannot be followed; it is returned as-is
|
|
94
|
+
* so the caller can verify the target's own state instead of guessing.
|
|
95
|
+
*
|
|
96
|
+
* @param {object} sdk - SDK client (request + baseURL)
|
|
97
|
+
* @param {object} initial - dispatch response from the operation endpoint
|
|
98
|
+
* @param {object} [options]
|
|
99
|
+
* @param {number} [options.timeoutMs]
|
|
100
|
+
* @param {number} [options.pollMs]
|
|
101
|
+
* @param {Function} [options.wait] - sleep seam for tests
|
|
102
|
+
* @param {Function} [options.now] - clock seam for tests
|
|
103
|
+
* @param {Function} [options.onProgress] - called with each normalized update
|
|
104
|
+
* @returns {Promise<object>} the last normalized progress
|
|
105
|
+
*/
|
|
106
|
+
export async function waitForCicdProgress(sdk, initial, options = {}) {
|
|
107
|
+
const {
|
|
108
|
+
timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS,
|
|
109
|
+
pollMs = DEFAULT_POLL_MS,
|
|
110
|
+
wait = sleep,
|
|
111
|
+
now = Date.now,
|
|
112
|
+
onProgress,
|
|
113
|
+
} = options;
|
|
114
|
+
|
|
115
|
+
let current = normalizeProgress(initial);
|
|
116
|
+
const deadline = now() + timeoutMs;
|
|
117
|
+
let tracked = Boolean(current.progress_id);
|
|
118
|
+
|
|
119
|
+
while (!isTerminalProgress(current)) {
|
|
120
|
+
if (now() >= deadline) {
|
|
121
|
+
throw new AppError(
|
|
122
|
+
CodeAPI,
|
|
123
|
+
`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for the update set operation (last status: ${current.label}).\n` +
|
|
124
|
+
'The operation may still be running on the instance. Inspect Retrieved Update Sets before retrying; jsn does not repeat it.',
|
|
125
|
+
'',
|
|
126
|
+
0,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
if (!tracked) return { ...current, tracked };
|
|
130
|
+
await wait(pollMs);
|
|
131
|
+
const response = await sdk.request(`${sdk.baseURL}/api/sn_cicd/progress/${encodeURIComponent(current.progress_id)}`, { method: 'GET' });
|
|
132
|
+
const next = normalizeProgress(response);
|
|
133
|
+
current = {
|
|
134
|
+
...next,
|
|
135
|
+
progress_id: next.progress_id || current.progress_id,
|
|
136
|
+
result_id: next.result_id || current.result_id,
|
|
137
|
+
};
|
|
138
|
+
tracked = Boolean(current.progress_id);
|
|
139
|
+
if (typeof onProgress === 'function') onProgress(current);
|
|
140
|
+
}
|
|
141
|
+
return { ...current, tracked };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function cicdUnavailable(error) {
|
|
145
|
+
if (error?.status === 404) return true;
|
|
146
|
+
if (error?.status === 400 && /Requested URI does not represent any resource/i.test(error.message || '')) return true;
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* A sn_cicd error body can be an operation result rather than a missing route.
|
|
152
|
+
* Live 404 for an unknown update set:
|
|
153
|
+
* {"result":{"status":"3","status_label":"Failed","error":"Update set with id ... cannot be found"}}
|
|
154
|
+
* That is a rejected operation, not an absent plugin.
|
|
155
|
+
*/
|
|
156
|
+
function cicdOperationError(error) {
|
|
157
|
+
const body = error?.message;
|
|
158
|
+
if (typeof body !== 'string') return '';
|
|
159
|
+
// errAPI prefixes the HTTP status, so the JSON envelope may not start the
|
|
160
|
+
// message. Parse from the first brace.
|
|
161
|
+
const start = body.indexOf('{');
|
|
162
|
+
if (start < 0) return '';
|
|
163
|
+
try {
|
|
164
|
+
const result = JSON.parse(body.slice(start))?.result;
|
|
165
|
+
if (result && typeof result === 'object') {
|
|
166
|
+
return text(result.error || result.status_message || result.status_detail).trim();
|
|
167
|
+
}
|
|
168
|
+
} catch { /* not a JSON error envelope */ }
|
|
169
|
+
return '';
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Start a sn_cicd update-set operation and wait for its tracker.
|
|
174
|
+
* @param {object} sdk
|
|
175
|
+
* @param {'preview'|'commit'} operation
|
|
176
|
+
* @param {string} sysID - sys_remote_update_set sys_id
|
|
177
|
+
*/
|
|
178
|
+
export async function runUpdateSetOperation(sdk, operation, sysID, options = {}) {
|
|
179
|
+
const endpoint = `${sdk.baseURL}/api/sn_cicd/update_set/${operation}/${encodeURIComponent(sysID)}`;
|
|
180
|
+
let response;
|
|
181
|
+
try {
|
|
182
|
+
response = await sdk.request(endpoint, { method: 'POST', body: '{}' });
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error?.status === 403) {
|
|
185
|
+
throw new AppError(
|
|
186
|
+
CodeUsage,
|
|
187
|
+
`This account cannot use the CICD Update Set API; no ${operation} was started.`,
|
|
188
|
+
'The account needs the sn_cicd.sys_ci_automation role. Preview and commit the set in ServiceNow instead.',
|
|
189
|
+
403,
|
|
190
|
+
error,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
const platformError = cicdOperationError(error);
|
|
194
|
+
if (platformError) {
|
|
195
|
+
throw new AppError(
|
|
196
|
+
CodeAPI,
|
|
197
|
+
`The CICD API rejected the ${operation}: ${platformError}`,
|
|
198
|
+
`Nothing was ${operation === 'preview' ? 'previewed' : 'committed'}. Inspect the retrieved update set and try again.`,
|
|
199
|
+
error.status || 0,
|
|
200
|
+
error,
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (cicdUnavailable(error)) {
|
|
204
|
+
throw new AppError(
|
|
205
|
+
CodeUsage,
|
|
206
|
+
`The CICD Update Set API is not available on this instance; no ${operation} was started.`,
|
|
207
|
+
'The sn_cicd plugin (com.glide.continuousdelivery) provides preview/commit. ' +
|
|
208
|
+
'Preview and commit the set in ServiceNow instead: System Update Sets > Retrieved Update Sets.',
|
|
209
|
+
error.status || 0,
|
|
210
|
+
error,
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const final = await waitForCicdProgress(sdk, response, options);
|
|
217
|
+
if (!isSuccessfulProgress(final)) {
|
|
218
|
+
const detail = final.message ? `: ${final.message}` : '';
|
|
219
|
+
throw new AppError(
|
|
220
|
+
CodeAPI,
|
|
221
|
+
`Update set ${operation} did not succeed (${final.label})${detail}`,
|
|
222
|
+
`Inspect Retrieved Update Sets on ${sdk.baseURL} before retrying; jsn does not retry the operation.`,
|
|
223
|
+
0,
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
return final;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function previewUpdateSet(sdk, sysID, options = {}) {
|
|
230
|
+
return runUpdateSetOperation(sdk, 'preview', sysID, options);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export async function commitUpdateSet(sdk, sysID, options = {}) {
|
|
234
|
+
return runUpdateSetOperation(sdk, 'commit', sysID, options);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Normalize a sys_update_preview_problem row without assuming optional fields. */
|
|
238
|
+
export function normalizePreviewProblem(record) {
|
|
239
|
+
const status = text(record?.status).toLowerCase();
|
|
240
|
+
return {
|
|
241
|
+
sys_id: text(record?.sys_id),
|
|
242
|
+
type: text(record?.type).toLowerCase(),
|
|
243
|
+
description: text(record?.description) || text(record?.problem) || text(record?.message),
|
|
244
|
+
status,
|
|
245
|
+
resolved: RESOLVED_PROBLEM_STATUSES.has(status),
|
|
246
|
+
missing_item: text(record?.missing_item),
|
|
247
|
+
missing_item_table: text(record?.missing_item_table),
|
|
248
|
+
remote_update: text(record?.remote_update_set),
|
|
249
|
+
available_actions: text(record?.available_actions),
|
|
250
|
+
sys_created_on: text(record?.sys_created_on),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Read the preview problems recorded for a retrieved update set.
|
|
256
|
+
* @returns {Promise<{problems: object[], count: number, unresolved: object[], truncated: boolean}>}
|
|
257
|
+
*/
|
|
258
|
+
export async function listPreviewProblems(sdk, sysID, { limit = 500 } = {}) {
|
|
259
|
+
const params = new URLSearchParams();
|
|
260
|
+
params.set('sysparm_query', `remote_update_set=${sysID}^ORDERBYsys_created_on`);
|
|
261
|
+
params.set('sysparm_display_value', 'all');
|
|
262
|
+
params.set('sysparm_limit', String(limit));
|
|
263
|
+
const records = await sdk.listStrict(PREVIEW_PROBLEM_TABLE, params);
|
|
264
|
+
const problems = records.map(normalizePreviewProblem);
|
|
265
|
+
const unresolved = problems.filter((problem) => !problem.resolved);
|
|
266
|
+
return { problems, count: problems.length, unresolved, truncated: problems.length >= limit };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Refuse to continue while the platform still considers preview problems
|
|
271
|
+
* unresolved. jsn never accepts, skips, or ignores one on the operator's behalf.
|
|
272
|
+
*/
|
|
273
|
+
export function assertNoUnresolvedProblems({ problems, unresolved }) {
|
|
274
|
+
if (!unresolved.length) return;
|
|
275
|
+
const lines = unresolved.slice(0, 10).map((problem) => {
|
|
276
|
+
const target = problem.missing_item_table
|
|
277
|
+
? `${problem.missing_item_table}${problem.missing_item ? `/${problem.missing_item}` : ''}`
|
|
278
|
+
: (problem.remote_update || problem.sys_id);
|
|
279
|
+
return `- ${problem.description || '(no description)'} [${target}]`;
|
|
280
|
+
});
|
|
281
|
+
const more = unresolved.length > lines.length ? `\n… and ${unresolved.length - lines.length} more` : '';
|
|
282
|
+
throw errUsage(
|
|
283
|
+
`Refusing to commit: ${unresolved.length} of ${problems.length} preview problem(s) are unresolved.\n` +
|
|
284
|
+
`${lines.join('\n')}${more}\n` +
|
|
285
|
+
'Resolve each problem in ServiceNow (Accept or Skip remote update), then rerun preview. jsn does not resolve problems automatically.',
|
|
286
|
+
);
|
|
287
|
+
}
|
package/src/welcome.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// First-run welcome (issue #387).
|
|
2
|
+
//
|
|
3
|
+
// A brand-new install that runs bare `jsn` gets grouped help, which assumes
|
|
4
|
+
// the reader already knows what to do with it. This adds a short orientation
|
|
5
|
+
// above that help, exactly once, only when a human is reading it.
|
|
6
|
+
//
|
|
7
|
+
// Invariants (see docs/DECISIONS.md):
|
|
8
|
+
// - at most once: a marker file in the XDG config dir records that the note
|
|
9
|
+
// was shown, and it is created exclusively so two racing first runs cannot
|
|
10
|
+
// both print it;
|
|
11
|
+
// - human terminal only: no --json/--quiet/--csv/--markdown/--get, no piped
|
|
12
|
+
// output, no agent/CI environments;
|
|
13
|
+
// - never instead of help: the grouped help below it is unchanged;
|
|
14
|
+
// - never an instance or auth operation: the note only points at local and
|
|
15
|
+
// interactive commands, so it cannot block setup or require credentials;
|
|
16
|
+
// - nothing on this path reaches the network, prompts, or reads an instance;
|
|
17
|
+
// - not shown to an already-configured installation (profiles exist);
|
|
18
|
+
// - plain ASCII at every width, so NO_COLOR, TERM=dumb and narrow terminals
|
|
19
|
+
// all read the same thing.
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import os from 'node:os';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import { globalConfigDir } from './config.js';
|
|
25
|
+
import { canPrompt } from './helpers.js';
|
|
26
|
+
import { getVersion } from './commands/version.js';
|
|
27
|
+
|
|
28
|
+
/** Marker file in the XDG config dir. Presence means "already welcomed". */
|
|
29
|
+
export const WELCOME_MARKER = '.welcomed';
|
|
30
|
+
|
|
31
|
+
/** Line budget for the note at 80 columns (issue #387 hard limit). */
|
|
32
|
+
export const WELCOME_MAX_LINES = 12;
|
|
33
|
+
|
|
34
|
+
/** The note never uses more than this many columns, however wide the terminal. */
|
|
35
|
+
const MAX_WIDTH = 80;
|
|
36
|
+
|
|
37
|
+
/** Below this, descriptions and prose get one word per line; commands never split. */
|
|
38
|
+
const MIN_WIDTH = 24;
|
|
39
|
+
|
|
40
|
+
const HUMAN_FORMATS = new Set(['', 'auto', 'styled']);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* What a first run actually needs next. Every command here exists, is visible
|
|
44
|
+
* to a profile-less install, and works without an instance:
|
|
45
|
+
* - `jsn setup` opens the interactive add-connection wizard (and defaults);
|
|
46
|
+
* - `jsn auth login <instance>` adds one connection without the wizard;
|
|
47
|
+
* - `jsn --help` is the grouped command list this note sits above;
|
|
48
|
+
* - `jsn docs search` queries ServiceNow documentation, not an instance;
|
|
49
|
+
* - `jsn skill install` writes the bundled agent skill from local files.
|
|
50
|
+
*/
|
|
51
|
+
const STEPS = [
|
|
52
|
+
{ command: 'jsn setup', detail: 'first connection + defaults, interactive' },
|
|
53
|
+
{ command: 'jsn auth login <instance>', detail: 'one connection, scriptable, no wizard' },
|
|
54
|
+
{ command: 'jsn --help', detail: 'every command and flag' },
|
|
55
|
+
{ command: 'jsn docs search <query>', detail: 'search ServiceNow documentation' },
|
|
56
|
+
{ command: 'jsn skill install', detail: 'install the jsn skill for your AI agent' },
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolve the terminal width this note may use. Absent or nonsense columns
|
|
61
|
+
* fall back to 80, so a non-interactive writer still gets the documented
|
|
62
|
+
* layout.
|
|
63
|
+
*
|
|
64
|
+
* @param {number|undefined} columns
|
|
65
|
+
* @returns {number}
|
|
66
|
+
*/
|
|
67
|
+
function layoutWidth(columns) {
|
|
68
|
+
const numeric = Number(columns);
|
|
69
|
+
if (!Number.isFinite(numeric) || numeric <= 0) return MAX_WIDTH;
|
|
70
|
+
return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, Math.floor(numeric)));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Greedy word wrap that never truncates: a word longer than the width is left
|
|
75
|
+
* whole on its own line rather than cut. Command names are passed with
|
|
76
|
+
* `atomic: true` and are never split at all.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} text
|
|
79
|
+
* @param {number} width
|
|
80
|
+
* @param {string} [indent]
|
|
81
|
+
* @returns {string[]}
|
|
82
|
+
*/
|
|
83
|
+
function wrapText(text, width, indent = '') {
|
|
84
|
+
const words = String(text).split(/\s+/).filter(Boolean);
|
|
85
|
+
const lines = [];
|
|
86
|
+
let current = '';
|
|
87
|
+
for (const word of words) {
|
|
88
|
+
if (!current) {
|
|
89
|
+
current = `${indent}${word}`;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (current.length + 1 + word.length <= width) {
|
|
93
|
+
current += ` ${word}`;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
lines.push(current);
|
|
97
|
+
current = `${indent}${word}`;
|
|
98
|
+
}
|
|
99
|
+
if (current) lines.push(current);
|
|
100
|
+
return lines;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Candidate labels for "where config lives". The first honest label that fits
|
|
105
|
+
* the width wins, so a long XDG path is replaced by the switch that produced
|
|
106
|
+
* it rather than pushed off the screen.
|
|
107
|
+
*
|
|
108
|
+
* @param {object} env
|
|
109
|
+
* @param {string} configDir
|
|
110
|
+
* @returns {string[]}
|
|
111
|
+
*/
|
|
112
|
+
function configLabels(env, configDir) {
|
|
113
|
+
const home = os.homedir();
|
|
114
|
+
const replaceHome = (value) => (home && value.startsWith(`${home}${path.sep}`)
|
|
115
|
+
? `~${value.slice(home.length)}`
|
|
116
|
+
: value);
|
|
117
|
+
const labels = [`Config: ${replaceHome(path.join(configDir, 'config.json'))}`];
|
|
118
|
+
if (env.XDG_CONFIG_HOME) labels.push('Config: $XDG_CONFIG_HOME/servicenow/config.json');
|
|
119
|
+
labels.push('Config: ~/.config/servicenow/config.json');
|
|
120
|
+
return [...new Set(labels)];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Render the "Next steps" block. A wide terminal gets command and description
|
|
125
|
+
* on one aligned row; a narrow one puts the description underneath, indented,
|
|
126
|
+
* so the command name is always intact.
|
|
127
|
+
*
|
|
128
|
+
* @param {number} width
|
|
129
|
+
* @returns {string[]}
|
|
130
|
+
*/
|
|
131
|
+
function renderSteps(width) {
|
|
132
|
+
const commandWidth = Math.max(...STEPS.map((step) => step.command.length));
|
|
133
|
+
const alignedColumn = 4 + commandWidth + 2;
|
|
134
|
+
const oneLine = STEPS.every((step) => alignedColumn + step.detail.length <= width);
|
|
135
|
+
const lines = [];
|
|
136
|
+
for (const step of STEPS) {
|
|
137
|
+
if (oneLine) {
|
|
138
|
+
lines.push(` ${step.command.padEnd(commandWidth)} ${step.detail}`);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
lines.push(` ${step.command}`);
|
|
142
|
+
lines.push(...wrapText(step.detail, width, ' '));
|
|
143
|
+
}
|
|
144
|
+
return lines;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The orientation text. Kept short: it must fit above the grouped help without
|
|
149
|
+
* pushing it off the first screen, and it must stay inside 12 lines at 80
|
|
150
|
+
* columns.
|
|
151
|
+
*
|
|
152
|
+
* Everything shown is derived from local state: the version comes from the
|
|
153
|
+
* installed package.json, the config path from the same resolution the CLI
|
|
154
|
+
* uses, and the update command from the version's release channel. No network.
|
|
155
|
+
*
|
|
156
|
+
* @param {object} [opts]
|
|
157
|
+
* @param {number} [opts.columns] — terminal width (defaults to process.stdout.columns)
|
|
158
|
+
* @param {object} [opts.env] — environment (defaults to process.env)
|
|
159
|
+
* @param {string} [opts.configDir] — config dir the marker lives in
|
|
160
|
+
* @param {string} [opts.version] — installed version (defaults to package.json)
|
|
161
|
+
* @returns {string[]} lines
|
|
162
|
+
*/
|
|
163
|
+
export function welcomeLines({
|
|
164
|
+
columns = process.stdout?.columns,
|
|
165
|
+
env = process.env,
|
|
166
|
+
configDir = globalConfigDir(),
|
|
167
|
+
version = getVersion(),
|
|
168
|
+
} = {}) {
|
|
169
|
+
const width = layoutWidth(columns);
|
|
170
|
+
const labels = configLabels(env, configDir);
|
|
171
|
+
const configLabel = labels.find((label) => label.length <= width)
|
|
172
|
+
|| labels.reduce((shortest, label) => (label.length < shortest.length ? label : shortest));
|
|
173
|
+
const title = version && version !== '0.0.0'
|
|
174
|
+
? `Welcome to jsn ${version} (ServiceNow from your terminal)`
|
|
175
|
+
: 'Welcome to jsn (ServiceNow from your terminal)';
|
|
176
|
+
return [
|
|
177
|
+
...wrapText(title, width),
|
|
178
|
+
...wrapText(configLabel, width),
|
|
179
|
+
'',
|
|
180
|
+
' Next steps',
|
|
181
|
+
...renderSteps(width),
|
|
182
|
+
'',
|
|
183
|
+
...wrapText('Nothing above needs an instance. jsn asks for credentials only when needed.', width),
|
|
184
|
+
...wrapText('Prints once. Hide it with JSN_NO_WELCOME=1. Update with jsn upgrade.', width),
|
|
185
|
+
];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The orientation text as a single string (no trailing newline).
|
|
190
|
+
*
|
|
191
|
+
* @param {object} [opts] — same inputs as welcomeLines
|
|
192
|
+
* @returns {string}
|
|
193
|
+
*/
|
|
194
|
+
export function welcomeText(opts = {}) {
|
|
195
|
+
return welcomeLines(opts).join('\n');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Marker path for a given config dir (injectable for tests).
|
|
200
|
+
*
|
|
201
|
+
* @param {string} [configDir]
|
|
202
|
+
* @returns {string}
|
|
203
|
+
*/
|
|
204
|
+
export function welcomeMarkerPath(configDir = globalConfigDir()) {
|
|
205
|
+
return path.join(configDir, WELCOME_MARKER);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Decide whether this invocation may show the first-run welcome.
|
|
210
|
+
*
|
|
211
|
+
* Pure except for the marker existence check, so callers and tests can pass
|
|
212
|
+
* every input explicitly.
|
|
213
|
+
*
|
|
214
|
+
* `JSN_NO_WELCOME` is honoured only as the literal value `1`; `0`, an empty
|
|
215
|
+
* value and an unset variable all mean "normal first-run behavior".
|
|
216
|
+
*
|
|
217
|
+
* @param {object} [opts]
|
|
218
|
+
* @param {object} [opts.argv] — parsed args (for `--get` and global format flags)
|
|
219
|
+
* @param {string} [opts.requestedFormat] — format resolved from the same argv
|
|
220
|
+
* @param {object} [opts.cfg] — loaded profile config
|
|
221
|
+
* @param {object} [opts.env] — environment (defaults to process.env)
|
|
222
|
+
* @param {string} [opts.configDir] — config dir holding the marker
|
|
223
|
+
* @param {boolean} [opts.interactive] — a human is reachable (defaults to canPrompt())
|
|
224
|
+
* @returns {boolean}
|
|
225
|
+
*/
|
|
226
|
+
export function shouldShowWelcome({
|
|
227
|
+
argv = {},
|
|
228
|
+
requestedFormat = '',
|
|
229
|
+
cfg = {},
|
|
230
|
+
env = process.env,
|
|
231
|
+
configDir = globalConfigDir(),
|
|
232
|
+
interactive = canPrompt(),
|
|
233
|
+
} = {}) {
|
|
234
|
+
if (env.JSN_NO_WELCOME === '1') return false;
|
|
235
|
+
// Machine-readable output and one-shot extraction never get prose.
|
|
236
|
+
if (!HUMAN_FORMATS.has(requestedFormat || '')) return false;
|
|
237
|
+
if (argv && argv.get) return false;
|
|
238
|
+
if (!interactive) return false;
|
|
239
|
+
// An installation that already has a connection is not a first run. Profiles
|
|
240
|
+
// are the durable record of that (an env-provided instance URL is momentary).
|
|
241
|
+
if (cfg && (Object.keys(cfg.profiles || {}).length > 0 || cfg.defaultProfile)) return false;
|
|
242
|
+
try {
|
|
243
|
+
if (fs.existsSync(welcomeMarkerPath(configDir))) return false;
|
|
244
|
+
} catch {
|
|
245
|
+
// Unreadable config dir: showing the note once more is harmless.
|
|
246
|
+
}
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Exclusively record that the welcome was shown.
|
|
252
|
+
*
|
|
253
|
+
* Two first runs racing on the same config dir must not both print the note
|
|
254
|
+
* and must never leave a half-written marker, so the marker is created by
|
|
255
|
+
* hard-linking a fully written temp file: `link(2)` fails with EEXIST for every
|
|
256
|
+
* process but the winner, and the marker path only ever points at complete
|
|
257
|
+
* content.
|
|
258
|
+
*
|
|
259
|
+
* @param {string} [configDir]
|
|
260
|
+
* @returns {'claimed'|'taken'|'unwritable'} — 'taken' means another process
|
|
261
|
+
* already recorded (or recorded concurrently) the note.
|
|
262
|
+
*/
|
|
263
|
+
export function claimWelcome(configDir = globalConfigDir()) {
|
|
264
|
+
const marker = welcomeMarkerPath(configDir);
|
|
265
|
+
const temp = `${marker}.${process.pid}.tmp`;
|
|
266
|
+
const stamp = `${new Date().toISOString()} pid=${process.pid}\n`;
|
|
267
|
+
try {
|
|
268
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o750 });
|
|
269
|
+
fs.writeFileSync(temp, stamp, { mode: 0o600 });
|
|
270
|
+
} catch {
|
|
271
|
+
// A read-only or missing config dir must not break the command; the note
|
|
272
|
+
// may be shown again on the next run.
|
|
273
|
+
try { fs.unlinkSync(temp); } catch { /* never created */ }
|
|
274
|
+
return 'unwritable';
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
fs.linkSync(temp, marker);
|
|
278
|
+
return 'claimed';
|
|
279
|
+
} catch (err) {
|
|
280
|
+
if (err && err.code === 'EEXIST') return 'taken';
|
|
281
|
+
// Filesystems without hard links: exclusive create is still a single
|
|
282
|
+
// winner, it just cannot guarantee the marker appears complete.
|
|
283
|
+
try {
|
|
284
|
+
fs.writeFileSync(marker, stamp, { flag: 'wx', mode: 0o600 });
|
|
285
|
+
return 'claimed';
|
|
286
|
+
} catch (fallbackError) {
|
|
287
|
+
if (fallbackError && fallbackError.code === 'EEXIST') return 'taken';
|
|
288
|
+
return 'unwritable';
|
|
289
|
+
}
|
|
290
|
+
} finally {
|
|
291
|
+
try { fs.unlinkSync(temp); } catch { /* already gone */ }
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Boolean form of claimWelcome for callers that only need "did this process
|
|
297
|
+
* record the note".
|
|
298
|
+
*
|
|
299
|
+
* @param {string} [configDir]
|
|
300
|
+
* @returns {boolean}
|
|
301
|
+
*/
|
|
302
|
+
export function markWelcomeSeen(configDir = globalConfigDir()) {
|
|
303
|
+
return claimWelcome(configDir) === 'claimed';
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Show the welcome (above the caller's own help output) when this is a first
|
|
308
|
+
* run, then record it. Returns the text that was shown, or '' when nothing was.
|
|
309
|
+
*
|
|
310
|
+
* The marker is claimed before anything is printed, so an interrupted run
|
|
311
|
+
* (Ctrl-C) can leave the note unshown but never printed twice.
|
|
312
|
+
*
|
|
313
|
+
* @param {object} [opts] — same inputs as shouldShowWelcome, plus the
|
|
314
|
+
* welcomeText inputs (columns, version)
|
|
315
|
+
* @returns {string}
|
|
316
|
+
*/
|
|
317
|
+
export function maybeShowWelcome(opts = {}) {
|
|
318
|
+
if (!shouldShowWelcome(opts)) return '';
|
|
319
|
+
const configDir = opts.configDir || globalConfigDir();
|
|
320
|
+
if (claimWelcome(configDir) === 'taken') return '';
|
|
321
|
+
const text = welcomeText({ ...opts, configDir });
|
|
322
|
+
process.stdout.write(`${text}\n\n`);
|
|
323
|
+
return text;
|
|
324
|
+
}
|