arthron 1.0.0 → 1.1.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/index.d.mts CHANGED
@@ -1,167 +1,4 @@
1
- //#region src/types/request.types.d.ts
2
- /**
3
- * What plugins see and return. `init.headers` is always a plain record with
4
- * lowercased names — spread it, read it, add to it — and the pipeline puts
5
- * it back into that shape after every request interceptor.
6
- */
7
- interface RequestContext {
8
- url: string;
9
- init: Omit<RequestInit, "headers"> & {
10
- headers: Record<string, string>;
11
- };
12
- /** Per-call settings for plugins (`RequestOptions.meta`); never sent. */
13
- meta: ArthronMeta;
14
- }
15
- /**
16
- * Per-call settings for plugins, passed as `api.get(path, { meta })` and
17
- * carried next to `init` — never sent to fetch. The built-in plugins read
18
- * `retry` and `timeout`; your own add keys by augmentation:
19
- *
20
- * ```ts
21
- * declare module "arthron" {
22
- * interface ArthronMeta { skipAuth?: boolean }
23
- * }
24
- * ```
25
- */
26
- interface ArthronMeta {
27
- /** `false` turns `retry()` off for this call; an object overrides its options. */
28
- retry?: false | Omit<RetryOptions, "sleep">;
29
- /** Deadline for this call in ms, overriding `timeout(ms)`. `Infinity` lifts it. */
30
- timeout?: number;
31
- }
32
- type RetryOptions = {
33
- /** Number of retries after the first attempt. Default 2 (3 requests total). */
34
- retries?: number;
35
- /** Statuses worth retrying. Network errors (status 0) always are. */
36
- retryOn?: readonly number[];
37
- /** Methods safe to repeat (QUERY is, per RFC 10008). Compared case-insensitively. */
38
- methods?: readonly string[];
39
- /**
40
- * Backoff in ms for retry number `retry` (0-based). Default "full jitter":
41
- * a random share of 300 · 2^retry, so clients that failed together do not
42
- * retry together.
43
- */
44
- delay?: (retry: number, error: unknown) => number;
45
- /**
46
- * Your own verdict on one failure: `true` retries, `false` stops,
47
- * `undefined` leaves it to `retryOn`/`methods`. It sees every error — a
48
- * TimeoutError from a `timeout()` placed after `retry()` included — but
49
- * cannot exceed `retries`, resend a `ReadableStream` body, or retry a call
50
- * the caller aborted.
51
- */
52
- shouldRetry?: (error: unknown, attempt: number, ctx: RequestContext) => boolean | undefined;
53
- /** Called before each wait, for logs and metrics. */
54
- onRetry?: (error: unknown, attempt: number, waitMs: number) => void;
55
- /** Injectable for tests. Default `setTimeout`; rejects with the abort reason. */
56
- sleep?: (ms: number, signal?: AbortSignal | null) => Promise<void>;
57
- /**
58
- * Longest `Retry-After` (ms) worth honouring. Beyond it the request is not
59
- * retried at all. Default 60 000.
60
- */
61
- maxRetryAfter?: number;
62
- };
63
- type QueryValue = string | number | boolean | null | undefined;
64
- /**
65
- * Query parameters. `null`/`undefined` values are skipped, an array becomes
66
- * repeated keys (`ids=1&ids=2`), and a `URLSearchParams` is used as is.
67
- */
68
- type QueryParams = Record<string, QueryValue | readonly QueryValue[]> | URLSearchParams;
69
- /**
70
- * Headers as config and per-call options accept them: any `HeadersInit`, or a
71
- * plain object whose `null`/`undefined` values delete that header from the
72
- * layer underneath (a client default, an inherited header).
73
- */
74
- type HeadersOption = HeadersInit | Record<string, string | null | undefined>;
75
- //#endregion
76
- //#region src/error/arthron-error.d.ts
77
- type ArthronErrorInit = {
78
- message: string;
79
- status: number;
80
- statusText: string;
81
- headers: Headers;
82
- data: unknown;
83
- detail?: string | undefined;
84
- request: RequestContext;
85
- response?: Response;
86
- cause?: unknown;
87
- };
88
- /**
89
- * The only error arthron itself produces. Two sources: a response with
90
- * `ok === false`, or fetch rejecting outright (network failure, `status` 0).
91
- * Everything else — cancellation, interceptor bugs — is rethrown untouched.
92
- */
93
- export declare class ArthronError extends Error {
94
- readonly name = "ArthronError";
95
- /** HTTP status of the failed response; `0` when fetch itself failed (network). */
96
- readonly status: number;
97
- readonly statusText: string;
98
- /** Response headers; empty for network failures. Not enumerable — kept out of logs. */
99
- readonly headers: Headers;
100
- /** Parsed body: JSON if it parses, else the text, else `undefined`. */
101
- readonly data: unknown;
102
- /**
103
- * The server's own explanation, picked out of `data` (by default
104
- * `message` → `error` → `error.message` → `detail`; see the `errorDetail`
105
- * config). `undefined` when the body had none. Untrusted server text: show
106
- * it to users as text, never as HTML. `message`, by contrast, is written by
107
- * arthron — method, URL without query, status — and is meant for logs.
108
- */
109
- readonly detail: string | undefined;
110
- /**
111
- * The context that was sent — url and init after request interceptors.
112
- * Not enumerable: it holds credentials, so `JSON.stringify`, `console.error`
113
- * and error trackers leave it out. Read it directly when you need it.
114
- */
115
- readonly request: RequestContext;
116
- /** The failed Response, still readable — its body holds what arthron read (at most 64 KiB). Absent for network failures. Not enumerable. */
117
- readonly response: Response | undefined;
118
- /** The underlying error for network failures. */
119
- readonly cause: unknown;
120
- constructor(init: ArthronErrorInit);
121
- /** `instanceof ArthronError` holds for an error from any copy of the package. */
122
- static [Symbol.hasInstance](value: unknown): boolean;
123
- /** What serializers see: no headers, no body, no query or userinfo. */
124
- toJSON(): {
125
- name: string;
126
- message: string;
127
- detail: string | undefined;
128
- status: number;
129
- statusText: string;
130
- method: string;
131
- url: string;
132
- data: unknown;
133
- };
134
- }
135
- /** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
136
- export declare function isArthronError(error: unknown): error is ArthronError;
137
- //#endregion
138
- //#region src/types/plugin.types.d.ts
139
- /** Runs before each attempt. Returns the context to send (may be a new object). */
140
- type RequestInterceptor = (ctx: RequestContext) => RequestContext | Promise<RequestContext>;
141
- /** Runs after a successful attempt. The body is single-use — `clone()` to peek. */
142
- type ResponseInterceptor = (res: Response, ctx: RequestContext) => Response | Promise<Response>;
143
- /** Runs after a failed attempt. Returns the error to throw; it is always thrown. */
144
- type ErrorInterceptor = (err: ArthronError, ctx: RequestContext) => ArthronError | Promise<ArthronError>;
145
- /**
146
- * Wraps the whole call. `next` runs everything below it (request interceptors →
147
- * fetch → response/error interceptors) and may be called again to retry.
148
- * `next` rejects with an `ArthronError`, or with the untouched original when the
149
- * failure was a cancellation or a bug in a plugin.
150
- */
151
- type Middleware = (ctx: RequestContext, next: (ctx: RequestContext) => Promise<Response>) => Promise<Response>;
152
- interface Plugin {
153
- /**
154
- * Identity within a client: `use`/`extend` replace the plugin of the same
155
- * name in place, `without(name)` removes it. The built-ins are named
156
- * "retry", "timeout" and "logging". Leave it out to always append.
157
- */
158
- name?: string;
159
- middleware?: Middleware;
160
- request?: RequestInterceptor;
161
- response?: ResponseInterceptor;
162
- error?: ErrorInterceptor;
163
- }
164
- //#endregion
1
+ import { _ as HeadersOption, a as LogEvent$1, b as RetryOptions, d as Plugin, f as RequestInterceptor, g as ArthronMeta, h as isArthronError, i as logging$1, l as ErrorInterceptor, m as ArthronError, n as TimeoutOptions$1, o as LoggingOptions$1, p as ResponseInterceptor, r as retry$1, t as timeout$1, u as Middleware, v as QueryParams, y as RequestContext } from "./index-Bz1P80JN.mjs";
165
2
  //#region src/types/response.types.d.ts
166
3
  interface ArthronPromise extends Promise<Response> {
167
4
  /** The body as JSON. `T` is a cast — nothing checks it. */
@@ -353,79 +190,6 @@ export declare const defineInterceptor: {
353
190
  /** Identity helper: type-checks a plugin object literal without an annotation. */
354
191
  export declare const definePlugin: (plugin: Plugin) => Plugin;
355
192
  //#endregion
356
- //#region src/plugins/logging/logging.types.d.ts
357
- type LogEventBase = {
358
- method: string;
359
- path: string;
360
- };
361
- type LogEvent = ({
362
- phase: "start";
363
- } & LogEventBase) | ({
364
- phase: "success";
365
- status: number;
366
- ms: number;
367
- } & LogEventBase) | ({
368
- phase: "error";
369
- /** HTTP status for an ArthronError (0 = network); undefined for anything else. */
370
- status: number | undefined;
371
- ms: number;
372
- error: unknown;
373
- } & LogEventBase);
374
- type LoggingOptions = {
375
- /** Default `true`. The library never reads `NODE_ENV` — pass `isDev` yourself. */
376
- enabled?: boolean;
377
- logger?: Pick<Console, "log" | "error">;
378
- /** Receive structured events instead of the default console lines. */
379
- onEvent?: (event: LogEvent) => void;
380
- /** Clock in ms. Injectable for tests. */
381
- now?: () => number;
382
- };
383
- //#endregion
384
- //#region src/plugins/logging/logging.d.ts
385
- /**
386
- * One event when a request starts, one when it settles, with status and
387
- * elapsed time. Wraps the whole call, so retries are included in the time.
388
- * Default output is a console line per event; pass `onEvent` to get the
389
- * structured event instead. Cancellations are not reported.
390
- */
391
- export declare function logging(options?: LoggingOptions): Plugin;
392
- //#endregion
393
- //#region src/plugins/retry/retry.d.ts
394
- /**
395
- * Retry on network errors and the configured statuses by calling `next`
396
- * again — the whole attempt (request interceptors included) is re-run.
397
- * Only `ArthronError` is considered; cancellation and plugin bugs pass through.
398
- * A call can turn it off or override its options with `meta.retry`.
399
- */
400
- export declare function retry(options?: RetryOptions): Plugin;
401
- //#endregion
402
- //#region src/plugins/timeout/timeout.types.d.ts
403
- type TimeoutOptions = {
404
- /**
405
- * Also abort when no data has arrived for this many ms — while waiting for
406
- * the headers and between body chunks. Unlike the total deadline, a stream
407
- * that keeps flowing is never cut off: `timeout(Infinity, { idle: 30_000 })`.
408
- */
409
- idle?: number;
410
- };
411
- //#endregion
412
- //#region src/plugins/timeout/timeout.d.ts
413
- /**
414
- * Abort the request when it takes longer than `ms` — counted from the start
415
- * of the attempt until the body has been fully read, so a server that sends
416
- * headers and then stalls still trips it. With `idle`, also abort once no
417
- * data has arrived for that long. Rejects with a `TimeoutError` (a
418
- * `DOMException`, like `AbortSignal.timeout()` would give); it is not an
419
- * `ArthronError`, so error interceptors and `retry` leave it alone.
420
- *
421
- * A call can change the total deadline with `meta.timeout`.
422
- *
423
- * Deadlines are timers on an AbortController — not `AbortSignal.timeout`,
424
- * since the idle one restarts — joined to the caller's signal with
425
- * `AbortSignal.any`.
426
- */
427
- export declare function timeout(ms: number, options?: TimeoutOptions): Plugin;
428
- //#endregion
429
193
  //#region src/response/schema-validation.d.ts
430
194
  /**
431
195
  * `.json(schema)` got a body that does not match. Not an ArthronError: the
@@ -438,5 +202,19 @@ export declare class SchemaError extends Error {
438
202
  constructor(issues: readonly SchemaIssue[]);
439
203
  }
440
204
  //#endregion
441
- export type { Arthron, ArthronConfig, ArthronMeta, ArthronPromise, ErrorDetailResolver, ErrorInterceptor, HeadersOption, HttpMethod, InferOutput, LogEvent, LoggingOptions, Middleware, NdjsonOptions, Plugin, QueryParams, RequestContext, RequestInitWithBody, RequestInterceptor, RequestOptions, ResponseInterceptor, RetryOptions, SchemaIssue, SseEvent, SseOptions, StandardSchemaV1, TimeoutOptions };
205
+ //#region src/index.d.ts
206
+ /** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
207
+ export declare const logging: typeof logging$1;
208
+ /** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
209
+ export declare const retry: typeof retry$1;
210
+ /** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
211
+ export declare const timeout: typeof timeout$1;
212
+ /** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
213
+ export type LogEvent = LogEvent$1;
214
+ /** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
215
+ export type LoggingOptions = LoggingOptions$1;
216
+ /** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
217
+ export type TimeoutOptions = TimeoutOptions$1;
218
+ //#endregion
219
+ export { type Arthron, type ArthronConfig, ArthronError, type ArthronMeta, type ArthronPromise, type ErrorDetailResolver, type ErrorInterceptor, type HeadersOption, type HttpMethod, type InferOutput, type Middleware, type NdjsonOptions, type Plugin, type QueryParams, type RequestContext, type RequestInitWithBody, type RequestInterceptor, type RequestOptions, type ResponseInterceptor, type RetryOptions, type SchemaIssue, type SseEvent, type SseOptions, type StandardSchemaV1, isArthronError };
442
220
  //# sourceMappingURL=index.d.mts.map