@npora/request 1.0.1 → 1.2.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 CHANGED
@@ -123,7 +123,9 @@ const cache = cachePlugin()
123
123
  const request = createClient()
124
124
  .use(retryPlugin({
125
125
  retries: 2,
126
- delay: 200
126
+ delay: 200,
127
+ jitter: true,
128
+ maxElapsedTime: 10000
127
129
  }))
128
130
  .use(cache)
129
131
  .use(authPlugin({
@@ -155,6 +157,27 @@ Built-in plugins:
155
157
  Plugin-owned request options belong under `extensions`. Third-party plugins can
156
158
  augment `RequestExtensions` through TypeScript module augmentation.
157
159
 
160
+ Inject a structured logger when request correlation and timing are needed:
161
+
162
+ ```ts
163
+ const request = createClient().use(
164
+ loggerPlugin({
165
+ logger: {
166
+ info(_message, entry) {
167
+ applicationLogger.info(entry)
168
+ },
169
+ error(_message, entry) {
170
+ applicationLogger.error(entry)
171
+ }
172
+ }
173
+ })
174
+ )
175
+ ```
176
+
177
+ Lifecycle entries include a request identifier and timestamp. Completed
178
+ responses include total duration and attempt count; errors include the failed
179
+ attempt number. The default logger continues to use `console`.
180
+
158
181
  ## Interceptors
159
182
 
160
183
  ```ts
package/dist/index.cjs CHANGED
@@ -683,6 +683,7 @@ function setHeader(headers, key, value) {
683
683
  // src/core/RequestContext.ts
684
684
  var RequestContext = class {
685
685
  constructor(config) {
686
+ this.attempt = 0;
686
687
  this.config = config;
687
688
  this.startTime = Date.now();
688
689
  }
@@ -757,6 +758,7 @@ var Pipeline = class {
757
758
  context.error = void 0;
758
759
  context.response = void 0;
759
760
  attempt += 1;
761
+ context.attempt = attempt;
760
762
  try {
761
763
  await waitForRetry(
762
764
  decision.delay ?? 0,
@@ -2097,58 +2099,118 @@ function createProgress2(loaded, total) {
2097
2099
 
2098
2100
  // src/plugins/loggerPlugin.ts
2099
2101
  function loggerPlugin(defaultOptions = {}) {
2102
+ let nextRequestId = 0;
2103
+ const states = /* @__PURE__ */ new WeakMap();
2100
2104
  return {
2101
2105
  name: "logger",
2102
2106
  install(context) {
2103
- context.interceptors.request.use((config) => {
2104
- const logger = resolveExtensionConfig(
2105
- config,
2107
+ context.hooks.onRequest((requestContext) => {
2108
+ const options = resolveExtensionConfig(
2109
+ requestContext.config,
2106
2110
  "logger"
2107
2111
  ) ?? defaultOptions;
2108
- if (logger.enabled === false) {
2109
- return config;
2112
+ if (options.enabled === false) {
2113
+ return;
2110
2114
  }
2111
- console.log("[Npora Request]", {
2115
+ const state = {
2116
+ requestId: options.createRequestId?.() ?? `request-${++nextRequestId}`,
2117
+ options
2118
+ };
2119
+ states.set(requestContext, state);
2120
+ emitInfo(options, {
2112
2121
  type: "request",
2113
- method: config.method ?? "GET",
2114
- url: redactURL(config.url)
2122
+ requestId: state.requestId,
2123
+ timestamp: requestContext.startTime,
2124
+ method: requestContext.config.method ?? "GET",
2125
+ url: redactURL(requestContext.config.url)
2115
2126
  });
2116
- return config;
2117
2127
  });
2118
- context.interceptors.response.use((response) => {
2119
- const logger = resolveExtensionConfig(
2120
- response.config,
2121
- "logger"
2122
- ) ?? defaultOptions;
2123
- if (logger.enabled === false) {
2124
- return response;
2128
+ context.hooks.onResponse((requestContext) => {
2129
+ const state = states.get(requestContext);
2130
+ if (!state || !requestContext.response) {
2131
+ return;
2125
2132
  }
2126
- console.log("[Npora Request]", {
2133
+ const timestamp = Date.now();
2134
+ emitInfo(state.options, {
2127
2135
  type: "response",
2128
- method: response.config.method ?? "GET",
2129
- url: redactURL(response.config.url),
2130
- status: response.status
2136
+ requestId: state.requestId,
2137
+ timestamp,
2138
+ duration: Math.max(0, timestamp - requestContext.startTime),
2139
+ attempts: requestContext.attempt + 1,
2140
+ method: requestContext.config.method ?? "GET",
2141
+ url: redactURL(requestContext.config.url),
2142
+ status: requestContext.response.status
2131
2143
  });
2132
- return response;
2133
2144
  });
2134
- context.interceptors.error.use((error) => {
2135
- const config = error instanceof RequestError ? error.config : void 0;
2136
- const logger = config ? resolveExtensionConfig(
2137
- config,
2138
- "logger"
2139
- ) ?? defaultOptions : defaultOptions;
2140
- if (logger.enabled === false) {
2141
- return error;
2145
+ context.hooks.onError((requestContext) => {
2146
+ let state = states.get(requestContext);
2147
+ if (!state) {
2148
+ const options = resolveExtensionConfig(
2149
+ requestContext.config,
2150
+ "logger"
2151
+ ) ?? defaultOptions;
2152
+ if (options.enabled === false) {
2153
+ return;
2154
+ }
2155
+ state = {
2156
+ requestId: options.createRequestId?.() ?? `request-${++nextRequestId}`,
2157
+ options
2158
+ };
2159
+ states.set(requestContext, state);
2160
+ emitInfo(options, {
2161
+ type: "request",
2162
+ requestId: state.requestId,
2163
+ timestamp: requestContext.startTime,
2164
+ method: requestContext.config.method ?? "GET",
2165
+ url: redactURL(requestContext.config.url)
2166
+ });
2142
2167
  }
2143
- console.error(
2144
- "[Npora Request]",
2145
- createErrorLog(error)
2168
+ const timestamp = Date.now();
2169
+ emitError(
2170
+ state.options,
2171
+ createErrorLog(
2172
+ requestContext.error,
2173
+ state.requestId,
2174
+ timestamp,
2175
+ Math.max(0, timestamp - requestContext.startTime),
2176
+ requestContext.attempt + 1,
2177
+ requestContext.config.method ?? "GET",
2178
+ redactURL(requestContext.config.url)
2179
+ )
2146
2180
  );
2147
- return error;
2148
2181
  });
2149
2182
  }
2150
2183
  };
2151
2184
  }
2185
+ var consoleLogger = {
2186
+ info(message, entry) {
2187
+ console.log(message, entry);
2188
+ },
2189
+ error(message, entry) {
2190
+ console.error(message, entry);
2191
+ }
2192
+ };
2193
+ function resolveLogger(options) {
2194
+ return options.logger ?? consoleLogger;
2195
+ }
2196
+ function emitInfo(options, entry) {
2197
+ try {
2198
+ void Promise.resolve(
2199
+ resolveLogger(options).info("[Npora Request]", entry)
2200
+ ).catch(ignoreLoggerError);
2201
+ } catch {
2202
+ }
2203
+ }
2204
+ function emitError(options, entry) {
2205
+ try {
2206
+ void Promise.resolve(
2207
+ resolveLogger(options).error("[Npora Request]", entry)
2208
+ ).catch(ignoreLoggerError);
2209
+ } catch {
2210
+ }
2211
+ }
2212
+ function ignoreLoggerError() {
2213
+ }
2152
2214
  var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2153
2215
  "access_token",
2154
2216
  "api-key",
@@ -2210,27 +2272,35 @@ function findAuthorityEnd(url, authorityStart) {
2210
2272
  }
2211
2273
  return url.length;
2212
2274
  }
2213
- function createErrorLog(error) {
2275
+ function createErrorLog(error, requestId, timestamp, duration, attempt, method, url) {
2276
+ const lifecycle = {
2277
+ type: "error",
2278
+ requestId,
2279
+ timestamp,
2280
+ duration,
2281
+ attempt,
2282
+ method,
2283
+ url
2284
+ };
2214
2285
  if (error instanceof RequestError) {
2215
2286
  return {
2216
- type: "error",
2287
+ ...lifecycle,
2217
2288
  name: error.name,
2218
2289
  message: error.message,
2219
2290
  code: error.code,
2220
- status: error.status,
2221
- method: error.config?.method ?? "GET",
2222
- url: error.config ? redactURL(error.config.url) : void 0
2291
+ status: error.status
2223
2292
  };
2224
2293
  }
2225
2294
  if (error instanceof Error) {
2226
2295
  return {
2227
- type: "error",
2296
+ ...lifecycle,
2228
2297
  name: error.name,
2229
2298
  message: error.message
2230
2299
  };
2231
2300
  }
2232
2301
  return {
2233
- type: "error",
2302
+ ...lifecycle,
2303
+ name: "UnknownError",
2234
2304
  message: String(error)
2235
2305
  };
2236
2306
  }
@@ -2279,12 +2349,43 @@ function retryPlugin(defaultOptions = {}) {
2279
2349
  requestContext.error
2280
2350
  );
2281
2351
  const retryAfter = retryOptions.respectRetryAfter ? parseRetryAfter(requestContext.error) : void 0;
2352
+ const baseDelay = normalizeRetryDelay(
2353
+ retryAfter ?? configuredDelay,
2354
+ retryOptions.maxDelay
2355
+ );
2356
+ const elapsedTime = Math.max(
2357
+ 0,
2358
+ Date.now() - requestContext.startTime
2359
+ );
2360
+ const pendingEvent = {
2361
+ attempt: attempt + 1,
2362
+ delay: baseDelay,
2363
+ elapsedTime,
2364
+ error: requestContext.error
2365
+ };
2366
+ const jitteredDelay = retryAfter === void 0 ? await applyJitter(
2367
+ retryOptions.jitter,
2368
+ pendingEvent
2369
+ ) : baseDelay;
2370
+ const delay = normalizeRetryDelay(
2371
+ jitteredDelay,
2372
+ retryOptions.maxDelay
2373
+ );
2374
+ const event = {
2375
+ ...pendingEvent,
2376
+ delay
2377
+ };
2378
+ if (exceedsElapsedTimeBudget(
2379
+ elapsedTime,
2380
+ delay,
2381
+ retryOptions.maxElapsedTime
2382
+ )) {
2383
+ return void 0;
2384
+ }
2385
+ notifyRetry(retryOptions.onRetry, event);
2282
2386
  return {
2283
2387
  retry: true,
2284
- delay: normalizeRetryDelay(
2285
- retryAfter ?? configuredDelay,
2286
- retryOptions.maxDelay
2287
- )
2388
+ delay
2288
2389
  };
2289
2390
  });
2290
2391
  }
@@ -2298,7 +2399,12 @@ function normalizeRetryOptions(retry, defaults = {}) {
2298
2399
  delay: normalizeDelay(defaults.delay),
2299
2400
  respectRetryAfter: defaults.respectRetryAfter ?? true,
2300
2401
  maxDelay: normalizeMaxDelay(defaults.maxDelay),
2301
- shouldRetry: defaults.shouldRetry ?? defaultShouldRetry
2402
+ jitter: defaults.jitter ?? false,
2403
+ maxElapsedTime: normalizeMaxElapsedTime(
2404
+ defaults.maxElapsedTime
2405
+ ),
2406
+ shouldRetry: defaults.shouldRetry ?? defaultShouldRetry,
2407
+ onRetry: defaults.onRetry
2302
2408
  };
2303
2409
  }
2304
2410
  return {
@@ -2315,7 +2421,12 @@ function normalizeRetryOptions(retry, defaults = {}) {
2315
2421
  maxDelay: normalizeMaxDelay(
2316
2422
  retry?.maxDelay ?? defaults.maxDelay
2317
2423
  ),
2318
- shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry
2424
+ jitter: retry?.jitter ?? defaults.jitter ?? false,
2425
+ maxElapsedTime: normalizeMaxElapsedTime(
2426
+ retry?.maxElapsedTime ?? defaults.maxElapsedTime
2427
+ ),
2428
+ shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry,
2429
+ onRetry: retry?.onRetry ?? defaults.onRetry
2319
2430
  };
2320
2431
  }
2321
2432
  function normalizeMethods(methods) {
@@ -2336,6 +2447,15 @@ function normalizeRetries(retries) {
2336
2447
  }
2337
2448
  return Math.max(0, Math.floor(retries));
2338
2449
  }
2450
+ function normalizeMaxElapsedTime(maxElapsedTime) {
2451
+ if (maxElapsedTime === void 0) {
2452
+ return Number.POSITIVE_INFINITY;
2453
+ }
2454
+ if (!Number.isFinite(maxElapsedTime)) {
2455
+ return maxElapsedTime > 0 ? Number.POSITIVE_INFINITY : 0;
2456
+ }
2457
+ return Math.max(0, maxElapsedTime);
2458
+ }
2339
2459
  function normalizeDelay(delay) {
2340
2460
  if (typeof delay === "number") {
2341
2461
  const normalizedDelay = Math.max(0, delay);
@@ -2352,6 +2472,29 @@ function normalizeRetryDelay(delay, maxDelay) {
2352
2472
  }
2353
2473
  return Math.min(Math.max(0, delay), maxDelay);
2354
2474
  }
2475
+ async function applyJitter(jitter, event) {
2476
+ if (jitter === false) {
2477
+ return event.delay;
2478
+ }
2479
+ if (jitter === true) {
2480
+ return Math.random() * event.delay;
2481
+ }
2482
+ return jitter(event);
2483
+ }
2484
+ function exceedsElapsedTimeBudget(elapsedTime, delay, maxElapsedTime) {
2485
+ return elapsedTime >= maxElapsedTime || elapsedTime + delay > maxElapsedTime;
2486
+ }
2487
+ function notifyRetry(onRetry, event) {
2488
+ if (!onRetry) {
2489
+ return;
2490
+ }
2491
+ try {
2492
+ void Promise.resolve(onRetry(event)).catch(ignoreRetryObserverError);
2493
+ } catch {
2494
+ }
2495
+ }
2496
+ function ignoreRetryObserverError() {
2497
+ }
2355
2498
  function canRetryRequest(config, methods) {
2356
2499
  const method = config.method ?? "GET";
2357
2500
  if (!methods.has(method)) {
package/dist/index.d.cts CHANGED
@@ -27,7 +27,45 @@ interface RetryOptions {
27
27
  * @default 60000
28
28
  */
29
29
  maxDelay?: number;
30
+ /**
31
+ * Randomize the configured retry delay.
32
+ *
33
+ * `true` applies full jitter between zero and the configured delay.
34
+ * A function receives the pending retry event and returns the final delay.
35
+ * Server-provided Retry-After delays are not jittered.
36
+ *
37
+ * @default false
38
+ */
39
+ jitter?: boolean | ((event: RetryEvent) => number | Promise<number>);
40
+ /**
41
+ * Maximum elapsed time across the initial request, retries and planned
42
+ * retry delays.
43
+ *
44
+ * @default unlimited
45
+ */
46
+ maxElapsedTime?: number;
30
47
  shouldRetry?: (error: unknown, attempt: number) => boolean | Promise<boolean>;
48
+ /**
49
+ * Observe a scheduled retry.
50
+ *
51
+ * Callback failures are isolated from the request lifecycle.
52
+ */
53
+ onRetry?: (event: RetryEvent) => void | Promise<void>;
54
+ }
55
+ interface RetryEvent {
56
+ /**
57
+ * One-based retry number.
58
+ */
59
+ attempt: number;
60
+ /**
61
+ * Final delay before this retry in milliseconds.
62
+ */
63
+ delay: number;
64
+ /**
65
+ * Time elapsed since the request started in milliseconds.
66
+ */
67
+ elapsedTime: number;
68
+ error: unknown;
31
69
  }
32
70
  interface CacheOptions {
33
71
  enabled?: boolean;
@@ -40,6 +78,53 @@ interface AuthOptions {
40
78
  }
41
79
  interface LoggerOptions {
42
80
  enabled?: boolean;
81
+ /**
82
+ * Structured log destination.
83
+ *
84
+ * @default console
85
+ */
86
+ logger?: RequestLogger;
87
+ /**
88
+ * Create the identifier shared by all lifecycle entries for a request.
89
+ *
90
+ * @default a plugin-local monotonic identifier
91
+ */
92
+ createRequestId?: () => string;
93
+ }
94
+ interface RequestLogEntry {
95
+ type: 'request';
96
+ requestId: string;
97
+ timestamp: number;
98
+ method: HttpMethod;
99
+ url: string;
100
+ }
101
+ interface ResponseLogEntry {
102
+ type: 'response';
103
+ requestId: string;
104
+ timestamp: number;
105
+ duration: number;
106
+ attempts: number;
107
+ method: HttpMethod;
108
+ url: string;
109
+ status: number;
110
+ }
111
+ interface ErrorLogEntry {
112
+ type: 'error';
113
+ requestId: string;
114
+ timestamp: number;
115
+ duration: number;
116
+ attempt: number;
117
+ method: HttpMethod;
118
+ url: string;
119
+ name: string;
120
+ message: string;
121
+ code?: string;
122
+ status?: number;
123
+ }
124
+ type LoggerEntry = RequestLogEntry | ResponseLogEntry | ErrorLogEntry;
125
+ interface RequestLogger {
126
+ info(message: string, entry: RequestLogEntry | ResponseLogEntry): void | Promise<void>;
127
+ error(message: string, entry: ErrorLogEntry): void | Promise<void>;
43
128
  }
44
129
  type UploadData = FormData | Record<string, unknown>;
45
130
  /**
@@ -236,6 +321,7 @@ declare class RequestContext<T = unknown> {
236
321
  error?: unknown;
237
322
  readonly startTime: number;
238
323
  endTime?: number;
324
+ attempt: number;
239
325
  constructor(config: RequestConfig);
240
326
  }
241
327
 
@@ -487,4 +573,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
487
573
 
488
574
  declare function uploadPlugin(): Plugin;
489
575
 
490
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheOptions, type CachePlugin, type CachePluginOptions, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type ResponseType, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
576
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheOptions, type CachePlugin, type CachePluginOptions, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -27,7 +27,45 @@ interface RetryOptions {
27
27
  * @default 60000
28
28
  */
29
29
  maxDelay?: number;
30
+ /**
31
+ * Randomize the configured retry delay.
32
+ *
33
+ * `true` applies full jitter between zero and the configured delay.
34
+ * A function receives the pending retry event and returns the final delay.
35
+ * Server-provided Retry-After delays are not jittered.
36
+ *
37
+ * @default false
38
+ */
39
+ jitter?: boolean | ((event: RetryEvent) => number | Promise<number>);
40
+ /**
41
+ * Maximum elapsed time across the initial request, retries and planned
42
+ * retry delays.
43
+ *
44
+ * @default unlimited
45
+ */
46
+ maxElapsedTime?: number;
30
47
  shouldRetry?: (error: unknown, attempt: number) => boolean | Promise<boolean>;
48
+ /**
49
+ * Observe a scheduled retry.
50
+ *
51
+ * Callback failures are isolated from the request lifecycle.
52
+ */
53
+ onRetry?: (event: RetryEvent) => void | Promise<void>;
54
+ }
55
+ interface RetryEvent {
56
+ /**
57
+ * One-based retry number.
58
+ */
59
+ attempt: number;
60
+ /**
61
+ * Final delay before this retry in milliseconds.
62
+ */
63
+ delay: number;
64
+ /**
65
+ * Time elapsed since the request started in milliseconds.
66
+ */
67
+ elapsedTime: number;
68
+ error: unknown;
31
69
  }
32
70
  interface CacheOptions {
33
71
  enabled?: boolean;
@@ -40,6 +78,53 @@ interface AuthOptions {
40
78
  }
41
79
  interface LoggerOptions {
42
80
  enabled?: boolean;
81
+ /**
82
+ * Structured log destination.
83
+ *
84
+ * @default console
85
+ */
86
+ logger?: RequestLogger;
87
+ /**
88
+ * Create the identifier shared by all lifecycle entries for a request.
89
+ *
90
+ * @default a plugin-local monotonic identifier
91
+ */
92
+ createRequestId?: () => string;
93
+ }
94
+ interface RequestLogEntry {
95
+ type: 'request';
96
+ requestId: string;
97
+ timestamp: number;
98
+ method: HttpMethod;
99
+ url: string;
100
+ }
101
+ interface ResponseLogEntry {
102
+ type: 'response';
103
+ requestId: string;
104
+ timestamp: number;
105
+ duration: number;
106
+ attempts: number;
107
+ method: HttpMethod;
108
+ url: string;
109
+ status: number;
110
+ }
111
+ interface ErrorLogEntry {
112
+ type: 'error';
113
+ requestId: string;
114
+ timestamp: number;
115
+ duration: number;
116
+ attempt: number;
117
+ method: HttpMethod;
118
+ url: string;
119
+ name: string;
120
+ message: string;
121
+ code?: string;
122
+ status?: number;
123
+ }
124
+ type LoggerEntry = RequestLogEntry | ResponseLogEntry | ErrorLogEntry;
125
+ interface RequestLogger {
126
+ info(message: string, entry: RequestLogEntry | ResponseLogEntry): void | Promise<void>;
127
+ error(message: string, entry: ErrorLogEntry): void | Promise<void>;
43
128
  }
44
129
  type UploadData = FormData | Record<string, unknown>;
45
130
  /**
@@ -236,6 +321,7 @@ declare class RequestContext<T = unknown> {
236
321
  error?: unknown;
237
322
  readonly startTime: number;
238
323
  endTime?: number;
324
+ attempt: number;
239
325
  constructor(config: RequestConfig);
240
326
  }
241
327
 
@@ -487,4 +573,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
487
573
 
488
574
  declare function uploadPlugin(): Plugin;
489
575
 
490
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheOptions, type CachePlugin, type CachePluginOptions, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type ResponseType, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
576
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheOptions, type CachePlugin, type CachePluginOptions, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -645,6 +645,7 @@ function setHeader(headers, key, value) {
645
645
  // src/core/RequestContext.ts
646
646
  var RequestContext = class {
647
647
  constructor(config) {
648
+ this.attempt = 0;
648
649
  this.config = config;
649
650
  this.startTime = Date.now();
650
651
  }
@@ -719,6 +720,7 @@ var Pipeline = class {
719
720
  context.error = void 0;
720
721
  context.response = void 0;
721
722
  attempt += 1;
723
+ context.attempt = attempt;
722
724
  try {
723
725
  await waitForRetry(
724
726
  decision.delay ?? 0,
@@ -2059,58 +2061,118 @@ function createProgress2(loaded, total) {
2059
2061
 
2060
2062
  // src/plugins/loggerPlugin.ts
2061
2063
  function loggerPlugin(defaultOptions = {}) {
2064
+ let nextRequestId = 0;
2065
+ const states = /* @__PURE__ */ new WeakMap();
2062
2066
  return {
2063
2067
  name: "logger",
2064
2068
  install(context) {
2065
- context.interceptors.request.use((config) => {
2066
- const logger = resolveExtensionConfig(
2067
- config,
2069
+ context.hooks.onRequest((requestContext) => {
2070
+ const options = resolveExtensionConfig(
2071
+ requestContext.config,
2068
2072
  "logger"
2069
2073
  ) ?? defaultOptions;
2070
- if (logger.enabled === false) {
2071
- return config;
2074
+ if (options.enabled === false) {
2075
+ return;
2072
2076
  }
2073
- console.log("[Npora Request]", {
2077
+ const state = {
2078
+ requestId: options.createRequestId?.() ?? `request-${++nextRequestId}`,
2079
+ options
2080
+ };
2081
+ states.set(requestContext, state);
2082
+ emitInfo(options, {
2074
2083
  type: "request",
2075
- method: config.method ?? "GET",
2076
- url: redactURL(config.url)
2084
+ requestId: state.requestId,
2085
+ timestamp: requestContext.startTime,
2086
+ method: requestContext.config.method ?? "GET",
2087
+ url: redactURL(requestContext.config.url)
2077
2088
  });
2078
- return config;
2079
2089
  });
2080
- context.interceptors.response.use((response) => {
2081
- const logger = resolveExtensionConfig(
2082
- response.config,
2083
- "logger"
2084
- ) ?? defaultOptions;
2085
- if (logger.enabled === false) {
2086
- return response;
2090
+ context.hooks.onResponse((requestContext) => {
2091
+ const state = states.get(requestContext);
2092
+ if (!state || !requestContext.response) {
2093
+ return;
2087
2094
  }
2088
- console.log("[Npora Request]", {
2095
+ const timestamp = Date.now();
2096
+ emitInfo(state.options, {
2089
2097
  type: "response",
2090
- method: response.config.method ?? "GET",
2091
- url: redactURL(response.config.url),
2092
- status: response.status
2098
+ requestId: state.requestId,
2099
+ timestamp,
2100
+ duration: Math.max(0, timestamp - requestContext.startTime),
2101
+ attempts: requestContext.attempt + 1,
2102
+ method: requestContext.config.method ?? "GET",
2103
+ url: redactURL(requestContext.config.url),
2104
+ status: requestContext.response.status
2093
2105
  });
2094
- return response;
2095
2106
  });
2096
- context.interceptors.error.use((error) => {
2097
- const config = error instanceof RequestError ? error.config : void 0;
2098
- const logger = config ? resolveExtensionConfig(
2099
- config,
2100
- "logger"
2101
- ) ?? defaultOptions : defaultOptions;
2102
- if (logger.enabled === false) {
2103
- return error;
2107
+ context.hooks.onError((requestContext) => {
2108
+ let state = states.get(requestContext);
2109
+ if (!state) {
2110
+ const options = resolveExtensionConfig(
2111
+ requestContext.config,
2112
+ "logger"
2113
+ ) ?? defaultOptions;
2114
+ if (options.enabled === false) {
2115
+ return;
2116
+ }
2117
+ state = {
2118
+ requestId: options.createRequestId?.() ?? `request-${++nextRequestId}`,
2119
+ options
2120
+ };
2121
+ states.set(requestContext, state);
2122
+ emitInfo(options, {
2123
+ type: "request",
2124
+ requestId: state.requestId,
2125
+ timestamp: requestContext.startTime,
2126
+ method: requestContext.config.method ?? "GET",
2127
+ url: redactURL(requestContext.config.url)
2128
+ });
2104
2129
  }
2105
- console.error(
2106
- "[Npora Request]",
2107
- createErrorLog(error)
2130
+ const timestamp = Date.now();
2131
+ emitError(
2132
+ state.options,
2133
+ createErrorLog(
2134
+ requestContext.error,
2135
+ state.requestId,
2136
+ timestamp,
2137
+ Math.max(0, timestamp - requestContext.startTime),
2138
+ requestContext.attempt + 1,
2139
+ requestContext.config.method ?? "GET",
2140
+ redactURL(requestContext.config.url)
2141
+ )
2108
2142
  );
2109
- return error;
2110
2143
  });
2111
2144
  }
2112
2145
  };
2113
2146
  }
2147
+ var consoleLogger = {
2148
+ info(message, entry) {
2149
+ console.log(message, entry);
2150
+ },
2151
+ error(message, entry) {
2152
+ console.error(message, entry);
2153
+ }
2154
+ };
2155
+ function resolveLogger(options) {
2156
+ return options.logger ?? consoleLogger;
2157
+ }
2158
+ function emitInfo(options, entry) {
2159
+ try {
2160
+ void Promise.resolve(
2161
+ resolveLogger(options).info("[Npora Request]", entry)
2162
+ ).catch(ignoreLoggerError);
2163
+ } catch {
2164
+ }
2165
+ }
2166
+ function emitError(options, entry) {
2167
+ try {
2168
+ void Promise.resolve(
2169
+ resolveLogger(options).error("[Npora Request]", entry)
2170
+ ).catch(ignoreLoggerError);
2171
+ } catch {
2172
+ }
2173
+ }
2174
+ function ignoreLoggerError() {
2175
+ }
2114
2176
  var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2115
2177
  "access_token",
2116
2178
  "api-key",
@@ -2172,27 +2234,35 @@ function findAuthorityEnd(url, authorityStart) {
2172
2234
  }
2173
2235
  return url.length;
2174
2236
  }
2175
- function createErrorLog(error) {
2237
+ function createErrorLog(error, requestId, timestamp, duration, attempt, method, url) {
2238
+ const lifecycle = {
2239
+ type: "error",
2240
+ requestId,
2241
+ timestamp,
2242
+ duration,
2243
+ attempt,
2244
+ method,
2245
+ url
2246
+ };
2176
2247
  if (error instanceof RequestError) {
2177
2248
  return {
2178
- type: "error",
2249
+ ...lifecycle,
2179
2250
  name: error.name,
2180
2251
  message: error.message,
2181
2252
  code: error.code,
2182
- status: error.status,
2183
- method: error.config?.method ?? "GET",
2184
- url: error.config ? redactURL(error.config.url) : void 0
2253
+ status: error.status
2185
2254
  };
2186
2255
  }
2187
2256
  if (error instanceof Error) {
2188
2257
  return {
2189
- type: "error",
2258
+ ...lifecycle,
2190
2259
  name: error.name,
2191
2260
  message: error.message
2192
2261
  };
2193
2262
  }
2194
2263
  return {
2195
- type: "error",
2264
+ ...lifecycle,
2265
+ name: "UnknownError",
2196
2266
  message: String(error)
2197
2267
  };
2198
2268
  }
@@ -2241,12 +2311,43 @@ function retryPlugin(defaultOptions = {}) {
2241
2311
  requestContext.error
2242
2312
  );
2243
2313
  const retryAfter = retryOptions.respectRetryAfter ? parseRetryAfter(requestContext.error) : void 0;
2314
+ const baseDelay = normalizeRetryDelay(
2315
+ retryAfter ?? configuredDelay,
2316
+ retryOptions.maxDelay
2317
+ );
2318
+ const elapsedTime = Math.max(
2319
+ 0,
2320
+ Date.now() - requestContext.startTime
2321
+ );
2322
+ const pendingEvent = {
2323
+ attempt: attempt + 1,
2324
+ delay: baseDelay,
2325
+ elapsedTime,
2326
+ error: requestContext.error
2327
+ };
2328
+ const jitteredDelay = retryAfter === void 0 ? await applyJitter(
2329
+ retryOptions.jitter,
2330
+ pendingEvent
2331
+ ) : baseDelay;
2332
+ const delay = normalizeRetryDelay(
2333
+ jitteredDelay,
2334
+ retryOptions.maxDelay
2335
+ );
2336
+ const event = {
2337
+ ...pendingEvent,
2338
+ delay
2339
+ };
2340
+ if (exceedsElapsedTimeBudget(
2341
+ elapsedTime,
2342
+ delay,
2343
+ retryOptions.maxElapsedTime
2344
+ )) {
2345
+ return void 0;
2346
+ }
2347
+ notifyRetry(retryOptions.onRetry, event);
2244
2348
  return {
2245
2349
  retry: true,
2246
- delay: normalizeRetryDelay(
2247
- retryAfter ?? configuredDelay,
2248
- retryOptions.maxDelay
2249
- )
2350
+ delay
2250
2351
  };
2251
2352
  });
2252
2353
  }
@@ -2260,7 +2361,12 @@ function normalizeRetryOptions(retry, defaults = {}) {
2260
2361
  delay: normalizeDelay(defaults.delay),
2261
2362
  respectRetryAfter: defaults.respectRetryAfter ?? true,
2262
2363
  maxDelay: normalizeMaxDelay(defaults.maxDelay),
2263
- shouldRetry: defaults.shouldRetry ?? defaultShouldRetry
2364
+ jitter: defaults.jitter ?? false,
2365
+ maxElapsedTime: normalizeMaxElapsedTime(
2366
+ defaults.maxElapsedTime
2367
+ ),
2368
+ shouldRetry: defaults.shouldRetry ?? defaultShouldRetry,
2369
+ onRetry: defaults.onRetry
2264
2370
  };
2265
2371
  }
2266
2372
  return {
@@ -2277,7 +2383,12 @@ function normalizeRetryOptions(retry, defaults = {}) {
2277
2383
  maxDelay: normalizeMaxDelay(
2278
2384
  retry?.maxDelay ?? defaults.maxDelay
2279
2385
  ),
2280
- shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry
2386
+ jitter: retry?.jitter ?? defaults.jitter ?? false,
2387
+ maxElapsedTime: normalizeMaxElapsedTime(
2388
+ retry?.maxElapsedTime ?? defaults.maxElapsedTime
2389
+ ),
2390
+ shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry,
2391
+ onRetry: retry?.onRetry ?? defaults.onRetry
2281
2392
  };
2282
2393
  }
2283
2394
  function normalizeMethods(methods) {
@@ -2298,6 +2409,15 @@ function normalizeRetries(retries) {
2298
2409
  }
2299
2410
  return Math.max(0, Math.floor(retries));
2300
2411
  }
2412
+ function normalizeMaxElapsedTime(maxElapsedTime) {
2413
+ if (maxElapsedTime === void 0) {
2414
+ return Number.POSITIVE_INFINITY;
2415
+ }
2416
+ if (!Number.isFinite(maxElapsedTime)) {
2417
+ return maxElapsedTime > 0 ? Number.POSITIVE_INFINITY : 0;
2418
+ }
2419
+ return Math.max(0, maxElapsedTime);
2420
+ }
2301
2421
  function normalizeDelay(delay) {
2302
2422
  if (typeof delay === "number") {
2303
2423
  const normalizedDelay = Math.max(0, delay);
@@ -2314,6 +2434,29 @@ function normalizeRetryDelay(delay, maxDelay) {
2314
2434
  }
2315
2435
  return Math.min(Math.max(0, delay), maxDelay);
2316
2436
  }
2437
+ async function applyJitter(jitter, event) {
2438
+ if (jitter === false) {
2439
+ return event.delay;
2440
+ }
2441
+ if (jitter === true) {
2442
+ return Math.random() * event.delay;
2443
+ }
2444
+ return jitter(event);
2445
+ }
2446
+ function exceedsElapsedTimeBudget(elapsedTime, delay, maxElapsedTime) {
2447
+ return elapsedTime >= maxElapsedTime || elapsedTime + delay > maxElapsedTime;
2448
+ }
2449
+ function notifyRetry(onRetry, event) {
2450
+ if (!onRetry) {
2451
+ return;
2452
+ }
2453
+ try {
2454
+ void Promise.resolve(onRetry(event)).catch(ignoreRetryObserverError);
2455
+ } catch {
2456
+ }
2457
+ }
2458
+ function ignoreRetryObserverError() {
2459
+ }
2317
2460
  function canRetryRequest(config, methods) {
2318
2461
  const method = config.method ?? "GET";
2319
2462
  if (!methods.has(method)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",