@cadenya/widgets 1.0.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/README.md +133 -0
- package/api.md +66 -0
- package/dist/client.d.ts +33 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +49 -0
- package/dist/client.js.map +1 -0
- package/dist/core/error.d.ts +39 -0
- package/dist/core/error.d.ts.map +1 -0
- package/dist/core/error.js +56 -0
- package/dist/core/error.js.map +1 -0
- package/dist/core/http.d.ts +140 -0
- package/dist/core/http.d.ts.map +1 -0
- package/dist/core/http.js +525 -0
- package/dist/core/http.js.map +1 -0
- package/dist/core/pagination.d.ts +12 -0
- package/dist/core/pagination.d.ts.map +1 -0
- package/dist/core/pagination.js +29 -0
- package/dist/core/pagination.js.map +1 -0
- package/dist/core/sse.d.ts +44 -0
- package/dist/core/sse.d.ts.map +1 -0
- package/dist/core/sse.js +350 -0
- package/dist/core/sse.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/resources/config.d.ts +16 -0
- package/dist/resources/config.d.ts.map +1 -0
- package/dist/resources/config.js +21 -0
- package/dist/resources/config.js.map +1 -0
- package/dist/resources/conversations.d.ts +173 -0
- package/dist/resources/conversations.d.ts.map +1 -0
- package/dist/resources/conversations.js +150 -0
- package/dist/resources/conversations.js.map +1 -0
- package/dist/types.d.ts +461 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +29 -0
- package/src/client.ts +87 -0
- package/src/core/error.ts +69 -0
- package/src/core/http.ts +639 -0
- package/src/core/pagination.ts +27 -0
- package/src/core/sse.ts +338 -0
- package/src/index.ts +13 -0
- package/src/resources/config.ts +22 -0
- package/src/resources/conversations.ts +232 -0
- package/src/types.ts +512 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Error model. The API reports failures as a google.rpc.Status payload. */
|
|
2
|
+
|
|
3
|
+
export interface ErrorStatus {
|
|
4
|
+
code?: number;
|
|
5
|
+
message?: string;
|
|
6
|
+
details?: Array<Record<string, unknown>>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class APIError extends Error {
|
|
10
|
+
readonly status: number;
|
|
11
|
+
readonly code: number | undefined;
|
|
12
|
+
readonly details: Array<Record<string, unknown>> | undefined;
|
|
13
|
+
|
|
14
|
+
constructor(status: number, body: ErrorStatus | undefined, message?: string) {
|
|
15
|
+
super(message ?? body?.message ?? `HTTP ${status}`);
|
|
16
|
+
this.name = 'APIError';
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = body?.code;
|
|
19
|
+
this.details = body?.details;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class APIConnectionError extends Error {
|
|
24
|
+
constructor(cause: unknown) {
|
|
25
|
+
super('Connection error', { cause });
|
|
26
|
+
this.name = 'APIConnectionError';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class APIUserAbortError extends Error {
|
|
31
|
+
constructor() {
|
|
32
|
+
super('Request was aborted');
|
|
33
|
+
this.name = 'APIUserAbortError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The request could not be constructed locally (unserializable body, invalid
|
|
39
|
+
* argument). No network attempt was made and the call is never retried.
|
|
40
|
+
*/
|
|
41
|
+
export class APIRequestError extends Error {
|
|
42
|
+
constructor(message: string, cause: unknown) {
|
|
43
|
+
super(message, { cause });
|
|
44
|
+
this.name = 'APIRequestError';
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The configured request deadline elapsed before the response completed. */
|
|
49
|
+
export class APITimeoutError extends Error {
|
|
50
|
+
constructor(timeoutMs: number) {
|
|
51
|
+
super(`Request timed out after ${timeoutMs}ms`);
|
|
52
|
+
this.name = 'APITimeoutError';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The server answered outside the declared protocol: an empty/null body
|
|
58
|
+
* where a JSON document was promised, malformed JSON, or a 204 on an
|
|
59
|
+
* output-bearing operation.
|
|
60
|
+
*/
|
|
61
|
+
export class APIResponseError extends Error {
|
|
62
|
+
readonly status: number;
|
|
63
|
+
|
|
64
|
+
constructor(status: number, message: string, cause?: unknown) {
|
|
65
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
66
|
+
this.name = 'APIResponseError';
|
|
67
|
+
this.status = status;
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/core/http.ts
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal, dependency-less HTTP core built on global fetch (Node 18+,
|
|
3
|
+
* browsers, Deno, Bun). Handles auth, query serialization, retries with
|
|
4
|
+
* backoff, timeouts, and error mapping.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
APIConnectionError,
|
|
9
|
+
APIError,
|
|
10
|
+
APIRequestError,
|
|
11
|
+
APIResponseError,
|
|
12
|
+
APITimeoutError,
|
|
13
|
+
APIUserAbortError,
|
|
14
|
+
ErrorStatus,
|
|
15
|
+
} from './error.js';
|
|
16
|
+
|
|
17
|
+
export interface RequestOptions {
|
|
18
|
+
/**
|
|
19
|
+
* Auto-reconnect for SSE streams (default true): a mid-stream transport
|
|
20
|
+
* drop resumes from the last received event id, like EventSource. Clean
|
|
21
|
+
* stream end, close(), and abort never reconnect. Set false to surface
|
|
22
|
+
* drops as APIConnectionError instead.
|
|
23
|
+
*/
|
|
24
|
+
reconnect?: boolean;
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
maxRetries?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Per-request deadline in milliseconds (overrides the client default).
|
|
30
|
+
* Non-finite or <= 0 disables the deadline for this request.
|
|
31
|
+
*/
|
|
32
|
+
timeout?: number;
|
|
33
|
+
/**
|
|
34
|
+
* For streaming (SSE) requests: resume after the event with this id by
|
|
35
|
+
* sending it as the Last-Event-ID request header.
|
|
36
|
+
*/
|
|
37
|
+
lastEventId?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type QueryPrimitive = string | number | boolean;
|
|
41
|
+
export type QueryValue = QueryPrimitive | QueryPrimitive[] | undefined | null;
|
|
42
|
+
|
|
43
|
+
export interface RequestSpec {
|
|
44
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
45
|
+
path: string;
|
|
46
|
+
query?: Record<string, QueryValue>;
|
|
47
|
+
body?: unknown;
|
|
48
|
+
stream?: boolean;
|
|
49
|
+
/** The operation declares no response body (void): 204/empty succeed. */
|
|
50
|
+
void?: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type LogLevel = 'debug' | 'warn' | 'off';
|
|
54
|
+
|
|
55
|
+
/** Minimal logger surface; `console` satisfies it. */
|
|
56
|
+
export interface Logger {
|
|
57
|
+
debug(...args: unknown[]): void;
|
|
58
|
+
warn(...args: unknown[]): void;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface HttpClientOptions {
|
|
62
|
+
baseURL: string;
|
|
63
|
+
authHeader: () => Record<string, string>;
|
|
64
|
+
maxRetries?: number;
|
|
65
|
+
/** Deadline for ordinary (non-streaming) requests in ms. Default 60000. */
|
|
66
|
+
timeout?: number;
|
|
67
|
+
defaultHeaders?: Record<string, string>;
|
|
68
|
+
fetch?: typeof fetch;
|
|
69
|
+
/** Client-level default values for prominent params (e.g. a tenant/scope id). */
|
|
70
|
+
defaults?: Record<string, string | undefined>;
|
|
71
|
+
/** Destination for SDK logs. Defaults to `console`. */
|
|
72
|
+
logger?: Logger;
|
|
73
|
+
/**
|
|
74
|
+
* 'debug' logs every request/response line (method, path, status,
|
|
75
|
+
* duration — never headers or bodies); 'warn' (default) logs only
|
|
76
|
+
* retries; 'off' silences the SDK entirely.
|
|
77
|
+
*/
|
|
78
|
+
logLevel?: LogLevel;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const RETRYABLE_STATUS = new Set([408, 409, 429, 500, 502, 503, 504]);
|
|
82
|
+
|
|
83
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Encode one path segment, rejecting empty/whitespace values at the boundary
|
|
87
|
+
* — an empty segment would silently rewrite the route (/parents//children).
|
|
88
|
+
*/
|
|
89
|
+
export function pathSegment(name: string, value: string | undefined): string {
|
|
90
|
+
if (value === undefined || String(value).trim() === '') {
|
|
91
|
+
throw new Error(`Missing required path parameter '${name}'.`);
|
|
92
|
+
}
|
|
93
|
+
return encodeURIComponent(value);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Snapshot list params at call time so pagination cannot observe later
|
|
98
|
+
* caller mutations (array-valued filters are copied too). Auto-iteration
|
|
99
|
+
* must never combine pages from different result sets.
|
|
100
|
+
*/
|
|
101
|
+
export function snapshotParams<T>(params: T): T {
|
|
102
|
+
if (params === undefined || params === null || typeof params !== 'object') return params;
|
|
103
|
+
const copy: Record<string, unknown> = {};
|
|
104
|
+
for (const [key, value] of Object.entries(params as Record<string, unknown>)) {
|
|
105
|
+
copy[key] = Array.isArray(value) ? value.slice() : value;
|
|
106
|
+
}
|
|
107
|
+
return copy as T;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Automatic retries apply only to idempotent methods. A POST/PATCH that
|
|
112
|
+
* succeeds server-side but loses its response would be executed twice if
|
|
113
|
+
* retried; callers can opt a specific mutation in via options.maxRetries.
|
|
114
|
+
*/
|
|
115
|
+
const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Settle when the promise settles OR the signal aborts — a custom fetch (or
|
|
119
|
+
* body reader) that ignores AbortSignal must not be able to hold a deadlined
|
|
120
|
+
* request open forever. The orphaned promise's eventual rejection is
|
|
121
|
+
* swallowed; its resolution is discarded.
|
|
122
|
+
*/
|
|
123
|
+
function raceAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
|
124
|
+
if (!signal) return promise;
|
|
125
|
+
return new Promise<T>((resolve, reject) => {
|
|
126
|
+
const onAbort = () => {
|
|
127
|
+
promise.catch(() => {});
|
|
128
|
+
reject(new APIUserAbortError());
|
|
129
|
+
};
|
|
130
|
+
if (signal.aborted) {
|
|
131
|
+
onAbort();
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
135
|
+
promise.then(
|
|
136
|
+
(value) => {
|
|
137
|
+
signal.removeEventListener('abort', onAbort);
|
|
138
|
+
resolve(value);
|
|
139
|
+
},
|
|
140
|
+
(err) => {
|
|
141
|
+
signal.removeEventListener('abort', onAbort);
|
|
142
|
+
reject(err);
|
|
143
|
+
},
|
|
144
|
+
);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Deadline cleanup for streaming responses, handed from rawRequest to the
|
|
150
|
+
* Stream that owns the body. The forwarding listener must survive until the
|
|
151
|
+
* stream terminates (a caller abort has to unblock a pending read on a
|
|
152
|
+
* silent socket), so the Stream — not rawRequest — releases it.
|
|
153
|
+
*/
|
|
154
|
+
const streamCleanups = new WeakMap<Response, () => void>();
|
|
155
|
+
|
|
156
|
+
/** Claim (and remove) the cleanup registered for a streaming response. */
|
|
157
|
+
export function takeStreamCleanup(response: Response): (() => void) | undefined {
|
|
158
|
+
const cleanup = streamCleanups.get(response);
|
|
159
|
+
streamCleanups.delete(response);
|
|
160
|
+
return cleanup;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Merged caller-signal + deadline state for one request. */
|
|
164
|
+
interface Deadline {
|
|
165
|
+
signal: AbortSignal | undefined;
|
|
166
|
+
/** Stop the timer (body may keep streaming under the caller's signal). */
|
|
167
|
+
settle(): void;
|
|
168
|
+
/**
|
|
169
|
+
* Detach the abort-forwarding listener from the caller's signal. Call
|
|
170
|
+
* only when the request (including any stream body) is finished — a
|
|
171
|
+
* reused long-lived signal must not accumulate one listener per
|
|
172
|
+
* completed call.
|
|
173
|
+
*/
|
|
174
|
+
release(): void;
|
|
175
|
+
timedOut(): boolean;
|
|
176
|
+
ms: number;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* A lazily-parsing promise for one API call. Awaiting it (or `.then`) yields
|
|
181
|
+
* the decoded value exactly like a plain promise; `withResponse()` yields the
|
|
182
|
+
* decoded value together with the raw `Response` (status, headers); and
|
|
183
|
+
* `asResponse()` yields the raw `Response` WITHOUT consuming the body, so
|
|
184
|
+
* the caller owns reading it.
|
|
185
|
+
*/
|
|
186
|
+
export class APIPromise<T> implements Promise<T> {
|
|
187
|
+
private parsed: Promise<T> | undefined;
|
|
188
|
+
private observedRaw = false;
|
|
189
|
+
|
|
190
|
+
constructor(
|
|
191
|
+
private readonly responsePromise: Promise<Response>,
|
|
192
|
+
private readonly parseFn: (response: Response) => Promise<T>,
|
|
193
|
+
private readonly onRawAccess: () => void,
|
|
194
|
+
) {
|
|
195
|
+
// A dropped return value must still reach terminal cleanup: the request
|
|
196
|
+
// has already been sent, so unless raw access claims the body FIRST
|
|
197
|
+
// (synchronously, before any await), parsing starts on the next
|
|
198
|
+
// microtask — consuming the body and settling the deadline timer even
|
|
199
|
+
// when the caller never observes the promise. Rejections on this
|
|
200
|
+
// internal branch are swallowed; a caller who later awaits still gets
|
|
201
|
+
// them from the memoized parse.
|
|
202
|
+
queueMicrotask(() => {
|
|
203
|
+
if (!this.observedRaw) this.parse().catch(() => {});
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The raw `Response` after status checking and retries; the body is NOT
|
|
209
|
+
* consumed. Reading the body (and its timing) becomes the caller's
|
|
210
|
+
* responsibility — the request deadline stops at header acquisition.
|
|
211
|
+
*/
|
|
212
|
+
asResponse(): Promise<Response> {
|
|
213
|
+
// Must be called synchronously after the request (before any await):
|
|
214
|
+
// it claims body ownership away from the auto-parse safety net. Mixing
|
|
215
|
+
// a LATE asResponse() with parsed access yields a response whose body
|
|
216
|
+
// was already consumed by parsing — status/headers stay usable.
|
|
217
|
+
this.observedRaw = true;
|
|
218
|
+
return this.responsePromise.then((response) => {
|
|
219
|
+
this.onRawAccess();
|
|
220
|
+
return response;
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The decoded value together with the `Response` its body came from. */
|
|
225
|
+
async withResponse(): Promise<{ data: T; response: Response }> {
|
|
226
|
+
const response = await this.responsePromise;
|
|
227
|
+
const data = await this.parse();
|
|
228
|
+
return { data, response };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private parse(): Promise<T> {
|
|
232
|
+
this.parsed ??= this.responsePromise.then(this.parseFn);
|
|
233
|
+
return this.parsed;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
then<TResult1 = T, TResult2 = never>(
|
|
237
|
+
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
|
|
238
|
+
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
|
|
239
|
+
): Promise<TResult1 | TResult2> {
|
|
240
|
+
return this.parse().then(onfulfilled, onrejected);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
catch<TResult = never>(
|
|
244
|
+
onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,
|
|
245
|
+
): Promise<T | TResult> {
|
|
246
|
+
return this.parse().catch(onrejected);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
finally(onfinally?: (() => void) | null): Promise<T> {
|
|
250
|
+
return this.parse().finally(onfinally);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
readonly [Symbol.toStringTag] = 'APIPromise';
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export class HttpClient {
|
|
257
|
+
private readonly baseURL: string;
|
|
258
|
+
private readonly authHeader: () => Record<string, string>;
|
|
259
|
+
private readonly maxRetries: number;
|
|
260
|
+
private readonly timeout: number;
|
|
261
|
+
private readonly defaultHeaders: Record<string, string>;
|
|
262
|
+
private readonly fetchFn: typeof fetch;
|
|
263
|
+
private readonly logger: Logger;
|
|
264
|
+
private readonly logLevel: LogLevel;
|
|
265
|
+
|
|
266
|
+
/** Method + path + status only — headers and bodies are never logged. */
|
|
267
|
+
private logDebug(...args: unknown[]): void {
|
|
268
|
+
if (this.logLevel === 'debug') this.logger.debug('[sdk]', ...args);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
private logWarn(...args: unknown[]): void {
|
|
272
|
+
if (this.logLevel !== 'off') this.logger.warn('[sdk]', ...args);
|
|
273
|
+
}
|
|
274
|
+
readonly defaults: Record<string, string | undefined>;
|
|
275
|
+
|
|
276
|
+
constructor(options: HttpClientOptions) {
|
|
277
|
+
this.defaults = options.defaults ?? {};
|
|
278
|
+
this.logger = options.logger ?? console;
|
|
279
|
+
this.logLevel = options.logLevel ?? 'warn';
|
|
280
|
+
// Validate the STRUCTURE once: operation paths are appended to this
|
|
281
|
+
// value, so a query/fragment/userinfo would silently swallow the
|
|
282
|
+
// request path. Absolute http(s) with a host is required; a path
|
|
283
|
+
// prefix is supported and kept.
|
|
284
|
+
// A literal delimiter parses as an EMPTY search/hash and slips past
|
|
285
|
+
// the checks below; reject the characters outright.
|
|
286
|
+
if (options.baseURL.includes('?') || options.baseURL.includes('#')) {
|
|
287
|
+
throw new Error(
|
|
288
|
+
`baseURL '${options.baseURL}' must not carry userinfo, query, or fragment`,
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
let parsed: URL;
|
|
292
|
+
try {
|
|
293
|
+
parsed = new URL(options.baseURL);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
throw new Error(`baseURL '${options.baseURL}' is not an absolute URL`, { cause: err });
|
|
296
|
+
}
|
|
297
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
298
|
+
throw new Error(`baseURL '${options.baseURL}' must use http or https`);
|
|
299
|
+
}
|
|
300
|
+
if (parsed.hostname === '') {
|
|
301
|
+
throw new Error(`baseURL '${options.baseURL}' has no host`);
|
|
302
|
+
}
|
|
303
|
+
if (parsed.username !== '' || parsed.password !== '' || parsed.search !== '' || parsed.hash !== '') {
|
|
304
|
+
throw new Error(
|
|
305
|
+
`baseURL '${options.baseURL}' must not carry userinfo, query, or fragment`,
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
this.baseURL = (parsed.origin + parsed.pathname).replace(/\/+$/, '');
|
|
309
|
+
this.authHeader = options.authHeader;
|
|
310
|
+
this.maxRetries = options.maxRetries ?? 0;
|
|
311
|
+
this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
312
|
+
this.defaultHeaders = options.defaultHeaders ?? {};
|
|
313
|
+
this.fetchFn = options.fetch ?? fetch;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The APIPromise pipeline for JSON and void operations. The spec thunk
|
|
318
|
+
* runs inside the async context so synchronous setup failures (e.g. a
|
|
319
|
+
* missing client-default param) surface as rejections, exactly like the
|
|
320
|
+
* plain-promise path. The deadline spans fetch through decode; raw-access
|
|
321
|
+
* consumers release it at header acquisition and own body timing.
|
|
322
|
+
*/
|
|
323
|
+
requestAPI<T>(makeSpec: () => RequestSpec, options: RequestOptions = {}): APIPromise<T> {
|
|
324
|
+
const deadline = this.deadline(options);
|
|
325
|
+
let spec: RequestSpec;
|
|
326
|
+
const responsePromise = (async () => {
|
|
327
|
+
try {
|
|
328
|
+
spec = makeSpec();
|
|
329
|
+
return await this.rawRequest(spec, { ...options, signal: deadline.signal });
|
|
330
|
+
} catch (err) {
|
|
331
|
+
deadline.settle();
|
|
332
|
+
deadline.release();
|
|
333
|
+
if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);
|
|
334
|
+
throw err;
|
|
335
|
+
}
|
|
336
|
+
})();
|
|
337
|
+
const parseFn = async (response: Response): Promise<T> => {
|
|
338
|
+
try {
|
|
339
|
+
if (spec.void) {
|
|
340
|
+
void response.body?.cancel().catch(() => {});
|
|
341
|
+
return undefined as T;
|
|
342
|
+
}
|
|
343
|
+
if (response.status === 204) {
|
|
344
|
+
throw new APIResponseError(204, 'HTTP 204 where a JSON response was expected');
|
|
345
|
+
}
|
|
346
|
+
const text = await raceAbort(response.text(), deadline.signal);
|
|
347
|
+
if (text.trim() === '' || text.trim() === 'null') {
|
|
348
|
+
throw new APIResponseError(
|
|
349
|
+
response.status,
|
|
350
|
+
`HTTP ${response.status} with an empty or null body where a JSON response was expected`,
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
return JSON.parse(text) as T;
|
|
355
|
+
} catch (err) {
|
|
356
|
+
throw new APIResponseError(response.status, 'response body is not valid JSON', err);
|
|
357
|
+
}
|
|
358
|
+
} catch (err) {
|
|
359
|
+
if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);
|
|
360
|
+
throw err;
|
|
361
|
+
} finally {
|
|
362
|
+
deadline.settle();
|
|
363
|
+
deadline.release();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
return new APIPromise<T>(responsePromise, parseFn, () => {
|
|
367
|
+
deadline.settle();
|
|
368
|
+
deadline.release();
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async request<T>(spec: RequestSpec, options: RequestOptions = {}): Promise<T> {
|
|
373
|
+
// Ordinary JSON calls keep the deadline through body consumption and
|
|
374
|
+
// decoding — a response that stalls mid-body still times out.
|
|
375
|
+
const deadline = this.deadline(options);
|
|
376
|
+
try {
|
|
377
|
+
const response = await this.rawRequest(spec, { ...options, signal: deadline.signal });
|
|
378
|
+
// Branch on the GENERATED expectation, not the HTTP status: a void
|
|
379
|
+
// method accepts 204/empty, but an output-bearing method requires a
|
|
380
|
+
// JSON document — empty/null would fabricate a resource outside the
|
|
381
|
+
// declared contract, and malformed JSON must be a stable SDK error.
|
|
382
|
+
if (spec.void) {
|
|
383
|
+
void response.body?.cancel().catch(() => {});
|
|
384
|
+
return undefined as T;
|
|
385
|
+
}
|
|
386
|
+
if (response.status === 204) {
|
|
387
|
+
throw new APIResponseError(204, 'HTTP 204 where a JSON response was expected');
|
|
388
|
+
}
|
|
389
|
+
const text = await raceAbort(response.text(), deadline.signal);
|
|
390
|
+
if (text.trim() === '' || text.trim() === 'null') {
|
|
391
|
+
throw new APIResponseError(
|
|
392
|
+
response.status,
|
|
393
|
+
`HTTP ${response.status} with an empty or null body where a JSON response was expected`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
return JSON.parse(text) as T;
|
|
398
|
+
} catch (err) {
|
|
399
|
+
throw new APIResponseError(response.status, 'response body is not valid JSON', err);
|
|
400
|
+
}
|
|
401
|
+
} catch (err) {
|
|
402
|
+
if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);
|
|
403
|
+
throw err;
|
|
404
|
+
} finally {
|
|
405
|
+
deadline.settle();
|
|
406
|
+
deadline.release();
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async rawRequest(spec: RequestSpec, options: RequestOptions = {}): Promise<Response> {
|
|
411
|
+
const url = this.buildURL(spec.path, spec.query);
|
|
412
|
+
|
|
413
|
+
// One Headers instance; `set` is case-insensitive, so later layers
|
|
414
|
+
// OVERRIDE earlier ones regardless of spelling (object spread would keep
|
|
415
|
+
// both `Authorization` and `authorization` and fetch would join the two
|
|
416
|
+
// values into one corrupt header). Precedence: generated defaults →
|
|
417
|
+
// client defaults → auth → per-request → Last-Event-ID (the semantic
|
|
418
|
+
// option is the single source of resume state).
|
|
419
|
+
const headers = new Headers();
|
|
420
|
+
headers.set('Accept', spec.stream ? 'text/event-stream' : 'application/json');
|
|
421
|
+
if (spec.body !== undefined) headers.set('Content-Type', 'application/json');
|
|
422
|
+
for (const [key, value] of Object.entries(this.defaultHeaders)) headers.set(key, value);
|
|
423
|
+
for (const [key, value] of Object.entries(this.authHeader())) headers.set(key, value);
|
|
424
|
+
for (const [key, value] of Object.entries(options.headers ?? {})) headers.set(key, value);
|
|
425
|
+
if (options.lastEventId !== undefined) {
|
|
426
|
+
headers.set('Last-Event-ID', options.lastEventId);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Serialize ONCE, before the transport/retry loop: a circular object or
|
|
430
|
+
// BigInt is a caller bug, not a network failure — it must surface as a
|
|
431
|
+
// stable request-construction error and never be retried.
|
|
432
|
+
let bodyText: string | undefined;
|
|
433
|
+
if (spec.body !== undefined) {
|
|
434
|
+
try {
|
|
435
|
+
bodyText = JSON.stringify(spec.body);
|
|
436
|
+
} catch (err) {
|
|
437
|
+
throw new APIRequestError('request body is not JSON-serializable', err);
|
|
438
|
+
}
|
|
439
|
+
if (bodyText === undefined) {
|
|
440
|
+
throw new APIRequestError('request body serialized to undefined', undefined);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Streams bound only connection/response-header acquisition; the body's
|
|
445
|
+
// lifetime stays under the caller's AbortSignal.
|
|
446
|
+
const streamDeadline = spec.stream ? this.deadline(options) : undefined;
|
|
447
|
+
const signal = streamDeadline ? streamDeadline.signal : options.signal;
|
|
448
|
+
|
|
449
|
+
// An explicit per-request maxRetries opts in even for mutations.
|
|
450
|
+
const maxRetries = normalizeRetries(
|
|
451
|
+
options.maxRetries !== undefined
|
|
452
|
+
? options.maxRetries
|
|
453
|
+
: IDEMPOTENT_METHODS.has(spec.method)
|
|
454
|
+
? this.maxRetries
|
|
455
|
+
: 0,
|
|
456
|
+
);
|
|
457
|
+
|
|
458
|
+
const startedAt = Date.now();
|
|
459
|
+
for (let attempt = 0; ; attempt++) {
|
|
460
|
+
this.logDebug(`-> ${spec.method} ${spec.path}`, attempt > 0 ? `(attempt ${attempt + 1})` : '');
|
|
461
|
+
let response: Response;
|
|
462
|
+
try {
|
|
463
|
+
response = await raceAbort(
|
|
464
|
+
this.fetchFn(url, {
|
|
465
|
+
method: spec.method,
|
|
466
|
+
headers,
|
|
467
|
+
body: bodyText,
|
|
468
|
+
signal: signal ?? null,
|
|
469
|
+
}),
|
|
470
|
+
signal,
|
|
471
|
+
);
|
|
472
|
+
} catch (err) {
|
|
473
|
+
if (streamDeadline?.timedOut()) {
|
|
474
|
+
streamDeadline.settle();
|
|
475
|
+
streamDeadline.release();
|
|
476
|
+
throw new APITimeoutError(streamDeadline.ms);
|
|
477
|
+
}
|
|
478
|
+
if (signal?.aborted) {
|
|
479
|
+
streamDeadline?.settle();
|
|
480
|
+
streamDeadline?.release();
|
|
481
|
+
throw new APIUserAbortError();
|
|
482
|
+
}
|
|
483
|
+
if (attempt < maxRetries) {
|
|
484
|
+
this.logWarn(`retrying ${spec.method} ${spec.path} after connection error (attempt ${attempt + 1}/${maxRetries + 1})`);
|
|
485
|
+
await sleep(backoffMs(attempt, undefined), signal);
|
|
486
|
+
if (streamDeadline?.timedOut()) {
|
|
487
|
+
streamDeadline.settle();
|
|
488
|
+
streamDeadline.release();
|
|
489
|
+
throw new APITimeoutError(streamDeadline.ms);
|
|
490
|
+
}
|
|
491
|
+
if (signal?.aborted) throw new APIUserAbortError();
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
// Terminal connection failure: the deadline timer must not outlive
|
|
495
|
+
// the reported error (an orphaned timer holds the process open).
|
|
496
|
+
streamDeadline?.settle();
|
|
497
|
+
streamDeadline?.release();
|
|
498
|
+
throw new APIConnectionError(err);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (response.ok) {
|
|
502
|
+
this.logDebug(`<- ${response.status} ${spec.method} ${spec.path} (${Date.now() - startedAt}ms)`);
|
|
503
|
+
// Response headers acquired: the stream body is now unbounded. The
|
|
504
|
+
// forwarding listener stays attached (caller abort must reach the
|
|
505
|
+
// body); the Stream releases it at its terminal state.
|
|
506
|
+
if (streamDeadline) {
|
|
507
|
+
streamDeadline.settle();
|
|
508
|
+
streamCleanups.set(response, () => streamDeadline.release());
|
|
509
|
+
}
|
|
510
|
+
return response;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (RETRYABLE_STATUS.has(response.status) && attempt < maxRetries) {
|
|
514
|
+
this.logWarn(`retrying ${spec.method} ${spec.path} after HTTP ${response.status} (attempt ${attempt + 1}/${maxRetries + 1})`);
|
|
515
|
+
// Release the discarded response so its connection can be reused.
|
|
516
|
+
void response.body?.cancel().catch(() => {});
|
|
517
|
+
await sleep(backoffMs(attempt, response.headers.get('retry-after')), signal);
|
|
518
|
+
// A stream deadline that fired during backoff is a timeout, not a
|
|
519
|
+
// user abort — rawRequest has no outer mapper to reclassify it.
|
|
520
|
+
if (streamDeadline?.timedOut()) {
|
|
521
|
+
streamDeadline.settle();
|
|
522
|
+
streamDeadline.release();
|
|
523
|
+
throw new APITimeoutError(streamDeadline.ms);
|
|
524
|
+
}
|
|
525
|
+
if (signal?.aborted) throw new APIUserAbortError();
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
let body: ErrorStatus | undefined;
|
|
530
|
+
try {
|
|
531
|
+
body = (await response.json()) as ErrorStatus;
|
|
532
|
+
} catch {
|
|
533
|
+
body = undefined;
|
|
534
|
+
}
|
|
535
|
+
// The deadline stays active while consuming a non-2xx error body; if
|
|
536
|
+
// it expired there, report the timeout rather than a truncated
|
|
537
|
+
// APIError.
|
|
538
|
+
if (streamDeadline?.timedOut()) {
|
|
539
|
+
streamDeadline.settle();
|
|
540
|
+
streamDeadline.release();
|
|
541
|
+
throw new APITimeoutError(streamDeadline.ms);
|
|
542
|
+
}
|
|
543
|
+
streamDeadline?.settle();
|
|
544
|
+
streamDeadline?.release();
|
|
545
|
+
throw new APIError(response.status, body);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Merge the caller's signal with the configured deadline. The caller's
|
|
551
|
+
* abort always forwards; the timer marks timedOut so the thrown error can
|
|
552
|
+
* be classified as APITimeoutError rather than APIUserAbortError.
|
|
553
|
+
*/
|
|
554
|
+
private deadline(options: RequestOptions): Deadline {
|
|
555
|
+
const ms = options.timeout ?? this.timeout;
|
|
556
|
+
if (!Number.isFinite(ms) || ms <= 0) {
|
|
557
|
+
return { signal: options.signal, settle() {}, release() {}, timedOut: () => false, ms };
|
|
558
|
+
}
|
|
559
|
+
const controller = new AbortController();
|
|
560
|
+
let timedOut = false;
|
|
561
|
+
const timer = setTimeout(() => {
|
|
562
|
+
timedOut = true;
|
|
563
|
+
controller.abort();
|
|
564
|
+
}, ms);
|
|
565
|
+
const forward = () => controller.abort();
|
|
566
|
+
if (options.signal?.aborted) {
|
|
567
|
+
controller.abort();
|
|
568
|
+
} else {
|
|
569
|
+
options.signal?.addEventListener('abort', forward, { once: true });
|
|
570
|
+
}
|
|
571
|
+
let settled = false;
|
|
572
|
+
let released = false;
|
|
573
|
+
return {
|
|
574
|
+
signal: controller.signal,
|
|
575
|
+
settle() {
|
|
576
|
+
if (settled) return;
|
|
577
|
+
settled = true;
|
|
578
|
+
clearTimeout(timer);
|
|
579
|
+
},
|
|
580
|
+
release() {
|
|
581
|
+
if (released) return;
|
|
582
|
+
released = true;
|
|
583
|
+
options.signal?.removeEventListener('abort', forward);
|
|
584
|
+
},
|
|
585
|
+
timedOut: () => timedOut,
|
|
586
|
+
ms,
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
private buildURL(path: string, query?: Record<string, QueryValue>): string {
|
|
591
|
+
const url = new URL(this.baseURL + path);
|
|
592
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
593
|
+
if (value === undefined || value === null) continue;
|
|
594
|
+
// Arrays serialize as repeated params: ?state=a&state=b
|
|
595
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
596
|
+
url.searchParams.append(key, String(item));
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return url.toString();
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Retry counts must be bounded non-negative integers; anything else (NaN,
|
|
604
|
+
* Infinity, negatives, fractions) is treated as the nearest sane value. */
|
|
605
|
+
function normalizeRetries(value: number): number {
|
|
606
|
+
if (!Number.isFinite(value) || value <= 0) return 0;
|
|
607
|
+
return Math.min(Math.floor(value), 10);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function backoffMs(attempt: number, retryAfter: string | null | undefined): number {
|
|
611
|
+
if (retryAfter) {
|
|
612
|
+
// Retry-After is either delta-seconds or an HTTP-date. A parsed zero is
|
|
613
|
+
// a real answer (retry immediately), not a fall-through to backoff.
|
|
614
|
+
const seconds = Number(retryAfter);
|
|
615
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, 60_000);
|
|
616
|
+
const date = Date.parse(retryAfter);
|
|
617
|
+
if (Number.isFinite(date)) {
|
|
618
|
+
return Math.min(Math.max(date - Date.now(), 0), 60_000);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const base = 500 * 2 ** Math.min(attempt, 4);
|
|
622
|
+
return Math.min(base + Math.random() * base, 8000);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Sleep that wakes early when the signal aborts (caller re-checks it). */
|
|
626
|
+
function sleep(ms: number, signal?: AbortSignal | null): Promise<void> {
|
|
627
|
+
return new Promise((resolve) => {
|
|
628
|
+
if (signal?.aborted) return resolve();
|
|
629
|
+
const timer = setTimeout(() => {
|
|
630
|
+
signal?.removeEventListener('abort', onAbort);
|
|
631
|
+
resolve();
|
|
632
|
+
}, ms);
|
|
633
|
+
const onAbort = () => {
|
|
634
|
+
clearTimeout(timer);
|
|
635
|
+
resolve();
|
|
636
|
+
};
|
|
637
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
638
|
+
});
|
|
639
|
+
}
|