@basementuniverse/jsonpad-cli 1.0.0 → 1.3.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 +77 -1
- package/README.md +252 -27
- package/REFERENCE.md +1292 -3
- package/build/cli.js +8 -0
- package/build/client.js +185 -0
- package/build/commands/config.js +134 -0
- package/build/commands/history.js +205 -0
- package/build/commands/identities.js +372 -0
- package/build/commands/indexes.js +255 -0
- package/build/commands/items.js +329 -0
- package/build/commands/listen.js +173 -0
- package/build/commands/lists.js +237 -0
- package/build/commands/transfer.js +246 -0
- package/build/commands/whoami.js +121 -0
- package/build/completion.js +170 -0
- package/build/config.js +158 -0
- package/build/context.js +24 -8
- package/build/errors.js +56 -0
- package/build/indexes.js +24 -1
- package/build/input.js +167 -0
- package/build/output.js +191 -0
- package/build/program.js +85 -20
- package/build/realtime.js +13 -0
- package/build/reference.js +34 -15
- package/build/resources.js +224 -0
- package/package.json +4 -4
package/build/cli.js
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createContext } from './context.js';
|
|
3
3
|
import { run } from './program.js';
|
|
4
|
+
// When output is piped to something that stops reading early (e.g. head),
|
|
5
|
+
// there's nothing more to do
|
|
6
|
+
process.stdout.on('error', error => {
|
|
7
|
+
if (error.code === 'EPIPE') {
|
|
8
|
+
process.exit(process.exitCode ?? 0);
|
|
9
|
+
}
|
|
10
|
+
throw error;
|
|
11
|
+
});
|
|
4
12
|
process.exitCode = await run(process.argv.slice(2), createContext());
|
package/build/client.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { formatDate, formatNumber } from './output.js';
|
|
2
|
+
import { JSONPadError } from './sdk.js';
|
|
3
|
+
/**
|
|
4
|
+
* How many times a rate limited request is retried
|
|
5
|
+
*/
|
|
6
|
+
export const MAX_RETRIES = 5;
|
|
7
|
+
/**
|
|
8
|
+
* The longest the CLI waits before retrying a rate limited request. If the API
|
|
9
|
+
* asks for a longer wait, the error is reported instead
|
|
10
|
+
*/
|
|
11
|
+
export const MAX_RETRY_WAIT_SECONDS = 60;
|
|
12
|
+
/**
|
|
13
|
+
* Retries that wait at least this long are mentioned on stderr, so that a long
|
|
14
|
+
* wait doesn't look like the command has hung. Shorter ones happen all the
|
|
15
|
+
* time on plans with a minimum gap between requests, so they're only mentioned
|
|
16
|
+
* with --verbose
|
|
17
|
+
*/
|
|
18
|
+
export const RETRY_NOTICE_SECONDS = 5;
|
|
19
|
+
/**
|
|
20
|
+
* Methods that already handle being rate limited themselves
|
|
21
|
+
*/
|
|
22
|
+
const NOT_RETRIED = new Set(['waitForIndex']);
|
|
23
|
+
/**
|
|
24
|
+
* How long to wait before retrying a failed request, in milliseconds, or null
|
|
25
|
+
* if it shouldn't be retried
|
|
26
|
+
*
|
|
27
|
+
* Only rate limit errors are retried. A request refused because the monthly
|
|
28
|
+
* quota has run out is also a 429, but it won't succeed until the quota resets
|
|
29
|
+
*/
|
|
30
|
+
export function retryDelay(error, attempt) {
|
|
31
|
+
if (!(error instanceof JSONPadError) ||
|
|
32
|
+
error.status !== 429 ||
|
|
33
|
+
error.errorName !== 'RATE_LIMIT_EXCEEDED' ||
|
|
34
|
+
attempt >= MAX_RETRIES) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const seconds = error.retryAfter ?? 2 ** attempt;
|
|
38
|
+
return seconds <= MAX_RETRY_WAIT_SECONDS ? Math.max(seconds, 0) * 1000 : null;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Wrap a client so that its requests are retried when they're rate limited
|
|
42
|
+
*
|
|
43
|
+
* The API refuses a rate limited request before doing anything, so it's safe
|
|
44
|
+
* to retry any request, including ones that create things
|
|
45
|
+
*/
|
|
46
|
+
export function createRetryingClient(context, client) {
|
|
47
|
+
return new Proxy(client, {
|
|
48
|
+
get(target, property) {
|
|
49
|
+
const value = Reflect.get(target, property, target);
|
|
50
|
+
if (typeof value !== 'function') {
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
if (NOT_RETRIED.has(property)) {
|
|
54
|
+
return value.bind(target);
|
|
55
|
+
}
|
|
56
|
+
return (...args) => {
|
|
57
|
+
const result = value.apply(target, args);
|
|
58
|
+
// Only requests are retried, not e.g. addEventListener
|
|
59
|
+
if (!(result instanceof Promise)) {
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
const attempt = async (pending, count) => {
|
|
63
|
+
try {
|
|
64
|
+
return await pending;
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
const delay = retryDelay(error, count);
|
|
68
|
+
if (delay === null) {
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
if (delay >= RETRY_NOTICE_SECONDS * 1000 ||
|
|
72
|
+
context.globalOptions.verbose) {
|
|
73
|
+
context.error(context.colours.dim(`Rate limited, retrying in ${formatSeconds(delay)}...`));
|
|
74
|
+
}
|
|
75
|
+
await context.sleep(delay);
|
|
76
|
+
return attempt(value.apply(target, args), count + 1);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
return attempt(result, 0);
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function formatSeconds(milliseconds) {
|
|
85
|
+
const seconds = milliseconds / 1000;
|
|
86
|
+
return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)}s`;
|
|
87
|
+
}
|
|
88
|
+
const pacedContexts = new WeakSet();
|
|
89
|
+
/**
|
|
90
|
+
* Leave at least `interval` milliseconds between one response and the next
|
|
91
|
+
* request, so that a long run of requests (e.g. an import) keeps inside the
|
|
92
|
+
* plan's rate limits instead of being refused and retried
|
|
93
|
+
*
|
|
94
|
+
* Like --verbose, this wraps the global fetch, since the SDK uses it
|
|
95
|
+
*/
|
|
96
|
+
export function installRequestPacing(context, interval) {
|
|
97
|
+
if (interval <= 0 || pacedContexts.has(context)) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
pacedContexts.add(context);
|
|
101
|
+
const originalFetch = globalThis.fetch;
|
|
102
|
+
// Pacing starts now, since it's installed after a request (e.g. fetching the
|
|
103
|
+
// plan's limits) has just finished
|
|
104
|
+
let lastFinishedAt = Date.now();
|
|
105
|
+
globalThis.fetch = async (input, init) => {
|
|
106
|
+
const wait = lastFinishedAt + interval - Date.now();
|
|
107
|
+
if (wait > 0) {
|
|
108
|
+
await context.sleep(wait);
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return await originalFetch(input, init);
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
lastFinishedAt = Date.now();
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The gap between requests that keeps inside a plan's rate limits: its minimum
|
|
120
|
+
* gap between requests, or an even spread of its requests per minute,
|
|
121
|
+
* whichever is longer, plus a little leeway for the server's clock
|
|
122
|
+
*/
|
|
123
|
+
export function requestInterval(plan) {
|
|
124
|
+
const gap = Math.max(plan.rateLimit ?? 0, plan.maxRequestsPerMinute
|
|
125
|
+
? Math.ceil(60_000 / plan.maxRequestsPerMinute)
|
|
126
|
+
: 0);
|
|
127
|
+
return gap > 0 ? gap + 50 : 0;
|
|
128
|
+
}
|
|
129
|
+
const verboseContexts = new WeakSet();
|
|
130
|
+
/**
|
|
131
|
+
* Log every request and response to stderr, for --verbose
|
|
132
|
+
*
|
|
133
|
+
* The SDK uses the global fetch, so this wraps it. The token is sent in a
|
|
134
|
+
* header, which isn't logged
|
|
135
|
+
*/
|
|
136
|
+
export function installVerboseFetch(context) {
|
|
137
|
+
if (verboseContexts.has(context)) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
verboseContexts.add(context);
|
|
141
|
+
const { dim } = context.colours;
|
|
142
|
+
const originalFetch = globalThis.fetch;
|
|
143
|
+
globalThis.fetch = async (input, init) => {
|
|
144
|
+
const url = input instanceof Request
|
|
145
|
+
? input.url
|
|
146
|
+
: input.toString().replace(/\?$/, '');
|
|
147
|
+
const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
|
|
148
|
+
const started = Date.now();
|
|
149
|
+
context.error(dim(`> ${method} ${url}`));
|
|
150
|
+
try {
|
|
151
|
+
const response = await originalFetch(input, init);
|
|
152
|
+
const requestId = response.headers.get('x-request-id');
|
|
153
|
+
context.error(dim(`< ${response.status} ${response.statusText} (${Date.now() - started}ms${requestId ? `, request ${requestId}` : ''})`));
|
|
154
|
+
return response;
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
context.error(dim(`< failed: ${error instanceof Error ? error.message : error}`));
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Describe the rate limit and quota from a response, for --verbose, or null if
|
|
164
|
+
* the response didn't include them
|
|
165
|
+
*/
|
|
166
|
+
export function describeLimits(meta) {
|
|
167
|
+
if (!meta) {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
const parts = [];
|
|
171
|
+
if (meta.rateLimit) {
|
|
172
|
+
parts.push(`rate limit ${formatNumber(meta.rateLimit.remaining)}/${formatNumber(meta.rateLimit.total)} left this minute`);
|
|
173
|
+
}
|
|
174
|
+
if (meta.quota) {
|
|
175
|
+
const { total, remaining, resetAt, degraded } = meta.quota;
|
|
176
|
+
const reset = `resets ${formatDate(resetAt)}`;
|
|
177
|
+
parts.push(total !== null && remaining !== null
|
|
178
|
+
? `quota ${formatNumber(remaining)}/${formatNumber(total)} left, ${reset}`
|
|
179
|
+
: `no monthly quota`);
|
|
180
|
+
if (degraded) {
|
|
181
|
+
parts.push('degraded (reads are served at the free rate limit)');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return parts.length > 0 ? parts.join(' · ') : null;
|
|
185
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { configPath, maskToken, readConfig, validateProfileName, writeConfig, } from '../config.js';
|
|
2
|
+
import { CliError, EXIT_NOT_FOUND } from '../errors.js';
|
|
3
|
+
import { canPrompt, confirm, promptSecret, readStdin } from '../input.js';
|
|
4
|
+
import { addOutputOptions, printRecords, resolveOutputFormat, } from '../output.js';
|
|
5
|
+
export function defineConfig(command, context) {
|
|
6
|
+
command.description("Manage profiles: saved API tokens, so you don't need JSONPAD_TOKEN");
|
|
7
|
+
command
|
|
8
|
+
.command('set-profile')
|
|
9
|
+
.summary('Add or update a profile')
|
|
10
|
+
.description("Add or update a profile. The token is asked for in a terminal, or read from stdin (e.g. from a password manager). The global --api-url option sets the profile's API URL")
|
|
11
|
+
.argument('<name>', 'The profile name')
|
|
12
|
+
.option('--default', 'Make this the default profile')
|
|
13
|
+
.action((name, options, self) => setProfile(context, name, {
|
|
14
|
+
...options,
|
|
15
|
+
apiUrl: self.optsWithGlobals().apiUrl,
|
|
16
|
+
}));
|
|
17
|
+
command
|
|
18
|
+
.command('use')
|
|
19
|
+
.description('Choose the default profile')
|
|
20
|
+
.argument('<name>', 'The profile name')
|
|
21
|
+
.action((name) => useProfile(context, name));
|
|
22
|
+
addOutputOptions(command
|
|
23
|
+
.command('list')
|
|
24
|
+
.alias('ls')
|
|
25
|
+
.description('List profiles (tokens are masked)')
|
|
26
|
+
.action((options) => listProfiles(context, options)));
|
|
27
|
+
command
|
|
28
|
+
.command('remove')
|
|
29
|
+
.alias('rm')
|
|
30
|
+
.description('Remove a profile')
|
|
31
|
+
.argument('<name>', 'The profile name')
|
|
32
|
+
.option('-y, --yes', "Don't ask for confirmation")
|
|
33
|
+
.action((name, options) => removeProfile(context, name, options));
|
|
34
|
+
command
|
|
35
|
+
.command('path')
|
|
36
|
+
.description('Show where the config file is (set JSONPAD_CONFIG to use a different file)')
|
|
37
|
+
.action(() => context.log(configPath(context)));
|
|
38
|
+
return command;
|
|
39
|
+
}
|
|
40
|
+
function requireProfile(config, name) {
|
|
41
|
+
const profile = config.profiles[name];
|
|
42
|
+
if (!profile) {
|
|
43
|
+
throw new CliError(`There's no profile named "${name}". Run jsonpad config list to see your profiles`, EXIT_NOT_FOUND);
|
|
44
|
+
}
|
|
45
|
+
return profile;
|
|
46
|
+
}
|
|
47
|
+
async function readToken(context, name, existing) {
|
|
48
|
+
if (canPrompt(context)) {
|
|
49
|
+
return (await promptSecret(context, existing
|
|
50
|
+
? `API token for ${name} (leave empty to keep the current one): `
|
|
51
|
+
: `API token for ${name}: `)).trim();
|
|
52
|
+
}
|
|
53
|
+
return (await readStdin(context)).trim();
|
|
54
|
+
}
|
|
55
|
+
export async function setProfile(context, name, options) {
|
|
56
|
+
validateProfileName(name);
|
|
57
|
+
if (options.apiUrl !== undefined) {
|
|
58
|
+
try {
|
|
59
|
+
new URL(options.apiUrl);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new CliError(`--api-url must be a URL, e.g. http://localhost:3000`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const config = readConfig(context);
|
|
66
|
+
const existing = config.profiles[name];
|
|
67
|
+
const token = await readToken(context, name, !!existing);
|
|
68
|
+
if (!token && !existing) {
|
|
69
|
+
throw new CliError(canPrompt(context)
|
|
70
|
+
? 'A profile needs an API token'
|
|
71
|
+
: `A profile needs an API token. Pass it on stdin, e.g. jsonpad config set-profile ${name} < token.txt`);
|
|
72
|
+
}
|
|
73
|
+
config.profiles[name] = {
|
|
74
|
+
token: token || existing.token,
|
|
75
|
+
...((options.apiUrl ?? existing?.apiUrl)
|
|
76
|
+
? { apiUrl: options.apiUrl ?? existing.apiUrl }
|
|
77
|
+
: {}),
|
|
78
|
+
};
|
|
79
|
+
const isDefault = options.default || !config.defaultProfile;
|
|
80
|
+
if (isDefault) {
|
|
81
|
+
config.defaultProfile = name;
|
|
82
|
+
}
|
|
83
|
+
const file = writeConfig(context, config);
|
|
84
|
+
context.error(`${existing ? 'Updated' : 'Added'} profile ${context.colours.bold(name)}${isDefault ? ' (the default)' : ''} in ${file}`);
|
|
85
|
+
context.error(context.colours.dim(`Run jsonpad whoami${isDefault ? '' : ` --profile ${name}`} to check the token`));
|
|
86
|
+
}
|
|
87
|
+
export async function useProfile(context, name) {
|
|
88
|
+
const config = readConfig(context);
|
|
89
|
+
requireProfile(config, name);
|
|
90
|
+
config.defaultProfile = name;
|
|
91
|
+
writeConfig(context, config);
|
|
92
|
+
context.error(`The default profile is now ${context.colours.bold(name)}`);
|
|
93
|
+
}
|
|
94
|
+
export async function listProfiles(context, options) {
|
|
95
|
+
const format = resolveOutputFormat(context, options);
|
|
96
|
+
const config = readConfig(context);
|
|
97
|
+
const profiles = Object.entries(config.profiles).map(([name, profile]) => ({
|
|
98
|
+
name,
|
|
99
|
+
apiUrl: profile.apiUrl ?? null,
|
|
100
|
+
token: maskToken(profile.token),
|
|
101
|
+
default: name === config.defaultProfile,
|
|
102
|
+
}));
|
|
103
|
+
printRecords(context, format, profiles, {
|
|
104
|
+
id: profile => profile.name,
|
|
105
|
+
columns: [
|
|
106
|
+
{ header: '', value: profile => (profile.default ? '*' : '') },
|
|
107
|
+
{ header: 'NAME', value: profile => profile.name },
|
|
108
|
+
{ header: 'TOKEN', value: profile => profile.token },
|
|
109
|
+
{
|
|
110
|
+
header: 'API URL',
|
|
111
|
+
value: profile => profile.apiUrl ?? context.colours.dim('(default)'),
|
|
112
|
+
},
|
|
113
|
+
],
|
|
114
|
+
empty: 'No profiles. Add one with jsonpad config set-profile <name>',
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
export async function removeProfile(context, name, options) {
|
|
118
|
+
const config = readConfig(context);
|
|
119
|
+
requireProfile(config, name);
|
|
120
|
+
await confirm(context, {
|
|
121
|
+
question: `Remove the profile ${name}?`,
|
|
122
|
+
yes: options.yes,
|
|
123
|
+
});
|
|
124
|
+
delete config.profiles[name];
|
|
125
|
+
const wasDefault = config.defaultProfile === name;
|
|
126
|
+
if (wasDefault) {
|
|
127
|
+
delete config.defaultProfile;
|
|
128
|
+
}
|
|
129
|
+
writeConfig(context, config);
|
|
130
|
+
context.error(`Removed profile ${context.colours.bold(name)}`);
|
|
131
|
+
if (wasDefault && Object.keys(config.profiles).length > 0) {
|
|
132
|
+
context.error(context.colours.dim('It was the default profile. Choose another with jsonpad config use <name>'));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stats, events and event commands, which lists, items, indexes and
|
|
3
|
+
* identities all have
|
|
4
|
+
*/
|
|
5
|
+
import { InvalidArgumentError, Option } from 'commander';
|
|
6
|
+
import { addOutputOptions, formatNumber, formatTimestamp, printRecord, renderDetails, renderTable, resolveOutputFormat, } from '../output.js';
|
|
7
|
+
import { addAllOption, addPagingOptions, parseDate, printPages, removeUndefined, request, } from '../resources.js';
|
|
8
|
+
/**
|
|
9
|
+
* The API's default for how many days of stats to return
|
|
10
|
+
*/
|
|
11
|
+
const DEFAULT_STATS_DAYS = 7;
|
|
12
|
+
const MAX_STATS_DAYS = 90;
|
|
13
|
+
function parseDays(value) {
|
|
14
|
+
const days = Number(value);
|
|
15
|
+
if (!Number.isInteger(days) || days < 1 || days > MAX_STATS_DAYS) {
|
|
16
|
+
throw new InvalidArgumentError(`Must be a whole number from 1 to ${MAX_STATS_DAYS}.`);
|
|
17
|
+
}
|
|
18
|
+
return days;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Split a commander action's parameters into positional arguments and options
|
|
22
|
+
*/
|
|
23
|
+
function actionParameters(parameters) {
|
|
24
|
+
return [
|
|
25
|
+
parameters.slice(0, -2),
|
|
26
|
+
parameters[parameters.length - 2],
|
|
27
|
+
];
|
|
28
|
+
}
|
|
29
|
+
function addArguments(command, target) {
|
|
30
|
+
for (const [name, description] of target.arguments) {
|
|
31
|
+
command.argument(name, description);
|
|
32
|
+
}
|
|
33
|
+
return command;
|
|
34
|
+
}
|
|
35
|
+
async function resolveArguments(target, jsonpad, args) {
|
|
36
|
+
return target.resolve ? target.resolve(jsonpad, args) : args;
|
|
37
|
+
}
|
|
38
|
+
const article = (noun) => (/^[aeiou]/.test(noun) ? 'an' : 'a');
|
|
39
|
+
/**
|
|
40
|
+
* The day a stats bucket is for, as YYYY-MM-DD
|
|
41
|
+
*
|
|
42
|
+
* The API starts each day at midnight in its own time zone. A bucket that
|
|
43
|
+
* starts at midnight UTC is from a server on UTC, so its UTC date is the day;
|
|
44
|
+
* otherwise the server is (most likely) in the same time zone as this machine
|
|
45
|
+
* (e.g. a local server), so the local date is
|
|
46
|
+
*/
|
|
47
|
+
export function dateOf(date) {
|
|
48
|
+
const parsed = new Date(date);
|
|
49
|
+
const utc = parsed.getUTCHours() === 0 &&
|
|
50
|
+
parsed.getUTCMinutes() === 0 &&
|
|
51
|
+
parsed.getUTCSeconds() === 0;
|
|
52
|
+
const [year, month, day] = utc
|
|
53
|
+
? [parsed.getUTCFullYear(), parsed.getUTCMonth(), parsed.getUTCDate()]
|
|
54
|
+
: [parsed.getFullYear(), parsed.getMonth(), parsed.getDate()];
|
|
55
|
+
return `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Render stats as a summary of each series, and a table of counts by day
|
|
59
|
+
*/
|
|
60
|
+
export function renderStats(context, stats, days) {
|
|
61
|
+
const { dim } = context.colours;
|
|
62
|
+
const series = Object.entries(stats).filter((entry) => !!entry[1] &&
|
|
63
|
+
typeof entry[1] === 'object' &&
|
|
64
|
+
Array.isArray(entry[1].metrics));
|
|
65
|
+
const limit = (name) => {
|
|
66
|
+
const max = stats[`max${name[0].toUpperCase()}${name.slice(1)}`];
|
|
67
|
+
return typeof max === 'number' ? `, limit ${formatNumber(max)}` : '';
|
|
68
|
+
};
|
|
69
|
+
const summary = renderDetails(series.map(([name, { total, totalThisPeriod }]) => [
|
|
70
|
+
`${name[0].toUpperCase()}${name.slice(1)}`,
|
|
71
|
+
`${formatNumber(total)} ${dim(`(${formatNumber(totalThisPeriod)} in the last ${days === 1 ? 'day' : `${days} days`}${limit(name)})`)}`,
|
|
72
|
+
]));
|
|
73
|
+
const dates = [
|
|
74
|
+
...new Set(series.flatMap(([, { metrics }]) => metrics.map(metric => dateOf(metric.date)))),
|
|
75
|
+
].sort();
|
|
76
|
+
if (dates.length === 0) {
|
|
77
|
+
return summary;
|
|
78
|
+
}
|
|
79
|
+
const countOn = (metrics, date) => metrics.find(metric => dateOf(metric.date) === date);
|
|
80
|
+
const events = series.find(([name]) => name === 'events')?.[1];
|
|
81
|
+
const table = renderTable(context, [
|
|
82
|
+
{ header: 'DATE', value: (date) => date },
|
|
83
|
+
...series.map(([name, { metrics }]) => ({
|
|
84
|
+
header: name.toUpperCase(),
|
|
85
|
+
value: (date) => formatNumber(countOn(metrics, date)?.count ?? 0),
|
|
86
|
+
})),
|
|
87
|
+
...(events
|
|
88
|
+
? [
|
|
89
|
+
{
|
|
90
|
+
header: 'EVENT TYPES',
|
|
91
|
+
value: (date) => Object.entries(countOn(events.metrics, date)?.types ?? {})
|
|
92
|
+
.filter(([, count]) => count > 0)
|
|
93
|
+
.map(([type, count]) => `${type} ${formatNumber(count)}`)
|
|
94
|
+
.join(', ') || '-',
|
|
95
|
+
},
|
|
96
|
+
]
|
|
97
|
+
: []),
|
|
98
|
+
], dates);
|
|
99
|
+
return `${summary}\n\n${table}`;
|
|
100
|
+
}
|
|
101
|
+
export function defineStatsCommand(parent, context, target) {
|
|
102
|
+
const command = addArguments(parent.command('stats').description(target.description), target)
|
|
103
|
+
.option('--days <number>', `How many days of stats, up to ${MAX_STATS_DAYS} (default ${DEFAULT_STATS_DAYS})`, parseDays)
|
|
104
|
+
.addOption(new Option('-o, --output <format>', 'Output format (default: table in a terminal, otherwise json)').choices(['table', 'json']))
|
|
105
|
+
.option('--json', 'Output JSON (the same as --output json)');
|
|
106
|
+
return command.action(async (...parameters) => {
|
|
107
|
+
const [args, options] = actionParameters(parameters);
|
|
108
|
+
const format = resolveOutputFormat(context, options);
|
|
109
|
+
const jsonpad = context.createClient();
|
|
110
|
+
const resolved = await resolveArguments(target, jsonpad, args);
|
|
111
|
+
const stats = await request(context, () => target.fetch(jsonpad, resolved, removeUndefined({ days: options.days })));
|
|
112
|
+
if (format === 'table') {
|
|
113
|
+
context.log(renderStats(context, stats, options.days ?? DEFAULT_STATS_DAYS));
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
context.log(JSON.stringify(stats, null, 2));
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
function eventOutput(context) {
|
|
121
|
+
const { dim } = context.colours;
|
|
122
|
+
return {
|
|
123
|
+
id: event => event.id,
|
|
124
|
+
details: event => [
|
|
125
|
+
['ID', event.id],
|
|
126
|
+
['Type', event.type],
|
|
127
|
+
['Stream', event.stream],
|
|
128
|
+
['Model', event.modelId],
|
|
129
|
+
['Version', event.version ?? dim('(none)')],
|
|
130
|
+
['Created', formatTimestamp(event.createdAt)],
|
|
131
|
+
...(event.snapshot !== undefined
|
|
132
|
+
? [
|
|
133
|
+
['Snapshot', JSON.stringify(event.snapshot, null, 2)],
|
|
134
|
+
]
|
|
135
|
+
: []),
|
|
136
|
+
...(event.attachments !== undefined
|
|
137
|
+
? [
|
|
138
|
+
['Attachments', JSON.stringify(event.attachments, null, 2)],
|
|
139
|
+
]
|
|
140
|
+
: []),
|
|
141
|
+
],
|
|
142
|
+
columns: [
|
|
143
|
+
{ header: 'ID', value: event => event.id },
|
|
144
|
+
{ header: 'TYPE', value: event => event.type },
|
|
145
|
+
{ header: 'VERSION', value: event => event.version ?? '-' },
|
|
146
|
+
{ header: 'CREATED', value: event => formatTimestamp(event.createdAt) },
|
|
147
|
+
],
|
|
148
|
+
empty: 'No events',
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
export function defineEventCommands(parent, context, target) {
|
|
152
|
+
const contents = (command) => {
|
|
153
|
+
command
|
|
154
|
+
.option('--include-snapshot', `Include the ${target.noun} as it was after each event`)
|
|
155
|
+
.option('--include-attachments', "Include each event's attachments");
|
|
156
|
+
if (target.items) {
|
|
157
|
+
command.option('--include-guarded', 'Include guarded values in snapshots, for items the identity making the request owns');
|
|
158
|
+
}
|
|
159
|
+
return command;
|
|
160
|
+
};
|
|
161
|
+
const events = addArguments(parent
|
|
162
|
+
.command('events')
|
|
163
|
+
.description(`List ${article(target.noun)} ${target.noun}'s events, newest first by default`), target)
|
|
164
|
+
.addOption(new Option('--type <type>', 'Only events of this type').choices(target.types))
|
|
165
|
+
.option('--start-at <date>', 'Only events at or after this date, e.g. 2026-09-01', parseDate)
|
|
166
|
+
.option('--end-at <date>', 'Only events at or before this date', parseDate);
|
|
167
|
+
if (target.items) {
|
|
168
|
+
events.option('--restorable', 'Only events the item can be restored to (jsonpad items restore)');
|
|
169
|
+
}
|
|
170
|
+
contents(events);
|
|
171
|
+
addAllOption(events);
|
|
172
|
+
addPagingOptions(events, { choices: ['createdAt', 'type'] });
|
|
173
|
+
addOutputOptions(events).action(async (...parameters) => {
|
|
174
|
+
const [args, options] = actionParameters(parameters);
|
|
175
|
+
const jsonpad = context.createClient();
|
|
176
|
+
const resolved = await resolveArguments(target, jsonpad, args);
|
|
177
|
+
await printPages(context, options, paging => target.fetchEvents(jsonpad, resolved, removeUndefined({
|
|
178
|
+
...paging,
|
|
179
|
+
type: options.type,
|
|
180
|
+
startAt: options.startAt,
|
|
181
|
+
endAt: options.endAt,
|
|
182
|
+
restorable: options.restorable,
|
|
183
|
+
includeSnapshot: options.includeSnapshot,
|
|
184
|
+
includeAttachments: options.includeAttachments,
|
|
185
|
+
includeGuarded: options.includeGuarded,
|
|
186
|
+
})), eventOutput(context));
|
|
187
|
+
});
|
|
188
|
+
const event = addArguments(parent
|
|
189
|
+
.command('event')
|
|
190
|
+
.description(`Show one of ${article(target.noun)} ${target.noun}'s events`), target).argument('<event>', 'The event id');
|
|
191
|
+
contents(event);
|
|
192
|
+
addOutputOptions(event).action(async (...parameters) => {
|
|
193
|
+
const [args, options] = actionParameters(parameters);
|
|
194
|
+
const eventId = args[args.length - 1];
|
|
195
|
+
const format = resolveOutputFormat(context, options);
|
|
196
|
+
const jsonpad = context.createClient();
|
|
197
|
+
const resolved = await resolveArguments(target, jsonpad, args.slice(0, -1));
|
|
198
|
+
const found = await request(context, () => target.fetchEvent(jsonpad, resolved, eventId, removeUndefined({
|
|
199
|
+
includeSnapshot: options.includeSnapshot,
|
|
200
|
+
includeAttachments: options.includeAttachments,
|
|
201
|
+
includeGuarded: options.includeGuarded,
|
|
202
|
+
})));
|
|
203
|
+
printRecord(context, format, found, eventOutput(context));
|
|
204
|
+
});
|
|
205
|
+
}
|