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.
- package/LICENSE +21 -0
- package/NOTICE +13 -0
- package/README.md +189 -2
- package/dist/bin/priority-axi.js +17 -0
- package/dist/cli/parse.js +69 -0
- package/dist/cli/run.js +388 -0
- package/dist/cli/table.js +37 -0
- package/dist/commands/catalog.js +180 -0
- package/dist/commands/common.js +173 -0
- package/dist/commands/create.js +207 -0
- package/dist/commands/find.js +153 -0
- package/dist/commands/home.js +56 -0
- package/dist/commands/read.js +264 -0
- package/dist/commands/refresh.js +26 -0
- package/dist/commands/update.js +124 -0
- package/dist/config.js +76 -0
- package/dist/errors.js +149 -0
- package/dist/http.js +120 -0
- package/dist/index/build.js +169 -0
- package/dist/index/cache.js +129 -0
- package/dist/index/catalog.js +216 -0
- package/dist/odata.js +152 -0
- package/dist/output/html.js +58 -0
- package/dist/output/shape.js +57 -0
- package/dist/output/text.js +48 -0
- package/dist/output/toon.js +78 -0
- package/dist/search.js +118 -0
- package/dist/version.js +2 -0
- package/package.json +55 -4
package/dist/http.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// HTTP to Priority, directly or through the Gate (HTTPS_PROXY with
|
|
2
|
+
// NODE_USE_ENV_PROXY=1, set by the Comis wrapper). Reads may be retried once
|
|
3
|
+
// after a short 429. Writes are sent once and never retried, whatever happens.
|
|
4
|
+
import { serviceRoot } from './config.js';
|
|
5
|
+
import { AxiError, classify } from './errors.js';
|
|
6
|
+
import { VERSION } from './version.js';
|
|
7
|
+
export const READ_TIMEOUT_MS = 90_000;
|
|
8
|
+
/** Longer than the Gate's 45 s approval hold. */
|
|
9
|
+
export const WRITE_TIMEOUT_MS = 120_000;
|
|
10
|
+
const MAX_RETRY_AFTER_S = 15;
|
|
11
|
+
export const defaultDeps = {
|
|
12
|
+
fetch: (...args) => fetch(...args),
|
|
13
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
14
|
+
};
|
|
15
|
+
function headers(settings, withBody) {
|
|
16
|
+
const auth = Buffer.from(`${settings.user}:${settings.password}`).toString('base64');
|
|
17
|
+
return {
|
|
18
|
+
Accept: 'application/json',
|
|
19
|
+
'OData-Version': '4.0',
|
|
20
|
+
'User-Agent': `priority-axi/${VERSION}`,
|
|
21
|
+
Authorization: `Basic ${auth}`,
|
|
22
|
+
...(withBody ? { 'Content-Type': 'application/json' } : {}),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
async function once(settings, call, deps) {
|
|
26
|
+
if (call.method !== 'GET' && call.path.includes('%')) {
|
|
27
|
+
throw new AxiError('internal_error', 'A write path must not be percent-encoded.');
|
|
28
|
+
}
|
|
29
|
+
const url = `${serviceRoot(settings)}/${call.path}${call.query ?? ''}`;
|
|
30
|
+
const timeout = call.method === 'GET' ? READ_TIMEOUT_MS : WRITE_TIMEOUT_MS;
|
|
31
|
+
const started = performance.now();
|
|
32
|
+
let response;
|
|
33
|
+
try {
|
|
34
|
+
response = await deps.fetch(url, {
|
|
35
|
+
method: call.method,
|
|
36
|
+
headers: headers(settings, call.body !== undefined),
|
|
37
|
+
...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),
|
|
38
|
+
redirect: 'manual',
|
|
39
|
+
signal: AbortSignal.timeout(timeout),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
const timedOut = error instanceof Error && error.name === 'TimeoutError';
|
|
44
|
+
throw new AxiError('unreachable', timedOut
|
|
45
|
+
? `Priority did not answer within ${timeout / 1000} s.`
|
|
46
|
+
: 'Priority could not be reached. Check the address, or whether the Gate is running.');
|
|
47
|
+
}
|
|
48
|
+
let buffer;
|
|
49
|
+
try {
|
|
50
|
+
buffer = Buffer.from(await response.arrayBuffer());
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// Priority 23.1 can drop the connection part way through an answer.
|
|
54
|
+
throw new AxiError('unreachable', call.method === 'GET'
|
|
55
|
+
? 'Priority broke off its answer part way through. Try again with a smaller --limit or fewer --with sub-screens.'
|
|
56
|
+
: call.method === 'PATCH'
|
|
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.');
|
|
59
|
+
}
|
|
60
|
+
const text = buffer.toString('utf8');
|
|
61
|
+
let json;
|
|
62
|
+
let malformed = false;
|
|
63
|
+
try {
|
|
64
|
+
json = text ? JSON.parse(text) : undefined;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
json = undefined;
|
|
68
|
+
malformed = true;
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
status: response.status,
|
|
72
|
+
headers: response.headers,
|
|
73
|
+
json,
|
|
74
|
+
malformed,
|
|
75
|
+
...(malformed ? { text: text.slice(0, 8000) } : {}),
|
|
76
|
+
bytes: buffer.length,
|
|
77
|
+
ms: Math.round(performance.now() - started),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** Send a call and return the answer, or throw the classified error. */
|
|
81
|
+
export async function send(settings, call, deps = defaultDeps) {
|
|
82
|
+
let answer = await once(settings, call, deps);
|
|
83
|
+
if (answer.status === 429 && call.method === 'GET') {
|
|
84
|
+
const wait = Number(answer.headers.get('retry-after') ?? '');
|
|
85
|
+
if (Number.isFinite(wait) && wait >= 0 && wait <= MAX_RETRY_AFTER_S) {
|
|
86
|
+
await deps.sleep(wait * 1000);
|
|
87
|
+
answer = await once(settings, call, deps);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (answer.status >= 300 && answer.status < 400) {
|
|
91
|
+
throw new AxiError('priority_error', `Priority answered with a redirect (${answer.status}), which priority-axi does not follow.`);
|
|
92
|
+
}
|
|
93
|
+
const error = classify(answer, {
|
|
94
|
+
company: settings.company,
|
|
95
|
+
...call.context,
|
|
96
|
+
});
|
|
97
|
+
if (error)
|
|
98
|
+
throw error;
|
|
99
|
+
return answer;
|
|
100
|
+
}
|
|
101
|
+
/** The "value" array of a collection answer. */
|
|
102
|
+
export function rowsOf(answer) {
|
|
103
|
+
if (answer.malformed) {
|
|
104
|
+
throw new AxiError('priority_error', `Priority sent an incomplete answer (${answer.bytes} bytes). Try again with a smaller --limit or fewer --with sub-screens.`);
|
|
105
|
+
}
|
|
106
|
+
const value = answer.json?.value;
|
|
107
|
+
if (!Array.isArray(value) ||
|
|
108
|
+
value.some((r) => !r || typeof r !== 'object' || Array.isArray(r))) {
|
|
109
|
+
throw new AxiError('priority_error', 'Priority returned a collection priority-axi cannot read.');
|
|
110
|
+
}
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
/** The "value" string of a function answer such as GetPriorityVersion(). */
|
|
114
|
+
export function stringValue(answer, what) {
|
|
115
|
+
const value = answer.json?.value;
|
|
116
|
+
if (typeof value !== 'string' || !value) {
|
|
117
|
+
throw new AxiError('priority_error', `Priority returned no ${what}.`);
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Reduces Priority's JSON CSDL ($metadata?$format=json) to a compact index.
|
|
2
|
+
// Pure: no I/O. The index is derived data and can always be rebuilt.
|
|
3
|
+
import { AxiError, usage } from '../errors.js';
|
|
4
|
+
export const INDEX_FORMAT = 1;
|
|
5
|
+
const SUBFORM = /_SUBFORM$/;
|
|
6
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
7
|
+
const lastPart = (qualified) => qualified.split('.').pop() ?? qualified;
|
|
8
|
+
function invalid(detail) {
|
|
9
|
+
throw new AxiError('priority_error', `Priority returned metadata that priority-axi cannot read (${detail}).`);
|
|
10
|
+
}
|
|
11
|
+
export function buildIndex(csdl, meta) {
|
|
12
|
+
if (!isObject(csdl))
|
|
13
|
+
invalid('not an object');
|
|
14
|
+
const container = typeof csdl.$EntityContainer === 'string' ? csdl.$EntityContainer : '';
|
|
15
|
+
const nsName = Object.keys(csdl).find((k) => !k.startsWith('$'));
|
|
16
|
+
const ns = nsName ? csdl[nsName] : undefined;
|
|
17
|
+
if (!isObject(ns))
|
|
18
|
+
invalid('no schema');
|
|
19
|
+
const entities = ns[lastPart(container)];
|
|
20
|
+
if (!isObject(entities))
|
|
21
|
+
invalid('no entity container');
|
|
22
|
+
const sets = {};
|
|
23
|
+
for (const [name, entry] of Object.entries(entities)) {
|
|
24
|
+
if (isObject(entry) &&
|
|
25
|
+
entry.$Collection === true &&
|
|
26
|
+
typeof entry.$Type === 'string') {
|
|
27
|
+
sets[name] = lastPart(entry.$Type);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const types = {};
|
|
31
|
+
for (const [typeName, def] of Object.entries(ns)) {
|
|
32
|
+
if (!isObject(def) || def.$Kind !== 'EntityType')
|
|
33
|
+
continue;
|
|
34
|
+
const key = Array.isArray(def.$Key)
|
|
35
|
+
? def.$Key.filter((k) => typeof k === 'string')
|
|
36
|
+
: [];
|
|
37
|
+
const fields = [];
|
|
38
|
+
const subs = [];
|
|
39
|
+
for (const [name, prop] of Object.entries(def)) {
|
|
40
|
+
if (name.startsWith('$') || name.startsWith('@') || !isObject(prop))
|
|
41
|
+
continue;
|
|
42
|
+
if (prop.$Kind === 'NavigationProperty') {
|
|
43
|
+
const title = prop['@Priority.OData.Description'];
|
|
44
|
+
subs.push({
|
|
45
|
+
name: name.replace(SUBFORM, ''),
|
|
46
|
+
nav: name,
|
|
47
|
+
type: lastPart(typeof prop.$Type === 'string' ? prop.$Type : name),
|
|
48
|
+
...(typeof title === 'string' && title ? { title } : {}),
|
|
49
|
+
many: prop.$Collection === true,
|
|
50
|
+
});
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const field = {
|
|
54
|
+
name,
|
|
55
|
+
type: (typeof prop.$Type === 'string'
|
|
56
|
+
? prop.$Type
|
|
57
|
+
: 'Edm.String').replace(/^Edm\./, ''),
|
|
58
|
+
};
|
|
59
|
+
if (typeof prop.$MaxLength === 'number')
|
|
60
|
+
field.max = prop.$MaxLength;
|
|
61
|
+
const description = prop['@Priority.OData.Description'];
|
|
62
|
+
if (typeof description === 'string' && description)
|
|
63
|
+
field.description = description;
|
|
64
|
+
if (prop['@Org.OData.Core.V1.Permissions'] === 'Read')
|
|
65
|
+
field.readOnly = true;
|
|
66
|
+
if (prop['@Priority.OData.AutoUnique'] === true)
|
|
67
|
+
field.internalId = true;
|
|
68
|
+
const dateType = prop['@Priority.OData.DateType'];
|
|
69
|
+
if (typeof dateType === 'string' && dateType)
|
|
70
|
+
field.dateType = dateType;
|
|
71
|
+
fields.push(field);
|
|
72
|
+
}
|
|
73
|
+
types[typeName] = { key, fields, subs };
|
|
74
|
+
}
|
|
75
|
+
if (Object.keys(sets).length === 0)
|
|
76
|
+
invalid('no screens');
|
|
77
|
+
return {
|
|
78
|
+
format: INDEX_FORMAT,
|
|
79
|
+
version: meta.version,
|
|
80
|
+
builtAt: meta.builtAt,
|
|
81
|
+
sets,
|
|
82
|
+
types,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** Find a top-level screen: exact name first, then a unique case-insensitive match. */
|
|
86
|
+
export function resolveScreen(index, input) {
|
|
87
|
+
const exact = index.sets[input];
|
|
88
|
+
const names = Object.keys(index.sets);
|
|
89
|
+
const name = exact
|
|
90
|
+
? input
|
|
91
|
+
: (() => {
|
|
92
|
+
const matches = names.filter((n) => n.toLowerCase() === input.toLowerCase());
|
|
93
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
94
|
+
})();
|
|
95
|
+
const type = name ? index.types[index.sets[name] ?? ''] : undefined;
|
|
96
|
+
if (!name || !type) {
|
|
97
|
+
const near = suggest(input, names);
|
|
98
|
+
throw usage(`No screen named ${safeName(input)}.${near.length ? ` Did you mean ${near.join(', ')}?` : ''} Run \`priority-axi screens <text>\` to search.`);
|
|
99
|
+
}
|
|
100
|
+
return { name, type };
|
|
101
|
+
}
|
|
102
|
+
/** Find a sub-screen of a screen by its short name (ORDERITEMS) or its navigation name. */
|
|
103
|
+
export function resolveSub(index, screen, input) {
|
|
104
|
+
const upper = input.toUpperCase();
|
|
105
|
+
const sub = screen.type.subs.find((s) => s.name === input ||
|
|
106
|
+
s.nav === input ||
|
|
107
|
+
s.name.toUpperCase() === upper ||
|
|
108
|
+
s.nav.toUpperCase() === upper);
|
|
109
|
+
if (sub && !index.types[sub.type]) {
|
|
110
|
+
throw new AxiError('priority_error', `The metadata names ${screen.name} > ${sub.name} but does not describe it. Run \`priority-axi refresh\`.`);
|
|
111
|
+
}
|
|
112
|
+
const def = sub ? index.types[sub.type] : undefined;
|
|
113
|
+
if (!sub || !def) {
|
|
114
|
+
const near = suggest(input, screen.type.subs.map((s) => s.name));
|
|
115
|
+
throw usage(`${screen.name} has no sub-screen ${safeName(input)}.${near.length ? ` Did you mean ${near.join(', ')}?` : ''} Run \`priority-axi fields ${screen.name}\` to list them.`);
|
|
116
|
+
}
|
|
117
|
+
return { ...sub, def };
|
|
118
|
+
}
|
|
119
|
+
/** Find a field of a screen type: exact, then case-insensitive. */
|
|
120
|
+
export function resolveField(type, screenName, input) {
|
|
121
|
+
const upper = input.toUpperCase();
|
|
122
|
+
const field = type.fields.find((f) => f.name === input) ??
|
|
123
|
+
type.fields.find((f) => f.name === upper);
|
|
124
|
+
if (!field) {
|
|
125
|
+
const near = suggest(input, type.fields.map((f) => f.name));
|
|
126
|
+
throw usage(`${screenName} has no field ${safeName(input)}.${near.length ? ` Did you mean ${near.join(', ')}?` : ''} Run \`priority-axi fields ${screenName}\` to list them.`);
|
|
127
|
+
}
|
|
128
|
+
return field;
|
|
129
|
+
}
|
|
130
|
+
/** Echo a user-typed name only when it looks like a name; never echo arbitrary values. */
|
|
131
|
+
export function safeName(input) {
|
|
132
|
+
return /^[A-Za-z0-9_]{1,64}$/.test(input) ? input : 'with that name';
|
|
133
|
+
}
|
|
134
|
+
/** Up to five names: same name ignoring case, then names containing the input, then close edits. */
|
|
135
|
+
export function suggest(input, names, limit = 5) {
|
|
136
|
+
const q = input.toUpperCase();
|
|
137
|
+
if (!q)
|
|
138
|
+
return [];
|
|
139
|
+
const scored = [];
|
|
140
|
+
for (const name of names) {
|
|
141
|
+
const n = name.toUpperCase();
|
|
142
|
+
let score;
|
|
143
|
+
if (n === q)
|
|
144
|
+
score = 0;
|
|
145
|
+
else if (n.startsWith(q))
|
|
146
|
+
score = 1;
|
|
147
|
+
else if (n.includes(q))
|
|
148
|
+
score = 2;
|
|
149
|
+
else if (Math.abs(n.length - q.length) <= 2 && distance(n, q) <= 2)
|
|
150
|
+
score = 3;
|
|
151
|
+
if (score !== undefined)
|
|
152
|
+
scored.push([score, name]);
|
|
153
|
+
}
|
|
154
|
+
scored.sort((a, b) => a[0] - b[0] || a[1].length - b[1].length || a[1].localeCompare(b[1]));
|
|
155
|
+
return scored.slice(0, limit).map(([, name]) => name);
|
|
156
|
+
}
|
|
157
|
+
function distance(a, b) {
|
|
158
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
159
|
+
for (let i = 1; i <= a.length; i++) {
|
|
160
|
+
let prev = row[0] ?? 0;
|
|
161
|
+
row[0] = i;
|
|
162
|
+
for (let j = 1; j <= b.length; j++) {
|
|
163
|
+
const temp = row[j] ?? 0;
|
|
164
|
+
row[j] = Math.min((row[j] ?? 0) + 1, (row[j - 1] ?? 0) + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
165
|
+
prev = temp;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return row[b.length] ?? 0;
|
|
169
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// The cache is derived data. Every file is written to a temporary name and
|
|
2
|
+
// renamed, so a crash leaves the old file or the new one, never half of each.
|
|
3
|
+
// A file that cannot be read is treated as missing and rebuilt.
|
|
4
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
5
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { buildIndex, INDEX_FORMAT } from './build.js';
|
|
9
|
+
export const MAX_INDEX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
10
|
+
export function cacheDir(settings, env) {
|
|
11
|
+
const base = env.XDG_CACHE_HOME || join(homedir(), '.cache');
|
|
12
|
+
const id = createHash('sha256')
|
|
13
|
+
.update(`${settings.origin}|${settings.ini}|${settings.company}`)
|
|
14
|
+
.digest('hex')
|
|
15
|
+
.slice(0, 32);
|
|
16
|
+
return join(base, 'priority-axi', id);
|
|
17
|
+
}
|
|
18
|
+
export function readJson(path) {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function writeJsonAtomic(path, value) {
|
|
27
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
28
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
29
|
+
try {
|
|
30
|
+
writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
|
|
31
|
+
renameSync(tmp, path);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
rmSync(tmp, { force: true });
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function isIndex(value) {
|
|
39
|
+
if (!value || typeof value !== 'object')
|
|
40
|
+
return false;
|
|
41
|
+
const v = value;
|
|
42
|
+
return (v.format === INDEX_FORMAT &&
|
|
43
|
+
typeof v.version === 'string' &&
|
|
44
|
+
typeof v.builtAt === 'string' &&
|
|
45
|
+
!!v.sets &&
|
|
46
|
+
typeof v.sets === 'object' &&
|
|
47
|
+
!!v.types &&
|
|
48
|
+
typeof v.types === 'object');
|
|
49
|
+
}
|
|
50
|
+
export function readIndex(dir) {
|
|
51
|
+
const value = readJson(join(dir, 'index.json'));
|
|
52
|
+
return isIndex(value) ? value : undefined;
|
|
53
|
+
}
|
|
54
|
+
/** Why the cached index must be rebuilt, or undefined when it is fresh. */
|
|
55
|
+
export function staleReason(index, opts) {
|
|
56
|
+
if (!index)
|
|
57
|
+
return 'missing';
|
|
58
|
+
if (opts.refresh)
|
|
59
|
+
return 'refresh';
|
|
60
|
+
if (opts.liveVersion !== undefined && opts.liveVersion !== index.version)
|
|
61
|
+
return 'version';
|
|
62
|
+
const built = Date.parse(index.builtAt);
|
|
63
|
+
if (!Number.isFinite(built) || opts.now.getTime() - built > MAX_INDEX_AGE_MS)
|
|
64
|
+
return 'age';
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Return the cached index, rebuilding it when missing, older than seven days,
|
|
69
|
+
* built for another Priority version (when the live version is known), or on
|
|
70
|
+
* refresh. Commands that know no live version stay offline while the cache is fresh.
|
|
71
|
+
*/
|
|
72
|
+
export async function loadIndex(dir, source, opts) {
|
|
73
|
+
const cached = readIndex(dir);
|
|
74
|
+
const reason = staleReason(cached, opts);
|
|
75
|
+
if (cached && !reason)
|
|
76
|
+
return { index: cached };
|
|
77
|
+
const version = opts.liveVersion ?? (await source.fetchVersion());
|
|
78
|
+
const { csdl, bytes, ms } = await source.fetchMetadata();
|
|
79
|
+
const index = buildIndex(csdl, { version, builtAt: opts.now.toISOString() });
|
|
80
|
+
writeJsonAtomic(join(dir, 'index.json'), index);
|
|
81
|
+
return { index, rebuilt: { reason: reason ?? 'missing', bytes, ms } };
|
|
82
|
+
}
|
|
83
|
+
export function readReach(dir) {
|
|
84
|
+
const value = readJson(join(dir, 'reach.json'));
|
|
85
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
86
|
+
return {};
|
|
87
|
+
const out = {};
|
|
88
|
+
for (const [screen, entry] of Object.entries(value)) {
|
|
89
|
+
const e = entry;
|
|
90
|
+
if (e && (e.api === 'yes' || e.api === 'no') && typeof e.at === 'string') {
|
|
91
|
+
out[screen] = { api: e.api, at: e.at };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
/** Record the last API answer seen for a screen. Never fails the command. */
|
|
97
|
+
export function recordReach(dir, screen, api, now) {
|
|
98
|
+
try {
|
|
99
|
+
const reach = readReach(dir);
|
|
100
|
+
if (reach[screen]?.api === api)
|
|
101
|
+
return;
|
|
102
|
+
reach[screen] = { api, at: now.toISOString() };
|
|
103
|
+
writeJsonAtomic(join(dir, 'reach.json'), reach);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// The record is a convenience; losing it costs nothing.
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export function readCompany(dir, code, now) {
|
|
110
|
+
const value = readJson(join(dir, 'company.json'));
|
|
111
|
+
if (!value ||
|
|
112
|
+
value.code !== code ||
|
|
113
|
+
typeof value.title !== 'string' ||
|
|
114
|
+
typeof value.checkedAt !== 'string') {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
const at = Date.parse(value.checkedAt);
|
|
118
|
+
if (!Number.isFinite(at) || now.getTime() - at > MAX_INDEX_AGE_MS)
|
|
119
|
+
return undefined;
|
|
120
|
+
return { code: value.code, title: value.title, checkedAt: value.checkedAt };
|
|
121
|
+
}
|
|
122
|
+
export function writeCompany(dir, check) {
|
|
123
|
+
try {
|
|
124
|
+
writeJsonAtomic(join(dir, 'company.json'), check);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// Derived; the next command checks again.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// A local copy of one screen's key, description, unit, family and status
|
|
2
|
+
// columns, for `find`. Priority cannot search text (contains and startswith
|
|
3
|
+
// answer 501), so the catalog is pulled once, page by page, and searched
|
|
4
|
+
// locally. It is rebuilt after a day, or with --refresh. Like the index, it is
|
|
5
|
+
// derived data under the connection's cache directory.
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { usage } from '../errors.js';
|
|
8
|
+
import { queryString } from '../odata.js';
|
|
9
|
+
import { readJson, writeJsonAtomic } from './cache.js';
|
|
10
|
+
export const CATALOG_FORMAT = 1;
|
|
11
|
+
export const MAX_CATALOG_AGE_MS = 24 * 60 * 60 * 1000;
|
|
12
|
+
export const CATALOG_PAGE = 1000;
|
|
13
|
+
/** Pages read at once after the first, as the live sweep does. */
|
|
14
|
+
export const CATALOG_PARALLEL = 4;
|
|
15
|
+
/** Top-level records read at most; beyond this the catalog is marked partial. */
|
|
16
|
+
export const MAX_CATALOG_RECORDS = 200_000;
|
|
17
|
+
const unique = (names) => [
|
|
18
|
+
...new Set(names.filter((n) => !!n)),
|
|
19
|
+
];
|
|
20
|
+
const has = (type, name) => type.fields.some((f) => f.name === name);
|
|
21
|
+
/**
|
|
22
|
+
* A screen level's searchable columns: its key; its main description (the
|
|
23
|
+
* first editable text field named ...DES, such as PARTDES, CUSTDES or PROJDES,
|
|
24
|
+
* so a customer name copied onto a project does not win); the foreign
|
|
25
|
+
* description beside it; the sales unit; the family; the status; and the
|
|
26
|
+
* customer it belongs to (CUSTNAME and CUSTDES on a project).
|
|
27
|
+
*/
|
|
28
|
+
function level(type, label, hint) {
|
|
29
|
+
const key = type.key.filter((k) => has(type, k));
|
|
30
|
+
const named = type.fields.filter((f) => f.type === 'String' &&
|
|
31
|
+
!f.internalId &&
|
|
32
|
+
!key.includes(f.name) &&
|
|
33
|
+
f.name !== 'STATDES' &&
|
|
34
|
+
/DES$/.test(f.name));
|
|
35
|
+
const description = (named.find((f) => !f.readOnly) ?? named[0])?.name;
|
|
36
|
+
if (!description) {
|
|
37
|
+
throw usage(`${label} has no description field for find to search. ${hint}`);
|
|
38
|
+
}
|
|
39
|
+
const foreign = has(type, `E${description}`) ? `E${description}` : undefined;
|
|
40
|
+
const unit = ['PUNITNAME', 'UNITNAME'].find((n) => has(type, n));
|
|
41
|
+
const customer = description !== 'CUSTDES' &&
|
|
42
|
+
!key.includes('CUSTNAME') &&
|
|
43
|
+
has(type, 'CUSTDES')
|
|
44
|
+
? unique([has(type, 'CUSTNAME') ? 'CUSTNAME' : undefined, 'CUSTDES'])
|
|
45
|
+
: [];
|
|
46
|
+
return {
|
|
47
|
+
key,
|
|
48
|
+
description,
|
|
49
|
+
foreign,
|
|
50
|
+
unit,
|
|
51
|
+
family: has(type, 'FAMILYDES') ? 'FAMILYDES' : undefined,
|
|
52
|
+
status: has(type, 'STATDES') ? 'STATDES' : undefined,
|
|
53
|
+
customer,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export function layout(screen, sub) {
|
|
57
|
+
const top = level(screen.type, screen.name, `Use \`priority-axi get ${screen.name} --where F=V\` instead.`);
|
|
58
|
+
if (!sub) {
|
|
59
|
+
const columns = unique([
|
|
60
|
+
...top.key,
|
|
61
|
+
top.description,
|
|
62
|
+
top.foreign,
|
|
63
|
+
top.unit,
|
|
64
|
+
top.family,
|
|
65
|
+
top.status,
|
|
66
|
+
...top.customer,
|
|
67
|
+
]);
|
|
68
|
+
const own = unique([...top.key, top.description, top.foreign, top.family]);
|
|
69
|
+
return {
|
|
70
|
+
columns,
|
|
71
|
+
select: columns,
|
|
72
|
+
search: unique([
|
|
73
|
+
...own,
|
|
74
|
+
top.customer.includes('CUSTDES') ? 'CUSTDES' : undefined,
|
|
75
|
+
]),
|
|
76
|
+
show: unique([
|
|
77
|
+
...top.key,
|
|
78
|
+
top.description,
|
|
79
|
+
top.unit,
|
|
80
|
+
top.family,
|
|
81
|
+
...top.customer,
|
|
82
|
+
]),
|
|
83
|
+
status: unique([top.status]),
|
|
84
|
+
key: top.key,
|
|
85
|
+
parentKey: top.key,
|
|
86
|
+
own,
|
|
87
|
+
context: top.customer.length ? 'customer' : undefined,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
const low = level(sub.def, `${screen.name} > ${sub.name}`, `Use \`priority-axi show ${screen.name} <key> --with ${sub.name}\` instead.`);
|
|
91
|
+
const parent = unique([...top.key, top.description, top.status]);
|
|
92
|
+
const subFields = unique([
|
|
93
|
+
...low.key,
|
|
94
|
+
low.description,
|
|
95
|
+
low.foreign,
|
|
96
|
+
low.unit,
|
|
97
|
+
low.family,
|
|
98
|
+
low.status,
|
|
99
|
+
]);
|
|
100
|
+
// A sub-screen column named like a parent column is stored as SUB.FIELD.
|
|
101
|
+
const stored = (f) => f === undefined ? undefined : parent.includes(f) ? `${sub.name}.${f}` : f;
|
|
102
|
+
const own = unique([
|
|
103
|
+
...low.key.map(stored),
|
|
104
|
+
stored(low.description),
|
|
105
|
+
stored(low.foreign),
|
|
106
|
+
stored(low.family),
|
|
107
|
+
]);
|
|
108
|
+
return {
|
|
109
|
+
columns: [...parent, ...subFields.map((f) => stored(f))],
|
|
110
|
+
select: parent,
|
|
111
|
+
subSelect: subFields,
|
|
112
|
+
search: unique([...own, top.description]),
|
|
113
|
+
own,
|
|
114
|
+
context: 'parent',
|
|
115
|
+
show: unique([
|
|
116
|
+
...low.key.map(stored),
|
|
117
|
+
stored(low.description),
|
|
118
|
+
stored(low.unit),
|
|
119
|
+
...top.key,
|
|
120
|
+
top.description,
|
|
121
|
+
]),
|
|
122
|
+
status: unique([top.status, stored(low.status)]),
|
|
123
|
+
key: low.key.map((k) => stored(k)),
|
|
124
|
+
parentKey: top.key,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function catalogPath(dir, screen, sub) {
|
|
128
|
+
return join(dir, 'find', `${screen}${sub ? `.${sub}` : ''}.json`);
|
|
129
|
+
}
|
|
130
|
+
export function readCatalog(dir, screen, sub, columns, now) {
|
|
131
|
+
const value = readJson(catalogPath(dir, screen, sub));
|
|
132
|
+
if (!value ||
|
|
133
|
+
value.format !== CATALOG_FORMAT ||
|
|
134
|
+
value.screen !== screen ||
|
|
135
|
+
value.sub !== sub ||
|
|
136
|
+
!Array.isArray(value.rows) ||
|
|
137
|
+
!Array.isArray(value.columns) ||
|
|
138
|
+
value.columns.join(',') !== columns.join(',') ||
|
|
139
|
+
typeof value.builtAt !== 'string') {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
const age = now.getTime() - Date.parse(value.builtAt);
|
|
143
|
+
if (!(age >= 0 && age < MAX_CATALOG_AGE_MS))
|
|
144
|
+
return undefined;
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
export function writeCatalog(dir, catalog) {
|
|
148
|
+
writeJsonAtomic(catalogPath(dir, catalog.screen, catalog.sub), catalog);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Read every record, ordered by the key, CATALOG_PAGE at a time: the first page
|
|
152
|
+
* alone, then CATALOG_PARALLEL pages at once until a short page.
|
|
153
|
+
*/
|
|
154
|
+
export async function pullCatalog(screen, sub, lay, read, now) {
|
|
155
|
+
const order = screen.type.key.filter((k) => has(screen.type, k)).join(',');
|
|
156
|
+
const query = (skip) => queryString({
|
|
157
|
+
$select: lay.select.join(','),
|
|
158
|
+
$orderby: order || undefined,
|
|
159
|
+
$top: CATALOG_PAGE,
|
|
160
|
+
$skip: skip || undefined,
|
|
161
|
+
$expand: sub && lay.subSelect
|
|
162
|
+
? `${sub.nav}($select=${lay.subSelect.join(',')})`
|
|
163
|
+
: undefined,
|
|
164
|
+
});
|
|
165
|
+
const rows = [];
|
|
166
|
+
let records = 0;
|
|
167
|
+
let partial = false;
|
|
168
|
+
const take = (page) => {
|
|
169
|
+
records += page.length;
|
|
170
|
+
for (const record of page) {
|
|
171
|
+
const head = lay.select.map((c) => record[c] ?? null);
|
|
172
|
+
if (!sub || !lay.subSelect) {
|
|
173
|
+
rows.push(head);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const value = record[sub.nav];
|
|
177
|
+
const lines = Array.isArray(value)
|
|
178
|
+
? value
|
|
179
|
+
: value && typeof value === 'object'
|
|
180
|
+
? [value]
|
|
181
|
+
: [];
|
|
182
|
+
for (const line of lines) {
|
|
183
|
+
rows.push([...head, ...lay.subSelect.map((c) => line[c] ?? null)]);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
const first = await read(query(0));
|
|
188
|
+
take(first);
|
|
189
|
+
let done = first.length < CATALOG_PAGE;
|
|
190
|
+
let skip = CATALOG_PAGE;
|
|
191
|
+
while (!done) {
|
|
192
|
+
if (records >= MAX_CATALOG_RECORDS) {
|
|
193
|
+
partial = true;
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
const pages = await Promise.all(Array.from({ length: CATALOG_PARALLEL }, (_, i) => read(query(skip + i * CATALOG_PAGE))));
|
|
197
|
+
skip += CATALOG_PARALLEL * CATALOG_PAGE;
|
|
198
|
+
for (const page of pages) {
|
|
199
|
+
take(page);
|
|
200
|
+
if (page.length < CATALOG_PAGE) {
|
|
201
|
+
done = true;
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
format: CATALOG_FORMAT,
|
|
208
|
+
builtAt: now.toISOString(),
|
|
209
|
+
screen: screen.name,
|
|
210
|
+
...(sub ? { sub: sub.name } : {}),
|
|
211
|
+
columns: lay.columns,
|
|
212
|
+
rows,
|
|
213
|
+
records,
|
|
214
|
+
...(partial ? { partial: true } : {}),
|
|
215
|
+
};
|
|
216
|
+
}
|