@basementuniverse/jsonpad-cli 1.4.0 → 1.6.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/CHANGELOG.md +62 -0
- package/README.md +108 -0
- package/REFERENCE.md +192 -3
- package/build/commands/flows.js +100 -0
- package/build/commands/lists.js +115 -1
- package/build/commands/rules.js +307 -0
- package/build/commands/schema/export.js +83 -0
- package/build/commands/schema/sync.js +35 -4
- package/build/errors.js +3 -0
- package/build/flows.js +153 -0
- package/build/program.js +6 -0
- package/build/rules.js +241 -0
- package/build/sdk.js +1 -1
- package/package.json +4 -2
package/build/commands/lists.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
1
3
|
import { CliError } from '../errors.js';
|
|
2
|
-
import { canPrompt, confirm, readJsonInput } from '../input.js';
|
|
4
|
+
import { canPrompt, confirm, readJsonInput, readStdin } from '../input.js';
|
|
5
|
+
import { compileRules, readJsonFile, readTextFile, runRuleTests, } from '../rules.js';
|
|
3
6
|
import { addOutputOptions, formatFlags, formatNumber, formatTimestamp, printRecord, printRecords, resolveOutputFormat, } from '../output.js';
|
|
4
7
|
import { addBooleanOption, addAllOption, addPagingOptions, addTaggedOption, addTagsOption, nullable, readBody, removeUndefined, printPages, request, } from '../resources.js';
|
|
5
8
|
import { defineEventCommands, defineStatsCommand } from './history.js';
|
|
@@ -43,6 +46,17 @@ export function listDetails(context, list) {
|
|
|
43
46
|
['Tags', list.tags?.length ? list.tags.join(', ') : dim('(none)')],
|
|
44
47
|
['Items', formatNumber(list.itemCount ?? 0)],
|
|
45
48
|
['Flags', formatFlags(list, [...FLAGS])],
|
|
49
|
+
// Only the account owner and tokens that can update the list see these
|
|
50
|
+
...(list.rules !== undefined
|
|
51
|
+
? [
|
|
52
|
+
[
|
|
53
|
+
'Write rules',
|
|
54
|
+
list.rules
|
|
55
|
+
? `${list.rules.split('\n').length} lines (jsonpad lists rules get ${list.pathName || list.id})`
|
|
56
|
+
: dim('(none)'),
|
|
57
|
+
],
|
|
58
|
+
]
|
|
59
|
+
: []),
|
|
46
60
|
];
|
|
47
61
|
if (list.generative) {
|
|
48
62
|
rows.push(['Prompt', list.generativePrompt || dim('(none)')]);
|
|
@@ -105,6 +119,105 @@ async function listBody(context, options) {
|
|
|
105
119
|
...Object.fromEntries(FLAGS.map(flag => [flag, options[flag]])),
|
|
106
120
|
});
|
|
107
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* jsonpad lists rules: read and write a list's write rules
|
|
124
|
+
*/
|
|
125
|
+
function defineListRules(command, context) {
|
|
126
|
+
command.description("Read and write a list's write rules");
|
|
127
|
+
command
|
|
128
|
+
.command('get', { isDefault: true })
|
|
129
|
+
.description("Show a list's write rules")
|
|
130
|
+
.argument('<list>', 'The list (id or path name)')
|
|
131
|
+
.option('--tests', 'Show the rule tests instead of the rules')
|
|
132
|
+
.option('-o, --out <file>', 'Write to a file, not stdout')
|
|
133
|
+
.action(async (listId, options) => {
|
|
134
|
+
const jsonpad = context.createClient();
|
|
135
|
+
const list = await request(context, () => jsonpad.fetchList(listId));
|
|
136
|
+
if (list.rules === undefined) {
|
|
137
|
+
throw new CliError("This token can't see the list's write rules: it needs permission to update the list");
|
|
138
|
+
}
|
|
139
|
+
const text = options.tests
|
|
140
|
+
? list.rulesTests
|
|
141
|
+
? `${JSON.stringify(list.rulesTests, null, 2)}\n`
|
|
142
|
+
: ''
|
|
143
|
+
: list.rules
|
|
144
|
+
? `${list.rules.replace(/\n?$/, '\n')}`
|
|
145
|
+
: '';
|
|
146
|
+
if (!text) {
|
|
147
|
+
context.error(`List ${listId} has no write rule${options.tests ? ' tests' : 's'}`);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (options.out) {
|
|
151
|
+
fs.writeFileSync(path.resolve(context.cwd, options.out), text);
|
|
152
|
+
context.error(`Wrote ${options.out}`);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
context.stdout.write(text);
|
|
156
|
+
});
|
|
157
|
+
command
|
|
158
|
+
.command('set')
|
|
159
|
+
.description("Set a list's write rules from a file")
|
|
160
|
+
.argument('<list>', 'The list (id or path name)')
|
|
161
|
+
.argument('[file]', 'The rule file, or - for stdin')
|
|
162
|
+
.option('--tests <file>', 'Also set the rule tests from this file')
|
|
163
|
+
.option('--remove', "Remove the list's rules")
|
|
164
|
+
.option('--skip-check', "Don't compile and test the rules here first (the API always checks them)")
|
|
165
|
+
.action(async (listId, file, options) => {
|
|
166
|
+
if (!file && !options.remove && !options.tests) {
|
|
167
|
+
throw new CliError('Give a rule file, --tests or --remove');
|
|
168
|
+
}
|
|
169
|
+
const rules = options.remove
|
|
170
|
+
? null
|
|
171
|
+
: file
|
|
172
|
+
? file === '-'
|
|
173
|
+
? await readStdin(context)
|
|
174
|
+
: readTextFile(context, file, 'the rule file')
|
|
175
|
+
: undefined;
|
|
176
|
+
const tests = options.tests
|
|
177
|
+
? readJsonFile(context, options.tests, 'the test file')
|
|
178
|
+
: undefined;
|
|
179
|
+
// Checked here first, so a mistake costs no requests
|
|
180
|
+
if (!options.skipCheck && rules) {
|
|
181
|
+
const ruleSet = compileRules(context, rules, file ?? 'the rules');
|
|
182
|
+
if (tests) {
|
|
183
|
+
runRuleTests(context, ruleSet, tests, options.tests);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const jsonpad = context.createClient();
|
|
187
|
+
const list = await request(context, () => jsonpad.updateList(listId, {
|
|
188
|
+
...(rules === undefined ? {} : { rules }),
|
|
189
|
+
...(tests === undefined ? {} : { rulesTests: tests }),
|
|
190
|
+
}));
|
|
191
|
+
context.error(rules === null
|
|
192
|
+
? `Removed the write rules from ${list.pathName || list.id}`
|
|
193
|
+
: `Saved the write rules on ${list.pathName || list.id}`);
|
|
194
|
+
});
|
|
195
|
+
addOutputOptions(command
|
|
196
|
+
.command('denials')
|
|
197
|
+
.description("The most recent writes the list's rules refused, newest first")
|
|
198
|
+
.argument('<list>', 'The list (id or path name)')).action(async (listId, options) => {
|
|
199
|
+
const format = resolveOutputFormat(context, options);
|
|
200
|
+
const jsonpad = context.createClient();
|
|
201
|
+
const denials = await request(context, () => jsonpad.fetchListRuleDenials(listId));
|
|
202
|
+
printRecords(context, format, denials, {
|
|
203
|
+
columns: [
|
|
204
|
+
{ header: 'When', value: denial => formatTimestamp(denial.createdAt) },
|
|
205
|
+
{ header: 'Operation', value: denial => denial.operation },
|
|
206
|
+
{
|
|
207
|
+
header: 'Refused by',
|
|
208
|
+
value: denial => denial.stage === 'allow'
|
|
209
|
+
? 'no allow statement'
|
|
210
|
+
: `require${denial.statementLabel ? ` "${denial.statementLabel}"` : ''} on line ${denial.statementLine}`,
|
|
211
|
+
},
|
|
212
|
+
{ header: 'Identity', value: denial => denial.identityId ?? '' },
|
|
213
|
+
{ header: 'Item', value: denial => denial.itemId ?? '' },
|
|
214
|
+
],
|
|
215
|
+
empty: "The list's rules haven't refused any writes",
|
|
216
|
+
id: denial => denial.id,
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
return command;
|
|
220
|
+
}
|
|
108
221
|
export function defineLists(command, context) {
|
|
109
222
|
command.description('Create, view, change and delete lists');
|
|
110
223
|
const list = command
|
|
@@ -218,6 +331,7 @@ export function defineLists(command, context) {
|
|
|
218
331
|
empty: 'Nothing found',
|
|
219
332
|
});
|
|
220
333
|
});
|
|
334
|
+
defineListRules(command.command('rules'), context);
|
|
221
335
|
const target = {
|
|
222
336
|
arguments: [['<list>', 'The list (id or path name)']],
|
|
223
337
|
};
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { applyJsonPatch, applyMergePatch, Evaluation, } from '@basementuniverse/jsonpad-rules';
|
|
2
|
+
import { CliError, EXIT_RULE_TESTS_FAILED, describeApiError, } from '../errors.js';
|
|
3
|
+
import { readJsonInput } from '../input.js';
|
|
4
|
+
import { checkEngineVersion, compileRules, defaultTestsFile, engineVersion, readJsonFile, readTextFile, runRuleTests, } from '../rules.js';
|
|
5
|
+
const ACTIONS = ['create', 'update', 'delete', 'restore'];
|
|
6
|
+
export function defineRules(command, context) {
|
|
7
|
+
command
|
|
8
|
+
.description("Check, test and try out a list's write rules")
|
|
9
|
+
.addHelpText('after', `\nRules are checked by the copy of the rules engine built into this CLI\n(version ${engineVersion}), so check and test need no network and don't\ncount against your request allowance. The API always has the final say.\n`);
|
|
10
|
+
command
|
|
11
|
+
.command('check')
|
|
12
|
+
.description("Check that a rule file compiles, and show the checker's warnings")
|
|
13
|
+
.argument('<file>', 'The rule file')
|
|
14
|
+
.option('--strict', 'Fail if there are any warnings')
|
|
15
|
+
.action((file, options) => checkRules(context, file, options));
|
|
16
|
+
command
|
|
17
|
+
.command('test')
|
|
18
|
+
.description('Run a rule set against its tests')
|
|
19
|
+
.argument('[rules]', 'The rule file (not needed with --list)')
|
|
20
|
+
.argument('[tests]', "The test file (default: the rule file with .tests.json, or the list's stored tests with --list)")
|
|
21
|
+
.option('--rules <file>', 'The rule file to test against --list')
|
|
22
|
+
.option('--list <list>', "Test against the API, using the list's stored rules and tests unless they're given")
|
|
23
|
+
.option('--filter <text>', 'Only tests whose name contains this text')
|
|
24
|
+
.option('--trace', 'Show how each rule was evaluated for a failing test')
|
|
25
|
+
.option('--json', 'Print the results as JSON')
|
|
26
|
+
.action((rules, tests, options) => testRules(context, rules, tests, options));
|
|
27
|
+
command
|
|
28
|
+
.command('eval')
|
|
29
|
+
.description('Check one write against a rule set, and show what each rule did')
|
|
30
|
+
.argument('[rules]', 'The rule file (not needed with --list)')
|
|
31
|
+
.requiredOption('--action <action>', `What the write does: ${ACTIONS.join(', ')}`)
|
|
32
|
+
.option('--list <list>', "Use the list's stored rules, and check with the API")
|
|
33
|
+
.option('--item <item>', 'Take the old data from this item (needs --list)')
|
|
34
|
+
.option('--old <json>', 'The data before the write (@file, - for stdin)')
|
|
35
|
+
.option('--new <json>', 'The data after the write (@file, - for stdin)')
|
|
36
|
+
.option('--patch <json>', 'A JSON Patch applied to the old data')
|
|
37
|
+
.option('--merge <json>', 'A JSON merge patch applied to the old data')
|
|
38
|
+
.option('--identity <json>', 'The identity making the write')
|
|
39
|
+
.option('--identity-id <id>', 'An existing identity making the write (needs --list)')
|
|
40
|
+
.option('--token <json>', 'The token making the write, e.g. \'{"tags":["writer"]}\'')
|
|
41
|
+
.option('--now <date>', 'The time of the write (ISO 8601)')
|
|
42
|
+
.option('--pointer <pointer>', 'The JSON pointer, for writes to part of an item')
|
|
43
|
+
.option('--trace', 'Show every expression that was evaluated')
|
|
44
|
+
.option('--json', 'Print the result as JSON')
|
|
45
|
+
.action((rules, options) => evalRules(context, rules, options));
|
|
46
|
+
return command;
|
|
47
|
+
}
|
|
48
|
+
async function checkRules(context, file, options) {
|
|
49
|
+
compileRules(context, readTextFile(context, file, 'the rule file'), file, {
|
|
50
|
+
strict: options.strict,
|
|
51
|
+
});
|
|
52
|
+
context.log(`${context.colours.green('✓')} ${file} compiles`);
|
|
53
|
+
}
|
|
54
|
+
async function testRules(context, rulesFile, testsFile, options) {
|
|
55
|
+
const file = rulesFile ?? options.rules;
|
|
56
|
+
if (options.list) {
|
|
57
|
+
return testAgainstApi(context, file, testsFile, options);
|
|
58
|
+
}
|
|
59
|
+
if (!file) {
|
|
60
|
+
throw new CliError('Give a rule file, or --list to test against the API');
|
|
61
|
+
}
|
|
62
|
+
const ruleSet = compileRules(context, readTextFile(context, file, 'the rule file'), file, { quiet: options.json });
|
|
63
|
+
const tests = testsFile ?? defaultTestsFile(file);
|
|
64
|
+
runRuleTests(context, ruleSet, readJsonFile(context, tests, 'the test file'), tests, { filter: options.filter, trace: options.trace, json: options.json });
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Run the same tests through the API, so the server agrees with this CLI
|
|
68
|
+
*/
|
|
69
|
+
async function testAgainstApi(context, rulesFile, testsFile, options) {
|
|
70
|
+
const jsonpad = context.createClient();
|
|
71
|
+
const rules = rulesFile
|
|
72
|
+
? readTextFile(context, rulesFile, 'the rule file')
|
|
73
|
+
: undefined;
|
|
74
|
+
let list;
|
|
75
|
+
try {
|
|
76
|
+
list = await jsonpad.fetchList(options.list);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
throw new CliError(describeApiError(error));
|
|
80
|
+
}
|
|
81
|
+
const document = testsFile
|
|
82
|
+
? readJsonFile(context, testsFile, 'the test file')
|
|
83
|
+
: list.rulesTests;
|
|
84
|
+
if (!document) {
|
|
85
|
+
throw new CliError(`List "${options.list}" has no stored rule tests: give a test file`);
|
|
86
|
+
}
|
|
87
|
+
const { tests, identities, fixtures, defaults } = document;
|
|
88
|
+
const resolve = (value) => typeof value === 'string' && fixtures && value in fixtures
|
|
89
|
+
? fixtures[value]
|
|
90
|
+
: value;
|
|
91
|
+
const { green, red } = context.colours;
|
|
92
|
+
let failed = 0;
|
|
93
|
+
for (const test of tests) {
|
|
94
|
+
if (options.filter && !String(test.name).includes(options.filter)) {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const identity = typeof test.identity === 'string'
|
|
98
|
+
? identities?.[test.identity]
|
|
99
|
+
: (test.identity ?? defaults?.identity);
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
result = await jsonpad.testListRules(options.list, {
|
|
103
|
+
rules,
|
|
104
|
+
action: test.action,
|
|
105
|
+
old: resolve(test.old),
|
|
106
|
+
new: resolve(test.new),
|
|
107
|
+
patch: test.patch,
|
|
108
|
+
merge: test.merge,
|
|
109
|
+
identity: identity ?? null,
|
|
110
|
+
token: test.token ?? defaults?.token,
|
|
111
|
+
now: test.now ?? defaults?.now,
|
|
112
|
+
pointer: test.pointer,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
throw new CliError(describeApiError(error));
|
|
117
|
+
}
|
|
118
|
+
checkEngineVersion(context, result.engineVersion);
|
|
119
|
+
const actual = result.allowed
|
|
120
|
+
? 'allow'
|
|
121
|
+
: result.status === 400 && result.stage === 'require'
|
|
122
|
+
? 'fail'
|
|
123
|
+
: 'deny';
|
|
124
|
+
const passed = typeof test.expect === 'string'
|
|
125
|
+
? actual === test.expect
|
|
126
|
+
: actual === 'fail' &&
|
|
127
|
+
(result.message ?? '').includes(test.expect.fail);
|
|
128
|
+
if (passed) {
|
|
129
|
+
context.log(`${green('✓')} ${test.name}`);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
failed++;
|
|
133
|
+
context.log(`${red('✗')} ${test.name} (the API said ${actual}${result.message ? `: ${result.message}` : ''})`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (failed > 0) {
|
|
137
|
+
throw new CliError(`${failed} ${failed === 1 ? 'test' : 'tests'} failed against the API`, EXIT_RULE_TESTS_FAILED);
|
|
138
|
+
}
|
|
139
|
+
context.log(`\n${green('All tests passed against the API')}`);
|
|
140
|
+
}
|
|
141
|
+
async function evalRules(context, rulesFile, options) {
|
|
142
|
+
if (!ACTIONS.includes(options.action)) {
|
|
143
|
+
throw new CliError(`--action must be one of: ${ACTIONS.join(', ')}`);
|
|
144
|
+
}
|
|
145
|
+
const read = async (name) => options[name] === undefined
|
|
146
|
+
? undefined
|
|
147
|
+
: await readJsonInput(context, `--${name}`, options[name]);
|
|
148
|
+
const [oldData, newData, patch, merge, identity, token] = await Promise.all([
|
|
149
|
+
read('old'),
|
|
150
|
+
read('new'),
|
|
151
|
+
read('patch'),
|
|
152
|
+
read('merge'),
|
|
153
|
+
read('identity'),
|
|
154
|
+
read('token'),
|
|
155
|
+
]);
|
|
156
|
+
if (options.list) {
|
|
157
|
+
return evalWithApi(context, rulesFile, options, {
|
|
158
|
+
old: oldData,
|
|
159
|
+
new: newData,
|
|
160
|
+
patch,
|
|
161
|
+
merge,
|
|
162
|
+
identity,
|
|
163
|
+
token,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (!rulesFile) {
|
|
167
|
+
throw new CliError('Give a rule file, or --list to check with the API');
|
|
168
|
+
}
|
|
169
|
+
if (options.item || options.identityId) {
|
|
170
|
+
throw new CliError('--item and --identity-id need --list');
|
|
171
|
+
}
|
|
172
|
+
const ruleSet = compileRules(context, readTextFile(context, rulesFile, 'the rule file'), rulesFile, { quiet: options.json });
|
|
173
|
+
const operation = options.action === 'restore' ? 'update' : options.action;
|
|
174
|
+
const now = options.now ? new Date(options.now) : new Date();
|
|
175
|
+
let after = newData ?? null;
|
|
176
|
+
if (patch !== undefined) {
|
|
177
|
+
after = applyJsonPatch(oldData ?? null, patch);
|
|
178
|
+
}
|
|
179
|
+
else if (merge !== undefined) {
|
|
180
|
+
after = applyMergePatch(oldData ?? null, merge);
|
|
181
|
+
}
|
|
182
|
+
const evaluation = new Evaluation(ruleSet, {
|
|
183
|
+
operation,
|
|
184
|
+
trace: 'values',
|
|
185
|
+
context: {
|
|
186
|
+
old: oldData ?? null,
|
|
187
|
+
new: after,
|
|
188
|
+
oldItem: operation === 'create'
|
|
189
|
+
? null
|
|
190
|
+
: {
|
|
191
|
+
id: 'item',
|
|
192
|
+
identityId: (identity?.id ?? null),
|
|
193
|
+
},
|
|
194
|
+
newItem: operation === 'delete'
|
|
195
|
+
? null
|
|
196
|
+
: {
|
|
197
|
+
id: 'item',
|
|
198
|
+
identityId: (identity?.id ?? null),
|
|
199
|
+
},
|
|
200
|
+
identity: identity ?? null,
|
|
201
|
+
token: token ?? { id: 'token', tags: [] },
|
|
202
|
+
list: { id: 'list', pathName: 'list', name: 'list' },
|
|
203
|
+
request: { action: options.action, pointer: options.pointer ?? null },
|
|
204
|
+
now,
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
const decision = evaluation.decision();
|
|
208
|
+
if (options.json) {
|
|
209
|
+
context.log(JSON.stringify(decision, null, 2));
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
printDecision(context, {
|
|
213
|
+
allowed: decision.allowed,
|
|
214
|
+
stage: decision.stage,
|
|
215
|
+
status: decision.status,
|
|
216
|
+
message: decision.message,
|
|
217
|
+
statement: decision.statement
|
|
218
|
+
? {
|
|
219
|
+
index: decision.statement.index,
|
|
220
|
+
kind: decision.statement.kind,
|
|
221
|
+
label: decision.statement.label,
|
|
222
|
+
line: decision.statement.span.line,
|
|
223
|
+
}
|
|
224
|
+
: null,
|
|
225
|
+
budget: decision.budget,
|
|
226
|
+
statements: decision.statements.map(statement => ({
|
|
227
|
+
kind: statement.kind,
|
|
228
|
+
label: statement.label,
|
|
229
|
+
line: statement.span.line,
|
|
230
|
+
result: statement.result,
|
|
231
|
+
error: statement.error,
|
|
232
|
+
})),
|
|
233
|
+
}, options.trace);
|
|
234
|
+
}
|
|
235
|
+
if (!decision.allowed) {
|
|
236
|
+
throw new CliError(decision.stage === 'require'
|
|
237
|
+
? `The write fails: ${decision.message}`
|
|
238
|
+
: 'The write is denied by the rules', EXIT_RULE_TESTS_FAILED);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
async function evalWithApi(context, rulesFile, options, write) {
|
|
242
|
+
const jsonpad = context.createClient();
|
|
243
|
+
let result;
|
|
244
|
+
try {
|
|
245
|
+
result = await jsonpad.testListRules(options.list, {
|
|
246
|
+
rules: rulesFile
|
|
247
|
+
? readTextFile(context, rulesFile, 'the rule file')
|
|
248
|
+
: undefined,
|
|
249
|
+
action: options.action,
|
|
250
|
+
itemId: options.item,
|
|
251
|
+
identityId: options.identityId,
|
|
252
|
+
now: options.now,
|
|
253
|
+
pointer: options.pointer,
|
|
254
|
+
...write,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
throw new CliError(describeApiError(error));
|
|
259
|
+
}
|
|
260
|
+
checkEngineVersion(context, result.engineVersion);
|
|
261
|
+
if (options.json) {
|
|
262
|
+
context.log(JSON.stringify(result, null, 2));
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
printDecision(context, {
|
|
266
|
+
allowed: result.allowed,
|
|
267
|
+
stage: result.stage,
|
|
268
|
+
status: result.status,
|
|
269
|
+
message: result.message,
|
|
270
|
+
statement: result.statement,
|
|
271
|
+
budget: result.budget,
|
|
272
|
+
statements: result.statements.map((statement) => ({
|
|
273
|
+
kind: statement.kind,
|
|
274
|
+
label: statement.label,
|
|
275
|
+
line: statement.line,
|
|
276
|
+
result: statement.result,
|
|
277
|
+
error: statement.error,
|
|
278
|
+
})),
|
|
279
|
+
}, options.trace);
|
|
280
|
+
}
|
|
281
|
+
if (!result.allowed) {
|
|
282
|
+
throw new CliError(result.stage === 'require'
|
|
283
|
+
? `The write fails: ${result.message}`
|
|
284
|
+
: `The write is ${result.stage === 'schema' ? 'invalid' : 'denied by the rules'}`, EXIT_RULE_TESTS_FAILED);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function printDecision(context, decision, trace) {
|
|
288
|
+
const { green, red, yellow, dim, bold } = context.colours;
|
|
289
|
+
context.log(decision.allowed
|
|
290
|
+
? `${green('allowed')}${decision.statement
|
|
291
|
+
? dim(` by ${decision.statement.kind}${decision.statement.label
|
|
292
|
+
? ` "${decision.statement.label}"`
|
|
293
|
+
: ''} on line ${decision.statement.line}`)
|
|
294
|
+
: ''}`
|
|
295
|
+
: `${red(decision.stage === 'require' ? 'failed' : 'denied')} ${dim(`(${decision.status}, at the ${decision.stage} stage)`)}${decision.message ? `: ${bold(decision.message)}` : ''}`);
|
|
296
|
+
if (trace || !decision.allowed) {
|
|
297
|
+
for (const statement of decision.statements) {
|
|
298
|
+
const outcome = statement.error
|
|
299
|
+
? yellow(`error: ${statement.error}`)
|
|
300
|
+
: statement.result
|
|
301
|
+
? green('true')
|
|
302
|
+
: dim('false');
|
|
303
|
+
context.log(` ${dim(`line ${statement.line}`)} ${statement.kind}${statement.label ? ` "${statement.label}"` : ''}: ${outcome}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
context.log(dim(`\n${decision.budget.used} of ${decision.budget.limit} budget used`));
|
|
307
|
+
}
|
|
@@ -12,6 +12,8 @@ export function defineExportSchema(command, context) {
|
|
|
12
12
|
.option('--tagged <tags>', 'Only lists with one of these comma-separated tags (repeat the option to require every group)', collect)
|
|
13
13
|
.option('--lists <path names>', 'Only these comma-separated lists')
|
|
14
14
|
.option('--out <file>', 'Write the document to a file, not stdout')
|
|
15
|
+
.option('--split-rules <directory>', "Write each list's write rules and rule tests to their own files in this directory, and reference them from the document (needs --out)")
|
|
16
|
+
.option('--split-flows <directory>', 'Write each flow and its tests to their own files in this directory (name.flow.json and name.tests.json), and reference them from the document (needs --out)')
|
|
15
17
|
.action((options) => exportSchema(context, options));
|
|
16
18
|
}
|
|
17
19
|
export async function exportSchema(context, options) {
|
|
@@ -35,6 +37,12 @@ export async function exportSchema(context, options) {
|
|
|
35
37
|
for (const warning of result.warnings) {
|
|
36
38
|
context.error(`${context.colours.yellow('warning')}: ${warning}`);
|
|
37
39
|
}
|
|
40
|
+
if (options.splitRules) {
|
|
41
|
+
splitRules(context, result.document, options);
|
|
42
|
+
}
|
|
43
|
+
if (options.splitFlows) {
|
|
44
|
+
splitFlows(context, result.document, options);
|
|
45
|
+
}
|
|
38
46
|
const json = `${JSON.stringify(result.document, null, 2)}\n`;
|
|
39
47
|
if (options.out) {
|
|
40
48
|
fs.writeFileSync(path.resolve(context.cwd, options.out), json);
|
|
@@ -44,3 +52,78 @@ export async function exportSchema(context, options) {
|
|
|
44
52
|
context.stdout.write(json);
|
|
45
53
|
}
|
|
46
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Move each list's rules and rule tests out of the document and into their
|
|
57
|
+
* own files, which the document then points at with rulesFile and
|
|
58
|
+
* rulesTestsFile
|
|
59
|
+
*/
|
|
60
|
+
function splitRules(context, document, options) {
|
|
61
|
+
if (!options.out) {
|
|
62
|
+
throw new CliError('--split-rules needs --out');
|
|
63
|
+
}
|
|
64
|
+
const directory = path.resolve(context.cwd, options.splitRules);
|
|
65
|
+
const documentDirectory = path.dirname(path.resolve(context.cwd, options.out));
|
|
66
|
+
let written = 0;
|
|
67
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
68
|
+
for (const [pathName, list] of Object.entries(document.lists)) {
|
|
69
|
+
const reference = (file) => {
|
|
70
|
+
const relative = path.relative(documentDirectory, file);
|
|
71
|
+
// Paths in the document are relative to the document, and always use
|
|
72
|
+
// forward slashes
|
|
73
|
+
return relative.split(path.sep).join('/');
|
|
74
|
+
};
|
|
75
|
+
if (typeof list.rules === 'string' || Array.isArray(list.rules)) {
|
|
76
|
+
const text = Array.isArray(list.rules)
|
|
77
|
+
? list.rules.join('\n')
|
|
78
|
+
: list.rules;
|
|
79
|
+
const file = path.join(directory, `${pathName}.rules`);
|
|
80
|
+
fs.writeFileSync(file, `${text.replace(/\n?$/, '\n')}`);
|
|
81
|
+
delete list.rules;
|
|
82
|
+
list.rulesFile = reference(file);
|
|
83
|
+
written++;
|
|
84
|
+
}
|
|
85
|
+
if (list.rulesTests) {
|
|
86
|
+
const file = path.join(directory, `${pathName}.tests.json`);
|
|
87
|
+
fs.writeFileSync(file, `${JSON.stringify(list.rulesTests, null, 2)}\n`);
|
|
88
|
+
delete list.rulesTests;
|
|
89
|
+
list.rulesTestsFile = reference(file);
|
|
90
|
+
written++;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
context.error(`Wrote ${written} rule ${written === 1 ? 'file' : 'files'} to ${options.splitRules}`);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Move each flow's document and tests out of the schema document and into
|
|
97
|
+
* their own files, which the schema document then points at with flowFile
|
|
98
|
+
* and flowTestsFile
|
|
99
|
+
*/
|
|
100
|
+
function splitFlows(context, document, options) {
|
|
101
|
+
if (!options.out) {
|
|
102
|
+
throw new CliError('--split-flows needs --out');
|
|
103
|
+
}
|
|
104
|
+
const directory = path.resolve(context.cwd, options.splitFlows);
|
|
105
|
+
const documentDirectory = path.dirname(path.resolve(context.cwd, options.out));
|
|
106
|
+
const reference = (file) => path.relative(documentDirectory, file).split(path.sep).join('/');
|
|
107
|
+
let written = 0;
|
|
108
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
109
|
+
for (const [name, flow] of Object.entries(document.flows ?? {})) {
|
|
110
|
+
if (flow.document) {
|
|
111
|
+
const file = path.join(directory, `${name}.flow.json`);
|
|
112
|
+
fs.writeFileSync(file, `${JSON.stringify(flow.document, null, 2)}\n`);
|
|
113
|
+
delete flow.document;
|
|
114
|
+
flow.flowFile = reference(file);
|
|
115
|
+
written++;
|
|
116
|
+
}
|
|
117
|
+
if (flow.tests) {
|
|
118
|
+
const file = path.join(directory, `${name}.tests.json`);
|
|
119
|
+
fs.writeFileSync(file, `${JSON.stringify(flow.tests, null, 2)}\n`);
|
|
120
|
+
delete flow.tests;
|
|
121
|
+
flow.flowTestsFile = reference(file);
|
|
122
|
+
written++;
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
delete flow.tests;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
context.error(`Wrote ${written} flow ${written === 1 ? 'file' : 'files'} to ${options.splitFlows}`);
|
|
129
|
+
}
|
|
@@ -2,11 +2,13 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { CliError, describeApiError, EXIT_DESTRUCTIVE_NOT_ALLOWED, EXIT_ERROR, EXIT_REBUILD_NOT_ALLOWED, } from '../../errors.js';
|
|
4
4
|
import { parseTimeout, waitForIndexes } from '../../indexes.js';
|
|
5
|
+
import { checkDocumentFlows, resolveFlowFiles } from '../../flows.js';
|
|
6
|
+
import { checkDocumentRules, printRuleDiff, resolveRuleFiles, } from '../../rules.js';
|
|
5
7
|
import { formatValue, plural } from '../../output.js';
|
|
6
8
|
export const DEFAULT_SCHEMA_FILE = 'jsonpad-schema.json';
|
|
7
9
|
export function defineSyncSchema(command, context) {
|
|
8
10
|
return command
|
|
9
|
-
.description('Create and update lists and
|
|
11
|
+
.description('Create and update lists, indexes and flows to match a schema document')
|
|
10
12
|
.argument('[file]', 'The schema document', DEFAULT_SCHEMA_FILE)
|
|
11
13
|
.option('--dry-run', 'Show what would change, without changing it')
|
|
12
14
|
.option('--allow-rebuild', "Allow changes that rebuild an index in a list with items (the index can't be used until the rebuild finishes)")
|
|
@@ -15,6 +17,8 @@ export function defineSyncSchema(command, context) {
|
|
|
15
17
|
.option('--wait', 'Wait for index builds to finish')
|
|
16
18
|
.option('--timeout <seconds>', 'How long --wait waits for each index (default 600)')
|
|
17
19
|
.option('--show-unchanged', "Also list resources that don't change")
|
|
20
|
+
.option('--skip-rule-tests', "Don't compile and test write rules here first (the API always checks them)")
|
|
21
|
+
.option('--skip-flow-tests', "Don't compile and test flows here first (the API always checks them)")
|
|
18
22
|
.option('--json', "Print the API's response as JSON")
|
|
19
23
|
.action((file, options) => syncSchema(context, file, options));
|
|
20
24
|
}
|
|
@@ -28,9 +32,11 @@ function printChange(context, change) {
|
|
|
28
32
|
'no-change': dim('='),
|
|
29
33
|
error: red('!'),
|
|
30
34
|
};
|
|
31
|
-
const name = change.resourceType === '
|
|
32
|
-
? `
|
|
33
|
-
:
|
|
35
|
+
const name = change.resourceType === 'flow'
|
|
36
|
+
? `flow ${bold(change.flow)}`
|
|
37
|
+
: change.resourceType === 'list'
|
|
38
|
+
? `list ${bold(change.list)}`
|
|
39
|
+
: `index ${bold(`${change.list}/${change.index}`)}`;
|
|
34
40
|
const action = change.action === 'no-change' ? 'no change' : change.action;
|
|
35
41
|
const build = change.build
|
|
36
42
|
? dim(` (${change.build.reason === 'created' ? 'build' : 'rebuild'}: ${change.build.items} ${change.build.items === 1 ? 'item' : 'items'}${change.build.requiresConfirmation ? ', needs --allow-rebuild' : ''})`)
|
|
@@ -49,6 +55,12 @@ function printChange(context, change) {
|
|
|
49
55
|
const deleted = deleteDetails.length > 0 ? dim(` (${deleteDetails.join(', ')})`) : '';
|
|
50
56
|
context.log(`${symbols[change.action]} ${name} ${dim(action)}${build}${deleted}`);
|
|
51
57
|
for (const [field, { from, to }] of Object.entries(change.fields || {})) {
|
|
58
|
+
// Rule text is usually many lines, so it's shown as a diff
|
|
59
|
+
if (field === 'rules') {
|
|
60
|
+
context.log(` ${field}:`);
|
|
61
|
+
printRuleDiff(context, from, to);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
52
64
|
context.log(change.action === 'create'
|
|
53
65
|
? ` ${field}: ${formatValue(to)}`
|
|
54
66
|
: ` ${field}: ${formatValue(from)} ${dim('->')} ${formatValue(to)}`);
|
|
@@ -58,6 +70,15 @@ function printChange(context, change) {
|
|
|
58
70
|
}
|
|
59
71
|
for (const error of change.errors || []) {
|
|
60
72
|
context.log(` ${red('error')}: ${error.message}`);
|
|
73
|
+
// Write rules that don't compile, and rule tests that failed
|
|
74
|
+
for (const diagnostic of (error.details?.diagnostics ?? [])) {
|
|
75
|
+
if (diagnostic.severity === 'error') {
|
|
76
|
+
context.log(` ${dim(`rules:${diagnostic.span.line}:${diagnostic.span.column}`)} ${diagnostic.message}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const failure of (error.details?.failures ?? [])) {
|
|
80
|
+
context.log(` ${red('✗')} ${failure.name} ${dim(`(${failure.actual}${failure.message ? `: ${failure.message}` : ''})`)}`);
|
|
81
|
+
}
|
|
61
82
|
}
|
|
62
83
|
}
|
|
63
84
|
function printSummary(context, result) {
|
|
@@ -85,6 +106,16 @@ export async function syncSchema(context, file, options) {
|
|
|
85
106
|
? `Can't find ${file}`
|
|
86
107
|
: `Can't read ${file}: ${error.message}`);
|
|
87
108
|
}
|
|
109
|
+
resolveRuleFiles(context, document, file);
|
|
110
|
+
resolveFlowFiles(context, document, file);
|
|
111
|
+
// Rules and their tests are checked here first, so a mistake costs no
|
|
112
|
+
// requests. The API checks them again, and has the final say
|
|
113
|
+
if (!options.skipRuleTests) {
|
|
114
|
+
checkDocumentRules(context, document);
|
|
115
|
+
}
|
|
116
|
+
if (!options.skipFlowTests) {
|
|
117
|
+
await checkDocumentFlows(context, document);
|
|
118
|
+
}
|
|
88
119
|
const jsonpad = context.createClient();
|
|
89
120
|
let result;
|
|
90
121
|
try {
|
package/build/errors.js
CHANGED
|
@@ -8,6 +8,9 @@ export const EXIT_CONFIRMATION_NEEDED = 5;
|
|
|
8
8
|
export const EXIT_NOT_FOUND = 6;
|
|
9
9
|
export const EXIT_PERMISSION_DENIED = 7;
|
|
10
10
|
export const EXIT_LIMIT_REACHED = 8;
|
|
11
|
+
export const EXIT_RULE_TESTS_FAILED = 9;
|
|
12
|
+
export const EXIT_TESTS_FAILED = EXIT_RULE_TESTS_FAILED;
|
|
13
|
+
export const EXIT_FLOW_FAILED = 10;
|
|
11
14
|
export const EXIT_INTERRUPTED = 130;
|
|
12
15
|
/**
|
|
13
16
|
* API errors (403s) that mean a plan limit was reached, rather than that the
|