priority-axi 0.0.0-stage → 0.2.0

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,264 @@
1
+ // get, changes and show: reads through $filter, never with a key in the path.
2
+ import { AxiError, usage } from '../errors.js';
3
+ import { rowsOf } from '../http.js';
4
+ import { resolveField, resolveScreen, resolveSub, } from '../index/build.js';
5
+ import { combineFilters, literal, orderBy, parseWhere, queryString, whereToFilter, } from '../odata.js';
6
+ import { defaultColumns, recordView, tableRow } from '../output/shape.js';
7
+ import { bounded, render } from '../output/toon.js';
8
+ import { builtNote, commandLine, intFlag, open, readScreen, screenIndex, shellWord, sinceFlag, str, strings, } from './common.js';
9
+ /** Fields asked for when no --fields is given: the key and the first candidates in form order. */
10
+ const CANDIDATES = 12;
11
+ /** Sub-screen lines shown per record without --full. */
12
+ const LINES = 5;
13
+ function candidateSelect(type) {
14
+ const keys = type.key.filter((k) => type.fields.some((f) => f.name === k));
15
+ const rest = type.fields
16
+ .filter((f) => !f.internalId && !keys.includes(f.name))
17
+ .slice(0, CANDIDATES)
18
+ .map((f) => f.name);
19
+ return [...keys, ...rest];
20
+ }
21
+ /**
22
+ * $expand for --with. Without --full, each line list is narrowed and capped on
23
+ * the server: Priority 23.1 honours $select and $top inside $expand (live S9),
24
+ * so a large order does not send every line. One extra line shows that more exist.
25
+ */
26
+ function expandOf(subs, full) {
27
+ if (!subs.length)
28
+ return undefined;
29
+ return subs
30
+ .map((x) => !x.many || full
31
+ ? x.nav
32
+ : `${x.nav}($select=${candidateSelect(x.def).join(',')};$top=${LINES + 1})`)
33
+ .join(',');
34
+ }
35
+ function explicitFields(type, screen, raw) {
36
+ if (raw === undefined)
37
+ return undefined;
38
+ const names = raw
39
+ .split(',')
40
+ .map((n) => n.trim())
41
+ .filter(Boolean);
42
+ if (!names.length)
43
+ throw usage('--fields needs field names, such as --fields CUSTNAME,CDES.');
44
+ const keys = type.key.filter((k) => type.fields.some((f) => f.name === k));
45
+ const chosen = names.map((n) => resolveField(type, screen, n).name);
46
+ return [...keys, ...chosen.filter((n) => !keys.includes(n))];
47
+ }
48
+ /** Lines of one sub-screen in a record, as a small table or one record. */
49
+ function subView(sub, value, fieldLimit, full) {
50
+ if (!sub.many) {
51
+ const one = value && typeof value === 'object' && !Array.isArray(value)
52
+ ? value
53
+ : undefined;
54
+ return { [sub.name]: one ? recordView(sub.def, one, fieldLimit) : null };
55
+ }
56
+ const lines = Array.isArray(value) ? value : [];
57
+ const shown = full ? lines : lines.slice(0, LINES);
58
+ const columns = defaultColumns(sub.def, shown);
59
+ return {
60
+ [sub.name]: shown.map((line) => tableRow(sub.def, line, columns, fieldLimit)),
61
+ ...(shown.length < lines.length
62
+ ? { [`${sub.name}_more`]: 'more lines exist; --full shows all' }
63
+ : {}),
64
+ };
65
+ }
66
+ function resolveWith(index, screen, raw) {
67
+ const subs = strings(raw).map((w) => resolveSub(index, screen, w));
68
+ return subs.filter((sub, i) => subs.findIndex((x) => x.nav === sub.nav) === i);
69
+ }
70
+ async function list(input, mode) {
71
+ const s = open(input);
72
+ const loaded = await screenIndex(s);
73
+ const { index } = loaded;
74
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
75
+ const v = input.values;
76
+ const limit = intFlag(v.limit, 'limit', 20, 1, 500);
77
+ const page = intFlag(v.page, 'page', 1, 1, 1_000_000);
78
+ const full = v.full === true;
79
+ const since = mode === 'changes' ? sinceFlag(v.since, input.io.now()) : undefined;
80
+ const filter = combineFilters(whereToFilter(strings(v.where), screen.type, screen.name), str(v.filter));
81
+ const keys = screen.type.key.filter((k) => screen.type.fields.some((f) => f.name === k));
82
+ const order = str(v.sort)
83
+ ? orderBy(String(v.sort), screen.type, screen.name)
84
+ : keys.join(',') || undefined;
85
+ const explicit = explicitFields(screen.type, screen.name, str(v.fields));
86
+ const subs = resolveWith(index, screen, v.with);
87
+ const select = explicit ?? (full ? undefined : candidateSelect(screen.type));
88
+ const answer = await readScreen(s, screen.name, queryString({
89
+ $filter: filter,
90
+ $select: select?.join(','),
91
+ $orderby: order,
92
+ $top: limit + 1,
93
+ $skip: page > 1 ? (page - 1) * limit : undefined,
94
+ $expand: expandOf(subs, full),
95
+ $since: since,
96
+ }));
97
+ const fetched = rowsOf(answer);
98
+ const more = fetched.length > limit;
99
+ const rows = fetched.slice(0, limit);
100
+ const columns = explicit ??
101
+ (full
102
+ ? screen.type.fields
103
+ .filter((f) => keys.includes(f.name) ||
104
+ (!f.internalId &&
105
+ rows.some((r) => r[f.name] !== null &&
106
+ r[f.name] !== '' &&
107
+ r[f.name] !== undefined)))
108
+ .map((f) => f.name)
109
+ : defaultColumns(screen.type, rows));
110
+ const noun = rows.length === 1 ? 'record' : 'records';
111
+ const place = mode === 'changes' ? ` changed since ${since}` : '';
112
+ const pageNote = page > 1 ? ` (page ${page})` : '';
113
+ const summary = `${rows.length} ${noun} from ${screen.name}${place}${pageNote}${more ? ', more exist' : ''}`;
114
+ if (!rows.length) {
115
+ const help = filter || since
116
+ ? [
117
+ `Run \`priority-axi fields ${screen.name}\` to check value types if you expected records; the filter's field names are valid, so no record matched`,
118
+ ]
119
+ : [];
120
+ return render({ summary, ...builtNote(loaded) }, help);
121
+ }
122
+ return bounded({
123
+ total: rows.length,
124
+ narrower: commandLine(mode, [screen.name], v, {
125
+ full: null,
126
+ limit: '20',
127
+ }),
128
+ build: (shown, fieldLimit) => {
129
+ const records = rows.slice(0, shown).map((row) => {
130
+ const base = tableRow(screen.type, row, columns, fieldLimit);
131
+ for (const sub of subs) {
132
+ Object.assign(base, subView(sub, row[sub.nav], fieldLimit, full));
133
+ }
134
+ return base;
135
+ });
136
+ const help = [];
137
+ if (more) {
138
+ help.push(`Run \`${commandLine(mode, [screen.name], v, { page: String(page + 1) })}\` for the next ${limit}`);
139
+ }
140
+ if (keys.length === 1) {
141
+ help.push(`Run \`priority-axi show ${screen.name} <${keys[0]}>\` for one record`);
142
+ }
143
+ return render({
144
+ summary,
145
+ ...builtNote(loaded),
146
+ records,
147
+ ...(shown < rows.length
148
+ ? {
149
+ omitted: `${rows.length - shown} records not shown; use --limit ${Math.max(1, shown)} or --full`,
150
+ }
151
+ : {}),
152
+ }, help);
153
+ },
154
+ }, full);
155
+ }
156
+ export const get = (input) => list(input, 'get');
157
+ export const changes = (input) => list(input, 'changes');
158
+ /** Key terms from a positional value (one-field keys) or --key F=V flags (compound keys). */
159
+ function keyTerms(screen, positional, flags) {
160
+ const keys = screen.type.key.filter((k) => screen.type.fields.some((f) => f.name === k));
161
+ if (!keys.length) {
162
+ throw usage(`${screen.name} has no key. Use \`priority-axi get ${screen.name} --where F=V\` instead.`);
163
+ }
164
+ if (positional !== undefined && flags.length)
165
+ throw usage('Give the key as an argument or with --key, not both.');
166
+ if (positional !== undefined) {
167
+ if (keys.length > 1) {
168
+ throw usage(`${screen.name} has a compound key (${keys.join(', ')}). Use ${keys.map((k) => `--key ${k}=<value>`).join(' ')}.`);
169
+ }
170
+ return [[keys[0] ?? '', positional]];
171
+ }
172
+ if (!flags.length) {
173
+ throw usage(keys.length === 1
174
+ ? `Missing the ${keys[0]} value: priority-axi show ${screen.name} <${keys[0]}>.`
175
+ : `Missing the key: ${keys.map((k) => `--key ${k}=<value>`).join(' ')}.`);
176
+ }
177
+ const terms = flags.map((flag) => {
178
+ const term = parseWhere(flag);
179
+ if (term.op !== '=')
180
+ throw usage('--key takes FIELD=VALUE.');
181
+ return [
182
+ resolveField(screen.type, screen.name, term.field).name,
183
+ term.value,
184
+ ];
185
+ });
186
+ const named = terms.map(([f]) => f);
187
+ const missing = keys.filter((k) => !named.includes(k));
188
+ const extra = named.filter((f) => !keys.includes(f));
189
+ if (missing.length || extra.length || new Set(named).size !== named.length) {
190
+ throw usage(`${screen.name}'s key is ${keys.join(', ')}; give each exactly once with --key.`);
191
+ }
192
+ return terms;
193
+ }
194
+ export async function show(input) {
195
+ const s = open(input);
196
+ const { index } = await screenIndex(s);
197
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
198
+ const v = input.values;
199
+ const full = v.full === true;
200
+ const all = v.all === true;
201
+ const terms = keyTerms(screen, input.positionals[1], strings(v.key));
202
+ const fieldOf = (name) => screen.type.fields.find((f) => f.name === name);
203
+ const filter = terms
204
+ .map(([name, value]) => {
205
+ const field = fieldOf(name);
206
+ if (!field)
207
+ throw usage(`${screen.name} has no field ${name}.`);
208
+ return `${name} eq ${literal(field, value)}`;
209
+ })
210
+ .join(' and ');
211
+ const subs = resolveWith(index, screen, v.with);
212
+ const answer = await readScreen(s, screen.name, queryString({
213
+ $filter: filter,
214
+ $top: 2,
215
+ $expand: expandOf(subs, full),
216
+ }));
217
+ const rows = rowsOf(answer);
218
+ const keyText = terms.map(([f, value]) => `${f} ${value}`).join(', ');
219
+ if (!rows.length) {
220
+ throw new AxiError('not_found', `No ${screen.name} record has ${keyText}. Run \`priority-axi get ${screen.name} --limit 5\` to see records.`, { screen: screen.name });
221
+ }
222
+ if (rows.length > 1) {
223
+ throw new AxiError('priority_rejected', `More than one ${screen.name} record has ${keyText}.`, {
224
+ screen: screen.name,
225
+ });
226
+ }
227
+ const row = rows[0] ?? {};
228
+ const keyNames = terms.map(([f]) => f);
229
+ const fullCommand = commandLine('show', input.positionals, v, { full: '' });
230
+ return bounded({
231
+ total: screen.type.fields.length,
232
+ narrower: `priority-axi show ${input.positionals.map(shellWord).join(' ')}`,
233
+ build: (shown, fieldLimit) => {
234
+ const view = recordView(screen.type, row, fieldLimit, all);
235
+ const ordered = {};
236
+ for (const k of keyNames)
237
+ if (k in view)
238
+ ordered[k] = view[k];
239
+ for (const [k, value] of Object.entries(view))
240
+ if (!(k in ordered))
241
+ ordered[k] = value;
242
+ const entries = Object.entries(ordered);
243
+ const record = Object.fromEntries(entries.slice(0, shown));
244
+ const omitted = entries.length - Math.min(shown, entries.length);
245
+ const lines = {};
246
+ for (const sub of subs) {
247
+ Object.assign(lines, subView(sub, row[sub.nav], fieldLimit, full));
248
+ }
249
+ // Fields cut at the standard 500 carry their own marker; say more only
250
+ // when fields were dropped or cut shorter to fit.
251
+ const shortened = omitted > 0 || fieldLimit < 500;
252
+ return render({
253
+ screen: screen.name,
254
+ record,
255
+ ...lines,
256
+ ...(shortened
257
+ ? {
258
+ more: `${omitted ? `${omitted} more fields; ` : ''}run ${fullCommand}`,
259
+ }
260
+ : {}),
261
+ });
262
+ },
263
+ }, full);
264
+ }
@@ -0,0 +1,26 @@
1
+ // Rebuild the screen index now.
2
+ import { loadIndex } from '../index/cache.js';
3
+ import { render } from '../output/toon.js';
4
+ import { checkCompany, indexSource, open, priorityVersion } from './common.js';
5
+ export async function refresh(input) {
6
+ const s = open(input);
7
+ const version = await priorityVersion(s);
8
+ await checkCompany(s, true);
9
+ const { index, rebuilt } = await loadIndex(s.dir, indexSource(s), {
10
+ now: input.io.now(),
11
+ refresh: true,
12
+ liveVersion: version,
13
+ });
14
+ const types = Object.values(index.types);
15
+ const doc = {
16
+ index: 'rebuilt',
17
+ version: index.version,
18
+ screens: Object.keys(index.sets).length,
19
+ types: types.length,
20
+ fields: types.reduce((n, t) => n + t.fields.length, 0),
21
+ };
22
+ if (rebuilt) {
23
+ doc.metadata = `${(rebuilt.bytes / 2 ** 20).toFixed(1)} MB in ${(rebuilt.ms / 1000).toFixed(1)} s`;
24
+ }
25
+ return render(doc, ['Run `priority-axi` for the home view']);
26
+ }
@@ -0,0 +1,124 @@
1
+ // update, add-line and update-line: change a record that exists. Each checks
2
+ // its fields against the index and sends one request, which inside Comis the
3
+ // Gate holds for the owner's approval. A record is named by its key in the
4
+ // path, NAME('KEY'), the only form the Gate's record type takes.
5
+ import { serviceRoot } from '../config.js';
6
+ import { usage } from '../errors.js';
7
+ import { send } from '../http.js';
8
+ import { resolveScreen, resolveSub, } from '../index/build.js';
9
+ import { recordSegment } from '../odata.js';
10
+ import { defaultColumns, tableRow } from '../output/shape.js';
11
+ import { render } from '../output/toon.js';
12
+ import { open, screenIndex, strings, tokenLine } from './common.js';
13
+ import { assign } from './create.js';
14
+ function fields(type, where, terms) {
15
+ const body = {};
16
+ for (const term of terms)
17
+ assign(type, where, body, term);
18
+ if (!Object.keys(body).length)
19
+ throw usage('Nothing to change: give --set FIELD=VALUE.');
20
+ for (const key of type.key)
21
+ if (key in body)
22
+ throw usage(`${key} names the record; an update cannot change it.`);
23
+ return body;
24
+ }
25
+ function keyOf(input, at, what) {
26
+ const key = input.positionals[at] ?? '';
27
+ if (!key)
28
+ throw usage(`Give ${what}.`);
29
+ return key;
30
+ }
31
+ async function write(input, s, w, command) {
32
+ const root = new URL(serviceRoot(s.settings)).pathname;
33
+ if (input.values['dry-run'] === true) {
34
+ return render({
35
+ dry_run: true,
36
+ request: `${w.method} ${root}/${w.path}`,
37
+ body: w.body,
38
+ transactions: 1,
39
+ }, [
40
+ `Run \`${tokenLine(command, input.tokens, ['dry-run'])}\` to send it; inside Comis the owner approves it first`,
41
+ ]);
42
+ }
43
+ // Sent once. A write is never retried; a held write is waited on with comis action wait.
44
+ const answer = await send(s.settings, {
45
+ method: w.method,
46
+ path: w.path,
47
+ body: w.body,
48
+ context: { screen: w.screen.name },
49
+ }, input.io.http);
50
+ const record = answer.json &&
51
+ typeof answer.json === 'object' &&
52
+ !Array.isArray(answer.json)
53
+ ? answer.json
54
+ : undefined;
55
+ return render({
56
+ [w.done]: w.screen.name,
57
+ request: `${w.method} ${root}/${w.path}`,
58
+ transactions: 1,
59
+ record: record
60
+ ? tableRow(w.shown, record, defaultColumns(w.shown, [record]), 500)
61
+ : null,
62
+ }, [
63
+ `Run \`priority-axi show ${w.screen.name} ${keyOf(input, 1, 'the key')} --with <SUB>\` to read it back`,
64
+ ]);
65
+ }
66
+ /** update <SCREEN> <key> --set F=V: change fields of one record. */
67
+ export async function update(input) {
68
+ const s = open(input);
69
+ const { index } = await screenIndex(s);
70
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
71
+ const key = keyOf(input, 1, `the key of the ${screen.name} record after the screen`);
72
+ const body = fields(screen.type, screen.name, strings(input.values.set));
73
+ return write(input, s, {
74
+ method: 'PATCH',
75
+ screen,
76
+ path: recordSegment(screen.name, screen.type, key),
77
+ body,
78
+ shown: screen.type,
79
+ done: 'updated',
80
+ }, 'update');
81
+ }
82
+ /** add-line <SCREEN> <key> <SUB> <F=V>...: add one line to a record. */
83
+ export async function addLine(input) {
84
+ const s = open(input);
85
+ const { index } = await screenIndex(s);
86
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
87
+ const key = keyOf(input, 1, `the key of the ${screen.name} record after the screen`);
88
+ const sub = resolveSub(index, screen, keyOf(input, 2, 'the sub-screen after the key'));
89
+ if (!sub.many)
90
+ throw usage(`${screen.name} > ${sub.name} holds one record; change it with update-line.`);
91
+ const where = `${screen.name} > ${sub.name}`;
92
+ const body = {};
93
+ for (const term of input.positionals.slice(3))
94
+ assign(sub.def, where, body, term);
95
+ if (!Object.keys(body).length)
96
+ throw usage(`Give the new line's fields after ${sub.name}, as FIELD=VALUE.`);
97
+ return write(input, s, {
98
+ method: 'POST',
99
+ screen,
100
+ path: `${recordSegment(screen.name, screen.type, key)}/${sub.nav}`,
101
+ body,
102
+ shown: sub.def,
103
+ done: 'added',
104
+ }, 'add-line');
105
+ }
106
+ /** update-line <SCREEN> <key> <SUB> <line-key> --set F=V: change one line. */
107
+ export async function updateLine(input) {
108
+ const s = open(input);
109
+ const { index } = await screenIndex(s);
110
+ const screen = resolveScreen(index, input.positionals[0] ?? '');
111
+ const key = keyOf(input, 1, `the key of the ${screen.name} record after the screen`);
112
+ const sub = resolveSub(index, screen, keyOf(input, 2, 'the sub-screen after the key'));
113
+ const line = keyOf(input, 3, `the line's key after ${sub.name}, such as ${sub.def.key.map((k) => `${k}=1`).join(',') || 'its number'}`);
114
+ const where = `${screen.name} > ${sub.name}`;
115
+ const body = fields(sub.def, where, strings(input.values.set));
116
+ return write(input, s, {
117
+ method: 'PATCH',
118
+ screen,
119
+ path: `${recordSegment(screen.name, screen.type, key)}/${recordSegment(sub.nav, sub.def, sub.def.key.length === 1 ? line.replace(new RegExp(`^${sub.def.key[0]}=`, 'i'), '') : line, true)}`,
120
+ body,
121
+ shown: sub.def,
122
+ done: 'updated',
123
+ }, 'update-line');
124
+ }
package/dist/config.js ADDED
@@ -0,0 +1,76 @@
1
+ // Settings come from the environment and from flags; flags win. The password
2
+ // is only ever read from PRIORITY_PASSWORD, which inside Comis holds a
3
+ // placeholder that the Gate swaps for the real one.
4
+ import { AxiError, usage } from './errors.js';
5
+ // The Gate's named path segment: [A-Za-z0-9._~-]+. A segment outside it, such
6
+ // as "tabula.ini,3", would not match any Gate rule.
7
+ const SEGMENT = /^[A-Za-z0-9._~-]+$/;
8
+ const SERVICE_ROOT = /^(https?:\/\/[^/]+)\/odata\/Priority\/([^/]+)\/([^/]+)\/?$/i;
9
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1)$/;
10
+ function originOf(raw) {
11
+ let url;
12
+ try {
13
+ url = new URL(raw);
14
+ }
15
+ catch {
16
+ throw usage('PRIORITY_URL is not a URL. Use https://host or the full service root https://host/odata/Priority/<ini>/<company>.');
17
+ }
18
+ if (url.username || url.password) {
19
+ throw usage('PRIORITY_URL must not contain a username or password.');
20
+ }
21
+ const plainLocal = url.protocol === 'http:' && LOCAL_HOST.test(url.hostname);
22
+ if (url.protocol !== 'https:' && !plainLocal) {
23
+ throw usage('PRIORITY_URL must use https.');
24
+ }
25
+ if ((url.pathname !== '/' && url.pathname !== '') || url.search || url.hash) {
26
+ throw usage('PRIORITY_URL must be https://host or the full service root https://host/odata/Priority/<ini>/<company>.');
27
+ }
28
+ return url.origin;
29
+ }
30
+ function segment(value, name) {
31
+ if (!SEGMENT.test(value)) {
32
+ throw usage(`${name} may contain only letters, digits and . _ ~ - (no commas or slashes).`);
33
+ }
34
+ return value;
35
+ }
36
+ export function readSettings(env, flags = {}) {
37
+ const rawUrl = (env.PRIORITY_URL ?? '').trim();
38
+ const password = env.PRIORITY_PASSWORD ?? '';
39
+ if (!rawUrl || !password) {
40
+ const missing = !rawUrl ? 'PRIORITY_URL' : 'PRIORITY_PASSWORD';
41
+ throw new AxiError('not_connected', `Priority is not connected: ${missing} is not set. Ask the owner to run \`comis connect priority\`.`);
42
+ }
43
+ let fromUrl = {};
44
+ let origin;
45
+ const root = SERVICE_ROOT.exec(rawUrl);
46
+ if (root?.[1] && root[2] && root[3]) {
47
+ origin = originOf(root[1]);
48
+ fromUrl = { ini: root[2], company: root[3] };
49
+ }
50
+ else {
51
+ origin = originOf(rawUrl.replace(/\/+$/, ''));
52
+ }
53
+ const ini = flags.ini || env.PRIORITY_INI || fromUrl.ini || 'tabula.ini';
54
+ const company = flags.company || env.PRIORITY_COMPANY || fromUrl.company || '';
55
+ const user = flags.user || env.PRIORITY_USER || '';
56
+ if (!company) {
57
+ throw new AxiError('missing_setting', 'No Priority company code. Ask the owner for it, then pass --company <code>.');
58
+ }
59
+ if (!user) {
60
+ throw new AxiError('missing_setting', 'No Priority API username. Ask the owner for it, then pass --user <name>.');
61
+ }
62
+ // Basic authentication cannot carry a colon in the username.
63
+ if (user.includes(':') || /\p{Cc}/u.test(user)) {
64
+ throw usage('The username (--user or PRIORITY_USER) must not contain a colon or control characters.');
65
+ }
66
+ return {
67
+ origin,
68
+ ini: segment(ini, 'The ini (--ini or PRIORITY_INI)'),
69
+ company: segment(company, 'The company (--company or PRIORITY_COMPANY)'),
70
+ user,
71
+ password,
72
+ };
73
+ }
74
+ export function serviceRoot(settings) {
75
+ return `${settings.origin}/odata/Priority/${settings.ini}/${settings.company}`;
76
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,149 @@
1
+ // The closed set of error codes and the classifier for HTTP answers from
2
+ // Priority and from the Comis Gate in front of it.
3
+ export class AxiError extends Error {
4
+ code;
5
+ fields;
6
+ constructor(code, message, fields = {}) {
7
+ super(message);
8
+ this.name = 'AxiError';
9
+ this.code = code;
10
+ this.fields = fields;
11
+ }
12
+ get exitCode() {
13
+ return this.code === 'usage' ? 2 : 1;
14
+ }
15
+ }
16
+ export const usage = (message) => new AxiError('usage', message);
17
+ // Priority's "API cannot be run for this screen", in the server's default
18
+ // language (Hebrew here) and in English (the ",3" language suffix).
19
+ export const NOT_ENABLED = [
20
+ /לא ניתן להפעיל API למסך זה/,
21
+ /API cannot be run for this (form|screen)/i,
22
+ ];
23
+ // Priority's "the company name sent is wrong, or switching company failed".
24
+ // Priority's "$since is supported only for screens with BPM" (QA, 23.1).
25
+ export const SINCE_NEEDS_BPM = [
26
+ /\$since[\s\S]*BPM/i,
27
+ /BPM[\s\S]*\$since/i,
28
+ ];
29
+ export const BAD_COMPANY = [
30
+ /שם החברה שנשלח לא תקין/,
31
+ /problem changing companies/i,
32
+ ];
33
+ const ENTITIES = {
34
+ amp: '&',
35
+ lt: '<',
36
+ gt: '>',
37
+ quot: '"',
38
+ apos: "'",
39
+ };
40
+ function xmlText(raw) {
41
+ return raw
42
+ .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')
43
+ .replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, name) => {
44
+ if (name[0] !== '#')
45
+ return ENTITIES[name.toLowerCase()] ?? whole;
46
+ const code = name[1] === 'x' || name[1] === 'X'
47
+ ? Number.parseInt(name.slice(2), 16)
48
+ : Number(name.slice(1));
49
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
50
+ });
51
+ }
52
+ /** Texts inside Priority's InterfaceErrors, in JSON ({text} or [{text}]) or XML. */
53
+ function interfaceErrors(json, text) {
54
+ const form = json
55
+ ?.FORM;
56
+ const found = form?.InterfaceErrors;
57
+ if (found !== undefined) {
58
+ const items = Array.isArray(found) ? found : [found];
59
+ return items
60
+ .flatMap((item) => {
61
+ const t = item && typeof item === 'object'
62
+ ? item.text
63
+ : item;
64
+ return Array.isArray(t) ? t : [t];
65
+ })
66
+ .map((t) => typeof t === 'object' && t ? t['#text'] : t)
67
+ .filter((t) => typeof t === 'string' && !!t.trim())
68
+ .map((t) => t.trim());
69
+ }
70
+ const block = text && /<InterfaceErrors\b[^>]*>([\s\S]*?)<\/InterfaceErrors>/i.exec(text);
71
+ if (!block?.[1])
72
+ return [];
73
+ return [...block[1].matchAll(/<text\b[^>]*>([\s\S]*?)<\/text>/gi)]
74
+ .map((m) => xmlText(m[1] ?? '').trim())
75
+ .filter(Boolean);
76
+ }
77
+ /** Priority's own words: an OData error message, or its form errors. */
78
+ export function priorityMessage(json, text) {
79
+ const error = json && typeof json === 'object'
80
+ ? json.error
81
+ : undefined;
82
+ const message = error && typeof error === 'object'
83
+ ? error.message
84
+ : undefined;
85
+ if (typeof message === 'string' && message.trim())
86
+ return message.trim();
87
+ const form = interfaceErrors(json, text);
88
+ return form.length ? form.join(' ') : undefined;
89
+ }
90
+ // Gate refusal codes with a sentence the agent can act on. Others fall back to
91
+ // a generic sentence that still carries the code.
92
+ const GATE_REFUSALS = {
93
+ secret_response: "The Gate withheld Priority's answer because it carried a credential.",
94
+ body_forgotten: 'The Gate no longer holds the body of this request. Run the command again only if the owner asks.',
95
+ out_of_budget: 'The Gate refused this request: the spending budget is used up.',
96
+ };
97
+ export function classify(answer, ctx = {}) {
98
+ const { status, headers, json } = answer;
99
+ const refusal = headers.get('comis-refusal');
100
+ const action = headers.get('comis-action')?.split(';')[0]?.trim();
101
+ if (status >= 200 && status < 300)
102
+ return null;
103
+ const screen = ctx.screen ? { screen: ctx.screen } : {};
104
+ if (refusal === 'approval_pending' || (status === 409 && action)) {
105
+ const id = action || 'unknown';
106
+ return new AxiError('held_for_approval', `The owner has an approval card for this request. Do not retry. Run \`comis action wait ${id}\`.`, { action: id });
107
+ }
108
+ if (refusal === 'reconnect_needed') {
109
+ return new AxiError('reconnect_needed', 'Priority refused the stored credential. Ask the owner to reconnect Priority.');
110
+ }
111
+ if (refusal) {
112
+ return new AxiError('refused', GATE_REFUSALS[refusal] ?? `The Gate refused this request (${refusal}).`, { refusal, ...screen });
113
+ }
114
+ const message = priorityMessage(json, answer.text);
115
+ if (status === 401) {
116
+ return new AxiError('auth_failed', 'Priority rejected the username or password. Check PRIORITY_USER and PRIORITY_PASSWORD.');
117
+ }
118
+ if (status === 400 && message && NOT_ENABLED.some((rx) => rx.test(message))) {
119
+ const name = ctx.screen ?? 'this screen';
120
+ return new AxiError('screen_not_enabled', `Priority does not allow API access to ${name}. Ask the owner to have the Priority administrator add ${name} to Limited Access/API Forms.`, { ...screen, priority: message });
121
+ }
122
+ if (status === 400 &&
123
+ message &&
124
+ SINCE_NEEDS_BPM.some((rx) => rx.test(message))) {
125
+ const name = ctx.screen ?? 'This screen';
126
+ return new AxiError('unsupported_query', `${name} has no status workflow (BPM) in Priority, and Priority tracks changes only on screens that have one. Use \`priority-axi get ${ctx.screen ?? '<SCREEN>'}\` with --where on a date field instead; \`priority-axi fields ${ctx.screen ?? '<SCREEN>'}\` lists them.`, { ...screen, priority: message });
127
+ }
128
+ if (status === 400 && message && BAD_COMPANY.some((rx) => rx.test(message))) {
129
+ return new AxiError('company_not_found', `Priority does not know company ${ctx.company ?? 'given'}. Check the company code with the owner.`, { priority: message });
130
+ }
131
+ if (status === 404) {
132
+ return new AxiError('not_found', ctx.screen
133
+ ? `Priority has no ${ctx.screen}. Check the name with \`priority-axi screens\`.`
134
+ : 'Priority answered 404 Not Found.', screen);
135
+ }
136
+ if (status === 409) {
137
+ return new AxiError('already_exists', 'Priority says this record already exists. Read it instead of creating it.', { ...screen, ...(message ? { priority: message } : {}) });
138
+ }
139
+ if (status === 429) {
140
+ return new AxiError('rate_limited', 'Priority is limiting requests. Wait a minute, then try again.');
141
+ }
142
+ if (status === 501) {
143
+ return new AxiError('unsupported_query', `Priority cannot run this query: ${message ?? 'not supported'}. Use the --where operators =, !=, >, >=, < and <=.`, screen);
144
+ }
145
+ if (status >= 400 && status < 500) {
146
+ return new AxiError('priority_rejected', message ?? `Priority answered ${status} with no message.`, { ...screen, status });
147
+ }
148
+ return new AxiError('priority_error', message ?? `Priority answered ${status} with no message.`, { ...screen, status });
149
+ }