@stateplane/cli 0.0.0 → 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.
@@ -0,0 +1,54 @@
1
+ export declare class StateplaneCliError extends Error {
2
+ readonly code: string;
3
+ readonly requestId?: string | undefined;
4
+ readonly retryAfter?: number | undefined;
5
+ readonly retryable: boolean;
6
+ constructor(code: string, requestId?: string | undefined, retryAfter?: number | undefined, retryable?: boolean);
7
+ }
8
+ export interface ClientOptions {
9
+ endpoint: string;
10
+ token: string;
11
+ fetch?: typeof fetch;
12
+ timeoutMs?: number;
13
+ sleep?: (ms: number) => Promise<void>;
14
+ }
15
+ /** A download's single deadline: the signal aborts every attempt and the body at `end`;
16
+ * the consumer of the body checks `expired` around each local write and before success. */
17
+ export interface Deadline {
18
+ signal: AbortSignal;
19
+ end: number;
20
+ expired(): boolean;
21
+ }
22
+ /** A thin HTTP client. Only read requests may be repeated automatically. */
23
+ export declare class StateplaneHttpClient {
24
+ private readonly endpoint;
25
+ private readonly token;
26
+ private readonly fetcher;
27
+ private readonly timeoutMs;
28
+ private readonly sleep;
29
+ constructor(options: ClientOptions);
30
+ /** One wire attempt; only an explicit safe-read response can request a repeat. A raw
31
+ * exchange returns a successful response unread, for a byte stream, and runs
32
+ * under the download's deadline, which never waits past its end. */
33
+ private exchange;
34
+ /** Resolve the route before any bearer token is attached to a request. */
35
+ private route;
36
+ /** A wire failure is ambiguous for writes, but a read can be repeated twice,
37
+ * within a download's deadline. */
38
+ private recoverWireFailure;
39
+ /** Validate the route once, then bound retries to read-only operations. */
40
+ request(method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', path: string, body?: unknown, extraHeaders?: Record<string, string>): Promise<unknown>;
41
+ /** Read a byte stream, such as a source's original, asking for it unencoded.
42
+ * The response is returned unread once its status is successful, with the
43
+ * deadline that bounds the whole download, including how its body is consumed;
44
+ * an error response is a CLI error. */
45
+ download(path: string): Promise<{
46
+ response: Response;
47
+ deadline: Deadline;
48
+ }>;
49
+ /** Send exact bytes with their media type, such as one upload attempt. Never repeated. */
50
+ upload(path: string, bytes: Uint8Array, contentType: string): Promise<unknown>;
51
+ /** A download passes its deadline: every attempt, each pause and the body share it.
52
+ * Any other request gives each attempt its own --timeout. */
53
+ private send;
54
+ }
@@ -0,0 +1,209 @@
1
+ import { isSafeHttpRead, parseV1Path } from '@stateplane/contracts';
2
+ export class StateplaneCliError extends Error {
3
+ code;
4
+ requestId;
5
+ retryAfter;
6
+ retryable;
7
+ constructor(code, requestId, retryAfter, retryable) {
8
+ super(code);
9
+ this.code = code;
10
+ this.requestId = requestId;
11
+ this.retryAfter = retryAfter;
12
+ this.name = 'StateplaneCliError';
13
+ this.retryable = retryable ?? ['RECEIPT_PENDING', 'PROVIDER_UNAVAILABLE', 'BACKPRESSURE', 'RATE_LIMITED', 'STALE_PLACEMENT'].includes(code);
14
+ }
15
+ }
16
+ function serializeBody(body) {
17
+ if (body === undefined)
18
+ return undefined;
19
+ let serialized;
20
+ try {
21
+ serialized = JSON.stringify(body);
22
+ }
23
+ catch {
24
+ throw new StateplaneCliError('INVALID_ARGUMENT');
25
+ }
26
+ if (serialized === undefined)
27
+ throw new StateplaneCliError('INVALID_ARGUMENT');
28
+ return serialized;
29
+ }
30
+ function retryAfter(response) {
31
+ const header = response.headers.get('retry-after');
32
+ return header && /^\d+$/.test(header) ? Math.min(5, Number(header)) : undefined;
33
+ }
34
+ function serverError(value, after) {
35
+ const envelope = value;
36
+ const code = typeof envelope?.error?.code === 'string' && /^[A-Z_]{1,64}$/.test(envelope.error.code)
37
+ ? envelope.error.code : 'PROVIDER_UNAVAILABLE';
38
+ const requestId = typeof envelope?.error?.requestId === 'string' && /^[a-zA-Z0-9_-]{1,80}$/.test(envelope.error.requestId)
39
+ ? envelope.error.requestId : undefined;
40
+ return new StateplaneCliError(code, requestId, after, typeof envelope?.error?.retryable === 'boolean' ? envelope.error.retryable : undefined);
41
+ }
42
+ class WireFailure extends Error {
43
+ }
44
+ const protectedHeaders = new Set(['authorization', 'proxy-authorization', 'cookie', 'host', 'accept', 'content-type',
45
+ 'content-length', 'transfer-encoding', 'origin', 'referer']);
46
+ function requestHeaders(token, serialized, extraHeaders) {
47
+ const headers = { Authorization: `Bearer ${token}`, Accept: 'application/json',
48
+ ...(serialized === undefined ? {} : { 'Content-Type': 'application/json' }) };
49
+ if (extraHeaders === undefined)
50
+ return Object.freeze(headers);
51
+ try {
52
+ for (const [name, value] of Object.entries(extraHeaders)) {
53
+ if (typeof value !== 'string' || protectedHeaders.has(name.toLowerCase()))
54
+ throw new StateplaneCliError('INVALID_ARGUMENT');
55
+ new Headers([[name, value]]); // validate before a write can reach the transport
56
+ headers[name.toLowerCase()] = value;
57
+ }
58
+ }
59
+ catch {
60
+ throw new StateplaneCliError('INVALID_ARGUMENT');
61
+ }
62
+ return Object.freeze(headers);
63
+ }
64
+ /** Keep provider exceptions out of CLI output, including verbose paths. */
65
+ async function wireFetch(fetcher, url, options) {
66
+ try {
67
+ return await fetcher(url, options);
68
+ }
69
+ catch {
70
+ throw new WireFailure();
71
+ }
72
+ }
73
+ async function wireJson(response) {
74
+ try {
75
+ return await response.json();
76
+ }
77
+ catch {
78
+ throw new WireFailure();
79
+ }
80
+ }
81
+ function deadlineOf(ms) {
82
+ const signal = AbortSignal.timeout(ms);
83
+ const end = Date.now() + ms;
84
+ return { signal, end, expired: () => signal.aborted || Date.now() >= end };
85
+ }
86
+ /** Whether a pause of `ms` ends before the deadline, so a repeat can still run. */
87
+ const fits = (ms, deadline) => !deadline || (!deadline.expired() && Date.now() + ms < deadline.end);
88
+ /** A thin HTTP client. Only read requests may be repeated automatically. */
89
+ export class StateplaneHttpClient {
90
+ endpoint;
91
+ token;
92
+ fetcher;
93
+ timeoutMs;
94
+ sleep;
95
+ constructor(options) {
96
+ const token = options.token;
97
+ try {
98
+ this.endpoint = new URL(options.endpoint);
99
+ }
100
+ catch {
101
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
102
+ }
103
+ if (!['https:', 'http:'].includes(this.endpoint.protocol) ||
104
+ (this.endpoint.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(this.endpoint.hostname)) ||
105
+ this.endpoint.username || this.endpoint.password ||
106
+ this.endpoint.search || this.endpoint.hash || this.endpoint.pathname !== '/' ||
107
+ typeof token !== 'string' || !token || /[\r\n\0]/.test(token))
108
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
109
+ this.token = token;
110
+ this.fetcher = options.fetch ?? fetch;
111
+ this.timeoutMs = options.timeoutMs ?? 30_000;
112
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 120_000)
113
+ throw new StateplaneCliError('INVALID_CONFIGURATION');
114
+ this.sleep = options.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms)));
115
+ }
116
+ /** One wire attempt; only an explicit safe-read response can request a repeat. A raw
117
+ * exchange returns a successful response unread, for a byte stream, and runs
118
+ * under the download's deadline, which never waits past its end. */
119
+ async exchange(method, url, payload, headers, safeRead, attempt, deadline) {
120
+ const response = await wireFetch(this.fetcher, url, { method, redirect: 'error',
121
+ signal: deadline?.signal ?? AbortSignal.timeout(this.timeoutMs),
122
+ headers,
123
+ body: payload });
124
+ const after = retryAfter(response);
125
+ if (safeRead && attempt < 2 && [429, 503].includes(response.status) && after !== undefined && fits(after * 1000, deadline)) {
126
+ await response.body?.cancel().catch(() => { });
127
+ await this.sleep(after * 1000);
128
+ return { retry: true };
129
+ }
130
+ if (deadline && response.ok)
131
+ return { retry: false, value: response };
132
+ const value = await wireJson(response);
133
+ if (!response.ok)
134
+ throw serverError(value, after);
135
+ return { retry: false, value };
136
+ }
137
+ /** Resolve the route before any bearer token is attached to a request. */
138
+ route(path) {
139
+ if (!path.startsWith('/v1/') || path.startsWith('//'))
140
+ throw new StateplaneCliError('INVALID_ARGUMENT');
141
+ let url;
142
+ try {
143
+ url = new URL(path, this.endpoint);
144
+ }
145
+ catch {
146
+ throw new StateplaneCliError('INVALID_ARGUMENT');
147
+ }
148
+ const segments = parseV1Path(url.pathname);
149
+ if (url.origin !== this.endpoint.origin || !segments)
150
+ throw new StateplaneCliError('INVALID_ARGUMENT');
151
+ return { url, segments };
152
+ }
153
+ /** A wire failure is ambiguous for writes, but a read can be repeated twice,
154
+ * within a download's deadline. */
155
+ async recoverWireFailure(safeRead, attempt, deadline) {
156
+ if (!safeRead)
157
+ throw new StateplaneCliError('OUTCOME_UNKNOWN');
158
+ if (attempt >= 2 || !fits(250 * (attempt + 1), deadline))
159
+ throw new StateplaneCliError('PROVIDER_UNAVAILABLE');
160
+ await this.sleep(250 * (attempt + 1));
161
+ }
162
+ /** Validate the route once, then bound retries to read-only operations. */
163
+ async request(method, path, body, extraHeaders) {
164
+ const route = this.route(path);
165
+ const serialized = serializeBody(body);
166
+ return this.send(method, route, serialized, requestHeaders(this.token, serialized, extraHeaders));
167
+ }
168
+ /** Read a byte stream, such as a source's original, asking for it unencoded.
169
+ * The response is returned unread once its status is successful, with the
170
+ * deadline that bounds the whole download, including how its body is consumed;
171
+ * an error response is a CLI error. */
172
+ async download(path) {
173
+ const deadline = deadlineOf(this.timeoutMs);
174
+ const response = await this.send('GET', this.route(path), undefined, Object.freeze({ Authorization: `Bearer ${this.token}`, Accept: '*/*', 'Accept-Encoding': 'identity' }), deadline);
175
+ return { response, deadline };
176
+ }
177
+ /** Send exact bytes with their media type, such as one upload attempt. Never repeated. */
178
+ async upload(path, bytes, contentType) {
179
+ const route = this.route(path);
180
+ let headers;
181
+ try {
182
+ new Headers([['content-type', contentType]]); // validate before a write can reach the transport
183
+ headers = Object.freeze({ Authorization: `Bearer ${this.token}`, Accept: 'application/json', 'Content-Type': contentType });
184
+ }
185
+ catch {
186
+ throw new StateplaneCliError('INVALID_ARGUMENT');
187
+ }
188
+ return this.send('POST', route, bytes, headers);
189
+ }
190
+ /** A download passes its deadline: every attempt, each pause and the body share it.
191
+ * Any other request gives each attempt its own --timeout. */
192
+ async send(method, { url, segments }, payload, headers, deadline) {
193
+ const safeRead = isSafeHttpRead(method, segments);
194
+ for (let attempt = 0; attempt < (safeRead ? 3 : 1); attempt++) {
195
+ try {
196
+ const result = await this.exchange(method, url, payload, headers, safeRead, attempt, deadline); // NOSONAR -- each retry depends on the preceding response
197
+ if (result.retry)
198
+ continue;
199
+ return result.value;
200
+ }
201
+ catch (error) {
202
+ if (!(error instanceof WireFailure))
203
+ throw error;
204
+ await this.recoverWireFailure(safeRead, attempt, deadline); // NOSONAR -- bounded read retries must remain sequential
205
+ }
206
+ }
207
+ throw new StateplaneCliError('PROVIDER_UNAVAILABLE');
208
+ }
209
+ }
package/package.json CHANGED
@@ -1 +1,40 @@
1
- {"name":"@stateplane/cli","version":"0.0.0"}
1
+ {
2
+ "name": "@stateplane/cli",
3
+ "version": "0.1.1",
4
+ "description": "Stateplane command line: shared state for all your agents. `npx stateplane` runs it.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "bin",
18
+ "README.md"
19
+ ],
20
+ "bin": {
21
+ "stateplane": "./bin/stateplane.js"
22
+ },
23
+ "engines": {
24
+ "node": ">=22.13.0"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/21nCo/stateplane.git",
29
+ "directory": "packages/cli"
30
+ },
31
+ "homepage": "https://github.com/21nCo/stateplane#readme",
32
+ "devDependencies": {
33
+ "esbuild": "0.28.1",
34
+ "@stateplane/contracts": "0.0.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.json && esbuild src/index.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/index.js",
38
+ "typecheck": "tsc -p tsconfig.json --noEmit"
39
+ }
40
+ }