@eserstack/httpclient 0.0.0-stage → 5.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/dist/client.js ADDED
@@ -0,0 +1,468 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * HttpClient — resilient HTTP client with timeout, retry, rate-limit handling,
4
+ * and request/response interceptors.
5
+ *
6
+ * Provides two APIs:
7
+ * - Throw-style: `client.get<T>(url)` — throws HttpClientError on failure
8
+ * - Result-style: `client.getResult<T>(url)` — returns Result<HttpResponse<T>, HttpClientError>
9
+ * for @eserstack/functions do-notation compatibility
10
+ *
11
+ * @module
12
+ */
13
+ import * as results from "@eserstack/primitives/results";
14
+ import * as errors from "./errors.js";
15
+ import * as interceptors from "./interceptors.js";
16
+ import * as goClientModule from "./go-client.js";
17
+ import * as goTransport from "./go-transport.js";
18
+ import * as retryPolicy from "./retry-policy.js";
19
+ // =============================================================================
20
+ // Defaults
21
+ // =============================================================================
22
+ const DEFAULT_TIMEOUT = 30_000;
23
+ const defaultDelayFn = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
24
+ // =============================================================================
25
+ // Internal Helpers
26
+ // =============================================================================
27
+ const resolveUrl = (baseUrl, path) => {
28
+ if (path.startsWith("http://") || path.startsWith("https://")) {
29
+ return path;
30
+ }
31
+ if (baseUrl !== undefined && baseUrl !== "") {
32
+ const base = baseUrl.replace(/\/$/, "");
33
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
34
+ return `${base}${normalizedPath}`;
35
+ }
36
+ return path;
37
+ };
38
+ export const parseRetryAfter = (header) => {
39
+ const ms = parseRetryAfterMs(header);
40
+ return ms !== null ? ms / 1_000 : null;
41
+ };
42
+ const parseRetryAfterMs = (header) => {
43
+ if (header === null)
44
+ return null;
45
+ const seconds = Number(header);
46
+ if (!Number.isNaN(seconds) && seconds >= 0) {
47
+ return Math.round(seconds * 1_000);
48
+ }
49
+ const date = new Date(header);
50
+ if (!Number.isNaN(date.getTime())) {
51
+ return Math.max(0, date.getTime() - Date.now());
52
+ }
53
+ return null;
54
+ };
55
+ export const extractRateLimitInfo = (hdrs) => {
56
+ const remaining = hdrs.get("X-RateLimit-Remaining") ?? hdrs.get("x-rate-limit-remaining");
57
+ const limit = hdrs.get("X-RateLimit-Limit") ?? hdrs.get("x-rate-limit-limit");
58
+ const reset = hdrs.get("X-RateLimit-Reset") ?? hdrs.get("x-rate-limit-reset");
59
+ const retryAfterHeader = hdrs.get("Retry-After");
60
+ if (remaining === null &&
61
+ limit === null &&
62
+ reset === null &&
63
+ retryAfterHeader === null) {
64
+ return undefined;
65
+ }
66
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
67
+ return {
68
+ ...(remaining !== null && { remaining: Number(remaining) }),
69
+ ...(limit !== null && { limit: Number(limit) }),
70
+ ...(reset !== null && { resetAt: Number(reset) }),
71
+ ...(retryAfterMs !== null && { retryAfterSeconds: retryAfterMs / 1_000 }),
72
+ };
73
+ };
74
+ const extractErrorBody = async (raw) => {
75
+ try {
76
+ return await raw.clone().json();
77
+ }
78
+ catch {
79
+ return await raw
80
+ .clone()
81
+ .text()
82
+ .catch(() => undefined);
83
+ }
84
+ };
85
+ const errorMessageFromBody = (body) => {
86
+ if (typeof body === "object" && body !== null) {
87
+ const b = body;
88
+ const msg = b["error"] ?? b["message"] ?? b["detail"] ?? b["title"];
89
+ if (msg !== undefined)
90
+ return String(msg);
91
+ }
92
+ return null;
93
+ };
94
+ // =============================================================================
95
+ // HttpClient
96
+ // =============================================================================
97
+ export class HttpClient {
98
+ config;
99
+ #goClientInit = null;
100
+ constructor(config) {
101
+ if (config?.transport === "native" && config.fetchFn !== undefined) {
102
+ throw new TypeError('HttpClient: fetchFn and transport "native" exclude each other; pass one of them');
103
+ }
104
+ this.config = config ?? {};
105
+ }
106
+ /** Return a new client with merged configuration (immutable). */
107
+ withDefaults(overrides) {
108
+ return new HttpClient({
109
+ ...this.config,
110
+ ...overrides,
111
+ headers: {
112
+ ...(this.config.headers ?? {}),
113
+ ...(overrides.headers ?? {}),
114
+ },
115
+ });
116
+ }
117
+ // ---------------------------------------------------------------------------
118
+ // Throw-style API
119
+ // ---------------------------------------------------------------------------
120
+ request(method, url, options) {
121
+ return this._execute(method, url, options);
122
+ }
123
+ get(url, options) {
124
+ return this._execute("GET", url, options);
125
+ }
126
+ post(url, options) {
127
+ return this._execute("POST", url, options);
128
+ }
129
+ put(url, options) {
130
+ return this._execute("PUT", url, options);
131
+ }
132
+ patch(url, options) {
133
+ return this._execute("PATCH", url, options);
134
+ }
135
+ delete(url, options) {
136
+ return this._execute("DELETE", url, options);
137
+ }
138
+ // ---------------------------------------------------------------------------
139
+ // Streaming throw-style API
140
+ // ---------------------------------------------------------------------------
141
+ /**
142
+ * Make a request and return the response body as a ReadableStream.
143
+ * Throws HttpClientError on non-2xx status (after retries).
144
+ *
145
+ * Key differences from `request<T>()`:
146
+ * - Body is NOT consumed or parsed — caller owns the stream lifecycle.
147
+ * - Retry applies to connection establishment only, not stream reading.
148
+ * - Timeout applies to the initial connection, not stream duration; on
149
+ * transport "native" the Go client's timeout covers the whole stream.
150
+ * - Response interceptors do NOT run (they require a parsed `data` field).
151
+ */
152
+ requestStream(method, url, options) {
153
+ return this._executeStream(method, url, options);
154
+ }
155
+ /**
156
+ * POST a request and return the response body as a ReadableStream.
157
+ * The only streaming convenience method provided — it is the only HTTP verb
158
+ * used for streaming in practice (SSE, NDJSON).
159
+ */
160
+ postStream(url, options) {
161
+ return this.requestStream("POST", url, options);
162
+ }
163
+ // ---------------------------------------------------------------------------
164
+ // Result-style API (@eserstack/functions do-notation compatibility)
165
+ // ---------------------------------------------------------------------------
166
+ requestResult(method, url, options) {
167
+ return results.fromPromise(this._execute(method, url, options), toHttpClientError);
168
+ }
169
+ getResult(url, options) {
170
+ return results.fromPromise(this._execute("GET", url, options), toHttpClientError);
171
+ }
172
+ postResult(url, options) {
173
+ return results.fromPromise(this._execute("POST", url, options), toHttpClientError);
174
+ }
175
+ putResult(url, options) {
176
+ return results.fromPromise(this._execute("PUT", url, options), toHttpClientError);
177
+ }
178
+ patchResult(url, options) {
179
+ return results.fromPromise(this._execute("PATCH", url, options), toHttpClientError);
180
+ }
181
+ deleteResult(url, options) {
182
+ return results.fromPromise(this._execute("DELETE", url, options), toHttpClientError);
183
+ }
184
+ // ---------------------------------------------------------------------------
185
+ // Streaming Result-style API
186
+ // ---------------------------------------------------------------------------
187
+ requestStreamResult(method, url, options) {
188
+ return results.fromPromise(this._executeStream(method, url, options), toHttpClientError);
189
+ }
190
+ postStreamResult(url, options) {
191
+ return results.fromPromise(this._executeStream("POST", url, options), toHttpClientError);
192
+ }
193
+ // ---------------------------------------------------------------------------
194
+ // Core implementation
195
+ // ---------------------------------------------------------------------------
196
+ /**
197
+ * Shared retry/timeout/error-handling core.
198
+ * Handles URL building, header merging, body serialization, retry loop,
199
+ * timeout via AbortSignal, rate-limit parsing, and error classification.
200
+ *
201
+ * The `onSuccess` callback is invoked once a 2xx response is received.
202
+ * It receives the raw Response, the sent Request, the retry count, and any
203
+ * extracted rate-limit info. Each public method variant supplies its own
204
+ * onSuccess: _execute parses JSON and runs response interceptors;
205
+ * _executeStream returns the body stream directly.
206
+ *
207
+ * This is the single source of truth for retry/timeout behavior — both
208
+ * _execute and _executeStream delegate entirely to this method, on the
209
+ * fetch and the native transport alike. The loop stays here because it runs
210
+ * the request interceptors before every attempt; the decisions come from
211
+ * the retry policy in Go (retry-policy.ts). `stream` tells the native
212
+ * transport to hand the body over unread.
213
+ */
214
+ async _executeFetch(method, url, options, stream, onSuccess) {
215
+ const delayFn = this.config._delayFn ?? defaultDelayFn;
216
+ // Build URL
217
+ const resolvedUrl = resolveUrl(this.config.baseUrl, url);
218
+ const fullUrl = new URL(resolvedUrl);
219
+ if (options?.params !== undefined) {
220
+ for (const [key, value] of Object.entries(options.params)) {
221
+ fullUrl.searchParams.set(key, value);
222
+ }
223
+ }
224
+ // Merge headers
225
+ const headers = {
226
+ ...(this.config.headers ?? {}),
227
+ ...(options?.headers ?? {}),
228
+ };
229
+ // Handle body
230
+ let body;
231
+ const bodyValue = options?.body;
232
+ if (bodyValue !== undefined) {
233
+ if (typeof bodyValue === "string" ||
234
+ bodyValue instanceof ArrayBuffer ||
235
+ ArrayBuffer.isView(bodyValue) ||
236
+ bodyValue instanceof Blob ||
237
+ bodyValue instanceof FormData ||
238
+ bodyValue instanceof URLSearchParams ||
239
+ bodyValue instanceof ReadableStream) {
240
+ body = bodyValue;
241
+ }
242
+ else if (typeof bodyValue === "object" && bodyValue !== null) {
243
+ body = JSON.stringify(bodyValue);
244
+ if (headers["Content-Type"] === undefined) {
245
+ headers["Content-Type"] = "application/json";
246
+ }
247
+ }
248
+ }
249
+ if (this.config.transport === "native" &&
250
+ body !== undefined &&
251
+ typeof body !== "string" &&
252
+ !(body instanceof URLSearchParams)) {
253
+ throw new errors.HttpClientError(`${method} request: transport "native" sends text bodies only (a string, URLSearchParams, or an object sent as JSON); send binary, form and stream bodies with the default fetch transport`);
254
+ }
255
+ // The retry policy lives in Go: it answers how many attempts this request
256
+ // gets and, after each failed one, whether and how long to wait. A stream
257
+ // body is consumed by the first attempt and cannot be sent again, so a
258
+ // request with one gets one attempt.
259
+ const replayable = !(body instanceof ReadableStream);
260
+ const plan = retryPolicy.resolveRetryPlan(this.config.retry, options?.retry, !replayable);
261
+ const timeout = options?.timeout ?? this.config.timeout ?? DEFAULT_TIMEOUT;
262
+ const requestInterceptors = this.config.interceptors?.request ?? [];
263
+ const fetchFn = await this.#resolveFetch(stream);
264
+ let retries = 0;
265
+ for (let attempt = 0; attempt < plan.maxAttempts; attempt++) {
266
+ if (attempt > 0) {
267
+ retries++;
268
+ }
269
+ let raw;
270
+ let sentRequest;
271
+ try {
272
+ // Build combined abort signal
273
+ const userSignal = options?.signal;
274
+ const timeoutSignal = AbortSignal.timeout(timeout);
275
+ const signal = userSignal !== undefined
276
+ ? AbortSignal.any([timeoutSignal, userSignal])
277
+ : timeoutSignal;
278
+ const init = {
279
+ method,
280
+ headers,
281
+ body,
282
+ signal,
283
+ // Node's fetch requires duplex for a stream body; browsers
284
+ // accept it.
285
+ ...(!replayable && { duplex: "half" }),
286
+ };
287
+ const initRequest = new Request(fullUrl.toString(), init);
288
+ // Attempts are sequential: a retry starts only after this one fails.
289
+ // oxlint-disable-next-line no-await-in-loop
290
+ sentRequest = await interceptors.applyRequestInterceptors(initRequest, requestInterceptors);
291
+ // Attempts are sequential: a retry starts only after this one fails.
292
+ // oxlint-disable-next-line no-await-in-loop
293
+ raw = await fetchFn(sentRequest);
294
+ }
295
+ catch (err) {
296
+ const e = err instanceof Error ? err : new Error(String(err));
297
+ const classified = errors.classifyError(e);
298
+ // Never retry timeout or user abort
299
+ if (classified instanceof errors.HttpTimeoutError ||
300
+ classified instanceof errors.HttpAbortError) {
301
+ throw classified;
302
+ }
303
+ const decision = retryPolicy.nextRetry(plan, attempt, 0, null);
304
+ if (!decision.retry) {
305
+ throw classified;
306
+ }
307
+ // The backoff must elapse before the next attempt starts.
308
+ // oxlint-disable-next-line no-await-in-loop
309
+ await delayFn(decision.delayMs);
310
+ continue;
311
+ }
312
+ // Successful connection — check HTTP status
313
+ const rateLimit = extractRateLimitInfo(raw.headers);
314
+ if (!raw.ok) {
315
+ // The error body decides whether and how this attempt is retried.
316
+ // oxlint-disable-next-line no-await-in-loop
317
+ const errorBody = await extractErrorBody(raw);
318
+ const statusMsg = errorMessageFromBody(errorBody) ?? `HTTP ${raw.status}`;
319
+ const retryAfterMs = rateLimit !== undefined
320
+ ? parseRetryAfterMs(raw.headers.get("Retry-After"))
321
+ : null;
322
+ const httpError = raw.status === 429
323
+ ? new errors.HttpRateLimitError(statusMsg, {
324
+ statusCode: raw.status,
325
+ response: raw,
326
+ body: errorBody,
327
+ ...(retryAfterMs !== null && {
328
+ retryAfter: retryAfterMs / 1_000,
329
+ }),
330
+ })
331
+ : new errors.HttpResponseError(statusMsg, {
332
+ statusCode: raw.status,
333
+ response: raw,
334
+ body: errorBody,
335
+ });
336
+ const decision = retryPolicy.nextRetry(plan, attempt, raw.status, retryAfterMs);
337
+ if (decision.retry) {
338
+ // The backoff, or a 429's Retry-After, must elapse before the next
339
+ // attempt starts.
340
+ // oxlint-disable-next-line no-await-in-loop
341
+ await delayFn(decision.delayMs);
342
+ continue;
343
+ }
344
+ throw httpError;
345
+ }
346
+ // 2xx: delegate to the variant-specific success handler. The await
347
+ // ends the loop; it returns on the first successful attempt.
348
+ // oxlint-disable-next-line no-await-in-loop
349
+ return await onSuccess(raw, sentRequest, retries, rateLimit);
350
+ }
351
+ // Every failed attempt either retries or throws, so the loop only ends
352
+ // here when the plan allows no attempt at all.
353
+ throw new errors.HttpClientError(`Request failed after ${plan.maxAttempts} attempt(s)`);
354
+ }
355
+ /** JSON-parsing variant — parses body, builds HttpResponse<T>, runs response interceptors. */
356
+ _execute(method, url, options) {
357
+ const responseInterceptors = this.config.interceptors?.response ?? [];
358
+ return this._executeFetch(method, url, options, false, async (raw, sentRequest, retries, rateLimit) => {
359
+ // Parse response body
360
+ let data;
361
+ if (raw.status === 204 ||
362
+ raw.status === 304 ||
363
+ raw.headers.get("Content-Length") === "0") {
364
+ data = undefined;
365
+ }
366
+ else {
367
+ const contentType = raw.headers.get("Content-Type") ?? "";
368
+ if (contentType.includes("application/json")) {
369
+ data = (await raw.json());
370
+ }
371
+ else {
372
+ const text = await raw.text();
373
+ try {
374
+ data = JSON.parse(text);
375
+ }
376
+ catch {
377
+ data = text;
378
+ }
379
+ }
380
+ }
381
+ let response = {
382
+ data,
383
+ status: raw.status,
384
+ statusText: raw.statusText,
385
+ headers: raw.headers,
386
+ request: sentRequest,
387
+ raw,
388
+ retries,
389
+ ...(rateLimit !== undefined && { rateLimit }),
390
+ };
391
+ response = await interceptors.applyResponseInterceptors(response, responseInterceptors);
392
+ return response;
393
+ });
394
+ }
395
+ /**
396
+ * Streaming variant — returns body as ReadableStream without consuming it.
397
+ * Response interceptors do NOT run (they require a parsed `data` field).
398
+ * Timeout applies to connection establishment only, not stream reading.
399
+ */
400
+ _executeStream(method, url, options) {
401
+ return this._executeFetch(method, url, options, true, (raw, sentRequest, retries, rateLimit) => {
402
+ if (raw.body === null) {
403
+ return Promise.reject(new errors.HttpNetworkError("Response body is null — server sent no body for a streaming request"));
404
+ }
405
+ return Promise.resolve({
406
+ body: raw.body,
407
+ status: raw.status,
408
+ statusText: raw.statusText,
409
+ headers: raw.headers,
410
+ request: sentRequest,
411
+ raw,
412
+ retries,
413
+ ...(rateLimit !== undefined && { rateLimit }),
414
+ });
415
+ });
416
+ }
417
+ // ---------------------------------------------------------------------------
418
+ // Transport
419
+ // ---------------------------------------------------------------------------
420
+ /**
421
+ * The function that sends one Request: `fetchFn` or the global fetch, or the
422
+ * Go client for `transport: "native"`.
423
+ */
424
+ async #resolveFetch(stream) {
425
+ if (this.config.transport !== "native") {
426
+ return this.config.fetchFn ?? fetch;
427
+ }
428
+ return goTransport.createGoFetch(await this.#nativeClient(), stream);
429
+ }
430
+ /** Creates the Go client on first use and reuses it until `close()`. */
431
+ #nativeClient() {
432
+ if (this.#goClientInit !== null) {
433
+ return this.#goClientInit;
434
+ }
435
+ const create = this.config._createGoClient ?? goClientModule.createGoHttpClient;
436
+ // The Go client's own retries stay off: the retry policy of this client
437
+ // (retry-policy.ts) runs on both transports. The Go timeout bounds each
438
+ // blocking call.
439
+ const init = create({
440
+ timeoutMs: this.config.timeout ?? DEFAULT_TIMEOUT,
441
+ }).catch((cause) => {
442
+ throw new errors.HttpClientError('transport "native": the Go HTTP client could not be created; remove transport: "native" to send requests with fetch', { cause: cause instanceof Error ? cause : new Error(String(cause)) });
443
+ });
444
+ this.#goClientInit = init;
445
+ return init;
446
+ }
447
+ /** Release the Go HTTP client handle that `transport: "native"` opened. */
448
+ close() {
449
+ const init = this.#goClientInit;
450
+ this.#goClientInit = null;
451
+ init?.then((client) => client.close(), () => {
452
+ // Creation failed, so there is no handle to release.
453
+ });
454
+ }
455
+ }
456
+ // =============================================================================
457
+ // Factory
458
+ // =============================================================================
459
+ export const createHttpClient = (config) => new HttpClient(config);
460
+ // =============================================================================
461
+ // Internal Utilities
462
+ // =============================================================================
463
+ const toHttpClientError = (e) => {
464
+ if (e instanceof errors.HttpClientError)
465
+ return e;
466
+ const err = e instanceof Error ? e : new Error(String(e));
467
+ return new errors.HttpClientError(err.message, { cause: err });
468
+ };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Typed HTTP error hierarchy for @eserstack/httpclient.
3
+ *
4
+ * Replaces the duplicated status-code classification logic in:
5
+ * - @eserstack/ai/errors.ts (classifyStatusCode / classifyAndWrap)
6
+ * - @eserstack/posts adapters (extractError helpers)
7
+ *
8
+ * After migration, those packages import from here instead.
9
+ *
10
+ * @module
11
+ */
12
+ export interface HttpClientErrorOptions {
13
+ statusCode?: number;
14
+ request?: Request;
15
+ response?: Response;
16
+ body?: unknown;
17
+ retryAfter?: number;
18
+ cause?: Error;
19
+ }
20
+ export declare class HttpClientError extends Error {
21
+ readonly statusCode: number | null;
22
+ readonly request: Request | null;
23
+ readonly response: Response | null;
24
+ readonly body: unknown;
25
+ readonly retryAfter: number | null;
26
+ constructor(message: string, options?: HttpClientErrorOptions);
27
+ }
28
+ /** Non-2xx HTTP response (generic). */
29
+ export declare class HttpResponseError extends HttpClientError {
30
+ readonly code: "RESPONSE_ERROR";
31
+ constructor(message: string, options?: HttpClientErrorOptions);
32
+ }
33
+ /** Request timed out via AbortSignal.timeout(). */
34
+ export declare class HttpTimeoutError extends HttpClientError {
35
+ readonly code: "TIMEOUT";
36
+ constructor(message: string, options?: HttpClientErrorOptions);
37
+ }
38
+ /** Request aborted via a user-supplied AbortSignal. */
39
+ export declare class HttpAbortError extends HttpClientError {
40
+ readonly code: "ABORT_ERROR";
41
+ constructor(message: string, options?: HttpClientErrorOptions);
42
+ }
43
+ /** HTTP 429 Too Many Requests. */
44
+ export declare class HttpRateLimitError extends HttpClientError {
45
+ readonly code: "RATE_LIMITED";
46
+ constructor(message: string, options?: HttpClientErrorOptions);
47
+ }
48
+ /** DNS lookup or TCP connection failure (no HTTP response received). */
49
+ export declare class HttpNetworkError extends HttpClientError {
50
+ readonly code: "NETWORK_ERROR";
51
+ constructor(message: string, options?: HttpClientErrorOptions);
52
+ }
53
+ /**
54
+ * Maps an HTTP status code to the appropriate error class.
55
+ * Returns null for status codes that don't have a dedicated type.
56
+ *
57
+ * Replaces @eserstack/ai/errors.ts:classifyStatusCode with HTTP-generic semantics
58
+ * (no AI-specific codes, no provider field).
59
+ */
60
+ export declare const classifyHttpStatus: (statusCode: number) => typeof HttpClientError | null;
61
+ /**
62
+ * Converts a native Error (or existing HttpClientError) to the most specific
63
+ * HttpClientError subclass. Inspects error.name for timeout/abort signals.
64
+ */
65
+ export declare const classifyError: (error: Error, response?: Response) => HttpClientError;
66
+ /**
67
+ * Wrap a native Error with a classified HttpClientError based on status code.
68
+ * Replaces @eserstack/ai/errors.ts:classifyAndWrap — no provider field here.
69
+ */
70
+ export declare const classifyAndWrap: (statusCode: number, original: Error, options?: Omit<HttpClientErrorOptions, "statusCode" | "cause">) => HttpClientError;
package/dist/errors.js ADDED
@@ -0,0 +1,132 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ // =============================================================================
3
+ // Error Hierarchy
4
+ // =============================================================================
5
+ export class HttpClientError extends Error {
6
+ statusCode;
7
+ request;
8
+ response;
9
+ body;
10
+ retryAfter;
11
+ constructor(message, options) {
12
+ super(message, { cause: options?.cause });
13
+ this.name = "HttpClientError";
14
+ this.statusCode = options?.statusCode ?? null;
15
+ this.request = options?.request ?? null;
16
+ this.response = options?.response ?? null;
17
+ this.body = options?.body;
18
+ this.retryAfter = options?.retryAfter ?? null;
19
+ }
20
+ }
21
+ /** Non-2xx HTTP response (generic). */
22
+ export class HttpResponseError extends HttpClientError {
23
+ code = "RESPONSE_ERROR";
24
+ constructor(message, options) {
25
+ super(message, options);
26
+ this.name = "HttpResponseError";
27
+ }
28
+ }
29
+ /** Request timed out via AbortSignal.timeout(). */
30
+ export class HttpTimeoutError extends HttpClientError {
31
+ code = "TIMEOUT";
32
+ constructor(message, options) {
33
+ super(message, options);
34
+ this.name = "HttpTimeoutError";
35
+ }
36
+ }
37
+ /** Request aborted via a user-supplied AbortSignal. */
38
+ export class HttpAbortError extends HttpClientError {
39
+ code = "ABORT_ERROR";
40
+ constructor(message, options) {
41
+ super(message, options);
42
+ this.name = "HttpAbortError";
43
+ }
44
+ }
45
+ /** HTTP 429 Too Many Requests. */
46
+ export class HttpRateLimitError extends HttpClientError {
47
+ code = "RATE_LIMITED";
48
+ constructor(message, options) {
49
+ super(message, options);
50
+ this.name = "HttpRateLimitError";
51
+ }
52
+ }
53
+ /** DNS lookup or TCP connection failure (no HTTP response received). */
54
+ export class HttpNetworkError extends HttpClientError {
55
+ code = "NETWORK_ERROR";
56
+ constructor(message, options) {
57
+ super(message, options);
58
+ this.name = "HttpNetworkError";
59
+ }
60
+ }
61
+ // =============================================================================
62
+ // Classification Utilities
63
+ // =============================================================================
64
+ /**
65
+ * Maps an HTTP status code to the appropriate error class.
66
+ * Returns null for status codes that don't have a dedicated type.
67
+ *
68
+ * Replaces @eserstack/ai/errors.ts:classifyStatusCode with HTTP-generic semantics
69
+ * (no AI-specific codes, no provider field).
70
+ */
71
+ export const classifyHttpStatus = (statusCode) => {
72
+ if (statusCode === 429)
73
+ return HttpRateLimitError;
74
+ if (statusCode >= 500 && statusCode <= 599)
75
+ return HttpResponseError;
76
+ if (statusCode === 408)
77
+ return HttpResponseError;
78
+ return null;
79
+ };
80
+ /**
81
+ * Converts a native Error (or existing HttpClientError) to the most specific
82
+ * HttpClientError subclass. Inspects error.name for timeout/abort signals.
83
+ */
84
+ export const classifyError = (error, response) => {
85
+ if (error instanceof HttpClientError)
86
+ return error;
87
+ // DOMException: TimeoutError from AbortSignal.timeout()
88
+ if (error.name === "TimeoutError") {
89
+ return new HttpTimeoutError(error.message, {
90
+ cause: error,
91
+ ...(response !== undefined && {
92
+ statusCode: response.status,
93
+ response,
94
+ }),
95
+ });
96
+ }
97
+ // DOMException: AbortError from user-supplied AbortSignal
98
+ if (error.name === "AbortError") {
99
+ return new HttpAbortError(error.message, { cause: error });
100
+ }
101
+ if (response !== undefined) {
102
+ const ErrorClass = classifyHttpStatus(response.status);
103
+ const opts = {
104
+ statusCode: response.status,
105
+ response,
106
+ cause: error,
107
+ };
108
+ return ErrorClass !== null
109
+ ? new ErrorClass(error.message, opts)
110
+ : new HttpResponseError(error.message, opts);
111
+ }
112
+ // Network-level failures (no response)
113
+ if (error.message.includes("Failed to fetch") ||
114
+ error.message.includes("fetch failed") ||
115
+ error.message.includes("ECONNREFUSED") ||
116
+ error.message.includes("ENOTFOUND")) {
117
+ return new HttpNetworkError(error.message, { cause: error });
118
+ }
119
+ return new HttpClientError(error.message, { cause: error });
120
+ };
121
+ /**
122
+ * Wrap a native Error with a classified HttpClientError based on status code.
123
+ * Replaces @eserstack/ai/errors.ts:classifyAndWrap — no provider field here.
124
+ */
125
+ export const classifyAndWrap = (statusCode, original, options) => {
126
+ const ErrorClass = classifyHttpStatus(statusCode) ?? HttpResponseError;
127
+ return new ErrorClass(original.message, {
128
+ ...options,
129
+ statusCode,
130
+ cause: original,
131
+ });
132
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * This package's view of the Go bridge.
3
+ *
4
+ * The loader itself lives in `@eserstack/ajan/ffi/client` and is shared with
5
+ * every other package, so the whole process opens the library once. This module
6
+ * stays as the import path the package's own code already uses.
7
+ */
8
+ export { describeLoadFailure, ensureLib, getLib, getLoadError, requireLibSync, } from "@eserstack/ajan/ffi/client";
9
+ export { registerRequestSignal } from "@eserstack/ajan/ffi/request-signals";