priority-axi 0.2.0 → 0.2.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 +24 -18
- package/dist/cli/parse.js +3 -2
- package/dist/cli/run.js +16 -6
- package/dist/commands/common.js +6 -3
- package/dist/commands/create.js +65 -4
- package/dist/commands/find.js +15 -10
- package/dist/commands/read.js +58 -11
- package/dist/commands/refresh.js +3 -1
- package/dist/commands/update.js +2 -2
- package/dist/config.js +11 -1
- package/dist/errors.js +40 -7
- package/dist/http.js +140 -13
- package/dist/index/cache.js +93 -6
- package/dist/index/catalog.js +1 -1
- package/dist/odata.js +28 -3
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ Until then, reads end with `code: screen_not_enabled`. The home view, `screens`,
|
|
|
57
57
|
priority-axi home view: connection, version, company, next steps
|
|
58
58
|
priority-axi screens [<text>] find screens by name or description
|
|
59
59
|
priority-axi fields <SCREEN> [--sub <SUB>] a screen's fields, key and sub-screens
|
|
60
|
-
priority-axi get <SCREEN> [--where F=V]... [--fields A,B] [--with <SUB>]... [--sort F[:desc]] [--limit N] [--page N]
|
|
60
|
+
priority-axi get <SCREEN> [--where F=V]... [--fields A,B] [--with <SUB>]... [--sort F[:desc]] [--limit N] [--page N | --offset N]
|
|
61
61
|
priority-axi show <SCREEN> <key> [--with <SUB>]...
|
|
62
62
|
priority-axi changes <SCREEN> --since 7d recent changes, on screens with a BPM status workflow
|
|
63
63
|
priority-axi find <SCREEN> <words>... records by words in their name or description
|
|
@@ -111,6 +111,8 @@ priority-axi update-line ORDERS SO26000102 ORDERITEMS KLINE=1 --set TQUANT=3 --d
|
|
|
111
111
|
|
|
112
112
|
`--where` takes `F=V`, `F!=V`, `F>V`, `F>=V`, `F<V` and `F<=V`. Values are typed from the screen's metadata, so you never write OData quotes. `--filter` passes raw OData for anything else the server supports.
|
|
113
113
|
|
|
114
|
+
**Dates and times are Priority's local (company) time,** in `--where`, `--set` and `--json-file`: write `2026-11-20` or `2026-11-20T08:00`. priority-axi sends the digits as written. Priority ignores an offset such as `+02:00`, so priority-axi drops it and never converts the time to UTC. `changes --since` is the exception: it takes UTC, such as `2026-11-01T06:00:00Z`, or `7d` and `24h`.
|
|
115
|
+
|
|
114
116
|
Priority answers 501 to `contains` and `startswith`. For text that starts with `ABC`, use a range: `--where 'F>=ABC' --where 'F<ABD'`.
|
|
115
117
|
|
|
116
118
|
Always filter large document screens such as orders and invoices. Without a filter, Priority goes through every record before it answers, even when you ask for one.
|
|
@@ -127,28 +129,29 @@ Records that are not in use are left out unless you pass `--all`. When no record
|
|
|
127
129
|
|
|
128
130
|
## Output and errors
|
|
129
131
|
|
|
130
|
-
- **Lists** say how many records they show and whether more exist. Priority reports no totals.
|
|
132
|
+
- **Lists** say how many records they show and whether more exist. Priority reports no totals. When the size limit drops records, the summary says `N of M shown`, and the next-page hint continues with `--offset` at the first record not shown.
|
|
131
133
|
- **Size:** long values are cut at 500 characters, and the whole output at about 4,000. `--full` lifts both limits, up to 256 KB.
|
|
132
134
|
- **Text safety:** invisible and bidirectional control characters are shown as `\uXXXX`, and values that look like credentials are withheld. Remarks, which Priority stores as HTML, are shown as plain text.
|
|
133
135
|
- **Errors** print `message`, `code` and `usage` on stdout.
|
|
134
136
|
- **Exit codes:** 0 on success, 1 on an error, 2 on a usage error.
|
|
135
137
|
|
|
136
|
-
| Code | Meaning
|
|
137
|
-
| -------------------------------------------------- |
|
|
138
|
-
| `usage` | The command line is wrong; `usage` shows the right form
|
|
139
|
-
| `not_connected`, `missing_setting` | A setting is missing
|
|
140
|
-
| `auth_failed` | Priority refused the username or password
|
|
141
|
-
| `company_not_found` | The API user cannot reach that company
|
|
142
|
-
| `screen_not_enabled` | The screen is not in Limited Access / API Forms
|
|
143
|
-
| `not_found` | No record has that key
|
|
144
|
-
| `already_exists` | A create clashed with an existing key
|
|
145
|
-
| `priority_rejected` | Priority refused the request; its own message is shown
|
|
146
|
-
| `
|
|
147
|
-
| `
|
|
148
|
-
| `
|
|
149
|
-
| `
|
|
150
|
-
| `
|
|
151
|
-
| `
|
|
138
|
+
| Code | Meaning |
|
|
139
|
+
| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
140
|
+
| `usage` | The command line is wrong; `usage` shows the right form |
|
|
141
|
+
| `not_connected`, `missing_setting` | A setting is missing |
|
|
142
|
+
| `auth_failed` | Priority refused the username or password |
|
|
143
|
+
| `company_not_found` | The API user cannot reach that company |
|
|
144
|
+
| `screen_not_enabled` | The screen is not in Limited Access / API Forms |
|
|
145
|
+
| `not_found` | No record has that key |
|
|
146
|
+
| `already_exists` | A create clashed with an existing key |
|
|
147
|
+
| `priority_rejected` | Priority refused the request; its own message is shown |
|
|
148
|
+
| `partly_saved` | Priority saved a new record but refused one of its lines; do not create it again |
|
|
149
|
+
| `unsupported_query` | Priority cannot run that query |
|
|
150
|
+
| `rate_limited` | Too many requests; wait and try again |
|
|
151
|
+
| `held_for_approval`, `reconnect_needed`, `refused` | Inside Comis: the owner must approve, the owner must reconnect, or the Gate refused |
|
|
152
|
+
| `unreachable`, `priority_error` | The server could not be reached, did not answer in time, or failed; after a write, it may have been saved |
|
|
153
|
+
| `output_too_large` | Even `--full` would exceed 256 KB; narrow the query |
|
|
154
|
+
| `internal_error` | A bug in priority-axi; please [report it](https://github.com/comisai/priority-axi/issues) |
|
|
152
155
|
|
|
153
156
|
## Writes
|
|
154
157
|
|
|
@@ -156,6 +159,9 @@ Records that are not in use are left out unless you pass `--all`. When no record
|
|
|
156
159
|
|
|
157
160
|
- **Dry run:** `--dry-run` shows the request and how many API transactions it will cost: one per record and one per line.
|
|
158
161
|
- **Sent once:** a write is never retried. Inside Comis, the Gate holds it until the owner approves it.
|
|
162
|
+
- **When the answer is lost:** if the connection breaks or times out after a write was sent, or Priority answers with a server error, the message says Priority may have saved it. Check with `show` or `get`, and do not send it again blindly.
|
|
163
|
+
- **Partly saved creates:** Priority saves a new record and its lines one by one, with no rollback. When it refuses a line, the record is already saved without it. priority-axi reports `partly_saved`, names the saved record (or the `get` that finds it), and points to `add-line`. Never create it again.
|
|
164
|
+
- **Time limits:** inside Comis, `COMIS_DEADLINE` bounds every command. Reads stop one second before it and say to run the command from a worker. A write is refused without sending when fewer than 50 s remain, since the owner's approval can take 45 s. The first index build and a cold `find` catalog each take about 30 s.
|
|
159
165
|
- **Updates name the record in the path:** `PATCH ORDERS('SO26000102')`, `POST ORDERS('SO26000102')/ORDERITEMS_SUBFORM` and `PATCH ORDERS('SO26000102')/ORDERITEMS_SUBFORM(KLINE=1)`. A key value is a typed literal; it may not hold a slash, a percent sign, a backslash, a control character or two dots in a row, and the record's key fields cannot be changed. Deleting is not supported.
|
|
160
166
|
- **Fields the metadata does not mark:** Priority may require them, and then refuses with `priority_rejected` and its own message.
|
|
161
167
|
|
package/dist/cli/parse.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
import { usage } from '../errors.js';
|
|
6
6
|
import { commandName, } from './table.js';
|
|
7
|
-
|
|
7
|
+
/** "flag --x", or just "flag" when the name is not safe to repeat back. */
|
|
8
|
+
const shownFlag = (raw) => /^--?[A-Za-z0-9][A-Za-z0-9_-]{0,40}$/.test(raw) ? `flag ${raw}` : 'flag';
|
|
8
9
|
export function parseCommand(spec, argv) {
|
|
9
10
|
const name = commandName(spec);
|
|
10
11
|
const options = {};
|
|
@@ -33,7 +34,7 @@ export function parseCommand(spec, argv) {
|
|
|
33
34
|
continue;
|
|
34
35
|
const f = spec.flags[token.name];
|
|
35
36
|
if (!f) {
|
|
36
|
-
throw usage(`Unknown
|
|
37
|
+
throw usage(`Unknown ${shownFlag(token.rawName)} for \`${name}\`. ${valid.length ? `Valid flags: ${valid.join(', ')}.` : 'It takes no flags.'}`);
|
|
37
38
|
}
|
|
38
39
|
if (f.type === 'boolean' && token.inlineValue)
|
|
39
40
|
throw usage(`--${token.name} takes no value.`);
|
package/dist/cli/run.js
CHANGED
|
@@ -64,7 +64,7 @@ export const COMMANDS = [
|
|
|
64
64
|
type: 'string',
|
|
65
65
|
multiple: true,
|
|
66
66
|
value: '<F=V>',
|
|
67
|
-
summary:
|
|
67
|
+
summary: "Filter: F=V, F!=V, F>V, F>=V, F<V or F<=V. Dates and times are Priority's local (company) time",
|
|
68
68
|
},
|
|
69
69
|
filter: {
|
|
70
70
|
type: 'string',
|
|
@@ -89,6 +89,11 @@ export const COMMANDS = [
|
|
|
89
89
|
summary: 'Records per page, default 20, at most 500',
|
|
90
90
|
},
|
|
91
91
|
page: { type: 'string', value: '<n>', summary: 'Page number, default 1' },
|
|
92
|
+
offset: {
|
|
93
|
+
type: 'string',
|
|
94
|
+
value: '<n>',
|
|
95
|
+
summary: 'Records to skip first, instead of --page',
|
|
96
|
+
},
|
|
92
97
|
full: {
|
|
93
98
|
type: 'boolean',
|
|
94
99
|
summary: 'Every non-empty field, no size limit',
|
|
@@ -132,13 +137,13 @@ export const COMMANDS = [
|
|
|
132
137
|
type: 'string',
|
|
133
138
|
required: true,
|
|
134
139
|
value: '<time>',
|
|
135
|
-
summary: 'From when: 7d, 24h, 2026-11-01 or a full UTC time',
|
|
140
|
+
summary: 'From when: 7d, 24h, 2026-11-01 or a full UTC time such as 2026-11-01T06:00:00Z',
|
|
136
141
|
},
|
|
137
142
|
where: {
|
|
138
143
|
type: 'string',
|
|
139
144
|
multiple: true,
|
|
140
145
|
value: '<F=V>',
|
|
141
|
-
summary:
|
|
146
|
+
summary: "Filter, as for get; times are Priority's local time",
|
|
142
147
|
},
|
|
143
148
|
fields: { type: 'string', value: '<A,B>', summary: 'Columns to show' },
|
|
144
149
|
limit: {
|
|
@@ -147,6 +152,11 @@ export const COMMANDS = [
|
|
|
147
152
|
summary: 'Records per page, default 20, at most 500',
|
|
148
153
|
},
|
|
149
154
|
page: { type: 'string', value: '<n>', summary: 'Page number, default 1' },
|
|
155
|
+
offset: {
|
|
156
|
+
type: 'string',
|
|
157
|
+
value: '<n>',
|
|
158
|
+
summary: 'Records to skip first, instead of --page',
|
|
159
|
+
},
|
|
150
160
|
full: {
|
|
151
161
|
type: 'boolean',
|
|
152
162
|
summary: 'Every non-empty field, no size limit',
|
|
@@ -196,7 +206,7 @@ export const COMMANDS = [
|
|
|
196
206
|
type: 'string',
|
|
197
207
|
multiple: true,
|
|
198
208
|
value: '<F=V>',
|
|
199
|
-
summary:
|
|
209
|
+
summary: "A field of the new record; times are Priority's local (company) time",
|
|
200
210
|
},
|
|
201
211
|
line: {
|
|
202
212
|
type: 'string',
|
|
@@ -229,7 +239,7 @@ export const COMMANDS = [
|
|
|
229
239
|
type: 'string',
|
|
230
240
|
multiple: true,
|
|
231
241
|
value: '<F=V>',
|
|
232
|
-
summary:
|
|
242
|
+
summary: "A field to change; times are Priority's local (company) time",
|
|
233
243
|
},
|
|
234
244
|
'dry-run': {
|
|
235
245
|
type: 'boolean',
|
|
@@ -271,7 +281,7 @@ export const COMMANDS = [
|
|
|
271
281
|
type: 'string',
|
|
272
282
|
multiple: true,
|
|
273
283
|
value: '<F=V>',
|
|
274
|
-
summary:
|
|
284
|
+
summary: "A field of the line to change; times are Priority's local (company) time",
|
|
275
285
|
},
|
|
276
286
|
'dry-run': {
|
|
277
287
|
type: 'boolean',
|
package/dist/commands/common.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Shared steps for commands that talk to Priority.
|
|
2
2
|
import { readSettings } from '../config.js';
|
|
3
3
|
import { AxiError, usage } from '../errors.js';
|
|
4
|
-
import { rowsOf, send, stringValue } from '../http.js';
|
|
5
|
-
import { cacheDir, loadIndex, readCompany, readIndex, recordReach, staleReason, writeCompany, } from '../index/cache.js';
|
|
4
|
+
import { rowsOf, send, stringValue, timeLeft } from '../http.js';
|
|
5
|
+
import { cacheDir, LOCK_WAIT_MS, loadIndex, readCompany, readIndex, recordReach, staleReason, writeCompany, } from '../index/cache.js';
|
|
6
6
|
import { screenSegment, utc } from '../odata.js';
|
|
7
7
|
const text = (v) => (typeof v === 'string' ? v : undefined);
|
|
8
8
|
export function open(input) {
|
|
@@ -67,7 +67,10 @@ export async function screenIndex(s) {
|
|
|
67
67
|
if (cached && !staleReason(cached, { now }))
|
|
68
68
|
return { index: cached };
|
|
69
69
|
await checkCompany(s, false);
|
|
70
|
-
return loadIndex(s.dir, indexSource(s), {
|
|
70
|
+
return loadIndex(s.dir, indexSource(s), {
|
|
71
|
+
now,
|
|
72
|
+
lockWaitMs: Math.min(LOCK_WAIT_MS, timeLeft(s.settings, s.input.io.http)),
|
|
73
|
+
});
|
|
71
74
|
}
|
|
72
75
|
/** A note for output when this command had to build the index first. */
|
|
73
76
|
export function builtNote(loaded) {
|
package/dist/commands/create.js
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { serviceRoot } from '../config.js';
|
|
5
5
|
import { AxiError, usage } from '../errors.js';
|
|
6
|
-
import { send } from '../http.js';
|
|
6
|
+
import { rowsOf, send } from '../http.js';
|
|
7
7
|
import { resolveField, resolveScreen, resolveSub, } from '../index/build.js';
|
|
8
8
|
import { recordReach } from '../index/cache.js';
|
|
9
|
-
import { parseWhere, screenSegment,
|
|
9
|
+
import { literal, localTime, parseWhere, queryString, screenSegment, } from '../odata.js';
|
|
10
10
|
import { defaultColumns, tableRow } from '../output/shape.js';
|
|
11
11
|
import { render } from '../output/toon.js';
|
|
12
|
-
import { open, screenIndex, shellWord, str, strings, tokenLine, } from './common.js';
|
|
12
|
+
import { open, readScreen, screenIndex, shellWord, str, strings, tokenLine, } from './common.js';
|
|
13
13
|
const INTEGER = new Set(['Int16', 'Int32', 'Int64', 'Byte', 'SByte']);
|
|
14
14
|
const DECIMAL = new Set(['Decimal', 'Double', 'Single']);
|
|
15
15
|
function writable(field, where) {
|
|
@@ -45,7 +45,7 @@ export function typedValue(field, raw, where) {
|
|
|
45
45
|
return raw === 'true';
|
|
46
46
|
}
|
|
47
47
|
if (field.type === 'DateTimeOffset')
|
|
48
|
-
return
|
|
48
|
+
return localTime(raw, field.name);
|
|
49
49
|
throw usage(`${field.name} has type ${field.type}, which create cannot set.`);
|
|
50
50
|
}
|
|
51
51
|
export function assign(type, where, target, term) {
|
|
@@ -150,6 +150,61 @@ function assemble(body, lines) {
|
|
|
150
150
|
}
|
|
151
151
|
return out;
|
|
152
152
|
}
|
|
153
|
+
/**
|
|
154
|
+
* Priority saves a deep insert line by line and does not roll back: when it
|
|
155
|
+
* refuses line 2 or later (line 1 is the record itself), the record and any
|
|
156
|
+
* earlier lines are saved (live, 23.1), and its answer names no key. Report
|
|
157
|
+
* that as partly_saved, find the saved record with one read, and point to
|
|
158
|
+
* add-line, so the record is never created twice.
|
|
159
|
+
*/
|
|
160
|
+
async function partlySaved(s, screen, header, lines, error) {
|
|
161
|
+
const line = error.formLine ?? 2;
|
|
162
|
+
const keys = screen.type.key.filter((k) => screen.type.fields.some((f) => f.name === k));
|
|
163
|
+
const terms = Object.entries(header).filter((entry) => ['string', 'number', 'boolean'].includes(typeof entry[1]));
|
|
164
|
+
const key = keys.length === 1 ? keys[0] : undefined;
|
|
165
|
+
const lookup = [
|
|
166
|
+
`priority-axi get ${screen.name}`,
|
|
167
|
+
...terms.map(([f, v]) => `--where ${shellWord(`${f}=${String(v)}`)}`),
|
|
168
|
+
...(key ? [`--sort ${key}:desc`] : []),
|
|
169
|
+
'--limit 3',
|
|
170
|
+
].join(' ');
|
|
171
|
+
let found = [];
|
|
172
|
+
if (key && terms.length) {
|
|
173
|
+
try {
|
|
174
|
+
const filter = terms
|
|
175
|
+
.map(([f, v]) => {
|
|
176
|
+
const field = resolveField(screen.type, screen.name, f);
|
|
177
|
+
return `${field.name} eq ${literal(field, String(v))}`;
|
|
178
|
+
})
|
|
179
|
+
.join(' and ');
|
|
180
|
+
const answer = await readScreen(s, screen.name, queryString({
|
|
181
|
+
$filter: filter,
|
|
182
|
+
$select: key,
|
|
183
|
+
$orderby: `${key} desc`,
|
|
184
|
+
$top: 3,
|
|
185
|
+
}));
|
|
186
|
+
found = rowsOf(answer)
|
|
187
|
+
.map((r) => r[key])
|
|
188
|
+
.filter((v) => (typeof v === 'string' && v !== '') || typeof v === 'number')
|
|
189
|
+
.map(String);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
found = [];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const subs = [...new Set(lines.map((l) => l.sub.name))];
|
|
196
|
+
const sub = subs.length === 1 ? subs[0] : '<SUB>';
|
|
197
|
+
const first = found[0];
|
|
198
|
+
const where = first
|
|
199
|
+
? `The saved record is most likely ${first}, the newest ${screen.name} with these fields${found.length > 1 ? ` (older matches: ${found.slice(1).join(', ')})` : ''}; check it with \`priority-axi show ${screen.name} ${shellWord(first)}${sub === '<SUB>' ? '' : ` --with ${sub}`}\`. Add the corrected lines to it with \`priority-axi add-line ${screen.name} ${shellWord(first)} ${sub} F=V...\`.`
|
|
200
|
+
: `Find it with \`${lookup}\`, then add the corrected lines to it with \`priority-axi add-line ${screen.name} <key> ${sub} F=V...\`.`;
|
|
201
|
+
return new AxiError('partly_saved', `Priority saved the ${screen.name} record, and any lines before line ${line}, but refused line ${line} (line 1 is the record itself). Do not create it again. ${where}`, {
|
|
202
|
+
screen: screen.name,
|
|
203
|
+
line,
|
|
204
|
+
...(first ? { saved: first } : { find: lookup }),
|
|
205
|
+
priority: error.message,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
153
208
|
export async function create(input) {
|
|
154
209
|
const s = open(input);
|
|
155
210
|
const { index } = await screenIndex(s);
|
|
@@ -187,6 +242,12 @@ export async function create(input) {
|
|
|
187
242
|
catch (error) {
|
|
188
243
|
if (error instanceof AxiError && error.code === 'screen_not_enabled')
|
|
189
244
|
recordReach(s.dir, screen.name, 'no', now);
|
|
245
|
+
if (error instanceof AxiError &&
|
|
246
|
+
error.code === 'priority_rejected' &&
|
|
247
|
+
lines.length > 0 &&
|
|
248
|
+
(error.formLine ?? 0) >= 2) {
|
|
249
|
+
throw await partlySaved(s, screen, body, lines, error);
|
|
250
|
+
}
|
|
190
251
|
throw error;
|
|
191
252
|
}
|
|
192
253
|
recordReach(s.dir, screen.name, 'yes', now);
|
package/dist/commands/find.js
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
// word was in the record itself, or `parent` / `customer` when some were only
|
|
8
8
|
// there.
|
|
9
9
|
import { usage } from '../errors.js';
|
|
10
|
-
import { rowsOf } from '../http.js';
|
|
10
|
+
import { rowsOf, timeLeft } from '../http.js';
|
|
11
11
|
import { resolveScreen, resolveSub } from '../index/build.js';
|
|
12
|
-
import {
|
|
12
|
+
import { LOCK_WAIT_MS, withBuildLock } from '../index/cache.js';
|
|
13
|
+
import { catalogPath, layout, pullCatalog, readCatalog, writeCatalog, } from '../index/catalog.js';
|
|
13
14
|
import { bounded, cut, render } from '../output/toon.js';
|
|
14
15
|
import { haystack, missing, queryTerms, rank } from '../search.js';
|
|
15
16
|
import { builtNote, commandLine, intFlag, open, readScreen, screenIndex, str, } from './common.js';
|
|
@@ -38,17 +39,21 @@ export async function find(input) {
|
|
|
38
39
|
const lay = layout(screen, sub);
|
|
39
40
|
const label = sub ? `${screen.name} > ${sub.name}` : screen.name;
|
|
40
41
|
const now = input.io.now();
|
|
41
|
-
|
|
42
|
+
const cached = v.refresh === true
|
|
42
43
|
? undefined
|
|
43
44
|
: readCatalog(s.dir, screen.name, sub?.name, lay.columns, now);
|
|
44
45
|
let pulled;
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
46
|
+
const catalog = cached ??
|
|
47
|
+
(await withBuildLock(`${catalogPath(s.dir, screen.name, sub?.name)}.lock`, () => v.refresh === true
|
|
48
|
+
? undefined
|
|
49
|
+
: readCatalog(s.dir, screen.name, sub?.name, lay.columns, now), async () => {
|
|
50
|
+
const started = performance.now();
|
|
51
|
+
const built = await pullCatalog(screen, sub, lay, async (query) => rowsOf(await readScreen(s, screen.name, query)), now);
|
|
52
|
+
writeCatalog(s.dir, built);
|
|
53
|
+
const seconds = Math.max(1, Math.round((performance.now() - started) / 1000));
|
|
54
|
+
pulled = `built now: ${built.rows.length} ${sub ? 'lines' : 'records'} from Priority in ${seconds} s`;
|
|
55
|
+
return built;
|
|
56
|
+
}, Math.min(LOCK_WAIT_MS, timeLeft(s.settings, input.io.http))));
|
|
52
57
|
const at = (name) => catalog.columns.indexOf(name);
|
|
53
58
|
const statusAt = lay.status.map(at).filter((i) => i >= 0);
|
|
54
59
|
const searchAt = lay.search.map(at).filter((i) => i >= 0);
|
package/dist/commands/read.js
CHANGED
|
@@ -18,20 +18,50 @@ function candidateSelect(type) {
|
|
|
18
18
|
.map((f) => f.name);
|
|
19
19
|
return [...keys, ...rest];
|
|
20
20
|
}
|
|
21
|
+
/** The key fields of a sub-screen's lines that its type defines, to order them. */
|
|
22
|
+
function lineKey(sub) {
|
|
23
|
+
return sub.def.key.filter((k) => sub.def.fields.some((f) => f.name === k));
|
|
24
|
+
}
|
|
21
25
|
/**
|
|
22
26
|
* $expand for --with. Without --full, each line list is narrowed and capped on
|
|
23
27
|
* the server: Priority 23.1 honours $select and $top inside $expand (live S9),
|
|
24
28
|
* so a large order does not send every line. One extra line shows that more exist.
|
|
29
|
+
* Lines are ordered by their key, since Priority sends them in its own order.
|
|
25
30
|
*/
|
|
26
31
|
function expandOf(subs, full) {
|
|
27
32
|
if (!subs.length)
|
|
28
33
|
return undefined;
|
|
29
34
|
return subs
|
|
30
|
-
.map((x) =>
|
|
31
|
-
|
|
32
|
-
|
|
35
|
+
.map((x) => {
|
|
36
|
+
if (!x.many)
|
|
37
|
+
return x.nav;
|
|
38
|
+
const key = lineKey(x);
|
|
39
|
+
const options = [
|
|
40
|
+
...(full ? [] : [`$select=${candidateSelect(x.def).join(',')}`]),
|
|
41
|
+
...(key.length ? [`$orderby=${key.join(',')}`] : []),
|
|
42
|
+
...(full ? [] : [`$top=${LINES + 1}`]),
|
|
43
|
+
];
|
|
44
|
+
return options.length ? `${x.nav}(${options.join(';')})` : x.nav;
|
|
45
|
+
})
|
|
33
46
|
.join(',');
|
|
34
47
|
}
|
|
48
|
+
/** Lines in key order, whatever order Priority sent them in. */
|
|
49
|
+
function byKey(sub, lines) {
|
|
50
|
+
const key = lineKey(sub);
|
|
51
|
+
if (!key.length)
|
|
52
|
+
return lines;
|
|
53
|
+
const cmp = (a, b) => typeof a === 'number' && typeof b === 'number'
|
|
54
|
+
? a - b
|
|
55
|
+
: String(a ?? '').localeCompare(String(b ?? ''));
|
|
56
|
+
return [...lines].sort((a, b) => {
|
|
57
|
+
for (const k of key) {
|
|
58
|
+
const c = cmp(a[k], b[k]);
|
|
59
|
+
if (c)
|
|
60
|
+
return c;
|
|
61
|
+
}
|
|
62
|
+
return 0;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
35
65
|
function explicitFields(type, screen, raw) {
|
|
36
66
|
if (raw === undefined)
|
|
37
67
|
return undefined;
|
|
@@ -53,7 +83,7 @@ function subView(sub, value, fieldLimit, full) {
|
|
|
53
83
|
: undefined;
|
|
54
84
|
return { [sub.name]: one ? recordView(sub.def, one, fieldLimit) : null };
|
|
55
85
|
}
|
|
56
|
-
const lines = Array.isArray(value) ? value : [];
|
|
86
|
+
const lines = Array.isArray(value) ? byKey(sub, value) : [];
|
|
57
87
|
const shown = full ? lines : lines.slice(0, LINES);
|
|
58
88
|
const columns = defaultColumns(sub.def, shown);
|
|
59
89
|
return {
|
|
@@ -75,6 +105,12 @@ async function list(input, mode) {
|
|
|
75
105
|
const v = input.values;
|
|
76
106
|
const limit = intFlag(v.limit, 'limit', 20, 1, 500);
|
|
77
107
|
const page = intFlag(v.page, 'page', 1, 1, 1_000_000);
|
|
108
|
+
const byOffset = v.offset !== undefined;
|
|
109
|
+
if (byOffset && v.page !== undefined)
|
|
110
|
+
throw usage('Use --page or --offset, not both.');
|
|
111
|
+
const offset = intFlag(v.offset, 'offset', 0, 0, 500_000_000);
|
|
112
|
+
// The first record of this read, counted from 0.
|
|
113
|
+
const start = byOffset ? offset : (page - 1) * limit;
|
|
78
114
|
const full = v.full === true;
|
|
79
115
|
const since = mode === 'changes' ? sinceFlag(v.since, input.io.now()) : undefined;
|
|
80
116
|
const filter = combineFilters(whereToFilter(strings(v.where), screen.type, screen.name), str(v.filter));
|
|
@@ -90,7 +126,7 @@ async function list(input, mode) {
|
|
|
90
126
|
$select: select?.join(','),
|
|
91
127
|
$orderby: order,
|
|
92
128
|
$top: limit + 1,
|
|
93
|
-
$skip:
|
|
129
|
+
$skip: start || undefined,
|
|
94
130
|
$expand: expandOf(subs, full),
|
|
95
131
|
$since: since,
|
|
96
132
|
}));
|
|
@@ -109,8 +145,13 @@ async function list(input, mode) {
|
|
|
109
145
|
: defaultColumns(screen.type, rows));
|
|
110
146
|
const noun = rows.length === 1 ? 'record' : 'records';
|
|
111
147
|
const place = mode === 'changes' ? ` changed since ${since}` : '';
|
|
112
|
-
const pageNote =
|
|
113
|
-
|
|
148
|
+
const pageNote = byOffset && offset > 0
|
|
149
|
+
? ` (from record ${offset + 1})`
|
|
150
|
+
: page > 1
|
|
151
|
+
? ` (page ${page})`
|
|
152
|
+
: '';
|
|
153
|
+
const summaryOf = (shown) => `${rows.length} ${noun} from ${screen.name}${place}${pageNote}${more ? ', more exist' : ''}${shown < rows.length ? `; ${shown} of ${rows.length} shown` : ''}`;
|
|
154
|
+
const summary = summaryOf(rows.length);
|
|
114
155
|
if (!rows.length) {
|
|
115
156
|
const help = filter || since
|
|
116
157
|
? [
|
|
@@ -134,19 +175,25 @@ async function list(input, mode) {
|
|
|
134
175
|
return base;
|
|
135
176
|
});
|
|
136
177
|
const help = [];
|
|
137
|
-
if (
|
|
138
|
-
|
|
178
|
+
if (shown < rows.length) {
|
|
179
|
+
// Continue at the first record not shown, so none is skipped.
|
|
180
|
+
help.push(`Run \`${commandLine(mode, [screen.name], v, { page: null, offset: String(start + shown) })}\` for the records after the ${shown} shown`);
|
|
181
|
+
}
|
|
182
|
+
else if (more) {
|
|
183
|
+
help.push(byOffset
|
|
184
|
+
? `Run \`${commandLine(mode, [screen.name], v, { offset: String(start + limit) })}\` for the next ${limit}`
|
|
185
|
+
: `Run \`${commandLine(mode, [screen.name], v, { page: String(page + 1) })}\` for the next ${limit}`);
|
|
139
186
|
}
|
|
140
187
|
if (keys.length === 1) {
|
|
141
188
|
help.push(`Run \`priority-axi show ${screen.name} <${keys[0]}>\` for one record`);
|
|
142
189
|
}
|
|
143
190
|
return render({
|
|
144
|
-
summary,
|
|
191
|
+
summary: summaryOf(shown),
|
|
145
192
|
...builtNote(loaded),
|
|
146
193
|
records,
|
|
147
194
|
...(shown < rows.length
|
|
148
195
|
? {
|
|
149
|
-
omitted: `${rows.length - shown} records not shown;
|
|
196
|
+
omitted: `${rows.length - shown} records not shown to keep the output small; the first help line continues after them, or use --full`,
|
|
150
197
|
}
|
|
151
198
|
: {}),
|
|
152
199
|
}, help);
|
package/dist/commands/refresh.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Rebuild the screen index now.
|
|
2
|
-
import {
|
|
2
|
+
import { timeLeft } from '../http.js';
|
|
3
|
+
import { LOCK_WAIT_MS, loadIndex } from '../index/cache.js';
|
|
3
4
|
import { render } from '../output/toon.js';
|
|
4
5
|
import { checkCompany, indexSource, open, priorityVersion } from './common.js';
|
|
5
6
|
export async function refresh(input) {
|
|
@@ -10,6 +11,7 @@ export async function refresh(input) {
|
|
|
10
11
|
now: input.io.now(),
|
|
11
12
|
refresh: true,
|
|
12
13
|
liveVersion: version,
|
|
14
|
+
lockWaitMs: Math.min(LOCK_WAIT_MS, timeLeft(s.settings, input.io.http)),
|
|
13
15
|
});
|
|
14
16
|
const types = Object.values(index.types);
|
|
15
17
|
const doc = {
|
package/dist/commands/update.js
CHANGED
|
@@ -9,7 +9,7 @@ import { resolveScreen, resolveSub, } from '../index/build.js';
|
|
|
9
9
|
import { recordSegment } from '../odata.js';
|
|
10
10
|
import { defaultColumns, tableRow } from '../output/shape.js';
|
|
11
11
|
import { render } from '../output/toon.js';
|
|
12
|
-
import { open, screenIndex, strings, tokenLine } from './common.js';
|
|
12
|
+
import { open, screenIndex, shellWord, strings, tokenLine } from './common.js';
|
|
13
13
|
import { assign } from './create.js';
|
|
14
14
|
function fields(type, where, terms) {
|
|
15
15
|
const body = {};
|
|
@@ -60,7 +60,7 @@ async function write(input, s, w, command) {
|
|
|
60
60
|
? tableRow(w.shown, record, defaultColumns(w.shown, [record]), 500)
|
|
61
61
|
: null,
|
|
62
62
|
}, [
|
|
63
|
-
`Run \`priority-axi show ${w.screen.name} ${keyOf(input, 1, 'the key')} --with <SUB>\` to read it back`,
|
|
63
|
+
`Run \`priority-axi show ${w.screen.name} ${shellWord(keyOf(input, 1, 'the key'))} --with <SUB>\` to read it back`,
|
|
64
64
|
]);
|
|
65
65
|
}
|
|
66
66
|
/** update <SCREEN> <key> --set F=V: change fields of one record. */
|
package/dist/config.js
CHANGED
|
@@ -63,13 +63,23 @@ export function readSettings(env, flags = {}) {
|
|
|
63
63
|
if (user.includes(':') || /\p{Cc}/u.test(user)) {
|
|
64
64
|
throw usage('The username (--user or PRIORITY_USER) must not contain a colon or control characters.');
|
|
65
65
|
}
|
|
66
|
-
|
|
66
|
+
const settings = {
|
|
67
67
|
origin,
|
|
68
68
|
ini: segment(ini, 'The ini (--ini or PRIORITY_INI)'),
|
|
69
69
|
company: segment(company, 'The company (--company or PRIORITY_COMPANY)'),
|
|
70
70
|
user,
|
|
71
71
|
password,
|
|
72
72
|
};
|
|
73
|
+
// Comis sets COMIS_DEADLINE for every shell call; the command is killed then.
|
|
74
|
+
const deadline = env.COMIS_DEADLINE;
|
|
75
|
+
if (deadline !== undefined && deadline !== '') {
|
|
76
|
+
const n = Number(deadline);
|
|
77
|
+
if (!/^[1-9][0-9]*$/.test(deadline) || !Number.isSafeInteger(n)) {
|
|
78
|
+
throw usage('COMIS_DEADLINE must be a time in epoch milliseconds, a positive whole number.');
|
|
79
|
+
}
|
|
80
|
+
settings.deadline = n;
|
|
81
|
+
}
|
|
82
|
+
return settings;
|
|
73
83
|
}
|
|
74
84
|
export function serviceRoot(settings) {
|
|
75
85
|
return `${settings.origin}/odata/Priority/${settings.ini}/${settings.company}`;
|
package/dist/errors.js
CHANGED
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
export class AxiError extends Error {
|
|
4
4
|
code;
|
|
5
5
|
fields;
|
|
6
|
+
/**
|
|
7
|
+
* The lowest line of a deep-insert body that Priority's form errors name
|
|
8
|
+
* ("שורה 2-" or "Line 2-"; line 1 is the record itself). Not printed.
|
|
9
|
+
*/
|
|
10
|
+
formLine;
|
|
6
11
|
constructor(code, message, fields = {}) {
|
|
7
12
|
super(message);
|
|
8
13
|
this.name = 'AxiError';
|
|
@@ -74,6 +79,19 @@ function interfaceErrors(json, text) {
|
|
|
74
79
|
.map((m) => xmlText(m[1] ?? '').trim())
|
|
75
80
|
.filter(Boolean);
|
|
76
81
|
}
|
|
82
|
+
// Priority numbers the lines of a deep insert from 1, the record itself, and
|
|
83
|
+
// starts each form error with its line: "שורה 2- ..." or "Line 2- ...".
|
|
84
|
+
const FORM_LINE = /^(?:שורה|Line)\s*(\d+)\s*-/i;
|
|
85
|
+
/** The lowest line number Priority's form errors name, if every error names one. */
|
|
86
|
+
export function formLine(json, text) {
|
|
87
|
+
const lines = interfaceErrors(json, text).map((t) => {
|
|
88
|
+
const m = FORM_LINE.exec(t);
|
|
89
|
+
return m ? Number(m[1]) : Number.NaN;
|
|
90
|
+
});
|
|
91
|
+
if (!lines.length || lines.some((n) => !Number.isSafeInteger(n)))
|
|
92
|
+
return undefined;
|
|
93
|
+
return Math.min(...lines);
|
|
94
|
+
}
|
|
77
95
|
/** Priority's own words: an OData error message, or its form errors. */
|
|
78
96
|
export function priorityMessage(json, text) {
|
|
79
97
|
const error = json && typeof json === 'object'
|
|
@@ -93,6 +111,7 @@ const GATE_REFUSALS = {
|
|
|
93
111
|
secret_response: "The Gate withheld Priority's answer because it carried a credential.",
|
|
94
112
|
body_forgotten: 'The Gate no longer holds the body of this request. Run the command again only if the owner asks.',
|
|
95
113
|
out_of_budget: 'The Gate refused this request: the spending budget is used up.',
|
|
114
|
+
policy_refused: 'The Gate refused this request: this workbench may not send it. A reader workbench cannot write; ask the main agent to do it.',
|
|
96
115
|
};
|
|
97
116
|
export function classify(answer, ctx = {}) {
|
|
98
117
|
const { status, headers, json } = answer;
|
|
@@ -113,7 +132,7 @@ export function classify(answer, ctx = {}) {
|
|
|
113
132
|
}
|
|
114
133
|
const message = priorityMessage(json, answer.text);
|
|
115
134
|
if (status === 401) {
|
|
116
|
-
return new AxiError('auth_failed', 'Priority rejected the username or password. Check PRIORITY_USER and PRIORITY_PASSWORD.');
|
|
135
|
+
return new AxiError('auth_failed', 'Priority rejected the username or password. Do not retry: after 3 failed sign-ins Priority locks the API user for 30 minutes. Check PRIORITY_USER and PRIORITY_PASSWORD with the owner first.');
|
|
117
136
|
}
|
|
118
137
|
if (status === 400 && message && NOT_ENABLED.some((rx) => rx.test(message))) {
|
|
119
138
|
const name = ctx.screen ?? 'this screen';
|
|
@@ -128,22 +147,36 @@ export function classify(answer, ctx = {}) {
|
|
|
128
147
|
if (status === 400 && message && BAD_COMPANY.some((rx) => rx.test(message))) {
|
|
129
148
|
return new AxiError('company_not_found', `Priority does not know company ${ctx.company ?? 'given'}. Check the company code with the owner.`, { priority: message });
|
|
130
149
|
}
|
|
150
|
+
const said = message ? { priority: message } : {};
|
|
151
|
+
const write = ctx.method !== undefined && ctx.method !== 'GET';
|
|
131
152
|
if (status === 404) {
|
|
132
|
-
return new AxiError('not_found',
|
|
133
|
-
? `Priority
|
|
134
|
-
:
|
|
153
|
+
return new AxiError('not_found', write
|
|
154
|
+
? `Priority found no such ${ctx.screen ? `${ctx.screen} record or line` : 'record'} (404). Check the key with \`priority-axi show ${ctx.screen ?? '<SCREEN>'} <key>\`.`
|
|
155
|
+
: ctx.screen
|
|
156
|
+
? `Priority has no ${ctx.screen}. Check the name with \`priority-axi screens\`.`
|
|
157
|
+
: 'Priority answered 404 Not Found.', { ...screen, ...said });
|
|
135
158
|
}
|
|
136
159
|
if (status === 409) {
|
|
137
|
-
|
|
160
|
+
if (ctx.method === 'PATCH') {
|
|
161
|
+
return new AxiError('priority_rejected', `Priority refused the change as a conflict (409)${message ? `: ${message.replace(/[.!?]?$/, '.')}` : '.'} Read the record with \`priority-axi show\` before changing it again.`, { ...screen, status, ...said });
|
|
162
|
+
}
|
|
163
|
+
return new AxiError('already_exists', 'Priority says this record already exists. Read it with `priority-axi show` instead of creating it again.', { ...screen, ...said });
|
|
138
164
|
}
|
|
139
165
|
if (status === 429) {
|
|
140
|
-
|
|
166
|
+
const after = headers.get('retry-after');
|
|
167
|
+
return new AxiError('rate_limited', after
|
|
168
|
+
? 'Priority is limiting requests. Wait a minute, then try again.'
|
|
169
|
+
: 'Priority is limiting requests, or it has locked the API user after failed sign-ins (Priority 26.1 and later lock it for 30 minutes). Wait before trying again, and do not retry in a loop.');
|
|
141
170
|
}
|
|
142
171
|
if (status === 501) {
|
|
143
172
|
return new AxiError('unsupported_query', `Priority cannot run this query: ${message ?? 'not supported'}. Use the --where operators =, !=, >, >=, < and <=.`, screen);
|
|
144
173
|
}
|
|
145
174
|
if (status >= 400 && status < 500) {
|
|
146
|
-
|
|
175
|
+
const rejected = new AxiError('priority_rejected', message ?? `Priority answered ${status} with no message.`, { ...screen, status });
|
|
176
|
+
const line = formLine(json, answer.text);
|
|
177
|
+
if (line !== undefined)
|
|
178
|
+
rejected.formLine = line;
|
|
179
|
+
return rejected;
|
|
147
180
|
}
|
|
148
181
|
return new AxiError('priority_error', message ?? `Priority answered ${status} with no message.`, { ...screen, status });
|
|
149
182
|
}
|
package/dist/http.js
CHANGED
|
@@ -4,9 +4,14 @@
|
|
|
4
4
|
import { serviceRoot } from './config.js';
|
|
5
5
|
import { AxiError, classify } from './errors.js';
|
|
6
6
|
import { VERSION } from './version.js';
|
|
7
|
-
|
|
7
|
+
/** Priority Cloud drops a request after 3 minutes; an unfiltered document read took 86 s live. */
|
|
8
|
+
export const READ_TIMEOUT_MS = 150_000;
|
|
8
9
|
/** Longer than the Gate's 45 s approval hold. */
|
|
9
10
|
export const WRITE_TIMEOUT_MS = 120_000;
|
|
11
|
+
/** A write needs the Gate's 45 s approval hold and Priority's answer. */
|
|
12
|
+
export const WRITE_MIN_MS = 50_000;
|
|
13
|
+
/** Priority caps an answer at 350 MB; priority-axi reads at most this much. */
|
|
14
|
+
export const MAX_ANSWER_BYTES = 32 * 2 ** 20;
|
|
10
15
|
const MAX_RETRY_AFTER_S = 15;
|
|
11
16
|
export const defaultDeps = {
|
|
12
17
|
fetch: (...args) => fetch(...args),
|
|
@@ -22,12 +27,113 @@ function headers(settings, withBody) {
|
|
|
22
27
|
...(withBody ? { 'Content-Type': 'application/json' } : {}),
|
|
23
28
|
};
|
|
24
29
|
}
|
|
30
|
+
/** Milliseconds left before COMIS_DEADLINE, less a one-second margin. */
|
|
31
|
+
export function timeLeft(settings, deps) {
|
|
32
|
+
return settings.deadline === undefined
|
|
33
|
+
? Number.POSITIVE_INFINITY
|
|
34
|
+
: settings.deadline - (deps.now ?? Date.now)() - 1000;
|
|
35
|
+
}
|
|
36
|
+
const WORKER = 'Run it from a worker, which has more time: the first index build and a cold find catalog each take about 30 s.';
|
|
37
|
+
// Errors that prove nothing was sent: no address, no connection, a refused
|
|
38
|
+
// TLS handshake or a refused proxy tunnel. Anything else may come after the
|
|
39
|
+
// request went out.
|
|
40
|
+
const BEFORE_SENDING = new Set([
|
|
41
|
+
'ECONNREFUSED',
|
|
42
|
+
'ENOTFOUND',
|
|
43
|
+
'EAI_AGAIN',
|
|
44
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
45
|
+
'DEPTH_ZERO_SELF_SIGNED_CERT',
|
|
46
|
+
'SELF_SIGNED_CERT_IN_CHAIN',
|
|
47
|
+
'ERR_TLS_HANDSHAKE_TIMEOUT',
|
|
48
|
+
'ERR_SSL_WRONG_VERSION_NUMBER',
|
|
49
|
+
]);
|
|
50
|
+
const TLS_HANDSHAKE = /^(CERT_|UNABLE_TO_|ERR_TLS_CERT_|ERR_SSL_TLSV1_ALERT_|ERR_SSL_SSLV3_ALERT_HANDSHAKE)/;
|
|
51
|
+
const PROXY_REFUSED = /Proxy response \(\d+\) !== 200 when HTTP Tunneling/;
|
|
52
|
+
/** True only when the error proves the request never left this machine. */
|
|
53
|
+
export function beforeSending(error) {
|
|
54
|
+
const codes = [];
|
|
55
|
+
let proxyRefused = false;
|
|
56
|
+
const walk = (e, depth) => {
|
|
57
|
+
if (!e || typeof e !== 'object' || depth > 6)
|
|
58
|
+
return;
|
|
59
|
+
const { code, message, cause, errors } = e;
|
|
60
|
+
if (typeof code === 'string')
|
|
61
|
+
codes.push(code);
|
|
62
|
+
if (typeof message === 'string' && PROXY_REFUSED.test(message))
|
|
63
|
+
proxyRefused = true;
|
|
64
|
+
if (Array.isArray(errors))
|
|
65
|
+
for (const x of errors)
|
|
66
|
+
walk(x, depth + 1);
|
|
67
|
+
walk(cause, depth + 1);
|
|
68
|
+
};
|
|
69
|
+
walk(error, 0);
|
|
70
|
+
if (proxyRefused)
|
|
71
|
+
return true;
|
|
72
|
+
return (codes.length > 0 &&
|
|
73
|
+
codes.every((c) => BEFORE_SENDING.has(c) || TLS_HANDSHAKE.test(c)));
|
|
74
|
+
}
|
|
75
|
+
/** What a write did, in words, for its error messages. */
|
|
76
|
+
function writeName(call) {
|
|
77
|
+
if (call.method === 'PATCH')
|
|
78
|
+
return 'update';
|
|
79
|
+
return call.path.includes('(') ? 'new line' : 'create';
|
|
80
|
+
}
|
|
81
|
+
const CHECK_FIRST = 'Check with `priority-axi show` or `priority-axi get` before sending it again. Do not retry.';
|
|
82
|
+
/** The sentence for a write whose outcome is unknown once it was sent. */
|
|
83
|
+
export function maySaved(call, what) {
|
|
84
|
+
return `${what}, so Priority may have saved the ${writeName(call)}. ${CHECK_FIRST}`;
|
|
85
|
+
}
|
|
86
|
+
/** Read the body, at most MAX_ANSWER_BYTES. */
|
|
87
|
+
async function readBody(response) {
|
|
88
|
+
if (!response.body)
|
|
89
|
+
return Buffer.alloc(0);
|
|
90
|
+
const reader = response.body.getReader();
|
|
91
|
+
const chunks = [];
|
|
92
|
+
let total = 0;
|
|
93
|
+
for (;;) {
|
|
94
|
+
const { done, value } = await reader.read();
|
|
95
|
+
if (done)
|
|
96
|
+
break;
|
|
97
|
+
total += value.byteLength;
|
|
98
|
+
if (total > MAX_ANSWER_BYTES) {
|
|
99
|
+
await reader.cancel().catch(() => { });
|
|
100
|
+
throw new TooLarge(total);
|
|
101
|
+
}
|
|
102
|
+
chunks.push(value);
|
|
103
|
+
}
|
|
104
|
+
return Buffer.concat(chunks, total);
|
|
105
|
+
}
|
|
106
|
+
class TooLarge extends Error {
|
|
107
|
+
bytes;
|
|
108
|
+
constructor(bytes) {
|
|
109
|
+
super('too large');
|
|
110
|
+
this.bytes = bytes;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
25
113
|
async function once(settings, call, deps) {
|
|
26
114
|
if (call.method !== 'GET' && call.path.includes('%')) {
|
|
27
115
|
throw new AxiError('internal_error', 'A write path must not be percent-encoded.');
|
|
28
116
|
}
|
|
117
|
+
const write = call.method !== 'GET';
|
|
118
|
+
const left = timeLeft(settings, deps);
|
|
119
|
+
if (write && left + 1000 < WRITE_MIN_MS) {
|
|
120
|
+
throw new AxiError('unreachable', `Only ${Math.max(0, Math.floor((left + 1000) / 1000))} s are left before this command's deadline (COMIS_DEADLINE): not enough time for the owner's approval hold, so nothing was sent. Run it in a worker, which has more time.`);
|
|
121
|
+
}
|
|
122
|
+
if (!write && left <= 0) {
|
|
123
|
+
throw new AxiError('unreachable', `The time for this command ran out before Priority was asked. ${WORKER}`);
|
|
124
|
+
}
|
|
125
|
+
const base = write
|
|
126
|
+
? (deps.timeouts?.write ?? WRITE_TIMEOUT_MS)
|
|
127
|
+
: (deps.timeouts?.read ?? READ_TIMEOUT_MS);
|
|
128
|
+
const timeout = Math.min(base, left);
|
|
129
|
+
const capped = left < base;
|
|
130
|
+
const seconds = Math.max(1, Math.round(timeout / 1000));
|
|
131
|
+
const timedOutText = () => write
|
|
132
|
+
? maySaved(call, `Priority did not answer within ${seconds} s after the ${writeName(call)} was sent`)
|
|
133
|
+
: capped
|
|
134
|
+
? `Priority did not answer within the ${seconds} s left before this command's deadline. ${WORKER}`
|
|
135
|
+
: `Priority did not answer within ${seconds} s. Filter large document screens, or read fewer records.`;
|
|
29
136
|
const url = `${serviceRoot(settings)}/${call.path}${call.query ?? ''}`;
|
|
30
|
-
const timeout = call.method === 'GET' ? READ_TIMEOUT_MS : WRITE_TIMEOUT_MS;
|
|
31
137
|
const started = performance.now();
|
|
32
138
|
let response;
|
|
33
139
|
try {
|
|
@@ -41,21 +147,31 @@ async function once(settings, call, deps) {
|
|
|
41
147
|
}
|
|
42
148
|
catch (error) {
|
|
43
149
|
const timedOut = error instanceof Error && error.name === 'TimeoutError';
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
150
|
+
if (timedOut)
|
|
151
|
+
throw new AxiError('unreachable', timedOutText());
|
|
152
|
+
if (beforeSending(error)) {
|
|
153
|
+
throw new AxiError('unreachable', `Priority could not be reached${write ? ', so nothing was sent' : ''}. Check the address, or whether the Gate is running.`);
|
|
154
|
+
}
|
|
155
|
+
throw new AxiError('unreachable', write
|
|
156
|
+
? maySaved(call, `The connection to Priority broke after the ${writeName(call)} was sent`)
|
|
157
|
+
: 'The connection to Priority broke before it answered. Try again; if it fails again, check the address or whether the Gate is running.');
|
|
47
158
|
}
|
|
48
159
|
let buffer;
|
|
49
160
|
try {
|
|
50
|
-
buffer =
|
|
161
|
+
buffer = await readBody(response);
|
|
51
162
|
}
|
|
52
|
-
catch {
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (error instanceof TooLarge) {
|
|
165
|
+
throw new AxiError('output_too_large', write
|
|
166
|
+
? maySaved(call, `Priority's answer is over ${MAX_ANSWER_BYTES / 2 ** 20} MB, more than priority-axi reads`)
|
|
167
|
+
: `Priority's answer is over ${MAX_ANSWER_BYTES / 2 ** 20} MB, more than priority-axi reads. Read less with --where, --fields, fewer --with sub-screens or a smaller --limit.`, { limit: MAX_ANSWER_BYTES });
|
|
168
|
+
}
|
|
169
|
+
if (error instanceof Error && error.name === 'TimeoutError')
|
|
170
|
+
throw new AxiError('unreachable', timedOutText());
|
|
53
171
|
// Priority 23.1 can drop the connection part way through an answer.
|
|
54
|
-
throw new AxiError('unreachable',
|
|
55
|
-
?
|
|
56
|
-
:
|
|
57
|
-
? 'Priority broke off its answer to the update, so it may have been applied. Check with priority-axi show before updating it again.'
|
|
58
|
-
: 'Priority broke off its answer to the create, so it may have been saved. Check with priority-axi get or show before creating it again.');
|
|
172
|
+
throw new AxiError('unreachable', write
|
|
173
|
+
? maySaved(call, `Priority broke off its answer to the ${writeName(call)}`)
|
|
174
|
+
: 'Priority broke off its answer part way through. Try again with a smaller --limit or fewer --with sub-screens.');
|
|
59
175
|
}
|
|
60
176
|
const text = buffer.toString('utf8');
|
|
61
177
|
let json;
|
|
@@ -82,7 +198,10 @@ export async function send(settings, call, deps = defaultDeps) {
|
|
|
82
198
|
let answer = await once(settings, call, deps);
|
|
83
199
|
if (answer.status === 429 && call.method === 'GET') {
|
|
84
200
|
const wait = Number(answer.headers.get('retry-after') ?? '');
|
|
85
|
-
if (Number.isFinite(wait) &&
|
|
201
|
+
if (Number.isFinite(wait) &&
|
|
202
|
+
wait >= 0 &&
|
|
203
|
+
wait <= MAX_RETRY_AFTER_S &&
|
|
204
|
+
wait * 1000 < timeLeft(settings, deps)) {
|
|
86
205
|
await deps.sleep(wait * 1000);
|
|
87
206
|
answer = await once(settings, call, deps);
|
|
88
207
|
}
|
|
@@ -92,8 +211,16 @@ export async function send(settings, call, deps = defaultDeps) {
|
|
|
92
211
|
}
|
|
93
212
|
const error = classify(answer, {
|
|
94
213
|
company: settings.company,
|
|
214
|
+
method: call.method,
|
|
95
215
|
...call.context,
|
|
96
216
|
});
|
|
217
|
+
if (error && call.method !== 'GET' && error.code === 'priority_error') {
|
|
218
|
+
// A server or proxy failure after the write went out: it may have landed.
|
|
219
|
+
const said = /[.!?]$/.test(error.message)
|
|
220
|
+
? error.message
|
|
221
|
+
: `${error.message}.`;
|
|
222
|
+
throw new AxiError(error.code, `${said} Priority may have saved the ${writeName(call)} anyway. ${CHECK_FIRST}`, error.fields);
|
|
223
|
+
}
|
|
97
224
|
if (error)
|
|
98
225
|
throw error;
|
|
99
226
|
return answer;
|
package/dist/index/cache.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// renamed, so a crash leaves the old file or the new one, never half of each.
|
|
3
3
|
// A file that cannot be read is treated as missing and rebuilt.
|
|
4
4
|
import { createHash, randomBytes } from 'node:crypto';
|
|
5
|
-
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
|
|
5
|
+
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
6
6
|
import { homedir } from 'node:os';
|
|
7
7
|
import { dirname, join } from 'node:path';
|
|
8
8
|
import { buildIndex, INDEX_FORMAT } from './build.js';
|
|
@@ -35,6 +35,79 @@ export function writeJsonAtomic(path, value) {
|
|
|
35
35
|
throw error;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
+
// ---------- an advisory lock around slow builds ----------
|
|
39
|
+
/** A lock older than this is from a run that died; it is taken over. */
|
|
40
|
+
export const LOCK_STALE_MS = 5 * 60 * 1000;
|
|
41
|
+
/** How long to wait for another run's build before building anyway. */
|
|
42
|
+
export const LOCK_WAIT_MS = 90_000;
|
|
43
|
+
const LOCK_POLL_MS = 250;
|
|
44
|
+
function alive(pid) {
|
|
45
|
+
try {
|
|
46
|
+
process.kill(pid, 0);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
return error.code === 'EPERM';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function stale(path, now) {
|
|
54
|
+
try {
|
|
55
|
+
const pid = Number(readFileSync(path, 'utf8').split(' ')[0]);
|
|
56
|
+
if (Number.isSafeInteger(pid) && pid > 0 && !alive(pid))
|
|
57
|
+
return true;
|
|
58
|
+
return now - statSync(path).mtimeMs > LOCK_STALE_MS;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Run a build while holding an advisory lock file, so that concurrent cold
|
|
66
|
+
* runs on one cache wait for one download instead of each pulling the same
|
|
67
|
+
* metadata or catalog. `ready` is checked after waiting: when another run
|
|
68
|
+
* built it meanwhile, its result is used. The lock is only a courtesy: when it
|
|
69
|
+
* cannot be taken within `waitMs`, or the cache cannot be written, the build
|
|
70
|
+
* runs anyway.
|
|
71
|
+
*/
|
|
72
|
+
export async function withBuildLock(path, ready, build, waitMs = LOCK_WAIT_MS) {
|
|
73
|
+
const until = Date.now() + Math.max(0, waitMs);
|
|
74
|
+
let held = false;
|
|
75
|
+
let waited = false;
|
|
76
|
+
for (;;) {
|
|
77
|
+
try {
|
|
78
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
79
|
+
const fd = openSync(path, 'wx', 0o600);
|
|
80
|
+
writeFileSync(fd, `${process.pid} ${new Date().toISOString()}`);
|
|
81
|
+
closeSync(fd);
|
|
82
|
+
held = true;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (error.code !== 'EEXIST')
|
|
87
|
+
break;
|
|
88
|
+
if (stale(path, Date.now())) {
|
|
89
|
+
rmSync(path, { force: true });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (Date.now() >= until)
|
|
93
|
+
break;
|
|
94
|
+
waited = true;
|
|
95
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
if (waited || held) {
|
|
100
|
+
const done = ready();
|
|
101
|
+
if (done !== undefined)
|
|
102
|
+
return done;
|
|
103
|
+
}
|
|
104
|
+
return await build();
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
if (held)
|
|
108
|
+
rmSync(path, { force: true });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
38
111
|
function isIndex(value) {
|
|
39
112
|
if (!value || typeof value !== 'object')
|
|
40
113
|
return false;
|
|
@@ -74,11 +147,25 @@ export async function loadIndex(dir, source, opts) {
|
|
|
74
147
|
const reason = staleReason(cached, opts);
|
|
75
148
|
if (cached && !reason)
|
|
76
149
|
return { index: cached };
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
150
|
+
return withBuildLock(join(dir, 'index.lock'), () => {
|
|
151
|
+
// Another run built it while this one waited. A refresh still rebuilds.
|
|
152
|
+
const built = readIndex(dir);
|
|
153
|
+
if (!built ||
|
|
154
|
+
opts.refresh ||
|
|
155
|
+
built.builtAt === cached?.builtAt ||
|
|
156
|
+
staleReason(built, { ...opts, refresh: false }))
|
|
157
|
+
return undefined;
|
|
158
|
+
return { index: built };
|
|
159
|
+
}, async () => {
|
|
160
|
+
const version = opts.liveVersion ?? (await source.fetchVersion());
|
|
161
|
+
const { csdl, bytes, ms } = await source.fetchMetadata();
|
|
162
|
+
const index = buildIndex(csdl, {
|
|
163
|
+
version,
|
|
164
|
+
builtAt: opts.now.toISOString(),
|
|
165
|
+
});
|
|
166
|
+
writeJsonAtomic(join(dir, 'index.json'), index);
|
|
167
|
+
return { index, rebuilt: { reason: reason ?? 'missing', bytes, ms } };
|
|
168
|
+
}, opts.lockWaitMs);
|
|
82
169
|
}
|
|
83
170
|
export function readReach(dir) {
|
|
84
171
|
const value = readJson(join(dir, 'reach.json'));
|
package/dist/index/catalog.js
CHANGED
|
@@ -124,7 +124,7 @@ export function layout(screen, sub) {
|
|
|
124
124
|
parentKey: top.key,
|
|
125
125
|
};
|
|
126
126
|
}
|
|
127
|
-
function catalogPath(dir, screen, sub) {
|
|
127
|
+
export function catalogPath(dir, screen, sub) {
|
|
128
128
|
return join(dir, 'find', `${screen}${sub ? `.${sub}` : ''}.json`);
|
|
129
129
|
}
|
|
130
130
|
export function readCatalog(dir, screen, sub, columns, now) {
|
package/dist/odata.js
CHANGED
|
@@ -23,7 +23,11 @@ const INTEGER = new Set(['Int16', 'Int32', 'Int64', 'Byte', 'SByte']);
|
|
|
23
23
|
const DECIMAL = new Set(['Decimal', 'Double', 'Single']);
|
|
24
24
|
const DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
25
25
|
const TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
26
|
-
|
|
26
|
+
const LOCAL = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(\.\d{1,7})?)?)?(?:Z|[+-]\d{2}:\d{2})?$/;
|
|
27
|
+
/**
|
|
28
|
+
* A UTC timestamp with seconds and Z, for --since only: Priority's $since
|
|
29
|
+
* honours the offset, and its docs recommend UTC with Z for it.
|
|
30
|
+
*/
|
|
27
31
|
export function utc(raw, flag) {
|
|
28
32
|
const day = DAY.exec(raw);
|
|
29
33
|
let ms;
|
|
@@ -36,10 +40,31 @@ export function utc(raw, flag) {
|
|
|
36
40
|
ms = TIME.test(raw) ? Date.parse(raw) : Number.NaN;
|
|
37
41
|
}
|
|
38
42
|
if (!Number.isFinite(ms)) {
|
|
39
|
-
throw usage(`Invalid date for ${flag}; use YYYY-MM-DD or a full time such as 2026-10-
|
|
43
|
+
throw usage(`Invalid date for ${flag}; use YYYY-MM-DD, 7d, 24h or a full UTC time such as 2026-10-01T06:00:00Z.`);
|
|
40
44
|
}
|
|
41
45
|
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
42
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* A date or time in Priority's local (company) time, for --where, --set and
|
|
49
|
+
* --json-file. Priority reads only the wall-clock digits of a DateTimeOffset
|
|
50
|
+
* in $filter and in a write body, and ignores its offset (live, 23.1). So the
|
|
51
|
+
* digits go out exactly as given, with any offset dropped, never converted to
|
|
52
|
+
* UTC. The Z only completes the literal's form.
|
|
53
|
+
*/
|
|
54
|
+
export function localTime(raw, flag) {
|
|
55
|
+
const m = LOCAL.exec(raw);
|
|
56
|
+
const [, y, mo, d, h = '00', mi = '00', sec = '00', frac = ''] = m ?? [];
|
|
57
|
+
const day = Date.UTC(Number(y), Number(mo) - 1, Number(d));
|
|
58
|
+
const real = m &&
|
|
59
|
+
new Date(day).toISOString().slice(0, 10) === `${y}-${mo}-${d}` &&
|
|
60
|
+
Number(h) < 24 &&
|
|
61
|
+
Number(mi) < 60 &&
|
|
62
|
+
Number(sec) < 60;
|
|
63
|
+
if (!real) {
|
|
64
|
+
throw usage(`Invalid date for ${flag}; use YYYY-MM-DD or YYYY-MM-DDTHH:MM in Priority's local (company) time, such as 2026-10-01T08:00. An offset is ignored, never converted.`);
|
|
65
|
+
}
|
|
66
|
+
return `${y}-${mo}-${d}T${h}:${mi}:${sec}${frac}Z`;
|
|
67
|
+
}
|
|
43
68
|
/** An OData literal for a value of this field's type. */
|
|
44
69
|
export function literal(field, raw) {
|
|
45
70
|
if (field.type === 'String')
|
|
@@ -61,7 +86,7 @@ export function literal(field, raw) {
|
|
|
61
86
|
return raw;
|
|
62
87
|
}
|
|
63
88
|
if (field.type === 'DateTimeOffset' || field.type === 'Date')
|
|
64
|
-
return
|
|
89
|
+
return localTime(raw, `--where ${field.name}`);
|
|
65
90
|
throw usage(`--where cannot filter ${field.name} (${field.type}); use --filter with raw OData.`);
|
|
66
91
|
}
|
|
67
92
|
export function whereToFilter(wheres, type, screenName) {
|
package/dist/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Kept equal to package.json by test/unit/version.test.ts.
|
|
2
|
-
export const VERSION = '0.2.
|
|
2
|
+
export const VERSION = '0.2.1';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "priority-axi",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "A command-line tool that lets AI agents read and create Priority ERP records through the REST API",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"@toon-format/toon": "4.4.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@biomejs/biome": "2.6.
|
|
53
|
+
"@biomejs/biome": "2.6.7",
|
|
54
54
|
"@types/node": "26.6.6",
|
|
55
55
|
"typescript": "7.0.2"
|
|
56
56
|
}
|