@basementuniverse/jsonpad-cli 1.3.0 → 1.5.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.
@@ -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,7 @@ 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)")
15
16
  .action((options) => exportSchema(context, options));
16
17
  }
17
18
  export async function exportSchema(context, options) {
@@ -35,6 +36,9 @@ export async function exportSchema(context, options) {
35
36
  for (const warning of result.warnings) {
36
37
  context.error(`${context.colours.yellow('warning')}: ${warning}`);
37
38
  }
39
+ if (options.splitRules) {
40
+ splitRules(context, result.document, options);
41
+ }
38
42
  const json = `${JSON.stringify(result.document, null, 2)}\n`;
39
43
  if (options.out) {
40
44
  fs.writeFileSync(path.resolve(context.cwd, options.out), json);
@@ -44,3 +48,43 @@ export async function exportSchema(context, options) {
44
48
  context.stdout.write(json);
45
49
  }
46
50
  }
51
+ /**
52
+ * Move each list's rules and rule tests out of the document and into their
53
+ * own files, which the document then points at with rulesFile and
54
+ * rulesTestsFile
55
+ */
56
+ function splitRules(context, document, options) {
57
+ if (!options.out) {
58
+ throw new CliError('--split-rules needs --out');
59
+ }
60
+ const directory = path.resolve(context.cwd, options.splitRules);
61
+ const documentDirectory = path.dirname(path.resolve(context.cwd, options.out));
62
+ let written = 0;
63
+ fs.mkdirSync(directory, { recursive: true });
64
+ for (const [pathName, list] of Object.entries(document.lists)) {
65
+ const reference = (file) => {
66
+ const relative = path.relative(documentDirectory, file);
67
+ // Paths in the document are relative to the document, and always use
68
+ // forward slashes
69
+ return relative.split(path.sep).join('/');
70
+ };
71
+ if (typeof list.rules === 'string' || Array.isArray(list.rules)) {
72
+ const text = Array.isArray(list.rules)
73
+ ? list.rules.join('\n')
74
+ : list.rules;
75
+ const file = path.join(directory, `${pathName}.rules`);
76
+ fs.writeFileSync(file, `${text.replace(/\n?$/, '\n')}`);
77
+ delete list.rules;
78
+ list.rulesFile = reference(file);
79
+ written++;
80
+ }
81
+ if (list.rulesTests) {
82
+ const file = path.join(directory, `${pathName}.tests.json`);
83
+ fs.writeFileSync(file, `${JSON.stringify(list.rulesTests, null, 2)}\n`);
84
+ delete list.rulesTests;
85
+ list.rulesTestsFile = reference(file);
86
+ written++;
87
+ }
88
+ }
89
+ context.error(`Wrote ${written} rule ${written === 1 ? 'file' : 'files'} to ${options.splitRules}`);
90
+ }
@@ -2,6 +2,7 @@ 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 { checkDocumentRules, printRuleDiff, resolveRuleFiles, } from '../../rules.js';
5
6
  import { formatValue, plural } from '../../output.js';
6
7
  export const DEFAULT_SCHEMA_FILE = 'jsonpad-schema.json';
7
8
  export function defineSyncSchema(command, context) {
@@ -15,6 +16,7 @@ export function defineSyncSchema(command, context) {
15
16
  .option('--wait', 'Wait for index builds to finish')
16
17
  .option('--timeout <seconds>', 'How long --wait waits for each index (default 600)')
17
18
  .option('--show-unchanged', "Also list resources that don't change")
19
+ .option('--skip-rule-tests', "Don't compile and test write rules here first (the API always checks them)")
18
20
  .option('--json', "Print the API's response as JSON")
19
21
  .action((file, options) => syncSchema(context, file, options));
20
22
  }
@@ -49,6 +51,12 @@ function printChange(context, change) {
49
51
  const deleted = deleteDetails.length > 0 ? dim(` (${deleteDetails.join(', ')})`) : '';
50
52
  context.log(`${symbols[change.action]} ${name} ${dim(action)}${build}${deleted}`);
51
53
  for (const [field, { from, to }] of Object.entries(change.fields || {})) {
54
+ // Rule text is usually many lines, so it's shown as a diff
55
+ if (field === 'rules') {
56
+ context.log(` ${field}:`);
57
+ printRuleDiff(context, from, to);
58
+ continue;
59
+ }
52
60
  context.log(change.action === 'create'
53
61
  ? ` ${field}: ${formatValue(to)}`
54
62
  : ` ${field}: ${formatValue(from)} ${dim('->')} ${formatValue(to)}`);
@@ -58,6 +66,15 @@ function printChange(context, change) {
58
66
  }
59
67
  for (const error of change.errors || []) {
60
68
  context.log(` ${red('error')}: ${error.message}`);
69
+ // Write rules that don't compile, and rule tests that failed
70
+ for (const diagnostic of (error.details?.diagnostics ?? [])) {
71
+ if (diagnostic.severity === 'error') {
72
+ context.log(` ${dim(`rules:${diagnostic.span.line}:${diagnostic.span.column}`)} ${diagnostic.message}`);
73
+ }
74
+ }
75
+ for (const failure of (error.details?.failures ?? [])) {
76
+ context.log(` ${red('✗')} ${failure.name} ${dim(`(${failure.actual}${failure.message ? `: ${failure.message}` : ''})`)}`);
77
+ }
61
78
  }
62
79
  }
63
80
  function printSummary(context, result) {
@@ -85,6 +102,12 @@ export async function syncSchema(context, file, options) {
85
102
  ? `Can't find ${file}`
86
103
  : `Can't read ${file}: ${error.message}`);
87
104
  }
105
+ resolveRuleFiles(context, document, file);
106
+ // Rules and their tests are checked here first, so a mistake costs no
107
+ // requests. The API checks them again, and has the final say
108
+ if (!options.skipRuleTests) {
109
+ checkDocumentRules(context, document);
110
+ }
88
111
  const jsonpad = context.createClient();
89
112
  let result;
90
113
  try {
package/build/errors.js CHANGED
@@ -8,6 +8,7 @@ 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;
11
12
  export const EXIT_INTERRUPTED = 130;
12
13
  /**
13
14
  * API errors (403s) that mean a plan limit was reached, rather than that the
package/build/program.js CHANGED
@@ -9,6 +9,7 @@ import { defineItems } from './commands/items.js';
9
9
  import { defineListen } from './commands/listen.js';
10
10
  import { defineLists } from './commands/lists.js';
11
11
  import { defineRebuildIndex } from './commands/rebuild-index.js';
12
+ import { defineRules } from './commands/rules.js';
12
13
  import { defineExportSchema } from './commands/schema/export.js';
13
14
  import { defineMoveLists } from './commands/schema/move.js';
14
15
  import { defineSyncSchema } from './commands/schema/sync.js';
@@ -45,6 +46,7 @@ export const EXIT_CODES_HELP = `Exit codes:
45
46
  7 The token isn't allowed to do this, or isn't valid
46
47
  8 Rate limited (after retrying), or a plan limit or the monthly quota was
47
48
  reached
49
+ 9 Write rule tests failed, or a rules check refused a write
48
50
 
49
51
  The schema commands and rebuild-index (and indexes rebuild) exit with 1 for
50
52
  every API error, as they did in @basementuniverse/jsonpad-sdk.`;
@@ -100,6 +102,7 @@ export function createProgram(context) {
100
102
  defineIndexes(program.command('indexes'), context);
101
103
  defineItems(program.command('items'), context);
102
104
  defineIdentities(program.command('identities'), context);
105
+ defineRules(program.command('rules'), context);
103
106
  defineWhoami(program.command('whoami'), context);
104
107
  defineConfig(program.command('config'), context);
105
108
  defineListen(program.command('listen'), context);
@@ -108,7 +108,7 @@ export async function request(context, send) {
108
108
  export function sdkPointer(pointer) {
109
109
  return pointer === undefined ? undefined : pointer.replace(/^\/+/, '');
110
110
  }
111
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
111
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
112
112
  /**
113
113
  * Find an identity's id from what was passed on the command line: its id,
114
114
  * group/name, or the name of an identity with no group