@npora/request 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/README.md CHANGED
@@ -1,47 +1,25 @@
1
1
  # @npora/request
2
2
 
3
- > A modern, TypeScript-first HTTP client built on top of the Fetch API.
3
+ A TypeScript-first HTTP client built on the standard Fetch API.
4
4
 
5
- Npora Request provides a consistent, extensible and production-ready request layer for modern JavaScript applications.
5
+ Npora Request adds typed configuration, a predictable request lifecycle,
6
+ interceptors, plugins, unified errors, retries, caching, authentication, and
7
+ upload/download progress without adding runtime dependencies.
6
8
 
7
- It does **not** replace Fetch.
9
+ ## Install
8
10
 
9
- It builds on top of the Fetch API while keeping the native request model.
10
-
11
- ---
12
-
13
- # Features
14
-
15
- - Fetch First
16
- - TypeScript First
17
- - Lightweight
18
- - Extensible
19
- - Zero Runtime Dependency
20
- - Plugin Architecture
21
- - Typed Extension Configuration
22
- - Client Default Inheritance
23
- - Retry, Cache and Authentication
24
- - Custom Adapter
25
- - Unified Error Handling
26
- - Browser and Web Worker Support
27
-
28
- ---
29
-
30
- # Installation
31
-
32
- ```bash
11
+ ```sh
33
12
  pnpm add @npora/request
34
13
  ```
35
14
 
36
- or
37
-
38
- ```bash
15
+ ```sh
39
16
  npm install @npora/request
40
17
  ```
41
18
 
42
- ---
19
+ Node.js 22 or newer is required. Modern Chromium, Edge, Safari, WebKit, and Web
20
+ Workers are supported through their native Fetch implementations.
43
21
 
44
- # Quick Start
22
+ ## Quick start
45
23
 
46
24
  ```ts
47
25
  import { createClient } from '@npora/request'
@@ -51,80 +29,52 @@ interface User {
51
29
  name: string
52
30
  }
53
31
 
54
- const request = createClient({
55
- baseURL: 'https://api.example.com'
32
+ const api = createClient({
33
+ baseURL: 'https://api.example.com',
34
+ timeout: 5000,
35
+ headers: {
36
+ 'x-app': 'dashboard'
37
+ }
56
38
  })
57
39
 
58
- const user = await request.get<User>('/users/1')
59
-
60
- console.log(user)
40
+ const user = await api.get<User>('/users/1')
61
41
  ```
62
42
 
63
- ---
64
-
65
- # Public API
43
+ Data-first methods return the parsed response body. Use a response method when
44
+ status, headers, or the native `Response` is needed:
66
45
 
67
46
  ```ts
68
- const request = createClient(options)
69
-
70
- const childRequest = request.extend(options)
71
-
72
- request.request(config)
73
-
74
- request.requestResponse(config)
75
-
76
- request.get(url)
77
-
78
- request.getResponse(url)
79
-
80
- request.post(url)
81
-
82
- request.put(url)
83
-
84
- request.patch(url)
85
-
86
- request.delete(url)
87
-
88
- request.head(url)
89
-
90
- request.options(url)
91
-
92
- request.use(plugin)
93
-
94
- request.unuse(pluginName)
95
-
96
- request.hasPlugin(pluginName)
97
-
98
- request.interceptors.request.use()
99
-
100
- request.interceptors.response.use()
47
+ const response = await api.getResponse<User>('/users/1')
101
48
 
102
- request.interceptors.error.use()
49
+ console.log(response.data)
50
+ console.log(response.status)
51
+ console.log(response.headers)
52
+ console.log(response.raw)
103
53
  ```
104
54
 
105
- Data-first methods return the parsed response body. Use `requestResponse()` or
106
- an HTTP `*Response()` method when status, headers or the native `Response` is
107
- needed.
108
-
109
- ---
110
-
111
- # Configuration
55
+ ## Request configuration
112
56
 
113
57
  ```ts
114
- const api = createClient({
115
- baseURL: 'https://api.example.com',
116
- timeout: 5000,
117
- headers: {
118
- 'x-app': 'dashboard'
119
- },
58
+ await api.post('/users', {
120
59
  query: {
121
- locale: 'en'
60
+ notify: true
61
+ },
62
+ json: {
63
+ name: 'Npora'
122
64
  },
123
65
  fetchOptions: {
124
66
  credentials: 'include'
125
67
  }
126
68
  })
69
+ ```
70
+
71
+ The body options `body`, `json`, `form`, and `formData` are mutually exclusive.
72
+ `GET` and `HEAD` requests cannot contain a body. Invalid configuration throws a
73
+ `RequestError` before the adapter sends a request.
74
+
75
+ Create isolated clients with inherited defaults:
127
76
 
77
+ ```ts
128
78
  const adminApi = api.extend({
129
79
  baseURL: 'https://api.example.com/admin',
130
80
  headers: {
@@ -133,45 +83,49 @@ const adminApi = api.extend({
133
83
  })
134
84
  ```
135
85
 
136
- `extend()` creates an isolated child client. It inherits configuration and the
137
- adapter, while plugins and interceptors remain instance-scoped.
138
-
139
- Request configuration overrides client defaults. Headers are merged
140
- case-insensitively, while query parameters, native Fetch options and extension
141
- configuration are merged by their documented rules.
86
+ The adapter and configuration are inherited. Plugins and interceptors remain
87
+ isolated to each client.
142
88
 
143
- ---
144
-
145
- # Complete Responses
89
+ ## HTTP methods
146
90
 
147
91
  ```ts
148
- const response = await api.getResponse<User>('/users/1')
149
-
150
- console.log(response.data)
151
- console.log(response.status)
152
- console.log(response.headers)
153
- console.log(response.raw)
92
+ api.request(config)
93
+ api.requestResponse(config)
94
+
95
+ api.get(url, config)
96
+ api.post(url, config)
97
+ api.put(url, config)
98
+ api.patch(url, config)
99
+ api.delete(url, config)
100
+ api.head(url, config)
101
+ api.options(url, config)
102
+
103
+ api.getResponse(url, config)
104
+ api.postResponse(url, config)
105
+ api.putResponse(url, config)
106
+ api.patchResponse(url, config)
107
+ api.deleteResponse(url, config)
108
+ api.headResponse(url, config)
109
+ api.optionsResponse(url, config)
154
110
  ```
155
111
 
156
- ---
157
-
158
- # Plugins
112
+ ## Plugins
159
113
 
160
114
  ```ts
161
115
  import {
162
116
  authPlugin,
163
117
  cachePlugin,
118
+ createClient,
164
119
  retryPlugin
165
120
  } from '@npora/request'
166
121
 
167
- const request = createClient({
168
- baseURL: 'https://api.example.com'
169
- })
122
+ const cache = cachePlugin()
123
+ const request = createClient()
170
124
  .use(retryPlugin({
171
125
  retries: 2,
172
126
  delay: 200
173
127
  }))
174
- .use(cachePlugin())
128
+ .use(cache)
175
129
  .use(authPlugin({
176
130
  token: () => accessToken,
177
131
  refreshToken
@@ -185,182 +139,119 @@ const user = await request.get<User>('/users/1', {
185
139
  }
186
140
  }
187
141
  })
142
+
143
+ cache.clear()
188
144
  ```
189
145
 
190
- Plugin configuration belongs under `extensions`. Top-level plugin fields are
191
- not part of `RequestConfig`.
146
+ Built-in plugins:
147
+
148
+ - `retryPlugin()`
149
+ - `cachePlugin()`
150
+ - `authPlugin()`
151
+ - `loggerPlugin()`
152
+ - `uploadPlugin()`
153
+ - `downloadPlugin()`
192
154
 
193
- ---
155
+ Plugin-owned request options belong under `extensions`. Third-party plugins can
156
+ augment `RequestExtensions` through TypeScript module augmentation.
194
157
 
195
- # Error Handling
158
+ Inject a structured logger when request correlation and timing are needed:
159
+
160
+ ```ts
161
+ const request = createClient().use(
162
+ loggerPlugin({
163
+ logger: {
164
+ info(_message, entry) {
165
+ applicationLogger.info(entry)
166
+ },
167
+ error(_message, entry) {
168
+ applicationLogger.error(entry)
169
+ }
170
+ }
171
+ })
172
+ )
173
+ ```
174
+
175
+ Lifecycle entries include a request identifier and timestamp. Completed
176
+ responses include total duration and attempt count; errors include the failed
177
+ attempt number. The default logger continues to use `console`.
178
+
179
+ ## Interceptors
180
+
181
+ ```ts
182
+ api.interceptors.request.use(config => config)
183
+ api.interceptors.response.use(response => response)
184
+ api.interceptors.error.use(error => error)
185
+ ```
186
+
187
+ An optional numeric priority controls execution order. Higher priorities run
188
+ first; equal priorities preserve registration order.
189
+
190
+ ## Errors
196
191
 
197
192
  ```ts
198
193
  import { RequestError } from '@npora/request'
199
194
 
200
195
  try {
201
- await request.get('/users/missing')
196
+ await api.get('/users/missing')
202
197
  } catch (error) {
203
198
  if (error instanceof RequestError) {
204
199
  console.error(error.code)
205
200
  console.error(error.status)
206
201
  console.error(error.data)
207
- console.error(error.response)
208
202
  }
209
203
  }
210
204
  ```
211
205
 
212
- Errors use stable codes including `CONFIG_ERROR`, `HTTP_ERROR`,
213
- `NETWORK_ERROR`, `TIMEOUT_ERROR`, `ABORT_ERROR` and `PARSER_ERROR`.
214
-
215
- ---
216
-
217
- # Examples
218
-
219
- See the `examples` directory.
220
-
221
- ```
222
- examples
223
- ├── basic.ts
224
- ├── custom-plugin.ts
225
- ├── error-handling.ts
226
- └── plugins.ts
227
- ```
228
-
229
- Examples are typechecked in CI with `pnpm test:examples`.
206
+ Stable request error codes:
230
207
 
231
- ---
208
+ - `CONFIG_ERROR`
209
+ - `HTTP_ERROR`
210
+ - `NETWORK_ERROR`
211
+ - `TIMEOUT_ERROR`
212
+ - `ABORT_ERROR`
213
+ - `PARSER_ERROR`
232
214
 
233
- # Performance
215
+ ## Documentation
234
216
 
235
- Run the request-pipeline benchmark:
217
+ - [API reference](https://github.com/npora/request/blob/main/docs/api.md)
218
+ - [Architecture](https://github.com/npora/request/blob/main/docs/architecture.md)
219
+ - [Migration from 0.x](https://github.com/npora/request/blob/main/docs/migration.md)
220
+ - [Security model](https://github.com/npora/request/blob/main/docs/security.md)
221
+ - [Testing and release gates](https://github.com/npora/request/blob/main/docs/testing.md)
222
+ - [Performance benchmarks](https://github.com/npora/request/blob/main/docs/benchmark.md)
223
+ - [Package size budgets](https://github.com/npora/request/blob/main/docs/package-size.md)
224
+ - [Changelog](https://github.com/npora/request/blob/main/CHANGELOG.md)
236
225
 
237
- ```sh
238
- pnpm benchmark
239
- ```
226
+ Project policies:
240
227
 
241
- It reports sequential and concurrent throughput, latency percentiles and heap
242
- movement for the adapter, client and plugin pipeline. CI stores a JSON report
243
- for comparisons between equivalent runners. See
244
- [`docs/benchmark.md`](docs/benchmark.md) for methodology and options.
228
+ - [Contributing](https://github.com/npora/request/blob/main/CONTRIBUTING.md)
229
+ - [Security reporting](https://github.com/npora/request/blob/main/SECURITY.md)
245
230
 
246
- Verify the built entrypoint, declaration, gzip and npm tarball size budgets:
231
+ ## Development
247
232
 
248
233
  ```sh
234
+ pnpm install --frozen-lockfile
235
+ pnpm typecheck
236
+ pnpm test:coverage
249
237
  pnpm build
250
- pnpm test:size
238
+ pnpm test:package
239
+ pnpm test:browser
251
240
  ```
252
241
 
253
- See [`docs/package-size.md`](docs/package-size.md) for the checked metrics and
254
- budget policy.
255
-
256
- The ecosystem evaluation covers Axios and nine representative GitHub request
257
- libraries with equivalent local HTTP workloads. Competitor packages were
258
- removed after measurement and are not project dependencies. See
259
- [`docs/comparison.md`](docs/comparison.md) for the snapshot and design
260
- decisions.
261
-
262
- ---
263
-
264
- # Documentation
265
-
266
- Project documentation is located in the `docs` directory.
267
-
268
- ```
269
- docs
270
- ├── benchmark.md
271
- ├── blueprint.md
272
- ├── comparison.md
273
- ├── features.md
274
- ├── package-size.md
275
- ├── structure.md
276
- └── api.md
277
- ```
278
-
279
- - **Blueprint** — Project vision and architecture
280
- - **Benchmark** — Performance measurement methodology
281
- - **Comparison** — Ten-library ecosystem evaluation
282
- - **Package Size** — Published asset budgets and regression checks
283
- - **Structure** — Directory responsibilities
284
- - **Features** — Product roadmap
285
- - **API** — Public API contract
286
-
287
- ---
288
-
289
- # Versioning
290
-
291
- Starting with 1.0, `@npora/request` follows Semantic Versioning.
292
-
293
- The stable public contract includes:
294
-
295
- - Package exports and their TypeScript declarations.
296
- - Documented client methods, configuration and response shapes.
297
- - Stable `RequestError` and `PluginError` codes.
298
- - Plugin lifecycle and extension configuration behavior.
299
-
300
- Breaking changes to this contract require a new major version. Internal modules
301
- that are not exported from the package root are not part of the public API.
302
-
303
- ---
304
-
305
- # Browser Support
306
-
307
- Supported runtimes:
308
-
309
- - Chrome
310
- - Edge
311
- - Safari
312
- - Node.js 22+
313
- - Web Workers
314
-
315
- Automated runtime coverage uses Node.js 22, 24, and 26 integration and package
316
- tests plus Playwright browser tests for Chromium and WebKit. Firefox is
317
- outside the current verification scope.
318
-
319
- Internet Explorer is **not supported**.
320
-
321
- ---
322
-
323
- # Roadmap
324
-
325
- ## v0.1
326
-
327
- Core
328
-
329
- - Client
330
- - Config
331
- - Pipeline
332
- - Adapter
333
- - Error
334
-
335
- ## v0.2
336
-
337
- Request
338
-
339
- - Timeout
340
- - Abort
341
- - Retry
342
- - Cache
343
-
344
- ## v0.3
345
-
346
- Business
347
-
348
- - Auth
349
- - Logger
350
- - Upload
351
- - Download
242
+ See the
243
+ [testing and release gates](https://github.com/npora/request/blob/main/docs/testing.md)
244
+ for the complete matrix.
352
245
 
353
- ## v1.0
246
+ ## Versioning
354
247
 
355
- - Stable SemVer API contract
356
- - Exact runtime and type export gates
357
- - Package-level behavior compatibility suite
358
- - Node.js 22, 24 and 26 verification
359
- - Chromium and WebKit verification
360
- - Automated npm, Git tag and GitHub Release publishing
248
+ `@npora/request` follows Semantic Versioning. Package-root exports, their
249
+ TypeScript declarations, documented behavior, stable error codes, and plugin
250
+ lifecycle are public API. Breaking changes require a new major version.
361
251
 
362
- ---
252
+ Internal modules that are not exported from the package root are not public
253
+ API.
363
254
 
364
- # License
255
+ ## License
365
256
 
366
257
  MIT © Npora Team
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",
@@ -2164,17 +2226,18 @@ var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2164
2226
  "token"
2165
2227
  ]);
2166
2228
  function redactURL(url) {
2167
- const queryIndex = url.indexOf("?");
2229
+ const safeURL = redactCredentials(url);
2230
+ const queryIndex = safeURL.indexOf("?");
2168
2231
  if (queryIndex === -1) {
2169
- return url;
2232
+ return safeURL;
2170
2233
  }
2171
- const hashIndex = url.indexOf("#", queryIndex);
2172
- const pathname = url.slice(0, queryIndex);
2173
- const query = url.slice(
2234
+ const hashIndex = safeURL.indexOf("#", queryIndex);
2235
+ const pathname = safeURL.slice(0, queryIndex);
2236
+ const query = safeURL.slice(
2174
2237
  queryIndex + 1,
2175
2238
  hashIndex === -1 ? void 0 : hashIndex
2176
2239
  );
2177
- const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
2240
+ const hash = hashIndex === -1 ? "" : safeURL.slice(hashIndex);
2178
2241
  const params = new URLSearchParams(query);
2179
2242
  for (const key of [...params.keys()]) {
2180
2243
  if (SENSITIVE_QUERY_KEYS.has(key.toLowerCase())) {
@@ -2184,27 +2247,60 @@ function redactURL(url) {
2184
2247
  const redactedQuery = params.toString();
2185
2248
  return `${pathname}${redactedQuery ? `?${redactedQuery}` : ""}${hash}`;
2186
2249
  }
2187
- function createErrorLog(error) {
2250
+ function redactCredentials(url) {
2251
+ const schemeIndex = url.indexOf("://");
2252
+ const authorityStart = schemeIndex === -1 ? url.startsWith("//") ? 2 : -1 : schemeIndex + 3;
2253
+ if (authorityStart === -1) {
2254
+ return url;
2255
+ }
2256
+ const authorityEnd = findAuthorityEnd(url, authorityStart);
2257
+ const credentialEnd = url.lastIndexOf(
2258
+ "@",
2259
+ authorityEnd - 1
2260
+ );
2261
+ if (credentialEnd < authorityStart) {
2262
+ return url;
2263
+ }
2264
+ return `${url.slice(0, authorityStart)}[REDACTED]@` + url.slice(credentialEnd + 1);
2265
+ }
2266
+ function findAuthorityEnd(url, authorityStart) {
2267
+ for (let index = authorityStart; index < url.length; index += 1) {
2268
+ const character = url[index];
2269
+ if (character === "/" || character === "?" || character === "#") {
2270
+ return index;
2271
+ }
2272
+ }
2273
+ return url.length;
2274
+ }
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
+ };
2188
2285
  if (error instanceof RequestError) {
2189
2286
  return {
2190
- type: "error",
2287
+ ...lifecycle,
2191
2288
  name: error.name,
2192
2289
  message: error.message,
2193
2290
  code: error.code,
2194
- status: error.status,
2195
- method: error.config?.method ?? "GET",
2196
- url: error.config ? redactURL(error.config.url) : void 0
2291
+ status: error.status
2197
2292
  };
2198
2293
  }
2199
2294
  if (error instanceof Error) {
2200
2295
  return {
2201
- type: "error",
2296
+ ...lifecycle,
2202
2297
  name: error.name,
2203
2298
  message: error.message
2204
2299
  };
2205
2300
  }
2206
2301
  return {
2207
- type: "error",
2302
+ ...lifecycle,
2303
+ name: "UnknownError",
2208
2304
  message: String(error)
2209
2305
  };
2210
2306
  }
package/dist/index.d.cts CHANGED
@@ -40,6 +40,53 @@ interface AuthOptions {
40
40
  }
41
41
  interface LoggerOptions {
42
42
  enabled?: boolean;
43
+ /**
44
+ * Structured log destination.
45
+ *
46
+ * @default console
47
+ */
48
+ logger?: RequestLogger;
49
+ /**
50
+ * Create the identifier shared by all lifecycle entries for a request.
51
+ *
52
+ * @default a plugin-local monotonic identifier
53
+ */
54
+ createRequestId?: () => string;
55
+ }
56
+ interface RequestLogEntry {
57
+ type: 'request';
58
+ requestId: string;
59
+ timestamp: number;
60
+ method: HttpMethod;
61
+ url: string;
62
+ }
63
+ interface ResponseLogEntry {
64
+ type: 'response';
65
+ requestId: string;
66
+ timestamp: number;
67
+ duration: number;
68
+ attempts: number;
69
+ method: HttpMethod;
70
+ url: string;
71
+ status: number;
72
+ }
73
+ interface ErrorLogEntry {
74
+ type: 'error';
75
+ requestId: string;
76
+ timestamp: number;
77
+ duration: number;
78
+ attempt: number;
79
+ method: HttpMethod;
80
+ url: string;
81
+ name: string;
82
+ message: string;
83
+ code?: string;
84
+ status?: number;
85
+ }
86
+ type LoggerEntry = RequestLogEntry | ResponseLogEntry | ErrorLogEntry;
87
+ interface RequestLogger {
88
+ info(message: string, entry: RequestLogEntry | ResponseLogEntry): void | Promise<void>;
89
+ error(message: string, entry: ErrorLogEntry): void | Promise<void>;
43
90
  }
44
91
  type UploadData = FormData | Record<string, unknown>;
45
92
  /**
@@ -236,6 +283,7 @@ declare class RequestContext<T = unknown> {
236
283
  error?: unknown;
237
284
  readonly startTime: number;
238
285
  endTime?: number;
286
+ attempt: number;
239
287
  constructor(config: RequestConfig);
240
288
  }
241
289
 
@@ -487,4 +535,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
487
535
 
488
536
  declare function uploadPlugin(): Plugin;
489
537
 
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 };
538
+ 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 RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -40,6 +40,53 @@ interface AuthOptions {
40
40
  }
41
41
  interface LoggerOptions {
42
42
  enabled?: boolean;
43
+ /**
44
+ * Structured log destination.
45
+ *
46
+ * @default console
47
+ */
48
+ logger?: RequestLogger;
49
+ /**
50
+ * Create the identifier shared by all lifecycle entries for a request.
51
+ *
52
+ * @default a plugin-local monotonic identifier
53
+ */
54
+ createRequestId?: () => string;
55
+ }
56
+ interface RequestLogEntry {
57
+ type: 'request';
58
+ requestId: string;
59
+ timestamp: number;
60
+ method: HttpMethod;
61
+ url: string;
62
+ }
63
+ interface ResponseLogEntry {
64
+ type: 'response';
65
+ requestId: string;
66
+ timestamp: number;
67
+ duration: number;
68
+ attempts: number;
69
+ method: HttpMethod;
70
+ url: string;
71
+ status: number;
72
+ }
73
+ interface ErrorLogEntry {
74
+ type: 'error';
75
+ requestId: string;
76
+ timestamp: number;
77
+ duration: number;
78
+ attempt: number;
79
+ method: HttpMethod;
80
+ url: string;
81
+ name: string;
82
+ message: string;
83
+ code?: string;
84
+ status?: number;
85
+ }
86
+ type LoggerEntry = RequestLogEntry | ResponseLogEntry | ErrorLogEntry;
87
+ interface RequestLogger {
88
+ info(message: string, entry: RequestLogEntry | ResponseLogEntry): void | Promise<void>;
89
+ error(message: string, entry: ErrorLogEntry): void | Promise<void>;
43
90
  }
44
91
  type UploadData = FormData | Record<string, unknown>;
45
92
  /**
@@ -236,6 +283,7 @@ declare class RequestContext<T = unknown> {
236
283
  error?: unknown;
237
284
  readonly startTime: number;
238
285
  endTime?: number;
286
+ attempt: number;
239
287
  constructor(config: RequestConfig);
240
288
  }
241
289
 
@@ -487,4 +535,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
487
535
 
488
536
  declare function uploadPlugin(): Plugin;
489
537
 
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 };
538
+ 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 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",
@@ -2126,17 +2188,18 @@ var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2126
2188
  "token"
2127
2189
  ]);
2128
2190
  function redactURL(url) {
2129
- const queryIndex = url.indexOf("?");
2191
+ const safeURL = redactCredentials(url);
2192
+ const queryIndex = safeURL.indexOf("?");
2130
2193
  if (queryIndex === -1) {
2131
- return url;
2194
+ return safeURL;
2132
2195
  }
2133
- const hashIndex = url.indexOf("#", queryIndex);
2134
- const pathname = url.slice(0, queryIndex);
2135
- const query = url.slice(
2196
+ const hashIndex = safeURL.indexOf("#", queryIndex);
2197
+ const pathname = safeURL.slice(0, queryIndex);
2198
+ const query = safeURL.slice(
2136
2199
  queryIndex + 1,
2137
2200
  hashIndex === -1 ? void 0 : hashIndex
2138
2201
  );
2139
- const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
2202
+ const hash = hashIndex === -1 ? "" : safeURL.slice(hashIndex);
2140
2203
  const params = new URLSearchParams(query);
2141
2204
  for (const key of [...params.keys()]) {
2142
2205
  if (SENSITIVE_QUERY_KEYS.has(key.toLowerCase())) {
@@ -2146,27 +2209,60 @@ function redactURL(url) {
2146
2209
  const redactedQuery = params.toString();
2147
2210
  return `${pathname}${redactedQuery ? `?${redactedQuery}` : ""}${hash}`;
2148
2211
  }
2149
- function createErrorLog(error) {
2212
+ function redactCredentials(url) {
2213
+ const schemeIndex = url.indexOf("://");
2214
+ const authorityStart = schemeIndex === -1 ? url.startsWith("//") ? 2 : -1 : schemeIndex + 3;
2215
+ if (authorityStart === -1) {
2216
+ return url;
2217
+ }
2218
+ const authorityEnd = findAuthorityEnd(url, authorityStart);
2219
+ const credentialEnd = url.lastIndexOf(
2220
+ "@",
2221
+ authorityEnd - 1
2222
+ );
2223
+ if (credentialEnd < authorityStart) {
2224
+ return url;
2225
+ }
2226
+ return `${url.slice(0, authorityStart)}[REDACTED]@` + url.slice(credentialEnd + 1);
2227
+ }
2228
+ function findAuthorityEnd(url, authorityStart) {
2229
+ for (let index = authorityStart; index < url.length; index += 1) {
2230
+ const character = url[index];
2231
+ if (character === "/" || character === "?" || character === "#") {
2232
+ return index;
2233
+ }
2234
+ }
2235
+ return url.length;
2236
+ }
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
+ };
2150
2247
  if (error instanceof RequestError) {
2151
2248
  return {
2152
- type: "error",
2249
+ ...lifecycle,
2153
2250
  name: error.name,
2154
2251
  message: error.message,
2155
2252
  code: error.code,
2156
- status: error.status,
2157
- method: error.config?.method ?? "GET",
2158
- url: error.config ? redactURL(error.config.url) : void 0
2253
+ status: error.status
2159
2254
  };
2160
2255
  }
2161
2256
  if (error instanceof Error) {
2162
2257
  return {
2163
- type: "error",
2258
+ ...lifecycle,
2164
2259
  name: error.name,
2165
2260
  message: error.message
2166
2261
  };
2167
2262
  }
2168
2263
  return {
2169
- type: "error",
2264
+ ...lifecycle,
2265
+ name: "UnknownError",
2170
2266
  message: String(error)
2171
2267
  };
2172
2268
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",
@@ -64,13 +64,18 @@
64
64
  "example:plugins": "tsx examples/plugins.ts",
65
65
  "test:coverage": "vitest run --coverage",
66
66
  "test:run": "vitest run",
67
+ "test:security": "vitest run test/security.test.ts",
68
+ "test:docs": "node test/docs.mjs",
67
69
  "test:types": "pnpm build && tsc -p test/types/tsconfig.json",
68
70
  "test:examples": "tsc -p examples/tsconfig.json",
69
71
  "test:package": "node test/package/esm.mjs && node test/package/cjs.cjs && node test/package/api-exports.mjs && node test/package/api-contract.mjs && node test/package/npm-pack-result.test.mjs && node test/package/manifest.mjs && pnpm test:size",
72
+ "test:registry": "node test/package/registry-install.mjs",
70
73
  "test:size": "node test/package/size.mjs",
71
74
  "test:browser": "playwright test --config=browser/playwright.config.ts",
72
75
  "test:browser:ui": "playwright test --config=browser/playwright.config.ts --ui",
73
76
  "test:browser:report": "playwright show-report playwright-report",
77
+ "audit:dependencies": "pnpm audit --audit-level high",
78
+ "audit:signatures": "pnpm audit signatures",
74
79
  "benchmark": "tsx benchmark/request.ts",
75
80
  "benchmark:types": "tsc -p benchmark/tsconfig.json"
76
81
  }