@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
package/src/sdk.js
CHANGED
|
@@ -2,10 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
import { batchRead } from './sdk-batch.js';
|
|
4
4
|
import { gunzipSync } from 'node:zlib';
|
|
5
|
-
import { AppError, CodeAPI, CodeAuth, errAuth, errAPI, errNetwork, errUsage } from './errors.js';
|
|
5
|
+
import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
|
|
6
6
|
import { getStringField } from './helpers.js';
|
|
7
7
|
import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
|
|
8
8
|
import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
|
|
9
|
+
import {
|
|
10
|
+
previewUpdateSet as previewRetrievedUpdateSet,
|
|
11
|
+
commitUpdateSet as commitRetrievedUpdateSet,
|
|
12
|
+
listPreviewProblems,
|
|
13
|
+
} from './update-set-apply.js';
|
|
9
14
|
|
|
10
15
|
const DEFAULT_TIMEOUT = 30000;
|
|
11
16
|
|
|
@@ -834,6 +839,32 @@ export class SDKClient {
|
|
|
834
839
|
}
|
|
835
840
|
}
|
|
836
841
|
|
|
842
|
+
/**
|
|
843
|
+
* Preview a loaded retrieved update set through the CICD Update Set API and
|
|
844
|
+
* wait for its progress tracker. Does not commit and does not resolve
|
|
845
|
+
* preview problems.
|
|
846
|
+
* @param {string} sysID - sys_remote_update_set sys_id
|
|
847
|
+
* @param {{timeoutMs?: number, pollMs?: number}} [opts]
|
|
848
|
+
*/
|
|
849
|
+
async previewUpdateSet(sysID, opts = {}) {
|
|
850
|
+
return previewRetrievedUpdateSet(this, sysID, opts);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* Commit a previewed retrieved update set through the CICD Update Set API and
|
|
855
|
+
* wait for its progress tracker.
|
|
856
|
+
* @param {string} sysID - sys_remote_update_set sys_id
|
|
857
|
+
* @param {{timeoutMs?: number, pollMs?: number}} [opts]
|
|
858
|
+
*/
|
|
859
|
+
async commitUpdateSet(sysID, opts = {}) {
|
|
860
|
+
return commitRetrievedUpdateSet(this, sysID, opts);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/** Read sys_update_preview_problem rows for a retrieved update set. */
|
|
864
|
+
async listUpdateSetPreviewProblems(sysID, opts = {}) {
|
|
865
|
+
return listPreviewProblems(this, sysID, opts);
|
|
866
|
+
}
|
|
867
|
+
|
|
837
868
|
/**
|
|
838
869
|
* Execute a background script on the ServiceNow instance via sys.scripts.do.
|
|
839
870
|
* Uses a 3-step session-establishment flow compatible with OAuth tokens:
|
|
@@ -974,6 +1005,40 @@ export class SDKClient {
|
|
|
974
1005
|
return variables;
|
|
975
1006
|
}
|
|
976
1007
|
|
|
1008
|
+
/**
|
|
1009
|
+
* Session material for channels that authorize like a browser (AMB).
|
|
1010
|
+
*
|
|
1011
|
+
* AMB does not accept bearer/basic headers on subscribe; it needs the
|
|
1012
|
+
* cookies and X-UserToken of a UI session. gck credentials already carry
|
|
1013
|
+
* them; basic/oauth profiles obtain them by warming the same session the
|
|
1014
|
+
* SDK uses for UI calls. A bearer-token profile that cannot warm a session
|
|
1015
|
+
* is an actionable error, never a silent fallback.
|
|
1016
|
+
*/
|
|
1017
|
+
async ambSession() {
|
|
1018
|
+
if (!this.authProvider) throw errAuth('No authentication configured');
|
|
1019
|
+
const creds = await this.authProvider.getCredentials();
|
|
1020
|
+
if (!creds) throw errAuth('No valid credentials');
|
|
1021
|
+
if (creds.auth_method === 'gck') {
|
|
1022
|
+
if (!creds.cookies) {
|
|
1023
|
+
throw errAuthHint('This gck credential has no session cookies, so AMB cannot open a channel.',
|
|
1024
|
+
'Re-import the browser session: jsn auth login --browser');
|
|
1025
|
+
}
|
|
1026
|
+
return { cookies: creds.cookies, userToken: creds.access_token || '', authMethod: 'gck' };
|
|
1027
|
+
}
|
|
1028
|
+
if (creds.auth_method === 'basic' || creds.auth_method === 'token' || creds.auth_method === 'oauth') {
|
|
1029
|
+
const cookies = await this._warmSession();
|
|
1030
|
+
if (!cookies) {
|
|
1031
|
+
throw errAuthHint(
|
|
1032
|
+
`${creds.auth_method} credentials could not open a UI session, which AMB requires.`,
|
|
1033
|
+
'Record watching needs a browser session. Run "jsn auth login --browser" and use that profile, or ask an administrator whether AMB is enabled for this account.',
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
return { cookies, userToken: this.sessionUserToken || '', authMethod: creds.auth_method };
|
|
1037
|
+
}
|
|
1038
|
+
throw errAuthHint(`Authentication method "${creds.auth_method}" cannot open an AMB session.`,
|
|
1039
|
+
'Use a browser-session (gck) profile: jsn auth login --browser');
|
|
1040
|
+
}
|
|
1041
|
+
|
|
977
1042
|
async _warmSession() {
|
|
978
1043
|
if (this.oauthCookies) return this.oauthCookies;
|
|
979
1044
|
if (!this._sessionPromise) {
|
package/src/store.js
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
// ServiceNow Store application discovery, inspection and explicit lifecycle
|
|
2
|
+
// operations.
|
|
3
|
+
//
|
|
4
|
+
// Wire contract
|
|
5
|
+
// -------------
|
|
6
|
+
// The App Client REST surface used here is the one documented by the App
|
|
7
|
+
// Client application itself (sn_appclient) and implemented by the reference
|
|
8
|
+
// Store CLI named in issue #400 (sonisoft-cnanda/now-sdk-ext-cli):
|
|
9
|
+
//
|
|
10
|
+
// POST /api/sn_appclient/appmanager/apps?tab_context=…&search_key=…
|
|
11
|
+
// &sysparm_limit=…&sysparm_offset=… -> result.apps[]
|
|
12
|
+
// GET /api/sn_appclient/appmanager/app/{app_sys_id} -> result.app_info_on_instance
|
|
13
|
+
// GET /api/sn_appclient/appmanager/app/install?app_id=…&version=…
|
|
14
|
+
// GET /api/sn_appclient/appmanager/app/update?app_id=…&version=…
|
|
15
|
+
// GET /api/sn_cicd/progress/{tracker_id} -> result{status,percent_complete,…}
|
|
16
|
+
//
|
|
17
|
+
// This contract has NOT been verified against a live Store-entitled instance
|
|
18
|
+
// from this repository: there is no such instance in CI and no way to obtain
|
|
19
|
+
// one. Discovery/inspection is implemented and tested against a mock
|
|
20
|
+
// transport; install/update are declared mutations behind the same contract
|
|
21
|
+
// and are labelled unverified in the PR. A maintainer with a Store-entitled
|
|
22
|
+
// instance must confirm the endpoints, the required roles, and the version
|
|
23
|
+
// list shape before treating the mutation path as proven.
|
|
24
|
+
//
|
|
25
|
+
// The search endpoint is POST-shaped (an empty JSON body), but performs no
|
|
26
|
+
// mutation. Read-only profiles may use it; `install`/`update` remain the only
|
|
27
|
+
// declared mutation subcommands.
|
|
28
|
+
|
|
29
|
+
import { AppError, errAPI, errAmbiguous, errNotFoundHint, errUsage, errUsageHint } from './errors.js';
|
|
30
|
+
import { isSysId, unwrapSysId } from './resolve-record.js';
|
|
31
|
+
|
|
32
|
+
/** Store tab contexts, as named by the App Client. */
|
|
33
|
+
export const STORE_TABS = {
|
|
34
|
+
available: 'available_for_you',
|
|
35
|
+
installed: 'installed',
|
|
36
|
+
updates: 'updates',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const APPS_PATH = '/api/sn_appclient/appmanager/apps';
|
|
40
|
+
const APP_PATH = '/api/sn_appclient/appmanager/app';
|
|
41
|
+
const INSTALL_PATH = '/api/sn_appclient/appmanager/app/install';
|
|
42
|
+
const UPDATE_PATH = '/api/sn_appclient/appmanager/app/update';
|
|
43
|
+
const PROGRESS_PATH = '/api/sn_cicd/progress';
|
|
44
|
+
|
|
45
|
+
const INSTALLED_FIELDS = 'sys_id,name,scope,version,active,latest_version,install_date,update_date';
|
|
46
|
+
const MAX_VERSION_ATTEMPTS = 6;
|
|
47
|
+
const DEFAULT_VERIFY_INTERVAL_MS = 2000;
|
|
48
|
+
|
|
49
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
50
|
+
|
|
51
|
+
/** Platform booleans arrive as true/false, 'true'/'false', or 1/0. */
|
|
52
|
+
export const storeFlag = value => value === true || value === 'true' || value === 1 || value === '1';
|
|
53
|
+
|
|
54
|
+
/** Unwrap a raw or display-valued field. */
|
|
55
|
+
export function storeText(record, field) {
|
|
56
|
+
const value = record?.[field];
|
|
57
|
+
if (value === undefined || value === null) return '';
|
|
58
|
+
if (typeof value === 'object') return String(value.value ?? value.display_value ?? '');
|
|
59
|
+
return String(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function boundedLimit(value = 20) {
|
|
63
|
+
if (!Number.isInteger(value) || value < 1 || value > 200) throw errUsage('--limit must be an integer from 1 to 200.');
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function boundedOffset(value = 0) {
|
|
68
|
+
if (!Number.isInteger(value) || value < 0) throw errUsage('--offset must be a nonnegative integer.');
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function boundedTimeout(value = 1800) {
|
|
73
|
+
if (!Number.isFinite(value) || value < 1 || value > 14400) throw errUsage('--timeout must be from 1 to 14400 seconds.');
|
|
74
|
+
return Math.round(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function boundedPoll(value = 5) {
|
|
78
|
+
if (!Number.isFinite(value) || value < 0 || value > 300) throw errUsage('--poll-interval must be from 0 to 300 seconds.');
|
|
79
|
+
return Math.round(value);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function requireIdentifier(value) {
|
|
83
|
+
const text = String(value ?? '').trim();
|
|
84
|
+
if (!text) throw errUsage('Provide a Store application by name, scope, or 32-character sys_id.');
|
|
85
|
+
return text;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The list endpoint ships `indicators` as a JSON-encoded string; the detail
|
|
90
|
+
* endpoint ships the same entries as a real array. Both carry the platform's
|
|
91
|
+
* own reason an application is unavailable here (for example
|
|
92
|
+
* `not_available_for_instance_type` -> "Unavailable for Instance" on a
|
|
93
|
+
* developer instance), which is the only place that reason appears.
|
|
94
|
+
*/
|
|
95
|
+
export function parseIndicators(value) {
|
|
96
|
+
if (value === undefined || value === null || value === '') return [];
|
|
97
|
+
const raw = typeof value === 'string' ? (() => { try { return JSON.parse(value); } catch { return []; } })() : value;
|
|
98
|
+
if (!Array.isArray(raw)) return [];
|
|
99
|
+
return raw.filter(item => item && typeof item === 'object').map(item => ({
|
|
100
|
+
id: storeText(item, 'id') || null,
|
|
101
|
+
type: storeText(item, 'type') || null,
|
|
102
|
+
message: storeText(item, 'message') || null,
|
|
103
|
+
tooltip: storeText(item, 'tooltip') || null,
|
|
104
|
+
}));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Reasons the platform gave for blocking an application here. */
|
|
108
|
+
export function blockingIndicators(indicators) {
|
|
109
|
+
return parseIndicators(indicators).filter(item => item.type === 'error');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* One row from the Store list, reduced to stable, documented fields.
|
|
114
|
+
*
|
|
115
|
+
* The list payload (POST /appmanager/apps) is NOT the detail payload: it has no
|
|
116
|
+
* `isInstalled`, `can_install_or_upgrade`, `is_store_app`, `isAppstorePlugin`,
|
|
117
|
+
* `price_type` or `needs_app_engine_licensing`. The installed marker on a list
|
|
118
|
+
* row is a non-empty `version` (an available row reports `version: null`), and
|
|
119
|
+
* the update marker is `update_available` ("1"). Reading the detail spellings
|
|
120
|
+
* off a list row reported every installed application as not installed.
|
|
121
|
+
*/
|
|
122
|
+
export function summarizeApplication(app) {
|
|
123
|
+
const version = storeText(app, 'version');
|
|
124
|
+
const indicators = parseIndicators(app?.indicators);
|
|
125
|
+
const blockedFlag = app?.block_install === undefined ? null : storeFlag(app.block_install);
|
|
126
|
+
// The list payload always carries `indicators` (an empty array when nothing
|
|
127
|
+
// blocks the app); only a payload without the key leaves the answer unknown.
|
|
128
|
+
const indicatorsReported = app?.indicators !== undefined && app?.indicators !== null;
|
|
129
|
+
return {
|
|
130
|
+
sys_id: storeText(app, 'sys_id'),
|
|
131
|
+
name: storeText(app, 'name'),
|
|
132
|
+
scope: storeText(app, 'scope'),
|
|
133
|
+
vendor: storeText(app, 'vendor'),
|
|
134
|
+
source: storeText(app, 'source'),
|
|
135
|
+
version: version || null,
|
|
136
|
+
latest_version: storeText(app, 'latest_version') || storeText(app, 'latest_version_display') || null,
|
|
137
|
+
installed: storeFlag(app?.isInstalled) || Boolean(version),
|
|
138
|
+
update_available: storeFlag(app?.isInstalledAndUpdateAvailable) || storeFlag(app?.update_available),
|
|
139
|
+
installable: app?.can_install_or_upgrade === undefined ? null : storeFlag(app.can_install_or_upgrade),
|
|
140
|
+
is_store_app: app?.is_store_app === undefined ? null : storeFlag(app.is_store_app),
|
|
141
|
+
is_plugin: app?.isAppstorePlugin === undefined ? null : storeFlag(app.isAppstorePlugin),
|
|
142
|
+
price_type: storeText(app, 'price_type') || null,
|
|
143
|
+
needs_app_engine_licensing: app?.needs_app_engine_licensing === undefined ? null : storeFlag(app.needs_app_engine_licensing),
|
|
144
|
+
blocked: blockedFlag === null && !indicatorsReported ? null : Boolean(blockedFlag) || blockingIndicators(indicators).length > 0,
|
|
145
|
+
indicators,
|
|
146
|
+
short_description: storeText(app, 'short_description') || null,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* List or search Store applications in one tab context.
|
|
152
|
+
*
|
|
153
|
+
* A 2xx body without `result.apps` is a malformed envelope — an unavailable
|
|
154
|
+
* source, never an empty catalogue.
|
|
155
|
+
*/
|
|
156
|
+
export async function listApplications(sdk, { tab = 'available', term, limit = 20, offset = 0 } = {}) {
|
|
157
|
+
if (!Object.hasOwn(STORE_TABS, tab)) throw errUsage(`--tab must be one of ${Object.keys(STORE_TABS).join(', ')}.`);
|
|
158
|
+
boundedLimit(limit);
|
|
159
|
+
boundedOffset(offset);
|
|
160
|
+
const searchKey = term === undefined || term === null ? '' : String(term).trim();
|
|
161
|
+
const params = new URLSearchParams({
|
|
162
|
+
tab_context: STORE_TABS[tab],
|
|
163
|
+
sysparm_limit: String(limit),
|
|
164
|
+
sysparm_offset: String(offset),
|
|
165
|
+
});
|
|
166
|
+
if (searchKey) params.set('search_key', searchKey);
|
|
167
|
+
const response = await sdk.request(`${sdk.baseURL}${APPS_PATH}?${params}`, { method: 'POST', body: '{}' });
|
|
168
|
+
const apps = response?.result?.apps;
|
|
169
|
+
if (!Array.isArray(apps)) {
|
|
170
|
+
throw new AppError('store_response_malformed',
|
|
171
|
+
'The Store application list returned no apps array. This is an unavailable source, not an empty catalogue.',
|
|
172
|
+
'Confirm this instance exposes the ServiceNow Store App Client API (sn_appclient) and that this account may use it.');
|
|
173
|
+
}
|
|
174
|
+
const rows = apps.filter(Boolean);
|
|
175
|
+
return {
|
|
176
|
+
tab,
|
|
177
|
+
tab_context: STORE_TABS[tab],
|
|
178
|
+
term: searchKey || null,
|
|
179
|
+
count: rows.length,
|
|
180
|
+
limit,
|
|
181
|
+
offset,
|
|
182
|
+
page_full: rows.length === limit,
|
|
183
|
+
apps: rows.map(summarizeApplication),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Full App Client detail for one app, or null when the client has no record. */
|
|
188
|
+
export async function applicationDetail(sdk, sysId) {
|
|
189
|
+
const response = await sdk.request(`${sdk.baseURL}${APP_PATH}/${encodeURIComponent(sysId)}`, { method: 'GET' });
|
|
190
|
+
const detail = response?.result?.app_info_on_instance;
|
|
191
|
+
return detail && typeof detail === 'object' ? detail : null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function versionList(detail) {
|
|
195
|
+
const raw = detail?.versions;
|
|
196
|
+
if (!Array.isArray(raw)) return [];
|
|
197
|
+
return raw
|
|
198
|
+
.map(item => (typeof item === 'string' ? item : storeText(item, 'version') || storeText(item, 'version_display') || storeText(item, 'name')))
|
|
199
|
+
.map(item => String(item).trim())
|
|
200
|
+
.filter(Boolean);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function detailName(detail, record, fallback) {
|
|
204
|
+
return storeText(detail, 'name') || storeText(record, 'name') || fallback || '';
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Resolve a human identifier to a Store app sys_id.
|
|
209
|
+
*
|
|
210
|
+
* Order: sys_id, installed/known `sys_store_app` scope, `sys_store_app` name,
|
|
211
|
+
* then the Store search endpoint (exact name or scope only). A company
|
|
212
|
+
* application-repository app is refused explicitly rather than treated as a
|
|
213
|
+
* Store app.
|
|
214
|
+
*/
|
|
215
|
+
export async function resolveApplication(sdk, identifier) {
|
|
216
|
+
const raw = requireIdentifier(identifier);
|
|
217
|
+
if (isSysId(raw)) {
|
|
218
|
+
const sysId = raw.toLowerCase();
|
|
219
|
+
let record = null;
|
|
220
|
+
try {
|
|
221
|
+
record = await sdk.get('sys_store_app', sysId);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error?.status !== 403 && error?.status !== 404) throw error;
|
|
224
|
+
}
|
|
225
|
+
return { sys_id: sysId, record, summary: null, matched_by: 'sys_id' };
|
|
226
|
+
}
|
|
227
|
+
if (/[\^=\n\r]/.test(raw)) {
|
|
228
|
+
throw errUsage('The identifier contains characters reserved by encoded queries; pass the application sys_id instead.');
|
|
229
|
+
}
|
|
230
|
+
for (const field of ['scope', 'name']) {
|
|
231
|
+
const rows = await sdk.listStrict('sys_store_app', {
|
|
232
|
+
sysparm_query: `${field}=${raw}`,
|
|
233
|
+
sysparm_fields: INSTALLED_FIELDS,
|
|
234
|
+
sysparm_limit: '2',
|
|
235
|
+
sysparm_display_value: 'false',
|
|
236
|
+
});
|
|
237
|
+
if (rows.length > 1) {
|
|
238
|
+
throw errAmbiguous('store applications', rows.map(row => `${storeText(row, 'name')} (${storeText(row, 'scope')})`));
|
|
239
|
+
}
|
|
240
|
+
if (rows.length === 1) return { sys_id: unwrapSysId(rows[0]), record: rows[0], summary: null, matched_by: field };
|
|
241
|
+
}
|
|
242
|
+
const found = await listApplications(sdk, { tab: 'available', term: raw, limit: 25, offset: 0 });
|
|
243
|
+
const wanted = raw.toLowerCase();
|
|
244
|
+
const matches = found.apps.filter(app => app.name.toLowerCase() === wanted || app.scope.toLowerCase() === wanted);
|
|
245
|
+
if (matches.length > 1) {
|
|
246
|
+
throw errAmbiguous('store applications', matches.map(app => `${app.name} (${app.scope}) ${app.sys_id}`));
|
|
247
|
+
}
|
|
248
|
+
if (matches.length === 1) return { sys_id: matches[0].sys_id, record: null, summary: matches[0], matched_by: 'store_search' };
|
|
249
|
+
const company = await sdk.list('sys_app', {
|
|
250
|
+
sysparm_query: `scope=${raw}`, sysparm_fields: 'sys_id,name,scope', sysparm_limit: '1',
|
|
251
|
+
}).catch(() => []);
|
|
252
|
+
if (company.length) {
|
|
253
|
+
throw new AppError('store_not_store_app',
|
|
254
|
+
`"${raw}" is not a ServiceNow Store application.`,
|
|
255
|
+
'It matches a company/application-repository application (sys_app). jsn store handles ServiceNow Store applications only; '
|
|
256
|
+
+ 'use `jsn records list --table sys_app` to inspect that one.');
|
|
257
|
+
}
|
|
258
|
+
throw errNotFoundHint('store application', raw,
|
|
259
|
+
`Search the Store for it: jsn store search "${raw}". Only exact name or scope matches are resolved here; pass the sys_id from a search result if several applications share a name.`);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Inspection view: installed state, available versions, entitlement flags,
|
|
264
|
+
* dependencies and compatibility data where the platform exposes them.
|
|
265
|
+
*/
|
|
266
|
+
export async function showApplication(sdk, identifier) {
|
|
267
|
+
const target = await resolveApplication(sdk, identifier);
|
|
268
|
+
let detail = null;
|
|
269
|
+
let detailUnavailable = null;
|
|
270
|
+
try {
|
|
271
|
+
detail = await applicationDetail(sdk, target.sys_id);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (error?.status === 403) detailUnavailable = 'forbidden';
|
|
274
|
+
else if (error?.status === 404) detailUnavailable = 'not_found';
|
|
275
|
+
else throw error;
|
|
276
|
+
}
|
|
277
|
+
if (!detail && !target.record && !target.summary && detailUnavailable) {
|
|
278
|
+
throw errNotFoundHint('store application', identifier,
|
|
279
|
+
'Neither the Store App Client nor the store application table returned this application. Check the identifier and this account\'s Store access.');
|
|
280
|
+
}
|
|
281
|
+
const record = target.record;
|
|
282
|
+
const installedFromDetail = Boolean(detail) && storeFlag(detail.isInstalled);
|
|
283
|
+
const installedFromRecord = !detail && record && storeText(record, 'version') && storeText(record, 'install_date');
|
|
284
|
+
const installed = installedFromDetail || installedFromRecord;
|
|
285
|
+
const installedVersion = storeText(detail, 'version') || (installedFromRecord ? storeText(record, 'version') : '');
|
|
286
|
+
const latestVersion = storeText(detail, 'latest_version') || storeText(detail, 'latest_version_display') || storeText(record, 'latest_version');
|
|
287
|
+
const versions = versionList(detail);
|
|
288
|
+
const indicators = Array.isArray(detail?.indicators) ? detail.indicators : parseIndicators(detail?.indicators);
|
|
289
|
+
const blocked = blockingIndicators(indicators);
|
|
290
|
+
const notes = [];
|
|
291
|
+
if (!detail) {
|
|
292
|
+
notes.push('Store App Client detail is unavailable, so entitlement, dependency and compatibility data could not be read.');
|
|
293
|
+
} else {
|
|
294
|
+
if (detail.can_install_or_upgrade === undefined) notes.push('The Store client did not report whether this application can be installed by this account.');
|
|
295
|
+
else if (!storeFlag(detail.can_install_or_upgrade)) notes.push('The Store client reports this application cannot be installed or upgraded by this account. The platform does not say whether entitlement, licensing, or compatibility is the cause.');
|
|
296
|
+
if (storeFlag(detail.block_install) || blocked.length) {
|
|
297
|
+
const reasons = blocked.map(item => item.message || item.tooltip).filter(Boolean).join('; ');
|
|
298
|
+
notes.push(`The Store client blocks this application on this instance${reasons ? `: ${reasons}` : ' (block_install=true)'}. A blocked application is refused before any install or update request is sent.`);
|
|
299
|
+
}
|
|
300
|
+
if (!versions.length) notes.push('No version list was returned; requested versions cannot be checked locally against the Store catalogue.');
|
|
301
|
+
notes.push('Compatibility and entitlement output is reported exactly as the platform supplies it; jsn does not infer purchase authorization or accept commercial terms.');
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
sys_id: target.sys_id,
|
|
305
|
+
name: detailName(detail, record, target.summary?.name),
|
|
306
|
+
scope: storeText(detail, 'scope') || storeText(record, 'scope') || target.summary?.scope || '',
|
|
307
|
+
vendor: storeText(detail, 'vendor') || target.summary?.vendor || null,
|
|
308
|
+
source: storeText(detail, 'source') || target.summary?.source || null,
|
|
309
|
+
matched_by: target.matched_by,
|
|
310
|
+
is_store_app: detail?.is_store_app === undefined ? target.summary?.is_store_app ?? null : storeFlag(detail.is_store_app),
|
|
311
|
+
is_plugin: detail?.isAppstorePlugin === undefined ? target.summary?.is_plugin ?? null : storeFlag(detail.isAppstorePlugin),
|
|
312
|
+
installed: installed ? {
|
|
313
|
+
version: installedVersion || null,
|
|
314
|
+
active: detail?.active === undefined && record?.active === undefined ? null : storeFlag(detail?.active ?? record?.active),
|
|
315
|
+
install_date: storeText(detail, 'install_date') || storeText(record, 'install_date') || null,
|
|
316
|
+
update_date: storeText(detail, 'update_date') || storeText(record, 'update_date') || null,
|
|
317
|
+
} : null,
|
|
318
|
+
available: detail ? {
|
|
319
|
+
latest_version: latestVersion || null,
|
|
320
|
+
update_available: storeFlag(detail.isInstalledAndUpdateAvailable),
|
|
321
|
+
versions: versions.length ? versions : null,
|
|
322
|
+
compatibilities: detail.compatibilities ?? null,
|
|
323
|
+
} : null,
|
|
324
|
+
entitlement: detail ? {
|
|
325
|
+
can_install_or_upgrade: detail.can_install_or_upgrade === undefined ? null : storeFlag(detail.can_install_or_upgrade),
|
|
326
|
+
can_install_or_upgrade_customization: detail.can_install_or_upgrade_customization === undefined
|
|
327
|
+
? null : storeFlag(detail.can_install_or_upgrade_customization),
|
|
328
|
+
needs_app_engine_licensing: storeFlag(detail.needs_app_engine_licensing),
|
|
329
|
+
price_type: storeText(detail, 'price_type') || null,
|
|
330
|
+
subscription_applicable: storeFlag(detail.isSubscriptionApplicable),
|
|
331
|
+
} : null,
|
|
332
|
+
dependencies: detail?.dependencies ?? null,
|
|
333
|
+
indicators,
|
|
334
|
+
blocked: detail ? Boolean(storeFlag(detail.block_install) || blocked.length) : null,
|
|
335
|
+
customization_available: storeFlag(detail?.isCustomizationUpdateAvailable),
|
|
336
|
+
detail_unavailable: detailUnavailable,
|
|
337
|
+
notes,
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function assertOfferedVersion(detail, wanted, name) {
|
|
342
|
+
const offered = versionList(detail);
|
|
343
|
+
if (offered.length && !offered.includes(wanted)) {
|
|
344
|
+
throw new AppError('store_version_unavailable',
|
|
345
|
+
`${name || 'This application'} does not offer version ${wanted}.`,
|
|
346
|
+
`Versions the Store reported: ${offered.join(', ')}. Pass one of those with --version.`);
|
|
347
|
+
}
|
|
348
|
+
return offered;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function assertInstallable(detail, verb, name) {
|
|
352
|
+
if (!detail) return false;
|
|
353
|
+
const blocked = blockingIndicators(detail.indicators);
|
|
354
|
+
if (storeFlag(detail.block_install) || blocked.length) {
|
|
355
|
+
const reasons = blocked.map(item => item.message || item.tooltip).filter(Boolean).join('; ');
|
|
356
|
+
const flag = storeFlag(detail.block_install) ? 'block_install=true' : `indicator ${blocked.map(item => item.id).filter(Boolean).join(', ')}`;
|
|
357
|
+
throw new AppError('store_app_not_installable',
|
|
358
|
+
`The Store client blocks ${verb === 'install' ? 'installing' : 'updating'} ${name || 'this application'} on this instance${reasons ? `: ${reasons}` : '.'}`,
|
|
359
|
+
`Reported flags: ${flag}. This is the platform's own refusal for this instance; `
|
|
360
|
+
+ 'an application can report can_install_or_upgrade=true and still be blocked here '
|
|
361
|
+
+ '(for example not_available_for_instance_type on a developer instance). '
|
|
362
|
+
+ `Run jsn store show ${name || '<application>'} to see the reported indicators, entitlement and compatibility fields.`);
|
|
363
|
+
}
|
|
364
|
+
if (detail.can_install_or_upgrade !== undefined && !storeFlag(detail.can_install_or_upgrade)) {
|
|
365
|
+
throw new AppError('store_app_not_installable',
|
|
366
|
+
`The Store client reports ${name || 'this application'} cannot be ${verb === 'install' ? 'installed' : 'updated'} by this account.`,
|
|
367
|
+
'Reported flags: can_install_or_upgrade=false. '
|
|
368
|
+
+ 'The platform does not distinguish entitlement, licensing and compatibility as the cause, and jsn does not infer authorization to buy an application or accept commercial terms. '
|
|
369
|
+
+ `Run jsn store show ${name || '<application>'} to see the entitlement and compatibility fields before asking a Store administrator.`);
|
|
370
|
+
}
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function resolvedForMutation(sdk, identifier) {
|
|
375
|
+
const target = await resolveApplication(sdk, identifier);
|
|
376
|
+
let detail = null;
|
|
377
|
+
let detailUnavailable = null;
|
|
378
|
+
try {
|
|
379
|
+
detail = await applicationDetail(sdk, target.sys_id);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error?.status === 403) detailUnavailable = 'forbidden';
|
|
382
|
+
else if (error?.status === 404) detailUnavailable = 'not_found';
|
|
383
|
+
else throw error;
|
|
384
|
+
}
|
|
385
|
+
if (!detail && !target.record && !target.summary) {
|
|
386
|
+
throw errNotFoundHint('store application', identifier,
|
|
387
|
+
'Neither the Store App Client nor the store application table returned this application. Search for it first: jsn store search "<term>".');
|
|
388
|
+
}
|
|
389
|
+
return { target, detail, detailUnavailable };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Resolve an exact app and version and describe the intended install. */
|
|
393
|
+
export async function prepareInstall(sdk, identifier, { version, demoData = false } = {}) {
|
|
394
|
+
const { target, detail, detailUnavailable } = await resolvedForMutation(sdk, identifier);
|
|
395
|
+
const wanted = String(version ?? '').trim();
|
|
396
|
+
if (!wanted) {
|
|
397
|
+
throw errUsageHint('Provide the exact version to install with --version.',
|
|
398
|
+
'jsn store show <app> reports the versions the Store returned; jsn never picks one for you.');
|
|
399
|
+
}
|
|
400
|
+
const app = {
|
|
401
|
+
sys_id: target.sys_id,
|
|
402
|
+
name: detailName(detail, target.record, target.summary?.name),
|
|
403
|
+
scope: storeText(detail, 'scope') || storeText(target.record, 'scope') || target.summary?.scope || '',
|
|
404
|
+
vendor: storeText(detail, 'vendor') || target.summary?.vendor || null,
|
|
405
|
+
};
|
|
406
|
+
const installedVersion = storeFlag(detail?.isInstalled)
|
|
407
|
+
? storeText(detail, 'version')
|
|
408
|
+
: (storeText(target.record, 'install_date') ? storeText(target.record, 'version') : '');
|
|
409
|
+
if (storeFlag(detail?.isInstalled) || installedVersion) {
|
|
410
|
+
throw new AppError('store_already_installed',
|
|
411
|
+
`${app.name || app.sys_id} is already installed${installedVersion ? ` at version ${installedVersion}` : ''}.`,
|
|
412
|
+
`Use an explicit update instead: jsn store update ${app.scope || app.sys_id} --version ${wanted}`);
|
|
413
|
+
}
|
|
414
|
+
const versions = assertOfferedVersion(detail, wanted, app.name);
|
|
415
|
+
const installable = assertInstallable(detail, 'install', app.name);
|
|
416
|
+
return {
|
|
417
|
+
operation: 'install',
|
|
418
|
+
app,
|
|
419
|
+
requested_version: wanted,
|
|
420
|
+
demo_data: Boolean(demoData),
|
|
421
|
+
installed_version: null,
|
|
422
|
+
versions: versions.length ? versions : null,
|
|
423
|
+
installable_checked: installable,
|
|
424
|
+
detail_unavailable: detailUnavailable,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Resolve an installed app and the exact version to update it to. */
|
|
429
|
+
export async function prepareUpdate(sdk, identifier, { version } = {}) {
|
|
430
|
+
const { target, detail, detailUnavailable } = await resolvedForMutation(sdk, identifier);
|
|
431
|
+
const app = {
|
|
432
|
+
sys_id: target.sys_id,
|
|
433
|
+
name: detailName(detail, target.record, target.summary?.name),
|
|
434
|
+
scope: storeText(detail, 'scope') || storeText(target.record, 'scope') || target.summary?.scope || '',
|
|
435
|
+
vendor: storeText(detail, 'vendor') || target.summary?.vendor || null,
|
|
436
|
+
};
|
|
437
|
+
const installedVersion = storeFlag(detail?.isInstalled)
|
|
438
|
+
? storeText(detail, 'version')
|
|
439
|
+
: (storeText(target.record, 'install_date') ? storeText(target.record, 'version') : '');
|
|
440
|
+
if (!storeFlag(detail?.isInstalled) && !installedVersion) {
|
|
441
|
+
throw new AppError('store_not_installed',
|
|
442
|
+
`${app.name || app.sys_id} is not installed on this instance.`,
|
|
443
|
+
`Install an exact version first: jsn store install ${app.scope || app.sys_id} --version <version>`);
|
|
444
|
+
}
|
|
445
|
+
const wanted = String(version ?? '').trim()
|
|
446
|
+
|| storeText(detail, 'latest_version')
|
|
447
|
+
|| storeText(detail, 'latest_version_display')
|
|
448
|
+
|| '';
|
|
449
|
+
const versions = versionList(detail);
|
|
450
|
+
if (!wanted) {
|
|
451
|
+
throw errUsageHint('Provide the exact version to update to with --version.',
|
|
452
|
+
versions.length ? `Versions the Store reported: ${versions.join(', ')}.` : 'The Store returned no latest version or version list to choose from.');
|
|
453
|
+
}
|
|
454
|
+
if (wanted === installedVersion) {
|
|
455
|
+
throw new AppError('store_version_unchanged',
|
|
456
|
+
`${app.name || app.sys_id} is already at version ${wanted}.`,
|
|
457
|
+
`Pick a different target version${versions.length ? `: ${versions.join(', ')}` : ''}.`);
|
|
458
|
+
}
|
|
459
|
+
assertOfferedVersion(detail, wanted, app.name);
|
|
460
|
+
const installable = assertInstallable(detail, 'update', app.name);
|
|
461
|
+
return {
|
|
462
|
+
operation: 'update',
|
|
463
|
+
app,
|
|
464
|
+
requested_version: wanted,
|
|
465
|
+
from_version: installedVersion || null,
|
|
466
|
+
demo_data: false,
|
|
467
|
+
versions: versions.length ? versions : null,
|
|
468
|
+
installable_checked: installable,
|
|
469
|
+
detail_unavailable: detailUnavailable,
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Submit the resolved operation and require a usable tracker id back. */
|
|
474
|
+
export async function dispatchOperation(sdk, plan) {
|
|
475
|
+
const path = plan.operation === 'update' ? UPDATE_PATH : INSTALL_PATH;
|
|
476
|
+
const params = new URLSearchParams({ app_id: plan.app.sys_id, version: plan.requested_version });
|
|
477
|
+
if (plan.operation === 'install') params.set('load_demo_data', String(Boolean(plan.demo_data)));
|
|
478
|
+
const response = await sdk.request(`${sdk.baseURL}${path}?${params}`, { method: 'GET' });
|
|
479
|
+
const result = response?.result;
|
|
480
|
+
if (!result || typeof result !== 'object') {
|
|
481
|
+
throw errAPI(200, `The ${plan.operation} request returned no result, so the application state is unknown. Inspect the application before retrying.`);
|
|
482
|
+
}
|
|
483
|
+
const tracker = result.tracker_id || result.trackerId || result.links?.progress?.id;
|
|
484
|
+
if (!isSysId(String(tracker ?? ''))) {
|
|
485
|
+
throw new AppError('store_tracker_missing',
|
|
486
|
+
`The ${plan.operation} submission was accepted but returned no tracker id. This is not a completed installation.`,
|
|
487
|
+
'Inspect the application and its install/upgrade history before retrying; do not resubmit automatically.');
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
tracker_id: String(tracker),
|
|
491
|
+
submitted_at: new Date().toISOString(),
|
|
492
|
+
provider_message: storeText(result, 'message') || null,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Read one progress tracker. Terminal is not the same as successful. */
|
|
497
|
+
export async function operationStatus(sdk, trackerId) {
|
|
498
|
+
const id = String(trackerId ?? '').trim();
|
|
499
|
+
if (!isSysId(id)) throw errUsage('Use the full 32-character tracker id reported by jsn store install/update.');
|
|
500
|
+
const response = await sdk.request(`${sdk.baseURL}${PROGRESS_PATH}/${encodeURIComponent(id)}`, { method: 'GET' });
|
|
501
|
+
const result = response?.result;
|
|
502
|
+
if (!result || typeof result !== 'object') {
|
|
503
|
+
throw new AppError('store_progress_unavailable',
|
|
504
|
+
`Progress tracker ${id} returned no result.`,
|
|
505
|
+
'The operation may still be running. Re-read the tracker before starting another operation; jsn never resubmits automatically.');
|
|
506
|
+
}
|
|
507
|
+
const percent = Number(result.percent_complete);
|
|
508
|
+
const status = storeText(result, 'status');
|
|
509
|
+
const error = storeText(result, 'error');
|
|
510
|
+
const label = storeText(result, 'status_label');
|
|
511
|
+
const message = storeText(result, 'status_message');
|
|
512
|
+
// The tracker's own detail line names the operation and the exact app and
|
|
513
|
+
// version it acted on; it is the only place a failed submission says what it
|
|
514
|
+
// tried to do.
|
|
515
|
+
const detail = storeText(result, 'status_detail');
|
|
516
|
+
const terminal = (Number.isFinite(percent) && percent >= 100) || status === '3' || Boolean(error);
|
|
517
|
+
return {
|
|
518
|
+
tracker_id: id,
|
|
519
|
+
status,
|
|
520
|
+
status_label: label || null,
|
|
521
|
+
status_message: message || null,
|
|
522
|
+
status_detail: detail || null,
|
|
523
|
+
percent_complete: Number.isFinite(percent) ? percent : null,
|
|
524
|
+
error: error || null,
|
|
525
|
+
terminal,
|
|
526
|
+
succeeded: terminal && !error && status !== '3',
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Poll a tracker until it is terminal or the wait expires.
|
|
532
|
+
*
|
|
533
|
+
* An expired wait means the operation is still on the instance: the result
|
|
534
|
+
* keeps the tracker id and says so, and nothing is cancelled or resubmitted.
|
|
535
|
+
*/
|
|
536
|
+
export async function waitForOperation(sdk, trackerId, {
|
|
537
|
+
pollIntervalMs = 5000, timeoutMs = 1800_000, onProgress, now = Date.now, wait = sleep,
|
|
538
|
+
} = {}) {
|
|
539
|
+
const startedAt = now();
|
|
540
|
+
let progress = await operationStatus(sdk, trackerId);
|
|
541
|
+
onProgress?.(progress);
|
|
542
|
+
while (!progress.terminal && now() - startedAt < timeoutMs) {
|
|
543
|
+
const remaining = timeoutMs - (now() - startedAt);
|
|
544
|
+
await wait(Math.max(0, Math.min(pollIntervalMs, remaining)));
|
|
545
|
+
progress = await operationStatus(sdk, trackerId);
|
|
546
|
+
onProgress?.(progress);
|
|
547
|
+
}
|
|
548
|
+
return { ...progress, wait_timed_out: !progress.terminal };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Read the installed record back after a reported success. A reported success
|
|
553
|
+
* is not a completed installation until the instance shows the version.
|
|
554
|
+
*
|
|
555
|
+
* verified: true — readback shows the requested version
|
|
556
|
+
* verified: false — readback shows a different version (or no record)
|
|
557
|
+
* verified: null — the record could not be read, so nothing is claimed
|
|
558
|
+
*/
|
|
559
|
+
export async function verifyInstalledVersion(sdk, { sys_id: sysId }, expectedVersion, {
|
|
560
|
+
attempts = MAX_VERSION_ATTEMPTS, intervalMs = DEFAULT_VERIFY_INTERVAL_MS, wait = sleep,
|
|
561
|
+
} = {}) {
|
|
562
|
+
let record = null;
|
|
563
|
+
let readable = false;
|
|
564
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
565
|
+
try {
|
|
566
|
+
record = await sdk.get('sys_store_app', sysId);
|
|
567
|
+
readable = true;
|
|
568
|
+
} catch (error) {
|
|
569
|
+
if (error?.status !== 403 && error?.status !== 404) throw error;
|
|
570
|
+
readable = false;
|
|
571
|
+
record = null;
|
|
572
|
+
}
|
|
573
|
+
if (readable && record && storeText(record, 'version') === expectedVersion) break;
|
|
574
|
+
if (attempt < attempts - 1 && intervalMs > 0) await wait(intervalMs);
|
|
575
|
+
}
|
|
576
|
+
if (!readable) {
|
|
577
|
+
return { verified: null, expected_version: expectedVersion, installed_version: null, source: 'sys_store_app', reason: 'readback_unavailable' };
|
|
578
|
+
}
|
|
579
|
+
const installed = storeText(record, 'version');
|
|
580
|
+
return {
|
|
581
|
+
verified: Boolean(record) && installed === expectedVersion,
|
|
582
|
+
expected_version: expectedVersion,
|
|
583
|
+
installed_version: installed || null,
|
|
584
|
+
active: record ? storeFlag(record.active) : null,
|
|
585
|
+
source: 'sys_store_app',
|
|
586
|
+
reason: !record ? 'record_missing' : (installed === expectedVersion ? 'version_confirmed' : 'version_mismatch'),
|
|
587
|
+
};
|
|
588
|
+
}
|