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/LICENSE +21 -0
- package/NOTICE +13 -0
- package/README.md +177 -2
- package/dist/bin/priority-axi.js +17 -0
- package/dist/cli/parse.js +69 -0
- package/dist/cli/run.js +323 -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/config.js +76 -0
- package/dist/errors.js +149 -0
- package/dist/http.js +118 -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 +108 -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
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// screens and fields: offline over the screen index once it is built.
|
|
2
|
+
import { resolveScreen, resolveSub, } from '../index/build.js';
|
|
3
|
+
import { readReach } from '../index/cache.js';
|
|
4
|
+
import { bounded, cut, render } from '../output/toon.js';
|
|
5
|
+
import { builtNote, commandLine, intFlag, open, screenIndex, shellWord, str, } from './common.js';
|
|
6
|
+
function scoreScreen(name, type, q) {
|
|
7
|
+
const lower = name.toLowerCase();
|
|
8
|
+
if (lower === q)
|
|
9
|
+
return { name, score: 0, match: 'name' };
|
|
10
|
+
if (lower.startsWith(q))
|
|
11
|
+
return { name, score: 1, match: 'name' };
|
|
12
|
+
if (lower.includes(q))
|
|
13
|
+
return { name, score: 2, match: 'name' };
|
|
14
|
+
const sub = type.subs.find((s) => s.name.toLowerCase().includes(q) || s.title?.toLowerCase().includes(q));
|
|
15
|
+
if (sub) {
|
|
16
|
+
return {
|
|
17
|
+
name,
|
|
18
|
+
score: 3,
|
|
19
|
+
match: `sub ${sub.name}${sub.title ? ` (${sub.title})` : ''}`,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const field = type.fields.find((f) => f.name.toLowerCase() === q || f.description?.toLowerCase().includes(q));
|
|
23
|
+
if (field) {
|
|
24
|
+
return {
|
|
25
|
+
name,
|
|
26
|
+
score: 4,
|
|
27
|
+
match: `field ${field.name}${field.description ? ` (${field.description})` : ''}`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
export async function screens(input) {
|
|
33
|
+
const s = open(input);
|
|
34
|
+
const loaded = await screenIndex(s);
|
|
35
|
+
const { index } = loaded;
|
|
36
|
+
const text = input.positionals[0]?.trim();
|
|
37
|
+
const q = text?.toLowerCase();
|
|
38
|
+
const limit = intFlag(input.values.limit, 'limit', 20, 1, 2000);
|
|
39
|
+
const full = input.values.full === true;
|
|
40
|
+
const reach = readReach(s.dir);
|
|
41
|
+
const api = (name) => reach[name]?.api ?? 'unknown';
|
|
42
|
+
const rank = (name) => api(name) === 'yes' ? 0 : api(name) === 'unknown' ? 1 : 2;
|
|
43
|
+
const hits = [];
|
|
44
|
+
for (const [name, typeName] of Object.entries(index.sets)) {
|
|
45
|
+
const type = index.types[typeName];
|
|
46
|
+
if (!type)
|
|
47
|
+
continue;
|
|
48
|
+
const hit = q
|
|
49
|
+
? scoreScreen(name, type, q)
|
|
50
|
+
: { name, score: 0, match: null };
|
|
51
|
+
if (hit)
|
|
52
|
+
hits.push(hit);
|
|
53
|
+
}
|
|
54
|
+
hits.sort((a, b) => a.score - b.score ||
|
|
55
|
+
rank(a.name) - rank(b.name) ||
|
|
56
|
+
a.name.localeCompare(b.name));
|
|
57
|
+
const rows = hits.map((h) => {
|
|
58
|
+
const type = index.types[index.sets[h.name] ?? ''];
|
|
59
|
+
return {
|
|
60
|
+
name: h.name,
|
|
61
|
+
key: type?.key.length ? type.key.join('+') : null,
|
|
62
|
+
api: api(h.name),
|
|
63
|
+
...(q ? { match: h.match } : { fields: type?.fields.length ?? 0 }),
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const noun = (n) => (n === 1 ? 'screen' : 'screens');
|
|
67
|
+
const total = rows.length;
|
|
68
|
+
const capped = full ? total : Math.min(limit, total);
|
|
69
|
+
const what = q
|
|
70
|
+
? `${total} ${noun(total)} match ${text}`
|
|
71
|
+
: `${total} ${noun(total)}`;
|
|
72
|
+
if (!total) {
|
|
73
|
+
return render({ summary: what, ...builtNote(loaded) }, [
|
|
74
|
+
'Run `priority-axi screens` to list every screen',
|
|
75
|
+
]);
|
|
76
|
+
}
|
|
77
|
+
return bounded({
|
|
78
|
+
total: capped,
|
|
79
|
+
narrower: `priority-axi screens ${text ? `${shellWord(text)} ` : ''}--limit 20`,
|
|
80
|
+
build: (shown, fieldLimit) => {
|
|
81
|
+
const listed = rows
|
|
82
|
+
.slice(0, shown)
|
|
83
|
+
.map((r) => 'match' in r &&
|
|
84
|
+
typeof r.match === 'string' &&
|
|
85
|
+
Number.isFinite(fieldLimit)
|
|
86
|
+
? { ...r, match: cut(r.match, Math.min(fieldLimit, 80)) }
|
|
87
|
+
: r);
|
|
88
|
+
const help = [];
|
|
89
|
+
if (shown < total) {
|
|
90
|
+
help.push(`Run \`${commandLine('screens', text ? [text] : [], input.values, { full: '', limit: null })}\` to list all ${total}`);
|
|
91
|
+
}
|
|
92
|
+
help.push("Run `priority-axi fields <SCREEN>` to see a screen's fields");
|
|
93
|
+
return render({
|
|
94
|
+
summary: shown < total ? `${what} (${shown} shown)` : what,
|
|
95
|
+
...builtNote(loaded),
|
|
96
|
+
screens: listed,
|
|
97
|
+
}, help);
|
|
98
|
+
},
|
|
99
|
+
}, full);
|
|
100
|
+
}
|
|
101
|
+
export function shortType(f) {
|
|
102
|
+
switch (f.type) {
|
|
103
|
+
case 'String':
|
|
104
|
+
return f.max ? `text(${f.max})` : 'text';
|
|
105
|
+
case 'Int16':
|
|
106
|
+
case 'Int32':
|
|
107
|
+
case 'Int64':
|
|
108
|
+
return 'int';
|
|
109
|
+
case 'Decimal':
|
|
110
|
+
case 'Double':
|
|
111
|
+
case 'Single':
|
|
112
|
+
return 'decimal';
|
|
113
|
+
case 'DateTimeOffset':
|
|
114
|
+
return f.dateType === 'Date' ? 'date' : 'datetime';
|
|
115
|
+
case 'Boolean':
|
|
116
|
+
return 'bool';
|
|
117
|
+
default:
|
|
118
|
+
return f.type.toLowerCase();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
export async function fields(input) {
|
|
122
|
+
const s = open(input);
|
|
123
|
+
const loaded = await screenIndex(s);
|
|
124
|
+
const { index } = loaded;
|
|
125
|
+
const screen = resolveScreen(index, input.positionals[0] ?? '');
|
|
126
|
+
const subName = str(input.values.sub);
|
|
127
|
+
const sub = subName ? resolveSub(index, screen, subName) : undefined;
|
|
128
|
+
const type = sub ? sub.def : screen.type;
|
|
129
|
+
const all = input.values.all === true;
|
|
130
|
+
const full = input.values.full === true;
|
|
131
|
+
const listed = type.fields.filter((f) => all || !f.internalId || type.key.includes(f.name));
|
|
132
|
+
const hidden = type.fields.length - listed.length;
|
|
133
|
+
const rows = listed.map((f) => {
|
|
134
|
+
const flags = [
|
|
135
|
+
type.key.includes(f.name) ? 'key' : '',
|
|
136
|
+
f.readOnly ? 'read-only' : '',
|
|
137
|
+
f.internalId ? 'id' : '',
|
|
138
|
+
].filter(Boolean);
|
|
139
|
+
return {
|
|
140
|
+
name: f.name,
|
|
141
|
+
type: shortType(f),
|
|
142
|
+
flags: flags.length ? flags.join(' ') : null,
|
|
143
|
+
description: f.description ?? null,
|
|
144
|
+
};
|
|
145
|
+
});
|
|
146
|
+
const target = sub ? `${screen.name} > ${sub.name}` : screen.name;
|
|
147
|
+
const summary = `${type.fields.length} fields${hidden ? ` (${hidden} internal ID${hidden === 1 ? '' : 's'} hidden; --all shows them)` : ''}`;
|
|
148
|
+
const head = {
|
|
149
|
+
screen: target,
|
|
150
|
+
...(sub?.title ? { title: sub.title } : {}),
|
|
151
|
+
...(sub ? { holds: sub.many ? 'lines' : 'one record' } : {}),
|
|
152
|
+
key: type.key.length ? type.key.join(', ') : null,
|
|
153
|
+
summary,
|
|
154
|
+
...builtNote(loaded),
|
|
155
|
+
};
|
|
156
|
+
const subs = sub ? [] : screen.type.subs.map((x) => x.name);
|
|
157
|
+
return bounded({
|
|
158
|
+
total: rows.length,
|
|
159
|
+
narrower: `priority-axi fields ${screen.name}`,
|
|
160
|
+
build: (shown) => {
|
|
161
|
+
const help = [
|
|
162
|
+
`Run \`priority-axi get ${screen.name} --limit 5\` to read records`,
|
|
163
|
+
];
|
|
164
|
+
if (shown < rows.length) {
|
|
165
|
+
help.push(`Run \`${commandLine('fields', [screen.name], input.values, { full: '' })}\` to list all ${rows.length} fields without the size limit (${shown} shown)`);
|
|
166
|
+
}
|
|
167
|
+
else if (subs.length) {
|
|
168
|
+
help.push(`Run \`priority-axi fields ${screen.name} --sub <SUB>\` for a sub-screen`);
|
|
169
|
+
}
|
|
170
|
+
return render({
|
|
171
|
+
...head,
|
|
172
|
+
fields: rows.slice(0, shown),
|
|
173
|
+
...(shown < rows.length
|
|
174
|
+
? { omitted: `${rows.length - shown} fields not shown` }
|
|
175
|
+
: {}),
|
|
176
|
+
...(subs.length ? { subforms: subs } : {}),
|
|
177
|
+
}, help);
|
|
178
|
+
},
|
|
179
|
+
}, full);
|
|
180
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Shared steps for commands that talk to Priority.
|
|
2
|
+
import { readSettings } from '../config.js';
|
|
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';
|
|
6
|
+
import { screenSegment, utc } from '../odata.js';
|
|
7
|
+
const text = (v) => (typeof v === 'string' ? v : undefined);
|
|
8
|
+
export function open(input) {
|
|
9
|
+
const settings = readSettings(input.io.env, {
|
|
10
|
+
company: text(input.values.company),
|
|
11
|
+
user: text(input.values.user),
|
|
12
|
+
ini: text(input.values.ini),
|
|
13
|
+
});
|
|
14
|
+
return { settings, dir: cacheDir(settings, input.io.env), input };
|
|
15
|
+
}
|
|
16
|
+
export async function priorityVersion(s) {
|
|
17
|
+
const answer = await send(s.settings, { method: 'GET', path: 'GetPriorityVersion()' }, s.input.io.http);
|
|
18
|
+
return stringValue(answer, 'version');
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Prove the company exists. Function calls such as GetPriorityVersion()
|
|
22
|
+
* accept any company code, so only GETCOMPANIES can tell. The answer is
|
|
23
|
+
* cached for seven days; `live` always asks Priority.
|
|
24
|
+
*/
|
|
25
|
+
export async function checkCompany(s, live) {
|
|
26
|
+
const now = s.input.io.now();
|
|
27
|
+
if (!live) {
|
|
28
|
+
const cached = readCompany(s.dir, s.settings.company, now);
|
|
29
|
+
if (cached)
|
|
30
|
+
return cached;
|
|
31
|
+
}
|
|
32
|
+
const answer = await send(s.settings, { method: 'GET', path: 'GETCOMPANIES' }, s.input.io.http);
|
|
33
|
+
const rows = rowsOf(answer);
|
|
34
|
+
const row = rows.find((r) => r.NAME === s.settings.company);
|
|
35
|
+
if (!row) {
|
|
36
|
+
const known = rows
|
|
37
|
+
.map((r) => r.NAME)
|
|
38
|
+
.filter((n) => typeof n === 'string');
|
|
39
|
+
throw new AxiError('company_not_found', `Priority does not list company ${s.settings.company} for this user.${known.length ? ` Companies: ${known.slice(0, 20).join(', ')}.` : ''} Check the code with the owner.`);
|
|
40
|
+
}
|
|
41
|
+
const check = {
|
|
42
|
+
code: s.settings.company,
|
|
43
|
+
title: typeof row.TITLE === 'string' ? row.TITLE : '',
|
|
44
|
+
checkedAt: now.toISOString(),
|
|
45
|
+
};
|
|
46
|
+
writeCompany(s.dir, check);
|
|
47
|
+
return check;
|
|
48
|
+
}
|
|
49
|
+
export function indexSource(s) {
|
|
50
|
+
return {
|
|
51
|
+
fetchVersion: () => priorityVersion(s),
|
|
52
|
+
fetchMetadata: async () => {
|
|
53
|
+
const answer = await send(s.settings, { method: 'GET', path: '$metadata', query: '?$format=json' }, s.input.io.http);
|
|
54
|
+
if (!answer.json)
|
|
55
|
+
throw new AxiError('priority_error', 'Priority returned metadata that is not JSON.');
|
|
56
|
+
return { csdl: answer.json, bytes: answer.bytes, ms: answer.ms };
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The screen index, offline while the cache is fresh. Before downloading the
|
|
62
|
+
* metadata, the company is checked, so a typo never builds a cache.
|
|
63
|
+
*/
|
|
64
|
+
export async function screenIndex(s) {
|
|
65
|
+
const now = s.input.io.now();
|
|
66
|
+
const cached = readIndex(s.dir);
|
|
67
|
+
if (cached && !staleReason(cached, { now }))
|
|
68
|
+
return { index: cached };
|
|
69
|
+
await checkCompany(s, false);
|
|
70
|
+
return loadIndex(s.dir, indexSource(s), { now });
|
|
71
|
+
}
|
|
72
|
+
/** A note for output when this command had to build the index first. */
|
|
73
|
+
export function builtNote(loaded) {
|
|
74
|
+
if (!loaded.rebuilt)
|
|
75
|
+
return {};
|
|
76
|
+
const mb = (loaded.rebuilt.bytes / 2 ** 20).toFixed(1);
|
|
77
|
+
return { index: `built now from Priority's metadata (${mb} MB)` };
|
|
78
|
+
}
|
|
79
|
+
/** Send a read for a screen, recording whether Priority allowed API access to it. */
|
|
80
|
+
export async function readScreen(s, screen, query) {
|
|
81
|
+
const now = s.input.io.now();
|
|
82
|
+
try {
|
|
83
|
+
const answer = await send(s.settings, {
|
|
84
|
+
method: 'GET',
|
|
85
|
+
path: screenSegment(screen),
|
|
86
|
+
query,
|
|
87
|
+
context: { screen },
|
|
88
|
+
}, s.input.io.http);
|
|
89
|
+
recordReach(s.dir, screen, 'yes', now);
|
|
90
|
+
return answer;
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof AxiError && error.code === 'screen_not_enabled') {
|
|
94
|
+
recordReach(s.dir, screen, 'no', now);
|
|
95
|
+
}
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// ---------- flag helpers ----------
|
|
100
|
+
export const str = (v) => typeof v === 'string' ? v : undefined;
|
|
101
|
+
export const strings = (v) => Array.isArray(v)
|
|
102
|
+
? v.filter((x) => typeof x === 'string')
|
|
103
|
+
: typeof v === 'string'
|
|
104
|
+
? [v]
|
|
105
|
+
: [];
|
|
106
|
+
export function intFlag(v, name, fallback, min, max) {
|
|
107
|
+
if (v === undefined)
|
|
108
|
+
return fallback;
|
|
109
|
+
const n = typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : Number.NaN;
|
|
110
|
+
if (!Number.isSafeInteger(n) || n < min || n > max) {
|
|
111
|
+
throw usage(`--${name} takes a whole number from ${min} to ${max}.`);
|
|
112
|
+
}
|
|
113
|
+
return n;
|
|
114
|
+
}
|
|
115
|
+
/** --since as a date, a full time, or a relative 7d or 24h. */
|
|
116
|
+
export function sinceFlag(v, now) {
|
|
117
|
+
if (typeof v !== 'string' || !v) {
|
|
118
|
+
throw usage('changes needs --since <time>, such as --since 7d, --since 24h or --since 2026-11-01.');
|
|
119
|
+
}
|
|
120
|
+
const rel = /^(\d{1,4})([dh])$/.exec(v);
|
|
121
|
+
if (rel) {
|
|
122
|
+
const hours = Number(rel[1]) * (rel[2] === 'd' ? 24 : 1);
|
|
123
|
+
return new Date(now.getTime() - hours * 3600_000)
|
|
124
|
+
.toISOString()
|
|
125
|
+
.replace(/\.\d{3}Z$/, 'Z');
|
|
126
|
+
}
|
|
127
|
+
return utc(v, '--since');
|
|
128
|
+
}
|
|
129
|
+
const SAFE_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
|
|
130
|
+
/** A shell word: bare when safe, otherwise single-quoted. */
|
|
131
|
+
export function shellWord(word) {
|
|
132
|
+
return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
|
|
133
|
+
}
|
|
134
|
+
/** Rebuild a command line for a help hint, with some flags replaced or removed. */
|
|
135
|
+
export function commandLine(name, positionals, values, change = {}) {
|
|
136
|
+
const parts = [`priority-axi ${name}`, ...positionals.map(shellWord)];
|
|
137
|
+
const seen = new Set();
|
|
138
|
+
const emit = (flag, value) => {
|
|
139
|
+
if (value === true)
|
|
140
|
+
parts.push(`--${flag}`);
|
|
141
|
+
else if (typeof value === 'string')
|
|
142
|
+
parts.push(`--${flag}`, shellWord(value));
|
|
143
|
+
};
|
|
144
|
+
for (const [flag, value] of Object.entries(values)) {
|
|
145
|
+
if (value === undefined || flag in change)
|
|
146
|
+
continue;
|
|
147
|
+
seen.add(flag);
|
|
148
|
+
if (Array.isArray(value))
|
|
149
|
+
for (const item of value)
|
|
150
|
+
emit(flag, item);
|
|
151
|
+
else
|
|
152
|
+
emit(flag, value);
|
|
153
|
+
}
|
|
154
|
+
for (const [flag, value] of Object.entries(change)) {
|
|
155
|
+
if (value !== null && !seen.has(flag))
|
|
156
|
+
emit(flag, value === '' ? true : value);
|
|
157
|
+
}
|
|
158
|
+
return parts.join(' ');
|
|
159
|
+
}
|
|
160
|
+
/** Rebuild a command in the order given, for commands where order carries meaning (create). */
|
|
161
|
+
export function tokenLine(name, tokens, drop = []) {
|
|
162
|
+
const parts = [`priority-axi ${name}`];
|
|
163
|
+
for (const token of tokens) {
|
|
164
|
+
if (token.kind === 'positional')
|
|
165
|
+
parts.push(shellWord(token.value));
|
|
166
|
+
else if (!drop.includes(token.name)) {
|
|
167
|
+
parts.push(`--${token.name}`);
|
|
168
|
+
if (token.value !== undefined)
|
|
169
|
+
parts.push(shellWord(token.value));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return parts.join(' ');
|
|
173
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// create: check everything against the index, build one deep-insert body,
|
|
2
|
+
// and send it once. Inside Comis the Gate holds it for the owner's approval.
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { serviceRoot } from '../config.js';
|
|
5
|
+
import { AxiError, usage } from '../errors.js';
|
|
6
|
+
import { send } from '../http.js';
|
|
7
|
+
import { resolveField, resolveScreen, resolveSub, } from '../index/build.js';
|
|
8
|
+
import { recordReach } from '../index/cache.js';
|
|
9
|
+
import { parseWhere, screenSegment, utc } from '../odata.js';
|
|
10
|
+
import { defaultColumns, tableRow } from '../output/shape.js';
|
|
11
|
+
import { render } from '../output/toon.js';
|
|
12
|
+
import { open, screenIndex, shellWord, str, strings, tokenLine, } from './common.js';
|
|
13
|
+
const INTEGER = new Set(['Int16', 'Int32', 'Int64', 'Byte', 'SByte']);
|
|
14
|
+
const DECIMAL = new Set(['Decimal', 'Double', 'Single']);
|
|
15
|
+
function writable(field, where) {
|
|
16
|
+
if (field.readOnly)
|
|
17
|
+
throw usage(`${field.name} is read-only in ${where}; Priority fills it.`);
|
|
18
|
+
if (field.internalId)
|
|
19
|
+
throw usage(`${field.name} is an internal ID in ${where}; Priority assigns it.`);
|
|
20
|
+
}
|
|
21
|
+
/** Convert one value to the JSON type Priority expects for this field. */
|
|
22
|
+
export function typedValue(field, raw, where) {
|
|
23
|
+
writable(field, where);
|
|
24
|
+
if (field.type === 'String') {
|
|
25
|
+
const length = [...raw].length;
|
|
26
|
+
if (field.max !== undefined && length > field.max) {
|
|
27
|
+
throw usage(`${field.name} holds at most ${field.max} characters; the value has ${length}.`);
|
|
28
|
+
}
|
|
29
|
+
return raw;
|
|
30
|
+
}
|
|
31
|
+
if (INTEGER.has(field.type)) {
|
|
32
|
+
const n = /^-?\d+$/.test(raw) ? Number(raw) : Number.NaN;
|
|
33
|
+
if (!Number.isSafeInteger(n))
|
|
34
|
+
throw usage(`${field.name} is a whole number.`);
|
|
35
|
+
return n;
|
|
36
|
+
}
|
|
37
|
+
if (DECIMAL.has(field.type)) {
|
|
38
|
+
if (!/^-?\d+(\.\d+)?$/.test(raw))
|
|
39
|
+
throw usage(`${field.name} is a number; write it with a point, such as 12.50.`);
|
|
40
|
+
return Number(raw);
|
|
41
|
+
}
|
|
42
|
+
if (field.type === 'Boolean') {
|
|
43
|
+
if (raw !== 'true' && raw !== 'false')
|
|
44
|
+
throw usage(`${field.name} is true or false.`);
|
|
45
|
+
return raw === 'true';
|
|
46
|
+
}
|
|
47
|
+
if (field.type === 'DateTimeOffset')
|
|
48
|
+
return utc(raw, field.name);
|
|
49
|
+
throw usage(`${field.name} has type ${field.type}, which create cannot set.`);
|
|
50
|
+
}
|
|
51
|
+
function assign(type, where, target, term) {
|
|
52
|
+
const t = parseWhere(term);
|
|
53
|
+
if (t.op !== '=')
|
|
54
|
+
throw usage(`Set fields with FIELD=VALUE; ${t.field} uses ${t.op}.`);
|
|
55
|
+
const field = resolveField(type, where, t.field);
|
|
56
|
+
if (field.name in target)
|
|
57
|
+
throw usage(`${field.name} is set more than once in ${where}.`);
|
|
58
|
+
target[field.name] = typedValue(field, t.value, where);
|
|
59
|
+
}
|
|
60
|
+
/** Build the body from --set and --line flags, in the order given. */
|
|
61
|
+
function fromFlags(index, screen, input) {
|
|
62
|
+
const body = {};
|
|
63
|
+
const lines = [];
|
|
64
|
+
let current;
|
|
65
|
+
let screenSeen = false;
|
|
66
|
+
for (const token of input.tokens) {
|
|
67
|
+
if (token.kind === 'positional') {
|
|
68
|
+
if (!screenSeen) {
|
|
69
|
+
screenSeen = true;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (!current) {
|
|
73
|
+
throw usage('A FIELD=VALUE after the screen belongs to a --line <SUB>. Use --set FIELD=VALUE for the record itself.');
|
|
74
|
+
}
|
|
75
|
+
assign(current.sub.def, `${screen.name} > ${current.sub.name}`, current.body, token.value);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (token.name === 'set') {
|
|
79
|
+
current = undefined;
|
|
80
|
+
assign(screen.type, screen.name, body, token.value ?? '');
|
|
81
|
+
}
|
|
82
|
+
else if (token.name === 'line') {
|
|
83
|
+
current = { sub: resolveSub(index, screen, token.value ?? ''), body: {} };
|
|
84
|
+
lines.push(current);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
current = undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { body, lines };
|
|
91
|
+
}
|
|
92
|
+
const scalar = (value, where) => {
|
|
93
|
+
if (typeof value === 'string')
|
|
94
|
+
return value;
|
|
95
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
96
|
+
return String(value);
|
|
97
|
+
throw usage(`${where}: each value must be text, a number or true/false. Leave out fields with no value.`);
|
|
98
|
+
};
|
|
99
|
+
/** Build the body from a JSON file of the same shape, through the same checks. */
|
|
100
|
+
function fromFile(index, screen, path) {
|
|
101
|
+
let raw;
|
|
102
|
+
try {
|
|
103
|
+
raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
throw usage('--json-file must name a readable JSON file.');
|
|
107
|
+
}
|
|
108
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
109
|
+
throw usage('--json-file must hold one JSON object.');
|
|
110
|
+
const body = {};
|
|
111
|
+
const lines = [];
|
|
112
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
113
|
+
const isSub = screen.type.subs.some((s) => s.nav === name || s.name === name);
|
|
114
|
+
if (!isSub) {
|
|
115
|
+
const field = resolveField(screen.type, screen.name, name);
|
|
116
|
+
body[field.name] = typedValue(field, scalar(value, field.name), screen.name);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const sub = resolveSub(index, screen, name);
|
|
120
|
+
const items = Array.isArray(value) ? value : [value];
|
|
121
|
+
for (const item of items) {
|
|
122
|
+
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
|
123
|
+
throw usage(`${sub.nav} must hold objects of FIELD: value.`);
|
|
124
|
+
}
|
|
125
|
+
const line = {};
|
|
126
|
+
for (const [f, v] of Object.entries(item)) {
|
|
127
|
+
const field = resolveField(sub.def, `${screen.name} > ${sub.name}`, f);
|
|
128
|
+
line[field.name] = typedValue(field, scalar(v, field.name), `${screen.name} > ${sub.name}`);
|
|
129
|
+
}
|
|
130
|
+
lines.push({ sub, body: line });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { body, lines };
|
|
134
|
+
}
|
|
135
|
+
function assemble(body, lines) {
|
|
136
|
+
const out = { ...body };
|
|
137
|
+
for (const { sub, body: line } of lines) {
|
|
138
|
+
if (!Object.keys(line).length)
|
|
139
|
+
throw usage(`--line ${sub.name} needs at least one FIELD=VALUE.`);
|
|
140
|
+
if (sub.many) {
|
|
141
|
+
const list = out[sub.nav] ?? [];
|
|
142
|
+
list.push(line);
|
|
143
|
+
out[sub.nav] = list;
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
if (out[sub.nav])
|
|
147
|
+
throw usage(`${sub.name} holds one record; give it one --line.`);
|
|
148
|
+
out[sub.nav] = line;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
export async function create(input) {
|
|
154
|
+
const s = open(input);
|
|
155
|
+
const { index } = await screenIndex(s);
|
|
156
|
+
const screen = resolveScreen(index, input.positionals[0] ?? '');
|
|
157
|
+
const file = str(input.values['json-file']);
|
|
158
|
+
const flagged = strings(input.values.set).length > 0 ||
|
|
159
|
+
strings(input.values.line).length > 0 ||
|
|
160
|
+
input.positionals.length > 1;
|
|
161
|
+
if (file && flagged)
|
|
162
|
+
throw usage('Use --json-file or --set/--line, not both.');
|
|
163
|
+
const { body, lines } = file
|
|
164
|
+
? fromFile(index, screen, file)
|
|
165
|
+
: fromFlags(index, screen, input);
|
|
166
|
+
const payload = assemble(body, lines);
|
|
167
|
+
if (!Object.keys(payload).length)
|
|
168
|
+
throw usage('Nothing to create: give --set FIELD=VALUE or --json-file <path>.');
|
|
169
|
+
const transactions = 1 + lines.length;
|
|
170
|
+
const path = `${new URL(serviceRoot(s.settings)).pathname}/${screenSegment(screen.name)}`;
|
|
171
|
+
if (input.values['dry-run'] === true) {
|
|
172
|
+
return render({ dry_run: true, request: `POST ${path}`, body: payload, transactions }, [
|
|
173
|
+
`Run \`${tokenLine('create', input.tokens, ['dry-run'])}\` to send it; inside Comis the owner approves it first`,
|
|
174
|
+
]);
|
|
175
|
+
}
|
|
176
|
+
const now = input.io.now();
|
|
177
|
+
let answer;
|
|
178
|
+
try {
|
|
179
|
+
// Sent once. A write is never retried; a held write is waited on with comis action wait.
|
|
180
|
+
answer = await send(s.settings, {
|
|
181
|
+
method: 'POST',
|
|
182
|
+
path: screenSegment(screen.name),
|
|
183
|
+
body: payload,
|
|
184
|
+
context: { screen: screen.name },
|
|
185
|
+
}, input.io.http);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (error instanceof AxiError && error.code === 'screen_not_enabled')
|
|
189
|
+
recordReach(s.dir, screen.name, 'no', now);
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
recordReach(s.dir, screen.name, 'yes', now);
|
|
193
|
+
const record = answer.json && typeof answer.json === 'object' ? answer.json : {};
|
|
194
|
+
const keys = screen.type.key.filter((k) => record[k] !== undefined && record[k] !== null && record[k] !== '');
|
|
195
|
+
const keyText = keys.map((k) => String(record[k])).join(', ');
|
|
196
|
+
const columns = defaultColumns(screen.type, [record]);
|
|
197
|
+
return render({
|
|
198
|
+
created: screen.name,
|
|
199
|
+
key: keyText || null,
|
|
200
|
+
transactions,
|
|
201
|
+
record: tableRow(screen.type, record, columns, 500),
|
|
202
|
+
}, keys.length === 1 && screen.type.key.length === 1
|
|
203
|
+
? [
|
|
204
|
+
`Run \`priority-axi show ${screen.name} ${shellWord(keyText)}\` to read it`,
|
|
205
|
+
]
|
|
206
|
+
: []);
|
|
207
|
+
}
|