priority-axi 0.0.0-stage → 0.1.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/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
+ }
package/dist/http.js ADDED
@@ -0,0 +1,118 @@
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
+ : '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.');
57
+ }
58
+ const text = buffer.toString('utf8');
59
+ let json;
60
+ let malformed = false;
61
+ try {
62
+ json = text ? JSON.parse(text) : undefined;
63
+ }
64
+ catch {
65
+ json = undefined;
66
+ malformed = true;
67
+ }
68
+ return {
69
+ status: response.status,
70
+ headers: response.headers,
71
+ json,
72
+ malformed,
73
+ ...(malformed ? { text: text.slice(0, 8000) } : {}),
74
+ bytes: buffer.length,
75
+ ms: Math.round(performance.now() - started),
76
+ };
77
+ }
78
+ /** Send a call and return the answer, or throw the classified error. */
79
+ export async function send(settings, call, deps = defaultDeps) {
80
+ let answer = await once(settings, call, deps);
81
+ if (answer.status === 429 && call.method === 'GET') {
82
+ const wait = Number(answer.headers.get('retry-after') ?? '');
83
+ if (Number.isFinite(wait) && wait >= 0 && wait <= MAX_RETRY_AFTER_S) {
84
+ await deps.sleep(wait * 1000);
85
+ answer = await once(settings, call, deps);
86
+ }
87
+ }
88
+ if (answer.status >= 300 && answer.status < 400) {
89
+ throw new AxiError('priority_error', `Priority answered with a redirect (${answer.status}), which priority-axi does not follow.`);
90
+ }
91
+ const error = classify(answer, {
92
+ company: settings.company,
93
+ ...call.context,
94
+ });
95
+ if (error)
96
+ throw error;
97
+ return answer;
98
+ }
99
+ /** The "value" array of a collection answer. */
100
+ export function rowsOf(answer) {
101
+ if (answer.malformed) {
102
+ throw new AxiError('priority_error', `Priority sent an incomplete answer (${answer.bytes} bytes). Try again with a smaller --limit or fewer --with sub-screens.`);
103
+ }
104
+ const value = answer.json?.value;
105
+ if (!Array.isArray(value) ||
106
+ value.some((r) => !r || typeof r !== 'object' || Array.isArray(r))) {
107
+ throw new AxiError('priority_error', 'Priority returned a collection priority-axi cannot read.');
108
+ }
109
+ return value;
110
+ }
111
+ /** The "value" string of a function answer such as GetPriorityVersion(). */
112
+ export function stringValue(answer, what) {
113
+ const value = answer.json?.value;
114
+ if (typeof value !== 'string' || !value) {
115
+ throw new AxiError('priority_error', `Priority returned no ${what}.`);
116
+ }
117
+ return value;
118
+ }
@@ -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
+ }