@basementuniverse/jsonpad-cli 1.4.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.
- package/CHANGELOG.md +31 -0
- package/README.md +60 -0
- package/REFERENCE.md +129 -0
- package/build/commands/lists.js +115 -1
- package/build/commands/rules.js +307 -0
- package/build/commands/schema/export.js +44 -0
- package/build/commands/schema/sync.js +23 -0
- package/build/errors.js +1 -0
- package/build/program.js +3 -0
- package/build/rules.js +241 -0
- package/build/sdk.js +1 -1
- package/package.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,37 @@ and this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
Dates are npm publish dates.
|
|
9
9
|
|
|
10
|
+
## [1.5.0] - 2026-09-23
|
|
11
|
+
|
|
12
|
+
Needs `@basementuniverse/jsonpad-sdk` 2.2.0, and the JSONPad API release with
|
|
13
|
+
write rules.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **`jsonpad rules`**, which uses the copy of the rules engine built into the
|
|
18
|
+
CLI, so it needs no network and costs no requests:
|
|
19
|
+
- `rules check` compiles a rule file and shows the checker's warnings, with
|
|
20
|
+
`--strict` to fail on them.
|
|
21
|
+
- `rules test` runs a rule set against its tests (`<name>.tests.json` by
|
|
22
|
+
default), with `--filter`, `--trace` and `--json`.
|
|
23
|
+
- `rules eval` checks one write and shows what each rule did.
|
|
24
|
+
- `rules test --list` and `rules eval --list` run the same checks through the
|
|
25
|
+
API, and warn when its rules engine isn't the one in this CLI.
|
|
26
|
+
- **`jsonpad lists rules`**: `get` (with `--tests` and `--out`), `set` (from a
|
|
27
|
+
file, with `--tests`, `--remove` and `--skip-check`) and `denials`, which
|
|
28
|
+
lists the writes a list's rules have refused.
|
|
29
|
+
- **Rule files in schema documents.** `rulesFile` and `rulesTestsFile` in a
|
|
30
|
+
list are read relative to the document and sent as `rules` and `rulesTests`,
|
|
31
|
+
so rule text lives in its own file in git. `sync-schema` compiles and tests
|
|
32
|
+
them before sending anything (`--skip-rule-tests` turns that off), and shows
|
|
33
|
+
a rule change as a line diff.
|
|
34
|
+
- `export-schema --split-rules <directory>` writes each list's rules and tests
|
|
35
|
+
to their own files and references them from the document.
|
|
36
|
+
- Exit code `9`, for write rule tests that fail and for a `rules eval` the
|
|
37
|
+
rules refuse.
|
|
38
|
+
- `sync-schema` shows the diagnostics and failing tests the API reports for a
|
|
39
|
+
change, not just its message.
|
|
40
|
+
|
|
10
41
|
## [1.4.0] - 2026-09-18
|
|
11
42
|
|
|
12
43
|
Needs `@basementuniverse/jsonpad-sdk` 2.1.0, and the JSONPad API release with
|
package/README.md
CHANGED
|
@@ -279,6 +279,60 @@ The schema commands are also available as `jsonpad schema sync`,
|
|
|
279
279
|
Run `jsonpad --help`, or `jsonpad <command> --help`, for every option. The full
|
|
280
280
|
command reference is in [REFERENCE.md](REFERENCE.md).
|
|
281
281
|
|
|
282
|
+
### Write rules
|
|
283
|
+
|
|
284
|
+
A list's [write rules](https://jsonpad.io/docs/write-rules) check every item
|
|
285
|
+
write made with an API token. The CLI has its own copy of the rules engine, so
|
|
286
|
+
checking and testing rules needs no network and doesn't count against your
|
|
287
|
+
request allowance.
|
|
288
|
+
|
|
289
|
+
```bash
|
|
290
|
+
# Check that a rule file compiles, and show the checker's warnings
|
|
291
|
+
jsonpad rules check rules/games.rules
|
|
292
|
+
|
|
293
|
+
# Run its tests (rules/games.tests.json unless another file is given)
|
|
294
|
+
jsonpad rules test rules/games.rules
|
|
295
|
+
jsonpad rules test rules/games.rules --filter timeout --trace
|
|
296
|
+
|
|
297
|
+
# Try one write, and see what each rule did
|
|
298
|
+
jsonpad rules eval rules/games.rules --action update \
|
|
299
|
+
--old @before.json --merge '{"status":"sent"}' \
|
|
300
|
+
--token '{"id":"t","tags":["writer"]}'
|
|
301
|
+
|
|
302
|
+
# The same checks through the API, which always has the final say
|
|
303
|
+
jsonpad rules test --list games
|
|
304
|
+
jsonpad rules eval --list games --action delete --item 098e58bc --identity-id 3e3ce22b
|
|
305
|
+
|
|
306
|
+
# Read and write a list's rules
|
|
307
|
+
jsonpad lists rules get games --out rules/games.rules
|
|
308
|
+
jsonpad lists rules set games rules/games.rules --tests rules/games.tests.json
|
|
309
|
+
jsonpad lists rules set games --remove
|
|
310
|
+
|
|
311
|
+
# See the writes the rules have refused, and why
|
|
312
|
+
jsonpad lists rules denials games
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
A rule set's rules and tests live in git alongside the schema document, which
|
|
316
|
+
points at them:
|
|
317
|
+
|
|
318
|
+
```json
|
|
319
|
+
{
|
|
320
|
+
"lists": {
|
|
321
|
+
"games": {
|
|
322
|
+
"name": "Games",
|
|
323
|
+
"indexable": true,
|
|
324
|
+
"rulesFile": "rules/games.rules",
|
|
325
|
+
"rulesTestsFile": "rules/games.tests.json"
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
`jsonpad sync-schema` reads those files, compiles the rules and runs their
|
|
332
|
+
tests before it sends anything, so a mistake costs no requests
|
|
333
|
+
(`--skip-rule-tests` turns that off). `jsonpad export-schema --split-rules
|
|
334
|
+
rules --out jsonpad-schema.json` writes them back out the same way.
|
|
335
|
+
|
|
282
336
|
### Output
|
|
283
337
|
|
|
284
338
|
Commands that output records print a table in a terminal, and JSON when their
|
|
@@ -337,6 +391,11 @@ press Tab.
|
|
|
337
391
|
## Continuous integration
|
|
338
392
|
|
|
339
393
|
```yaml
|
|
394
|
+
# Write rules are checked and tested without touching the API, so this needs
|
|
395
|
+
# no token and costs no requests
|
|
396
|
+
- name: Test the write rules
|
|
397
|
+
run: npx @basementuniverse/jsonpad-cli rules test rules/games.rules
|
|
398
|
+
|
|
340
399
|
- name: Sync the JSONPad schema
|
|
341
400
|
run: npx @basementuniverse/jsonpad-cli sync-schema --wait
|
|
342
401
|
env:
|
|
@@ -356,6 +415,7 @@ press Tab.
|
|
|
356
415
|
| `6` | Not found |
|
|
357
416
|
| `7` | The token isn't allowed to do this, or isn't valid |
|
|
358
417
|
| `8` | Rate limited (after retrying), or a plan limit or the quota was reached |
|
|
418
|
+
| `9` | Write rule tests failed, or a rules check refused a write |
|
|
359
419
|
|
|
360
420
|
A dry run exits the same way the real sync would.
|
|
361
421
|
|
package/REFERENCE.md
CHANGED
|
@@ -19,6 +19,9 @@ Run `jsonpad <command> --help` for the same information in a terminal.
|
|
|
19
19
|
- [`jsonpad lists update`](#jsonpad-lists-update): Change a list. Fields that aren't given are left as they are
|
|
20
20
|
- [`jsonpad lists delete`](#jsonpad-lists-delete): Delete a list. Its items and indexes are deleted in the background
|
|
21
21
|
- [`jsonpad lists search`](#jsonpad-lists-search): Search a list's items, using the indexes that allow searching
|
|
22
|
+
- [`jsonpad lists rules get`](#jsonpad-lists-rules-get): Show a list's write rules
|
|
23
|
+
- [`jsonpad lists rules set`](#jsonpad-lists-rules-set): Set a list's write rules from a file
|
|
24
|
+
- [`jsonpad lists rules denials`](#jsonpad-lists-rules-denials): The most recent writes the list's rules refused, newest first
|
|
22
25
|
- [`jsonpad lists stats`](#jsonpad-lists-stats): Show a list's stats: its items, indexes and events, by day
|
|
23
26
|
- [`jsonpad lists events`](#jsonpad-lists-events): List a list's events, newest first by default
|
|
24
27
|
- [`jsonpad lists event`](#jsonpad-lists-event): Show one of a list's events
|
|
@@ -69,6 +72,9 @@ Run `jsonpad <command> --help` for the same information in a terminal.
|
|
|
69
72
|
- [`jsonpad identities stats`](#jsonpad-identities-stats): Show an identity's events, by day
|
|
70
73
|
- [`jsonpad identities events`](#jsonpad-identities-events): List an identity's events, newest first by default
|
|
71
74
|
- [`jsonpad identities event`](#jsonpad-identities-event): Show one of an identity's events
|
|
75
|
+
- [`jsonpad rules check`](#jsonpad-rules-check): Check that a rule file compiles, and show the checker's warnings
|
|
76
|
+
- [`jsonpad rules test`](#jsonpad-rules-test): Run a rule set against its tests
|
|
77
|
+
- [`jsonpad rules eval`](#jsonpad-rules-eval): Check one write against a rule set, and show what each rule did
|
|
72
78
|
- [`jsonpad whoami`](#jsonpad-whoami): Show the token you're using, its plan's limits and usage
|
|
73
79
|
- [`jsonpad config set-profile`](#jsonpad-config-set-profile): Add or update a profile
|
|
74
80
|
- [`jsonpad config use`](#jsonpad-config-use): Choose the default profile
|
|
@@ -99,6 +105,7 @@ jsonpad sync-schema [options] [file]
|
|
|
99
105
|
| `--wait` | Wait for index builds to finish |
|
|
100
106
|
| `--timeout <seconds>` | How long --wait waits for each index (default 600) |
|
|
101
107
|
| `--show-unchanged` | Also list resources that don't change |
|
|
108
|
+
| `--skip-rule-tests` | Don't compile and test write rules here first (the API always checks them) |
|
|
102
109
|
| `--json` | Print the API's response as JSON |
|
|
103
110
|
|
|
104
111
|
### `jsonpad export-schema`
|
|
@@ -115,6 +122,7 @@ jsonpad export-schema [options]
|
|
|
115
122
|
| `--tagged <tags>` | Only lists with one of these comma-separated tags (repeat the option to require every group) |
|
|
116
123
|
| `--lists <path names>` | Only these comma-separated lists |
|
|
117
124
|
| `--out <file>` | Write the document to a file, not stdout |
|
|
125
|
+
| `--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) |
|
|
118
126
|
|
|
119
127
|
### `jsonpad move-lists`
|
|
120
128
|
|
|
@@ -329,6 +337,60 @@ jsonpad lists search [options] <list> <query>
|
|
|
329
337
|
| `--json` | Output JSON (the same as --output json) |
|
|
330
338
|
| `-q, --quiet` | Only output ids (the same as --output id) |
|
|
331
339
|
|
|
340
|
+
### `jsonpad lists rules get`
|
|
341
|
+
|
|
342
|
+
Show a list's write rules
|
|
343
|
+
|
|
344
|
+
```
|
|
345
|
+
jsonpad lists rules get [options] <list>
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
| Argument | Description |
|
|
349
|
+
| --- | --- |
|
|
350
|
+
| `list` | The list (id or path name) |
|
|
351
|
+
|
|
352
|
+
| Option | Description |
|
|
353
|
+
| --- | --- |
|
|
354
|
+
| `--tests` | Show the rule tests instead of the rules |
|
|
355
|
+
| `-o, --out <file>` | Write to a file, not stdout |
|
|
356
|
+
|
|
357
|
+
### `jsonpad lists rules set`
|
|
358
|
+
|
|
359
|
+
Set a list's write rules from a file
|
|
360
|
+
|
|
361
|
+
```
|
|
362
|
+
jsonpad lists rules set [options] <list> [file]
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
| Argument | Description |
|
|
366
|
+
| --- | --- |
|
|
367
|
+
| `list` | The list (id or path name) |
|
|
368
|
+
| `file` (optional) | The rule file, or - for stdin |
|
|
369
|
+
|
|
370
|
+
| Option | Description |
|
|
371
|
+
| --- | --- |
|
|
372
|
+
| `--tests <file>` | Also set the rule tests from this file |
|
|
373
|
+
| `--remove` | Remove the list's rules |
|
|
374
|
+
| `--skip-check` | Don't compile and test the rules here first (the API always checks them) |
|
|
375
|
+
|
|
376
|
+
### `jsonpad lists rules denials`
|
|
377
|
+
|
|
378
|
+
The most recent writes the list's rules refused, newest first
|
|
379
|
+
|
|
380
|
+
```
|
|
381
|
+
jsonpad lists rules denials [options] <list>
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
| Argument | Description |
|
|
385
|
+
| --- | --- |
|
|
386
|
+
| `list` | The list (id or path name) |
|
|
387
|
+
|
|
388
|
+
| Option | Description |
|
|
389
|
+
| --- | --- |
|
|
390
|
+
| `-o, --output <format>` | Output format (default: table in a terminal, otherwise json) (one of: table, json, ndjson, id) |
|
|
391
|
+
| `--json` | Output JSON (the same as --output json) |
|
|
392
|
+
| `-q, --quiet` | Only output ids (the same as --output id) |
|
|
393
|
+
|
|
332
394
|
### `jsonpad lists stats`
|
|
333
395
|
|
|
334
396
|
Show a list's stats: its items, indexes and events, by day
|
|
@@ -1387,6 +1449,72 @@ jsonpad identities event [options] <identity> <event>
|
|
|
1387
1449
|
| `--json` | Output JSON (the same as --output json) |
|
|
1388
1450
|
| `-q, --quiet` | Only output ids (the same as --output id) |
|
|
1389
1451
|
|
|
1452
|
+
### `jsonpad rules check`
|
|
1453
|
+
|
|
1454
|
+
Check that a rule file compiles, and show the checker's warnings
|
|
1455
|
+
|
|
1456
|
+
```
|
|
1457
|
+
jsonpad rules check [options] <file>
|
|
1458
|
+
```
|
|
1459
|
+
|
|
1460
|
+
| Argument | Description |
|
|
1461
|
+
| --- | --- |
|
|
1462
|
+
| `file` | The rule file |
|
|
1463
|
+
|
|
1464
|
+
| Option | Description |
|
|
1465
|
+
| --- | --- |
|
|
1466
|
+
| `--strict` | Fail if there are any warnings |
|
|
1467
|
+
|
|
1468
|
+
### `jsonpad rules test`
|
|
1469
|
+
|
|
1470
|
+
Run a rule set against its tests
|
|
1471
|
+
|
|
1472
|
+
```
|
|
1473
|
+
jsonpad rules test [options] [rules] [tests]
|
|
1474
|
+
```
|
|
1475
|
+
|
|
1476
|
+
| Argument | Description |
|
|
1477
|
+
| --- | --- |
|
|
1478
|
+
| `rules` (optional) | The rule file (not needed with --list) |
|
|
1479
|
+
| `tests` (optional) | The test file (default: the rule file with .tests.json, or the list's stored tests with --list) |
|
|
1480
|
+
|
|
1481
|
+
| Option | Description |
|
|
1482
|
+
| --- | --- |
|
|
1483
|
+
| `--rules <file>` | The rule file to test against --list |
|
|
1484
|
+
| `--list <list>` | Test against the API, using the list's stored rules and tests unless they're given |
|
|
1485
|
+
| `--filter <text>` | Only tests whose name contains this text |
|
|
1486
|
+
| `--trace` | Show how each rule was evaluated for a failing test |
|
|
1487
|
+
| `--json` | Print the results as JSON |
|
|
1488
|
+
|
|
1489
|
+
### `jsonpad rules eval`
|
|
1490
|
+
|
|
1491
|
+
Check one write against a rule set, and show what each rule did
|
|
1492
|
+
|
|
1493
|
+
```
|
|
1494
|
+
jsonpad rules eval [options] [rules]
|
|
1495
|
+
```
|
|
1496
|
+
|
|
1497
|
+
| Argument | Description |
|
|
1498
|
+
| --- | --- |
|
|
1499
|
+
| `rules` (optional) | The rule file (not needed with --list) |
|
|
1500
|
+
|
|
1501
|
+
| Option | Description |
|
|
1502
|
+
| --- | --- |
|
|
1503
|
+
| `--action <action>` | What the write does: create, update, delete, restore |
|
|
1504
|
+
| `--list <list>` | Use the list's stored rules, and check with the API |
|
|
1505
|
+
| `--item <item>` | Take the old data from this item (needs --list) |
|
|
1506
|
+
| `--old <json>` | The data before the write (@file, - for stdin) |
|
|
1507
|
+
| `--new <json>` | The data after the write (@file, - for stdin) |
|
|
1508
|
+
| `--patch <json>` | A JSON Patch applied to the old data |
|
|
1509
|
+
| `--merge <json>` | A JSON merge patch applied to the old data |
|
|
1510
|
+
| `--identity <json>` | The identity making the write |
|
|
1511
|
+
| `--identity-id <id>` | An existing identity making the write (needs --list) |
|
|
1512
|
+
| `--token <json>` | The token making the write, e.g. '{"tags":["writer"]}' |
|
|
1513
|
+
| `--now <date>` | The time of the write (ISO 8601) |
|
|
1514
|
+
| `--pointer <pointer>` | The JSON pointer, for writes to part of an item |
|
|
1515
|
+
| `--trace` | Show every expression that was evaluated |
|
|
1516
|
+
| `--json` | Print the result as JSON |
|
|
1517
|
+
|
|
1390
1518
|
### `jsonpad whoami`
|
|
1391
1519
|
|
|
1392
1520
|
Show the token you're using: what it can do, its plan's limits, and the account's usage this month
|
|
@@ -1546,6 +1674,7 @@ JSONPAD_TOKEN, then the default profile.
|
|
|
1546
1674
|
7 The token isn't allowed to do this, or isn't valid
|
|
1547
1675
|
8 Rate limited (after retrying), or a plan limit or the monthly quota was
|
|
1548
1676
|
reached
|
|
1677
|
+
9 Write rule tests failed, or a rules check refused a write
|
|
1549
1678
|
|
|
1550
1679
|
The schema commands and rebuild-index (and indexes rebuild) exit with 1 for
|
|
1551
1680
|
every API error, as they did in @basementuniverse/jsonpad-sdk.
|
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,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);
|
package/build/rules.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { compile, runTests, version as engineVersion, } from '@basementuniverse/jsonpad-rules';
|
|
4
|
+
import { CliError, EXIT_RULE_TESTS_FAILED } from './errors.js';
|
|
5
|
+
export { engineVersion };
|
|
6
|
+
/**
|
|
7
|
+
* Where `rules test` looks for a rule set's tests when it isn't told
|
|
8
|
+
*/
|
|
9
|
+
export function defaultTestsFile(rulesFile) {
|
|
10
|
+
return rulesFile.replace(/(\.[^./\\]+)?$/, '.tests.json');
|
|
11
|
+
}
|
|
12
|
+
export function readTextFile(context, file, what) {
|
|
13
|
+
try {
|
|
14
|
+
return fs.readFileSync(path.resolve(context.cwd, file), 'utf8');
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
throw new CliError(error.code === 'ENOENT'
|
|
18
|
+
? `Can't find ${file} (${what})`
|
|
19
|
+
: `Can't read ${file} (${what}): ${error.message}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function readJsonFile(context, file, what) {
|
|
23
|
+
const text = readTextFile(context, file, what);
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(text);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
throw new CliError(`${file} isn't valid JSON: ${error.message}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Print diagnostics as file:line:column, the way compilers do, so an editor
|
|
33
|
+
* can jump to them
|
|
34
|
+
*/
|
|
35
|
+
export function printDiagnostics(context, diagnostics, file) {
|
|
36
|
+
const { red, yellow, dim } = context.colours;
|
|
37
|
+
let errors = 0;
|
|
38
|
+
let warnings = 0;
|
|
39
|
+
for (const diagnostic of diagnostics) {
|
|
40
|
+
const isError = diagnostic.severity === 'error';
|
|
41
|
+
if (isError) {
|
|
42
|
+
errors++;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
warnings++;
|
|
46
|
+
}
|
|
47
|
+
context.log(`${dim(`${file}:${diagnostic.span.line}:${diagnostic.span.column}`)} ${isError ? red('error') : yellow('warning')} ${diagnostic.message} ${dim(`[${diagnostic.code}]`)}`);
|
|
48
|
+
}
|
|
49
|
+
return { errors, warnings };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Compile rule text, printing its diagnostics. Throws when it doesn't compile
|
|
53
|
+
*/
|
|
54
|
+
export function compileRules(context, text, file, options = {}) {
|
|
55
|
+
const { ruleSet, diagnostics } = compile(text);
|
|
56
|
+
const { errors, warnings } = options.quiet
|
|
57
|
+
? {
|
|
58
|
+
errors: diagnostics.filter(d => d.severity === 'error').length,
|
|
59
|
+
warnings: 0,
|
|
60
|
+
}
|
|
61
|
+
: printDiagnostics(context, diagnostics, file);
|
|
62
|
+
if (!ruleSet) {
|
|
63
|
+
throw new CliError(`${file} has ${errors} ${errors === 1 ? 'error' : 'errors'}`);
|
|
64
|
+
}
|
|
65
|
+
if (options.strict && warnings > 0) {
|
|
66
|
+
throw new CliError(`${file} has ${warnings} ${warnings === 1 ? 'warning' : 'warnings'} (--strict)`);
|
|
67
|
+
}
|
|
68
|
+
return ruleSet;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Print the result of one test, and its trace if asked for
|
|
72
|
+
*/
|
|
73
|
+
export function printTestResult(context, result, options = {}) {
|
|
74
|
+
const { green, red, dim } = context.colours;
|
|
75
|
+
const describe = (outcome, expectation) => {
|
|
76
|
+
if (typeof expectation === 'object') {
|
|
77
|
+
return `${outcome} (expected the write to fail with "${expectation.fail}")`;
|
|
78
|
+
}
|
|
79
|
+
return `${outcome} (expected ${expectation})`;
|
|
80
|
+
};
|
|
81
|
+
if (result.passed) {
|
|
82
|
+
context.log(`${green('✓')} ${result.name}`);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
context.log(`${red('✗')} ${result.name} ${dim(describe(result.actual, result.expected))}`);
|
|
86
|
+
if (result.message) {
|
|
87
|
+
context.log(` ${result.message}`);
|
|
88
|
+
}
|
|
89
|
+
if (options.trace && result.decision) {
|
|
90
|
+
for (const statement of result.decision.statements) {
|
|
91
|
+
const outcome = statement.error
|
|
92
|
+
? red(`error: ${statement.error}`)
|
|
93
|
+
: statement.result
|
|
94
|
+
? green('true')
|
|
95
|
+
: dim('false');
|
|
96
|
+
context.log(` ${dim(`line ${statement.span.line}`)} ${statement.kind}${statement.label ? ` "${statement.label}"` : ''}: ${outcome}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Run a test document against a rule set, printing each test, and throw if
|
|
102
|
+
* any of them fail
|
|
103
|
+
*/
|
|
104
|
+
export function runRuleTests(context, ruleSet, document, file, options = {}) {
|
|
105
|
+
const run = runTests(ruleSet, document, { filter: options.filter });
|
|
106
|
+
if (run.errors.length > 0) {
|
|
107
|
+
throw new CliError([
|
|
108
|
+
`${file} isn't a valid test document:`,
|
|
109
|
+
...run.errors.map(error => error.path
|
|
110
|
+
? ` ${error.path}: ${error.message}`
|
|
111
|
+
: ` ${error.message}`),
|
|
112
|
+
].join('\n'));
|
|
113
|
+
}
|
|
114
|
+
if (options.json) {
|
|
115
|
+
context.log(JSON.stringify({
|
|
116
|
+
passed: run.passed,
|
|
117
|
+
failed: run.failed,
|
|
118
|
+
results: run.results.map(result => ({
|
|
119
|
+
name: result.name,
|
|
120
|
+
passed: result.passed,
|
|
121
|
+
expected: result.expected,
|
|
122
|
+
actual: result.actual,
|
|
123
|
+
message: result.message,
|
|
124
|
+
})),
|
|
125
|
+
}, null, 2));
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
for (const result of run.results) {
|
|
129
|
+
printTestResult(context, result, options);
|
|
130
|
+
}
|
|
131
|
+
const { green, red } = context.colours;
|
|
132
|
+
context.log(`\n${run.passed} passed, ${run.failed > 0 ? red(`${run.failed} failed`) : green('0 failed')}`);
|
|
133
|
+
}
|
|
134
|
+
if (run.failed > 0) {
|
|
135
|
+
throw new CliError(`${run.failed} of ${run.results.length} ${run.results.length === 1 ? 'test' : 'tests'} failed`, EXIT_RULE_TESTS_FAILED);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Warn when the server's rules engine isn't the one built into this CLI: a
|
|
140
|
+
* rule set that passes here could still be refused there
|
|
141
|
+
*/
|
|
142
|
+
export function checkEngineVersion(context, serverVersion) {
|
|
143
|
+
if (!serverVersion) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const [major, minor] = engineVersion.split('.');
|
|
147
|
+
const [serverMajor, serverMinor] = serverVersion.split('.');
|
|
148
|
+
if (major !== serverMajor || minor !== serverMinor) {
|
|
149
|
+
context.error(`${context.colours.yellow('warning')}: this CLI has rules engine ${engineVersion}, and the API has ${serverVersion}. The API decides: check your rules with --list if they disagree`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Resolve the CLI-only rulesFile and rulesTestsFile fields in a schema sync
|
|
154
|
+
* document, relative to the document, into the rules and rulesTests the API
|
|
155
|
+
* takes
|
|
156
|
+
*/
|
|
157
|
+
export function resolveRuleFiles(context, document, documentFile) {
|
|
158
|
+
const directory = path.dirname(path.resolve(context.cwd, documentFile));
|
|
159
|
+
for (const [pathName, list] of Object.entries(document.lists ?? {})) {
|
|
160
|
+
for (const [field, target] of [
|
|
161
|
+
['rulesFile', 'rules'],
|
|
162
|
+
['rulesTestsFile', 'rulesTests'],
|
|
163
|
+
]) {
|
|
164
|
+
const file = list[field];
|
|
165
|
+
if (file === undefined) {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (list[target] !== undefined) {
|
|
169
|
+
throw new CliError(`List "${pathName}" has both ${field} and ${target}: use one or the other`);
|
|
170
|
+
}
|
|
171
|
+
const resolved = path.relative(context.cwd, path.resolve(directory, file));
|
|
172
|
+
list[target] =
|
|
173
|
+
target === 'rules'
|
|
174
|
+
? readTextFile(context, resolved, `${field} for list "${pathName}"`)
|
|
175
|
+
: readJsonFile(context, resolved, `${field} for list "${pathName}"`);
|
|
176
|
+
delete list[field];
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Compile and test the write rules in a schema sync document, before it's
|
|
182
|
+
* sent
|
|
183
|
+
*/
|
|
184
|
+
export function checkDocumentRules(context, document) {
|
|
185
|
+
for (const [pathName, list] of Object.entries(document.lists ?? {})) {
|
|
186
|
+
const rules = Array.isArray(list.rules)
|
|
187
|
+
? list.rules.join('\n')
|
|
188
|
+
: list.rules;
|
|
189
|
+
if (typeof rules !== 'string' || rules.trim() === '') {
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const where = `the rules for list "${pathName}"`;
|
|
193
|
+
const { ruleSet, diagnostics } = compile(rules);
|
|
194
|
+
printDiagnostics(context, diagnostics, where);
|
|
195
|
+
if (!ruleSet) {
|
|
196
|
+
throw new CliError(`${where} don't compile`);
|
|
197
|
+
}
|
|
198
|
+
if (list.rulesTests) {
|
|
199
|
+
runRuleTests(context, ruleSet, list.rulesTests, `the rule tests for list "${pathName}"`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Show a rule change as a line diff, since rule text is usually many lines
|
|
205
|
+
*/
|
|
206
|
+
export function printRuleDiff(context, from, to) {
|
|
207
|
+
const { green, red, dim } = context.colours;
|
|
208
|
+
// A file's trailing newline isn't a line of rules
|
|
209
|
+
const lines = (text) => text ? text.replace(/\n$/, '').split('\n') : [];
|
|
210
|
+
const before = lines(from);
|
|
211
|
+
const after = lines(to);
|
|
212
|
+
if (before.length === 0 && after.length === 0) {
|
|
213
|
+
context.log(` ${dim('(no rules)')}`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
// The common start and end are usually most of the text
|
|
217
|
+
let start = 0;
|
|
218
|
+
while (start < before.length &&
|
|
219
|
+
start < after.length &&
|
|
220
|
+
before[start] === after[start]) {
|
|
221
|
+
start++;
|
|
222
|
+
}
|
|
223
|
+
let end = 0;
|
|
224
|
+
while (end < before.length - start &&
|
|
225
|
+
end < after.length - start &&
|
|
226
|
+
before[before.length - 1 - end] === after[after.length - 1 - end]) {
|
|
227
|
+
end++;
|
|
228
|
+
}
|
|
229
|
+
if (start > 0) {
|
|
230
|
+
context.log(dim(` … ${start} unchanged ${start === 1 ? 'line' : 'lines'}`));
|
|
231
|
+
}
|
|
232
|
+
for (const line of before.slice(start, before.length - end)) {
|
|
233
|
+
context.log(red(` - ${line}`));
|
|
234
|
+
}
|
|
235
|
+
for (const line of after.slice(start, after.length - end)) {
|
|
236
|
+
context.log(green(` + ${line}`));
|
|
237
|
+
}
|
|
238
|
+
if (end > 0) {
|
|
239
|
+
context.log(dim(` … ${end} unchanged ${end === 1 ? 'line' : 'lines'}`));
|
|
240
|
+
}
|
|
241
|
+
}
|
package/build/sdk.js
CHANGED
|
@@ -2,4 +2,4 @@ import sdk from '@basementuniverse/jsonpad-sdk';
|
|
|
2
2
|
// The SDK is a UMD build, which Node loads as CommonJS, so an ES module only
|
|
3
3
|
// sees its exports object as the default import
|
|
4
4
|
export const JSONPad = sdk.default;
|
|
5
|
-
export const { IndexBuildError, JSONPadError } = sdk;
|
|
5
|
+
export const { IndexBuildError, JSONPadError, WriteRuleError } = sdk;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basementuniverse/jsonpad-cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Command line tool for JSONPad",
|
|
5
5
|
"author": "Gordon Larrigan <gordonlarrigan@gmail.com> (https://gordonlarrigan.com)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -39,7 +39,8 @@
|
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
41
|
"@basementuniverse/jsonpad-realtime-sdk": "^1.6.0",
|
|
42
|
-
"@basementuniverse/jsonpad-
|
|
42
|
+
"@basementuniverse/jsonpad-rules": "^1.0.0",
|
|
43
|
+
"@basementuniverse/jsonpad-sdk": "^2.2.0",
|
|
43
44
|
"commander": "^15.0.0"
|
|
44
45
|
},
|
|
45
46
|
"devDependencies": {
|