@stateplane/cli 0.0.0-stage → 0.1.1

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/dist/run.js ADDED
@@ -0,0 +1,736 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { open, unlink } from 'node:fs/promises';
4
+ import { readConfig, saveConfig, configureToken, loadToken, logoutConfig, removeTrackedTokens, withConfigMutation } from './config.js';
5
+ import { admitAggregation, admitAnalysisJob, analysisBounds } from '@stateplane/contracts';
6
+ import { StateplaneCliError, StateplaneHttpClient } from './transport.js';
7
+ const encoded = (value) => value === '.' || value === '..' ? `;${value}` : encodeURIComponent(value);
8
+ const switches = new Set(['retry-failed', 'json', 'token-stdin', 'help']);
9
+ /** Consume one option and return the next unread argv position. */
10
+ function parseOption(argv, index, flags) {
11
+ const item = argv[index];
12
+ const equals = item.indexOf('=');
13
+ const key = item.slice(2, equals < 0 ? undefined : equals);
14
+ if (!/^[a-z][a-z0-9-]*$/.test(key) || Object.hasOwn(flags, key))
15
+ throw new StateplaneCliError('INVALID_ARGUMENT');
16
+ if (switches.has(key)) {
17
+ if (equals >= 0)
18
+ throw new StateplaneCliError('INVALID_ARGUMENT');
19
+ flags[key] = true;
20
+ return index;
21
+ }
22
+ const value = equals >= 0 ? item.slice(equals + 1) : argv[++index];
23
+ if (value === undefined || (equals < 0 && value.startsWith('--')))
24
+ throw new StateplaneCliError('INVALID_ARGUMENT');
25
+ flags[key] = value;
26
+ return index;
27
+ }
28
+ /** Keep explicit flag presence and JSON value spelling through dispatch. */
29
+ function parse(argv) {
30
+ const words = [];
31
+ const flags = {};
32
+ let i = 0;
33
+ while (i < argv.length) {
34
+ const item = argv[i];
35
+ if (!item.startsWith('--')) {
36
+ words.push(item);
37
+ i++;
38
+ continue;
39
+ }
40
+ i = parseOption(argv, i, flags) + 1;
41
+ }
42
+ return { words, flags };
43
+ }
44
+ /* HTTP body budgets of the evidence routes (largeBody and smallBody in packages/api/src/http.ts). */
45
+ const largeBody = 3_145_728;
46
+ const smallBody = 32_768;
47
+ /** The search and bundle body budget (retrievalBody in packages/api/src/http.ts). */
48
+ const retrievalBody = 131_072;
49
+ /** The service's upload bound (sourceBounds.uploadBytes, 25 MiB). */
50
+ const uploadBytes = 26_214_400;
51
+ /** The service's text bound (1 MiB of UTF-8). */
52
+ const textBytes = 1_048_576;
53
+ /** Flags accepted by each evidence command, beside --space, --json and --timeout. */
54
+ const evidenceCommands = {
55
+ 'sources get': ['space', 'collection', 'id'],
56
+ 'sources content': ['space', 'collection', 'id', 'output'],
57
+ 'sources ingest-text': ['space', 'collection', 'idempotency-key', 'text', 'file', 'mime-type', 'locator', 'captured-at'],
58
+ 'sources ingest-reference': ['space', 'collection', 'idempotency-key', 'locator', 'mime-type', 'captured-at'],
59
+ 'sources delete': ['space', 'collection', 'id'],
60
+ 'sources extract': ['space', 'collection', 'id'],
61
+ 'sources extraction': ['space', 'collection', 'id', 'version'],
62
+ 'sources correct': ['space', 'collection', 'id', 'base-version', 'data', 'file'],
63
+ 'uploads create': ['space', 'collection', 'mime-type', 'max-bytes', 'sha256', 'expires-in'],
64
+ 'uploads send': ['space', 'collection', 'grant', 'file', 'mime-type', 'sha256'],
65
+ 'uploads finalize': ['space', 'collection', 'grant', 'attempt', 'locator', 'captured-at'],
66
+ 'uploads revoke': ['space', 'collection', 'grant'],
67
+ 'claims create': ['space', 'collection', 'idempotency-key', 'data', 'file'],
68
+ 'claims revise': ['space', 'collection', 'id', 'base-revision', 'data', 'file'],
69
+ 'claims review': ['space', 'collection', 'id', 'base-revision', 'status'],
70
+ 'claims delete': ['space', 'collection', 'id', 'base-revision'],
71
+ 'claims get': ['space', 'collection', 'id', 'revision'],
72
+ 'claims list': ['space', 'collection', 'status', 'citing-collection', 'citing-source', 'after', 'limit'],
73
+ 'links create': ['space', 'collection', 'idempotency-key', 'data', 'file'],
74
+ 'links get': ['space', 'collection', 'id'],
75
+ 'links delete': ['space', 'collection', 'id'],
76
+ 'links list': ['space', 'collection', 'endpoint-kind', 'endpoint-id', 'after', 'limit']
77
+ };
78
+ const common = ['json'];
79
+ const allowed = {
80
+ 'config endpoint': ['url'], 'config show': [],
81
+ 'auth login': ['token-stdin', 'store', 'timeout'], 'auth import': ['token-stdin', 'store'], 'auth logout': [],
82
+ 'spaces select': ['space'], 'spaces list': ['cursor'], 'spaces create': ['cell', 'space'],
83
+ 'spaces get': ['space'], 'spaces update': ['space', 'lifecycle'], 'spaces delete': ['space'], 'spaces erasure': ['space'],
84
+ 'collections list': ['space', 'cursor'], 'collections get': ['space', 'collection'],
85
+ 'collections define': ['space', 'collection', 'data', 'file'],
86
+ 'collections revise': ['space', 'collection', 'data', 'file', 'version'],
87
+ 'records get': ['space', 'collection', 'id'], 'records key': ['space', 'collection', 'key', 'mode'],
88
+ 'records projection': ['space', 'collection', 'id'],
89
+ 'records query': ['space', 'collection', 'predicates', 'limit', 'sort', 'cursor'],
90
+ 'records count': ['space', 'collection', 'predicates'],
91
+ 'records create': ['space', 'collection', 'idempotency-key', 'expected-schema-version', 'data', 'file', 'key'],
92
+ 'records replace': ['space', 'collection', 'idempotency-key', 'id', 'expected-revision', 'expected-schema-version', 'data', 'file'],
93
+ 'records patch': ['space', 'collection', 'idempotency-key', 'id', 'expected-revision', 'expected-schema-version', 'data', 'file'],
94
+ 'records delete': ['space', 'collection', 'idempotency-key', 'id', 'expected-revision', 'expected-schema-version'],
95
+ 'batches ingest': ['space', 'collection', 'operation-key', 'file', 'retry-failed'],
96
+ 'batches status': ['space', 'collection', 'operation-key'],
97
+ 'batches cancel': ['space', 'collection', 'operation-key'],
98
+ 'events list': ['space', 'collection', 'cursor'],
99
+ 'retrieval search': ['space', 'data', 'file'], 'retrieval bundle': ['space', 'data', 'file'],
100
+ 'retrieval status': ['space', 'collection'],
101
+ 'analysis aggregate': ['space', 'collection', 'data', 'file'],
102
+ 'analysis submit': ['space', 'collection', 'kind', 'data', 'file'],
103
+ 'analysis status': ['space', 'collection', 'job'], 'analysis cancel': ['space', 'collection', 'job'],
104
+ 'analysis page': ['space', 'collection', 'job', 'page'],
105
+ ...evidenceCommands
106
+ };
107
+ function validateFlags(resource, action, flags) {
108
+ const command = allowed[`${resource} ${action ?? ''}`];
109
+ if (!command)
110
+ throw new StateplaneCliError('INVALID_ARGUMENT');
111
+ const usesHttp = resource !== 'config' && resource !== 'auth' && !(resource === 'spaces' && action === 'select');
112
+ const accepted = new Set([...command, ...common, ...(usesHttp ? ['timeout'] : [])]);
113
+ if (Object.keys(flags).some(key => !accepted.has(key)))
114
+ throw new StateplaneCliError('INVALID_ARGUMENT');
115
+ if (flags.space === '' || flags.cell === '' || flags.sort === '' || flags.key === '')
116
+ throw new StateplaneCliError('INVALID_ARGUMENT');
117
+ if (flags.timeout !== undefined)
118
+ integer(required(flags, 'timeout'));
119
+ }
120
+ function required(flags, key) {
121
+ const value = flags[key];
122
+ if (typeof value !== 'string' || !value)
123
+ throw new StateplaneCliError('INVALID_ARGUMENT');
124
+ return value;
125
+ }
126
+ function cursor(flags) {
127
+ const value = flags.cursor;
128
+ if (typeof value !== 'string' || !value)
129
+ throw new StateplaneCliError('CURSOR_INVALID');
130
+ return value;
131
+ }
132
+ function integer(value) {
133
+ if (!/^[1-9]\d*$/.test(value))
134
+ throw new StateplaneCliError('INVALID_ARGUMENT');
135
+ const number = Number(value);
136
+ if (!Number.isSafeInteger(number) || number < 1)
137
+ throw new StateplaneCliError('INVALID_ARGUMENT');
138
+ return number;
139
+ }
140
+ /** Parse CLI JSON input. A number that overflows to Infinity is refused: JSON
141
+ * would send it as null, which is a different request from the one given. */
142
+ function parsed(value) {
143
+ try {
144
+ return JSON.parse(value, (_key, item) => {
145
+ if (typeof item === 'number' && !Number.isFinite(item))
146
+ throw new StateplaneCliError('INVALID_ARGUMENT');
147
+ return item;
148
+ });
149
+ }
150
+ catch {
151
+ throw new StateplaneCliError('INVALID_ARGUMENT');
152
+ }
153
+ }
154
+ /** The UTF-8 text of a file or stdin. keepBom keeps a leading byte order mark
155
+ * so text stored as an original keeps every byte of the file; JSON and tokens
156
+ * drop it. */
157
+ async function input(path, maxBytes, keepBom = false) {
158
+ const source = path === '-' ? process.stdin : createReadStream(path);
159
+ const chunks = [];
160
+ let size = 0;
161
+ try {
162
+ for await (const chunk of source) {
163
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
164
+ size += bytes.length;
165
+ if (size > maxBytes)
166
+ throw new StateplaneCliError('RATE_LIMITED', undefined, undefined, false);
167
+ chunks.push(bytes);
168
+ }
169
+ }
170
+ catch (error) {
171
+ if (error instanceof StateplaneCliError)
172
+ throw error;
173
+ throw new StateplaneCliError('INVALID_ARGUMENT');
174
+ }
175
+ try {
176
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: keepBom }).decode(Buffer.concat(chunks));
177
+ }
178
+ catch {
179
+ throw new StateplaneCliError('INVALID_ARGUMENT');
180
+ }
181
+ }
182
+ /** The JSON of --data or --file, at most maxBytes: by default the record and
183
+ * schema budget; an evidence command passes its route's body budget. */
184
+ async function payload(flags, maxBytes = 1_048_576) {
185
+ return parsed(await payloadText(flags, maxBytes));
186
+ }
187
+ /** The text of --data or --file, at most maxBytes. */
188
+ async function payloadText(flags, maxBytes) {
189
+ if (flags.data !== undefined && flags.file !== undefined)
190
+ throw new StateplaneCliError('INVALID_ARGUMENT');
191
+ const text = flags.file !== undefined ? await input(required(flags, 'file'), maxBytes) : required(flags, 'data');
192
+ if (Buffer.byteLength(text) > maxBytes)
193
+ throw new StateplaneCliError('RATE_LIMITED', undefined, undefined, false);
194
+ return text;
195
+ }
196
+ function withinWireBudget(value, maxBytes) {
197
+ // Match StateplaneHttpClient's JSON serialization for every JSON value. One it cannot serialize (nested past the
198
+ // stack) is refused as invalid, never reported as a retryable failure.
199
+ let serialized;
200
+ try {
201
+ serialized = JSON.stringify(value);
202
+ }
203
+ catch {
204
+ throw new StateplaneCliError('INVALID_ARGUMENT');
205
+ }
206
+ if (serialized === undefined)
207
+ throw new StateplaneCliError('INVALID_ARGUMENT');
208
+ if (Buffer.byteLength(serialized) > maxBytes)
209
+ throw new StateplaneCliError('RATE_LIMITED', undefined, undefined, false);
210
+ return value;
211
+ }
212
+ function endpoint(value) {
213
+ let url;
214
+ try {
215
+ url = new URL(value);
216
+ }
217
+ catch {
218
+ throw new StateplaneCliError('INVALID_ARGUMENT');
219
+ }
220
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
221
+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))))
222
+ throw new StateplaneCliError('INVALID_ARGUMENT');
223
+ return url.origin + '/';
224
+ }
225
+ function output(value) { process.stdout.write(JSON.stringify(value) + '\n'); }
226
+ function help() {
227
+ output({ usage: 'stateplane <config|auth|spaces|collections|records|batches|events|sources|uploads|claims|links|retrieval|analysis> <command> [--space ID] [--collection ID] [options]',
228
+ docs: 'See docs/http-cli.md for examples and recovery rules.' });
229
+ }
230
+ async function runConfig(action, flags, config) {
231
+ if (action === 'show')
232
+ return { endpoint: config.endpoint ?? null, space: config.space ?? null, tokenStore: config.tokenStore ?? null };
233
+ if (action !== 'endpoint')
234
+ throw new StateplaneCliError('INVALID_ARGUMENT');
235
+ const value = endpoint(required(flags, 'url'));
236
+ return withConfigMutation(async (current) => {
237
+ const changed = current.endpoint !== value;
238
+ if (current.endpoint && changed)
239
+ await removeTrackedTokens(current);
240
+ await saveConfig({ ...current, endpoint: value,
241
+ space: changed ? undefined : current.space,
242
+ tokenStore: changed ? undefined : current.tokenStore,
243
+ tokenLocations: changed ? undefined : current.tokenLocations });
244
+ return { endpoint: value, space: changed ? null : current.space ?? null };
245
+ });
246
+ }
247
+ async function runAuth(action, flags, config) {
248
+ if (action === 'logout') {
249
+ await withConfigMutation(current => logoutConfig(current));
250
+ return { configured: false };
251
+ }
252
+ if (action !== 'login' && action !== 'import')
253
+ throw new StateplaneCliError('INVALID_ARGUMENT');
254
+ if (!config.endpoint || flags['token-stdin'] !== true)
255
+ throw new StateplaneCliError('INVALID_ARGUMENT');
256
+ const store = flags.store ?? (process.platform === 'linux' ? 'keychain' : 'file');
257
+ if (store !== 'file' && store !== 'keychain')
258
+ throw new StateplaneCliError('INVALID_ARGUMENT');
259
+ const token = (await input('-', 4096)).replace(/\r?\n$/, '');
260
+ if (action === 'login')
261
+ await new StateplaneHttpClient({ endpoint: config.endpoint, token,
262
+ timeoutMs: flags.timeout ? integer(required(flags, 'timeout')) : undefined }).request('GET', '/v1/auth/session');
263
+ await withConfigMutation(async (current) => {
264
+ if (current.endpoint !== config.endpoint)
265
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
266
+ await configureToken(current, token, store);
267
+ });
268
+ return { configured: true, store };
269
+ }
270
+ async function runSpaces(client, action, flags, spacePath) {
271
+ if (action === 'list') {
272
+ const suffix = flags.cursor === undefined ? '' : `?cursor=${encoded(cursor(flags))}`;
273
+ return client.request('GET', `/v1/spaces${suffix}`);
274
+ }
275
+ if (action === 'create')
276
+ return client.request('POST', '/v1/spaces', withinWireBudget({ spaceId: required(flags, 'space'), ...(flags.cell ? { cellId: flags.cell } : {}) }, 4096));
277
+ if (action === 'get' && spacePath)
278
+ return client.request('GET', spacePath);
279
+ if (action === 'update' && spacePath)
280
+ return client.request('PATCH', spacePath, withinWireBudget({ lifecycle: required(flags, 'lifecycle') }, 4096));
281
+ if (action === 'delete' && spacePath)
282
+ return client.request('DELETE', spacePath);
283
+ if (action === 'erasure' && spacePath)
284
+ return client.request('GET', `${spacePath}/erasure`);
285
+ throw new StateplaneCliError('INVALID_ARGUMENT');
286
+ }
287
+ async function runCollections(client, action, flags, spacePath, collectionPath) {
288
+ if (action === 'list') {
289
+ const suffix = flags.cursor !== undefined ? `?cursor=${encoded(cursor(flags))}` : '';
290
+ return client.request('GET', `${spacePath}/collections${suffix}`);
291
+ }
292
+ if (action === 'get' && collectionPath)
293
+ return client.request('GET', collectionPath);
294
+ if (action === 'define' && collectionPath)
295
+ return client.request('PUT', collectionPath, withinWireBudget(await payload(flags), 1_048_576));
296
+ if (action === 'revise' && collectionPath)
297
+ return client.request('PATCH', collectionPath, withinWireBudget(await payload(flags), 1_048_576), { 'If-Match': String(integer(required(flags, 'version'))) });
298
+ throw new StateplaneCliError('INVALID_ARGUMENT');
299
+ }
300
+ async function mutationRequest(action, flags) {
301
+ const request = { operation: action, idempotencyKey: required(flags, 'idempotency-key') };
302
+ if (flags['expected-schema-version'] !== undefined)
303
+ request.expectedSchemaVersion = integer(required(flags, 'expected-schema-version'));
304
+ if (action === 'create') {
305
+ request.data = await payload(flags);
306
+ if (flags.key !== undefined)
307
+ request.externalKey = required(flags, 'key');
308
+ return request;
309
+ }
310
+ request.id = required(flags, 'id');
311
+ request.expectedRevision = integer(required(flags, 'expected-revision'));
312
+ if (action === 'replace')
313
+ request.data = await payload(flags);
314
+ if (action === 'patch') {
315
+ const patch = await payload(flags);
316
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch) ||
317
+ !patch.set || typeof patch.set !== 'object' || Array.isArray(patch.set) ||
318
+ !Array.isArray(patch.unset) || patch.unset.some(value => typeof value !== 'string'))
319
+ throw new StateplaneCliError('INVALID_ARGUMENT');
320
+ request.set = patch.set;
321
+ request.unset = patch.unset;
322
+ }
323
+ return request;
324
+ }
325
+ async function runRecords(client, action, flags, recordPath) {
326
+ if (action === 'get')
327
+ return client.request('GET', `${recordPath}/${encoded(required(flags, 'id'))}`);
328
+ if (action === 'key')
329
+ return client.request('GET', `${recordPath}/by-key/${encoded(required(flags, 'key'))}?mode=${encoded(required(flags, 'mode'))}`);
330
+ if (action === 'projection')
331
+ return client.request('GET', `${recordPath}/${encoded(required(flags, 'id'))}/projection`);
332
+ if (action === 'query')
333
+ return client.request('POST', `${recordPath}/query`, withinWireBudget({
334
+ predicates: parsed(typeof flags.predicates === 'string' ? flags.predicates : '[]'),
335
+ limit: integer(required(flags, 'limit')),
336
+ ...(flags.sort ? { sort: parsed(required(flags, 'sort')) } : {}),
337
+ ...(flags.cursor !== undefined ? { cursor: cursor(flags) } : {})
338
+ }, 32_768));
339
+ if (action === 'count')
340
+ return client.request('POST', `${recordPath}/count`, withinWireBudget(parsed(typeof flags.predicates === 'string' ? flags.predicates : '[]'), 32_768));
341
+ if (action && ['create', 'replace', 'patch', 'delete'].includes(action))
342
+ return client.request('POST', recordPath, withinWireBudget(await mutationRequest(action, flags), 1_048_576));
343
+ throw new StateplaneCliError('INVALID_ARGUMENT');
344
+ }
345
+ async function runBatches(client, action, flags, collectionPath) {
346
+ const operation = required(flags, 'operation-key');
347
+ const url = `${collectionPath}/batches/${encoded(operation)}`;
348
+ if (action === 'status')
349
+ return client.request('GET', url);
350
+ if (action === 'cancel')
351
+ return client.request('DELETE', url);
352
+ if (action !== 'ingest')
353
+ throw new StateplaneCliError('INVALID_ARGUMENT');
354
+ const lines = (await input(required(flags, 'file'), 3_145_728)).split(/\r?\n/).filter(Boolean);
355
+ if (!lines.length || lines.length > 20)
356
+ throw new StateplaneCliError('INVALID_ARGUMENT');
357
+ // Preserve each item string for HTTP-to-CLI same-key recovery.
358
+ const manifest = lines.map(line => { parsed(line); return line; });
359
+ const itemBytes = manifest.map(item => Buffer.byteLength(item));
360
+ if (itemBytes.some(size => size > 1_048_576) ||
361
+ itemBytes.reduce((sum, size) => sum + size, 0) > 2_097_152)
362
+ throw new StateplaneCliError('INVALID_ARGUMENT');
363
+ return client.request('PUT', url + (flags['retry-failed'] ? '?retryFailed=true' : ''), withinWireBudget(manifest, 3_145_728));
364
+ }
365
+ /** Optional string flags, copied under their request field names when supplied. */
366
+ function optional(flags, names) {
367
+ const out = {};
368
+ for (const [flag, field] of Object.entries(names))
369
+ if (flags[flag] !== undefined)
370
+ out[field] = required(flags, flag);
371
+ return out;
372
+ }
373
+ /** A JSON object payload extended with one field taken from a flag; the payload may not set it too.
374
+ * The payload is read within the route's body budget, which the caller checks again with the field added. */
375
+ async function objectWith(flags, field, value, maxBytes) {
376
+ const data = await payload(flags, maxBytes);
377
+ if (!data || typeof data !== 'object' || Array.isArray(data) || Object.hasOwn(data, field))
378
+ throw new StateplaneCliError('INVALID_ARGUMENT');
379
+ return { [field]: value, ...data };
380
+ }
381
+ /** The query string of the supplied parameters, each encoded once. */
382
+ function search(values) {
383
+ const params = new URLSearchParams();
384
+ for (const [key, value] of Object.entries(values))
385
+ if (value !== undefined)
386
+ params.append(key, value);
387
+ const text = params.toString();
388
+ return text ? `?${text}` : '';
389
+ }
390
+ async function fileBytes(path, maxBytes) {
391
+ const chunks = [];
392
+ let size = 0;
393
+ try {
394
+ for await (const chunk of createReadStream(path)) {
395
+ size += chunk.length;
396
+ if (size > maxBytes)
397
+ throw new StateplaneCliError('RATE_LIMITED', undefined, undefined, false);
398
+ chunks.push(chunk);
399
+ }
400
+ }
401
+ catch (error) {
402
+ if (error instanceof StateplaneCliError)
403
+ throw error;
404
+ throw new StateplaneCliError('INVALID_ARGUMENT');
405
+ }
406
+ return new Uint8Array(Buffer.concat(chunks));
407
+ }
408
+ /** Write all of one chunk at the file's current position; no progress is a
409
+ * failure, and no write starts once the download's deadline has passed. */
410
+ async function writeAll(file, chunk, deadline) {
411
+ let offset = 0;
412
+ while (offset < chunk.byteLength) {
413
+ if (deadline.expired())
414
+ throw new Error('deadline passed');
415
+ const { bytesWritten } = await file.write(chunk, offset, chunk.byteLength - offset); // NOSONAR -- writes keep stream order
416
+ if (!(bytesWritten > 0))
417
+ throw new Error('short write');
418
+ offset += bytesWritten;
419
+ }
420
+ }
421
+ /**
422
+ * Save a source's original to a new file and report it as JSON; stdout stays
423
+ * one JSON value. The file must not exist. The bytes are hashed as they are
424
+ * written, and the file counts as saved only once every byte is written and it
425
+ * has closed, all before the download's deadline. Any failure removes the file,
426
+ * once the pending write or close has settled, so cleanup never races a write.
427
+ * A body whose stream fails or is aborted, or a download that ends past its
428
+ * deadline (--timeout bounds the requests, the body, every local write and the
429
+ * close), fails retryable PROVIDER_UNAVAILABLE: the same read may succeed again,
430
+ * and no success is reported once the deadline has passed. Within the deadline, a
431
+ * write or close that fails, a digest that differs from Repr-Digest (which is required),
432
+ * or a length that differs from the Content-Length of an unencoded response
433
+ * fails nonretryable PROVIDER_UNAVAILABLE. A response without Content-Length (a
434
+ * chunked body) is verified by its digest alone.
435
+ */
436
+ async function saveContent(client, path, output) {
437
+ const { response, deadline } = await client.download(path);
438
+ if (response.status === 204) {
439
+ await response.body?.cancel().catch(() => { });
440
+ return { referenceOnly: true, output: null };
441
+ }
442
+ const digest = /^sha-256=:([A-Za-z0-9+/]{43}=):$/.exec(response.headers.get('repr-digest') ?? '')?.[1];
443
+ const declared = response.headers.get('content-length');
444
+ const encoding = response.headers.get('content-encoding');
445
+ // The Content-Length of a content coding counts encoded bytes, which fetch has already decoded.
446
+ const encoded = encoding !== null && encoding.trim().toLowerCase() !== 'identity';
447
+ let length = null;
448
+ if (declared !== null && !encoded)
449
+ length = /^(?:0|[1-9]\d*)$/.test(declared) ? Number(declared) : Number.NaN;
450
+ let file;
451
+ try {
452
+ file = await open(output, 'wx', 0o600);
453
+ }
454
+ catch {
455
+ await response.body?.cancel().catch(() => { });
456
+ throw new StateplaneCliError('INVALID_ARGUMENT');
457
+ }
458
+ const hash = createHash('sha256');
459
+ let bytes = 0;
460
+ let complete = true;
461
+ let interrupted = false;
462
+ const reader = response.body?.getReader();
463
+ while (reader && complete) {
464
+ let next;
465
+ try {
466
+ next = await reader.read();
467
+ }
468
+ catch {
469
+ interrupted = true;
470
+ complete = false;
471
+ break;
472
+ }
473
+ if (next.done)
474
+ break;
475
+ try {
476
+ await writeAll(file, next.value, deadline);
477
+ }
478
+ catch {
479
+ complete = false;
480
+ await reader.cancel().catch(() => { });
481
+ break;
482
+ }
483
+ hash.update(next.value);
484
+ bytes += next.value.byteLength;
485
+ }
486
+ complete &&= digest !== undefined && hash.digest('base64') === digest && (length === null || bytes === length);
487
+ try {
488
+ await file.close();
489
+ }
490
+ catch {
491
+ complete = false;
492
+ }
493
+ // Every write and the close have settled: a download that ended past its deadline is not saved.
494
+ const late = deadline.expired();
495
+ if (!complete || late) {
496
+ await unlink(output).catch(() => { });
497
+ throw new StateplaneCliError('PROVIDER_UNAVAILABLE', undefined, undefined, interrupted || late);
498
+ }
499
+ return { referenceOnly: false, output, bytes, sha256: Buffer.from(digest, 'base64').toString('hex'),
500
+ mimeType: response.headers.get('content-type') };
501
+ }
502
+ async function runSources(client, action, flags, base) {
503
+ const sources = `${base}/sources`;
504
+ if (action === 'ingest-text') {
505
+ if ((flags.text === undefined) === (flags.file === undefined))
506
+ throw new StateplaneCliError('INVALID_ARGUMENT');
507
+ const text = flags.file !== undefined ? await input(required(flags, 'file'), textBytes, true) : required(flags, 'text');
508
+ return client.request('POST', `${sources}/text`, withinWireBudget({ idempotencyKey: required(flags, 'idempotency-key'), text,
509
+ ...optional(flags, { 'mime-type': 'mimeType', locator: 'locator', 'captured-at': 'capturedAt' }) }, largeBody));
510
+ }
511
+ if (action === 'ingest-reference')
512
+ return client.request('POST', `${sources}/reference`, withinWireBudget({ idempotencyKey: required(flags, 'idempotency-key'),
513
+ locator: required(flags, 'locator'), ...optional(flags, { 'mime-type': 'mimeType', 'captured-at': 'capturedAt' }) }, smallBody));
514
+ const source = `${sources}/${encoded(required(flags, 'id'))}`;
515
+ if (action === 'get')
516
+ return client.request('GET', source);
517
+ if (action === 'delete')
518
+ return client.request('DELETE', source);
519
+ if (action === 'content')
520
+ return saveContent(client, `${source}/content`, required(flags, 'output'));
521
+ if (action === 'extract')
522
+ return client.request('POST', `${source}/extraction`);
523
+ if (action === 'extraction')
524
+ return client.request('GET', `${source}/extraction${search({
525
+ version: flags.version === undefined ? undefined : String(integer(required(flags, 'version')))
526
+ })}`);
527
+ if (action === 'correct')
528
+ return client.request('POST', `${source}/extraction/corrections`, withinWireBudget(await objectWith(flags, 'baseVersion', integer(required(flags, 'base-version')), largeBody), largeBody));
529
+ throw new StateplaneCliError('INVALID_ARGUMENT');
530
+ }
531
+ async function runUploads(client, action, flags, base) {
532
+ const uploads = `${base}/uploads`;
533
+ if (action === 'create')
534
+ return client.request('POST', uploads, withinWireBudget({ mimeType: required(flags, 'mime-type'),
535
+ maxBytes: integer(required(flags, 'max-bytes')), ...optional(flags, { sha256: 'sha256' }),
536
+ ...(flags['expires-in'] === undefined ? {} : { expiresInSeconds: integer(required(flags, 'expires-in')) }) }, smallBody));
537
+ const grant = `${uploads}/${encoded(required(flags, 'grant'))}`;
538
+ if (action === 'revoke')
539
+ return client.request('DELETE', grant);
540
+ if (action === 'finalize')
541
+ return client.request('POST', `${grant}/finalize`, withinWireBudget({ attemptId: required(flags, 'attempt'),
542
+ ...optional(flags, { locator: 'locator', 'captured-at': 'capturedAt' }) }, smallBody));
543
+ if (action === 'send') {
544
+ const mimeType = required(flags, 'mime-type');
545
+ const bytes = await fileBytes(required(flags, 'file'), uploadBytes);
546
+ return client.upload(`${grant}/attempts${search({ sha256: flags.sha256 === undefined ? undefined : required(flags, 'sha256') })}`, bytes, mimeType);
547
+ }
548
+ throw new StateplaneCliError('INVALID_ARGUMENT');
549
+ }
550
+ async function runClaims(client, action, flags, base) {
551
+ const claims = `${base}/claims`;
552
+ if (action === 'create')
553
+ return client.request('POST', claims, withinWireBudget(await objectWith(flags, 'idempotencyKey', required(flags, 'idempotency-key'), largeBody), largeBody));
554
+ if (action === 'list')
555
+ return client.request('GET', `${claims}${search({ status: flags.status === undefined ? undefined : required(flags, 'status'),
556
+ citingCollection: flags['citing-collection'] === undefined ? undefined : required(flags, 'citing-collection'),
557
+ citingSource: flags['citing-source'] === undefined ? undefined : required(flags, 'citing-source'),
558
+ after: flags.after === undefined ? undefined : required(flags, 'after'),
559
+ limit: flags.limit === undefined ? undefined : String(integer(required(flags, 'limit'))) })}`);
560
+ const claim = `${claims}/${encoded(required(flags, 'id'))}`;
561
+ if (action === 'get')
562
+ return client.request('GET', `${claim}${search({
563
+ revision: flags.revision === undefined ? undefined : String(integer(required(flags, 'revision')))
564
+ })}`);
565
+ const baseRevision = integer(required(flags, 'base-revision'));
566
+ if (action === 'revise')
567
+ return client.request('POST', `${claim}/revisions`, withinWireBudget(await objectWith(flags, 'baseRevision', baseRevision, largeBody), largeBody));
568
+ if (action === 'review')
569
+ return client.request('POST', `${claim}/reviews`, withinWireBudget({ baseRevision, status: required(flags, 'status') }, smallBody));
570
+ if (action === 'delete')
571
+ return client.request('DELETE', `${claim}${search({ baseRevision: String(baseRevision) })}`);
572
+ throw new StateplaneCliError('INVALID_ARGUMENT');
573
+ }
574
+ async function runLinks(client, action, flags, base) {
575
+ const links = `${base}/links`;
576
+ if (action === 'create')
577
+ return client.request('POST', links, withinWireBudget(await objectWith(flags, 'idempotencyKey', required(flags, 'idempotency-key'), smallBody), smallBody));
578
+ if (action === 'list')
579
+ return client.request('GET', `${links}${search({ endpointKind: required(flags, 'endpoint-kind'),
580
+ endpointId: required(flags, 'endpoint-id'), after: flags.after === undefined ? undefined : required(flags, 'after'),
581
+ limit: flags.limit === undefined ? undefined : String(integer(required(flags, 'limit'))) })}`);
582
+ const link = `${links}/${encoded(required(flags, 'id'))}`;
583
+ if (action === 'get')
584
+ return client.request('GET', link);
585
+ if (action === 'delete')
586
+ return client.request('DELETE', link);
587
+ throw new StateplaneCliError('INVALID_ARGUMENT');
588
+ }
589
+ /** Sources, uploads, claims and links of one collection, through the same HTTP routes as any client. */
590
+ async function runEvidence(client, resource, action, flags, collectionPath) {
591
+ if (!action)
592
+ throw new StateplaneCliError('INVALID_ARGUMENT');
593
+ if (resource === 'sources')
594
+ return runSources(client, action, flags, collectionPath);
595
+ if (resource === 'uploads')
596
+ return runUploads(client, action, flags, collectionPath);
597
+ if (resource === 'claims')
598
+ return runClaims(client, action, flags, collectionPath);
599
+ if (resource === 'links')
600
+ return runLinks(client, action, flags, collectionPath);
601
+ throw new StateplaneCliError('INVALID_ARGUMENT');
602
+ }
603
+ /** Route a selected collection without reading credentials again. */
604
+ async function runCollectionResource(client, resource, action, flags, spacePath) {
605
+ const collection = typeof flags.collection === 'string' ? flags.collection : undefined;
606
+ const collectionPath = collection ? `${spacePath}/collections/${encoded(collection)}` : '';
607
+ if (resource === 'collections')
608
+ return runCollections(client, action, flags, spacePath, collectionPath);
609
+ if (!collectionPath)
610
+ throw new StateplaneCliError('INVALID_ARGUMENT');
611
+ if (resource === 'records')
612
+ return runRecords(client, action, flags, `${collectionPath}/records`);
613
+ if (resource === 'batches')
614
+ return runBatches(client, action, flags, collectionPath);
615
+ if (['sources', 'uploads', 'claims', 'links'].includes(resource))
616
+ return runEvidence(client, resource, action, flags, collectionPath);
617
+ if (resource === 'analysis')
618
+ return runAnalysis(client, action, flags, collectionPath);
619
+ if (resource === 'events' && action === 'list') {
620
+ const suffix = flags.cursor !== undefined ? `?cursor=${encoded(cursor(flags))}` : '';
621
+ return client.request('GET', `${collectionPath}/events${suffix}`);
622
+ }
623
+ throw new StateplaneCliError('INVALID_ARGUMENT');
624
+ }
625
+ /** Search, bundles and projection status. A search or bundle request is the JSON object of --data or --file,
626
+ * sent as the HTTP body, so every transport passes the service the same request. */
627
+ async function runRetrieval(client, action, flags, spacePath) {
628
+ if (action === 'status')
629
+ return client.request('GET', `${spacePath}/collections/${encoded(required(flags, 'collection'))}/projections`);
630
+ const data = await payload(flags, retrievalBody);
631
+ if (!data || typeof data !== 'object' || Array.isArray(data))
632
+ throw new StateplaneCliError('INVALID_ARGUMENT');
633
+ return client.request('POST', `${spacePath}/${action === 'search' ? 'search' : 'bundles'}`, withinWireBudget(data, retrievalBody));
634
+ }
635
+ /** Aggregations and snapshot jobs of one collection. A spec is the JSON of --data or --file; a submission sends
636
+ * {kind, spec} as the HTTP body. Before sending, the text given is bounded as the HTTP body it stands for (the spec, or
637
+ * the spec in its envelope) by the bound HTTP reads (RATE_LIMITED), and text that does not parse is null, as over HTTP;
638
+ * then the checks HTTP and MCP make before admission (@stateplane/contracts) decide, so every transport refuses a
639
+ * request alike. */
640
+ async function runAnalysis(client, action, flags, collectionPath) {
641
+ const refuse = (code) => { throw new StateplaneCliError(code, undefined, undefined, false); };
642
+ const given = async (maxBytes, around = (text) => text) => {
643
+ const text = await payloadText(flags, maxBytes);
644
+ if (Buffer.byteLength(around(text)) > maxBytes)
645
+ refuse('RATE_LIMITED');
646
+ try {
647
+ return JSON.parse(text);
648
+ }
649
+ catch {
650
+ return null;
651
+ }
652
+ };
653
+ if (action === 'aggregate') {
654
+ const spec = await given(analysisBounds.bodyBytes);
655
+ const admitted = admitAggregation(spec);
656
+ if ('refused' in admitted)
657
+ return refuse(admitted.refused);
658
+ return client.request('POST', `${collectionPath}/aggregate`, spec);
659
+ }
660
+ if (action === 'submit') {
661
+ const kind = required(flags, 'kind');
662
+ const request = flags.data === undefined && flags.file === undefined ? { kind }
663
+ : { kind, spec: await given(analysisBounds.bodyBytes, text => `{"kind":${JSON.stringify(kind)},"spec":${text}}`) };
664
+ const admitted = admitAnalysisJob(request);
665
+ if ('refused' in admitted)
666
+ return refuse(admitted.refused);
667
+ return client.request('POST', `${collectionPath}/jobs`, request);
668
+ }
669
+ const job = `${collectionPath}/jobs/${encoded(required(flags, 'job'))}`;
670
+ if (action === 'status')
671
+ return client.request('GET', job);
672
+ if (action === 'cancel')
673
+ return client.request('DELETE', job);
674
+ if (action === 'page')
675
+ return client.request('GET', `${job}/pages/${encoded(required(flags, 'page'))}`);
676
+ throw new StateplaneCliError('INVALID_ARGUMENT');
677
+ }
678
+ /** Capture endpoint, selected space and token as one cross-process snapshot. */
679
+ async function runHttpCommand(resource, action, flags) {
680
+ const snapshot = await withConfigMutation(async (current) => ({ config: current, token: await loadToken(current) }));
681
+ if (!snapshot.config.endpoint)
682
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
683
+ const client = new StateplaneHttpClient({ endpoint: snapshot.config.endpoint, token: snapshot.token,
684
+ timeoutMs: flags.timeout ? integer(required(flags, 'timeout')) : undefined });
685
+ const space = typeof flags.space === 'string' ? flags.space : snapshot.config.space;
686
+ const spacePath = space ? `/v1/spaces/${encoded(space)}` : '';
687
+ if (resource === 'spaces')
688
+ return runSpaces(client, action, flags, spacePath);
689
+ if (!spacePath)
690
+ throw new StateplaneCliError('INVALID_ARGUMENT');
691
+ if (resource === 'retrieval')
692
+ return runRetrieval(client, action, flags, spacePath);
693
+ return runCollectionResource(client, resource, action, flags, spacePath);
694
+ }
695
+ /** One command produces one JSON value. Errors contain only stable fields;
696
+ * no token, provider response body, or input payload is printed. */
697
+ export async function runCli(argv) {
698
+ try {
699
+ const { words, flags } = parse(argv);
700
+ const [resource, action, ...rest] = words;
701
+ if (!resource || resource === 'help' || flags.help) {
702
+ help();
703
+ return 0;
704
+ }
705
+ if (rest.length)
706
+ throw new StateplaneCliError('INVALID_ARGUMENT');
707
+ validateFlags(resource, action, flags);
708
+ const config = await readConfig();
709
+ if (resource === 'config')
710
+ output(await runConfig(action, flags, config));
711
+ else if (resource === 'auth')
712
+ output(await runAuth(action, flags, config));
713
+ else if (resource === 'spaces' && action === 'select') {
714
+ const space = required(flags, 'space');
715
+ await withConfigMutation(async (current) => { await saveConfig({ ...current, space }); });
716
+ output({ space });
717
+ }
718
+ else
719
+ output(await runHttpCommand(resource, action, flags));
720
+ return 0;
721
+ }
722
+ catch (error) {
723
+ const localCode = error?.code;
724
+ let failure;
725
+ if (error instanceof StateplaneCliError)
726
+ failure = error;
727
+ else if (typeof localCode === 'string' &&
728
+ ['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'EISDIR', 'EROFS', 'ENOSPC'].includes(localCode))
729
+ failure = new StateplaneCliError('INVALID_CONFIGURATION');
730
+ else
731
+ failure = new StateplaneCliError('PROVIDER_UNAVAILABLE');
732
+ process.stderr.write(JSON.stringify({ contractVersion: '1', error: { code: failure.code, message: failure.code,
733
+ retryable: failure.retryable, requestId: failure.requestId ?? null } }) + '\n');
734
+ return 1;
735
+ }
736
+ }