@npora/request 1.15.1 → 1.17.1

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.
Files changed (142) hide show
  1. package/README.md +154 -6
  2. package/dist/{MockAdapter-H50LoFDu.d.ts → MockAdapter-5CFrxv9q.d.ts} +2 -2
  3. package/dist/{MockAdapter-ChWzzSnH.d.cts → MockAdapter-mR3CWESj.d.cts} +2 -2
  4. package/dist/{Plugin-0Eh51_et.d.ts → Plugin-C9ZQzyF6.d.ts} +7 -1
  5. package/dist/{Plugin-YysllE6z.d.cts → Plugin-Cxb-obdZ.d.cts} +7 -1
  6. package/dist/RequestError-B0HIY1zK.js +1 -0
  7. package/dist/RequestError-DrCr_lwO.cjs +1 -0
  8. package/dist/SchemaValidationError-Bls3Uxwj.d.cts +215 -0
  9. package/dist/SchemaValidationError-DRSiM7h7.d.ts +215 -0
  10. package/dist/{adapter-BeVVCcNG.d.cts → adapter-Bshqh0DY.d.cts} +1 -1
  11. package/dist/{adapter-ODzpt_dM.d.ts → adapter-YnK7Xzw4.d.ts} +1 -1
  12. package/dist/{authPlugin-B_YpkyC8.d.cts → authPlugin-BXi6WjtM.d.cts} +1 -1
  13. package/dist/{authPlugin-6E6_0dAO.d.ts → authPlugin-DdzlLQVo.d.ts} +1 -1
  14. package/dist/{cachePlugin-CvH26DBo.d.ts → cachePlugin-BZ0lLFOx.d.ts} +2 -2
  15. package/dist/cachePlugin-Bg1Q5N82.cjs +1 -0
  16. package/dist/{cachePlugin-B9Hvsprg.d.cts → cachePlugin-Bk7V57oZ.d.cts} +2 -2
  17. package/dist/cachePlugin-Blw0Mh9F.js +1 -0
  18. package/dist/{circuitBreakerPlugin-B45xghq9.d.cts → circuitBreakerPlugin-BG2PlHSo.d.cts} +2 -2
  19. package/dist/{circuitBreakerPlugin-DsH6YCNe.d.ts → circuitBreakerPlugin-CX7s4iAe.d.ts} +2 -2
  20. package/dist/{concurrencyPlugin-CuJMua41.d.cts → concurrencyPlugin-DeDnm7ND.d.cts} +2 -2
  21. package/dist/{concurrencyPlugin-dwGNFYrM.d.ts → concurrencyPlugin-HvGuOA2p.d.ts} +2 -2
  22. package/dist/core.cjs +1 -1
  23. package/dist/core.d.cts +5 -5
  24. package/dist/core.d.ts +5 -5
  25. package/dist/core.js +1 -1
  26. package/dist/createAbortError-CP4TUmou.js +1 -0
  27. package/dist/createAbortError-DYRmuiQS.cjs +1 -0
  28. package/dist/createClient-BXfcmvs2.js +1 -0
  29. package/dist/createClient-qfwP9cgC.cjs +1 -0
  30. package/dist/{downloadPlugin-CEXXJiDo.d.cts → downloadPlugin-BlA-z0Pj.d.cts} +1 -1
  31. package/dist/{downloadPlugin-s8VS8t9r.d.ts → downloadPlugin-BrXcygGo.d.ts} +1 -1
  32. package/dist/errorResponseTimeout-CUZ0Bx-G.cjs +1 -0
  33. package/dist/errorResponseTimeout-CuRn9Icm.js +1 -0
  34. package/dist/index.cjs +1 -1
  35. package/dist/index.d.cts +17 -14
  36. package/dist/index.d.ts +17 -14
  37. package/dist/index.js +1 -1
  38. package/dist/isBinaryBody-B0414zDU.cjs +1 -0
  39. package/dist/isBinaryBody-i4r46MoJ.js +1 -0
  40. package/dist/isReadableStream-0eF9O4Xl.cjs +1 -0
  41. package/dist/isReadableStream-O-PmslRY.js +1 -0
  42. package/dist/loggerPlugin-CBbwGZme.d.ts +6 -0
  43. package/dist/loggerPlugin-CZpdXtBt.d.cts +6 -0
  44. package/dist/openTelemetryMetricsPlugin-DIo7cT09.d.ts +42 -0
  45. package/dist/openTelemetryMetricsPlugin-VZ1ojbXJ.d.cts +42 -0
  46. package/dist/openTelemetryPlugin-CiRMppHI.d.ts +57 -0
  47. package/dist/openTelemetryPlugin-FAngP8jc.d.cts +57 -0
  48. package/dist/plugins/auth.cjs +1 -1
  49. package/dist/plugins/auth.d.cts +1 -1
  50. package/dist/plugins/auth.d.ts +1 -1
  51. package/dist/plugins/auth.js +1 -1
  52. package/dist/plugins/cache.cjs +1 -1
  53. package/dist/plugins/cache.d.cts +1 -1
  54. package/dist/plugins/cache.d.ts +1 -1
  55. package/dist/plugins/cache.js +1 -1
  56. package/dist/plugins/circuit-breaker.cjs +1 -1
  57. package/dist/plugins/circuit-breaker.d.cts +1 -1
  58. package/dist/plugins/circuit-breaker.d.ts +1 -1
  59. package/dist/plugins/circuit-breaker.js +1 -1
  60. package/dist/plugins/concurrency.cjs +1 -1
  61. package/dist/plugins/concurrency.d.cts +1 -1
  62. package/dist/plugins/concurrency.d.ts +1 -1
  63. package/dist/plugins/concurrency.js +1 -1
  64. package/dist/plugins/download.cjs +1 -1
  65. package/dist/plugins/download.d.cts +1 -1
  66. package/dist/plugins/download.d.ts +1 -1
  67. package/dist/plugins/download.js +1 -1
  68. package/dist/plugins/logger.cjs +1 -1
  69. package/dist/plugins/logger.d.cts +1 -1
  70. package/dist/plugins/logger.d.ts +1 -1
  71. package/dist/plugins/logger.js +1 -1
  72. package/dist/plugins/opentelemetry-metrics.cjs +1 -0
  73. package/dist/plugins/opentelemetry-metrics.d.cts +2 -0
  74. package/dist/plugins/opentelemetry-metrics.d.ts +2 -0
  75. package/dist/plugins/opentelemetry-metrics.js +1 -0
  76. package/dist/plugins/opentelemetry.cjs +1 -0
  77. package/dist/plugins/opentelemetry.d.cts +2 -0
  78. package/dist/plugins/opentelemetry.d.ts +2 -0
  79. package/dist/plugins/opentelemetry.js +1 -0
  80. package/dist/plugins/rate-limit.cjs +1 -0
  81. package/dist/plugins/rate-limit.d.cts +2 -0
  82. package/dist/plugins/rate-limit.d.ts +2 -0
  83. package/dist/plugins/rate-limit.js +1 -0
  84. package/dist/plugins/retry.cjs +1 -1
  85. package/dist/plugins/retry.d.cts +1 -1
  86. package/dist/plugins/retry.d.ts +1 -1
  87. package/dist/plugins/retry.js +1 -1
  88. package/dist/plugins/upload.cjs +1 -1
  89. package/dist/plugins/upload.d.cts +1 -1
  90. package/dist/plugins/upload.d.ts +1 -1
  91. package/dist/plugins/upload.js +1 -1
  92. package/dist/plugins.cjs +1 -1
  93. package/dist/plugins.d.cts +13 -10
  94. package/dist/plugins.d.ts +13 -10
  95. package/dist/plugins.js +1 -1
  96. package/dist/rateLimitPlugin-1rbZeJmP.d.cts +33 -0
  97. package/dist/rateLimitPlugin-CDpoD85h.js +1 -0
  98. package/dist/rateLimitPlugin-D5t-8kzP.d.ts +33 -0
  99. package/dist/rateLimitPlugin-uEH2OKgl.cjs +1 -0
  100. package/dist/resolveRequestOrigin-DzOB9oX9.cjs +1 -0
  101. package/dist/resolveRequestOrigin-jeuuD5SV.js +1 -0
  102. package/dist/{response-BhyS3PAL.d.ts → response-B6Z3qxyO.d.cts} +138 -13
  103. package/dist/{response-BhyS3PAL.d.cts → response-B6Z3qxyO.d.ts} +138 -13
  104. package/dist/retryPlugin-C0dORYIQ.d.cts +6 -0
  105. package/dist/retryPlugin-CVelhp0f.d.ts +6 -0
  106. package/dist/testing.cjs +1 -1
  107. package/dist/testing.d.cts +1 -1
  108. package/dist/testing.d.ts +1 -1
  109. package/dist/testing.js +1 -1
  110. package/dist/{uploadPlugin-Bb7EawRX.d.ts → uploadPlugin-BrzbWtAN.d.ts} +1 -1
  111. package/dist/{uploadPlugin-AfhFIsO7.d.cts → uploadPlugin-Ci0ys-ng.d.cts} +1 -1
  112. package/dist/validateResponseStatus-CYU2N49m.cjs +6 -0
  113. package/dist/validateResponseStatus-JYSqdThE.js +6 -0
  114. package/dist/{waitForSignal-DyyPvJd5.js → waitForSignal-C3rpyDkF.js} +1 -1
  115. package/dist/{waitForSignal-yR1BeU8f.cjs → waitForSignal-xjHyZ4cK.cjs} +1 -1
  116. package/dist/xhrTransport-C-8xl1bw.cjs +1 -0
  117. package/dist/xhrTransport-Doc_yozh.js +1 -0
  118. package/package.json +34 -13
  119. package/dist/RequestError-BH6V64XR.js +0 -1
  120. package/dist/RequestError-DPSv-HVF.cjs +0 -1
  121. package/dist/SchemaValidationError-CjvWT8YA.d.ts +0 -166
  122. package/dist/SchemaValidationError-WMTfqSBV.d.cts +0 -166
  123. package/dist/buildRequest-BRZwRLoN.cjs +0 -1
  124. package/dist/buildRequest-Cwt8XEWO.js +0 -1
  125. package/dist/cachePlugin-CSHwJYwI.js +0 -1
  126. package/dist/cachePlugin-ZPYdHbsM.cjs +0 -1
  127. package/dist/createAbortError-D4rRBq2B.js +0 -1
  128. package/dist/createAbortError-DJqbdYgk.cjs +0 -1
  129. package/dist/createClient-CibOTVAy.cjs +0 -1
  130. package/dist/createClient-I13D6XsD.js +0 -1
  131. package/dist/isURLSearchParams-B93cMCGj.js +0 -1
  132. package/dist/isURLSearchParams-o-c8Q42t.cjs +0 -1
  133. package/dist/loggerPlugin-C15EW7Sc.d.ts +0 -6
  134. package/dist/loggerPlugin-uOFiUtBi.d.cts +0 -6
  135. package/dist/resolveRequestOrigin-BndIJeZ7.js +0 -1
  136. package/dist/resolveRequestOrigin-CRATeWff.cjs +0 -1
  137. package/dist/retryPlugin-2mYKvWy3.d.ts +0 -6
  138. package/dist/retryPlugin-BqlUpmd0.d.cts +0 -6
  139. package/dist/validateResponseStatus-Dqzr342t.js +0 -4
  140. package/dist/validateResponseStatus-QAjcah2i.cjs +0 -4
  141. package/dist/xhrTransport-C0pg00i5.js +0 -1
  142. package/dist/xhrTransport-CeW2DDzo.cjs +0 -1
package/README.md CHANGED
@@ -27,6 +27,12 @@ authentication, and upload/download progress.
27
27
  composable plugins over the standard Fetch API.
28
28
  - **Use one predictable contract everywhere.** Browsers, Web Workers, Node.js,
29
29
  ESM, and CommonJS share the same typed lifecycle and stable error codes.
30
+ - **Keep native platform values native.** `URL`, `Request`, `Headers`,
31
+ `FormData`, `Blob`, `ArrayBuffer`, and `ReadableStream` retain their Fetch
32
+ semantics, including supported cross-realm inputs.
33
+ - **Bound untrusted traffic.** Separate request, successful response, and error
34
+ response limits prevent accidental buffering while preserving meaningful
35
+ error codes and cancellation.
30
36
  - **Ship less supply-chain risk.** The package has no runtime dependencies and
31
37
  verifies public exports, browser behavior, security regressions, and size
32
38
  budgets before release.
@@ -48,14 +54,27 @@ claims about every remote workload; commands and limitations are in the
48
54
  ## Features
49
55
 
50
56
  - Data-first and complete-response APIs with TypeScript inference.
57
+ - Native `URL` and `Request` inputs with explicit per-call overrides and stable
58
+ lifecycle snapshots.
59
+ - First-class RFC 10008 `QUERY` helpers with JSON bodies and safe retries for
60
+ replayable content.
61
+ - Query- and fragment-safe `baseURL` prefix composition.
51
62
  - Object query merging plus native ordered `URLSearchParams` through
52
63
  `searchParams`.
64
+ - Native multipart and URL-encoded response parsing through `formData`.
65
+ - Raw binary response parsing as a portable `Uint8Array` through `bytes`.
66
+ - Response-type-driven `Accept` negotiation with custom-header precedence.
67
+ - Standards-correct opaque and manual-redirect Fetch responses without false
68
+ HTTP or parser failures.
69
+ - Optional non-throwing HTTP status handling with parsed response data and
70
+ complete metadata.
53
71
  - Standard Schema v1 validation and transformation for untrusted responses.
54
72
  - Incremental SSE and NDJSON async iterables with cancellation and size limits.
55
73
  - Progress-aware file download streams that preserve backpressure and avoid
56
74
  buffering the complete response in memory.
57
75
  - Unified errors across Fetch, XHR, parsing, validation, timeouts, and aborts.
58
76
  - Request/response/error interceptors with deterministic priority ordering.
77
+ - Shallow-merged local request context for tracing and lifecycle policies.
59
78
  - Official retry, cache, circuit-breaker, concurrency, authentication, logger,
60
79
  upload, and download plugins.
61
80
  - Method-aware `MockAdapter` routing, matching, delays, failures, and history.
@@ -120,6 +139,44 @@ console.log(response.headers)
120
139
  console.log(response.raw)
121
140
  ```
122
141
 
142
+ ## Native Fetch inputs
143
+
144
+ Use a native `Request` directly when another platform layer already owns the
145
+ request construction. Client defaults and explicit overrides still participate
146
+ in the normal lifecycle, while an unchanged body is not cloned or buffered:
147
+
148
+ ```ts
149
+ const input = new Request('https://api.example.com/users/1', {
150
+ headers: {
151
+ authorization: `Bearer ${accessToken}`
152
+ }
153
+ })
154
+
155
+ const user = await api.request<User>(input, {
156
+ timeout: 3000
157
+ })
158
+ ```
159
+
160
+ Native `URL`, `Headers`, body values, cancellation signals, and Fetch options
161
+ remain available throughout interceptors, plugins, responses, and errors.
162
+
163
+ ## Content-bearing queries
164
+
165
+ Use the standardized `QUERY` method for safe, idempotent queries whose input
166
+ belongs in a typed request body instead of a long URL:
167
+
168
+ ```ts
169
+ const users = await api.query<User[]>('/users/search', {
170
+ json: {
171
+ status: 'active',
172
+ teams: ['platform', 'web']
173
+ }
174
+ })
175
+ ```
176
+
177
+ JSON supplies the required media type automatically. Replayable QUERY bodies
178
+ participate in safe retries when the retry plugin is installed.
179
+
123
180
  ## Response validation
124
181
 
125
182
  Validate untrusted response data with any Standard Schema v1 compatible
@@ -162,7 +219,9 @@ for await (const event of events) {
162
219
  console.log(event.event, event.data, event.id)
163
220
  }
164
221
 
165
- const records = await api.ndjson<User>('/users/export')
222
+ const records = await api.ndjson('/users/export', {
223
+ itemSchema: userSchema
224
+ })
166
225
 
167
226
  for await (const user of records) {
168
227
  console.log(user.name)
@@ -171,8 +230,29 @@ for await (const user of records) {
171
230
 
172
231
  Iteration is lazy and does not buffer the complete response. Breaking out of
173
232
  the loop cancels the response reader. `maxResponseSize` remains enforced while
174
- the stream is consumed. A response schema validates the parsed response value
175
- once; it does not validate individual SSE events or NDJSON records.
233
+ the stream is consumed. `itemSchema` validates and may transform each item
234
+ immediately before it is yielded, without buffering the rest of the stream.
235
+ Failures expose the item index and NDJSON line or SSE event metadata.
236
+
237
+ Native `FormData`, `Blob`, `ArrayBuffer`, and `ReadableStream` request bodies
238
+ also work when created by another same-origin window or iframe. Detection does
239
+ not lock streams, and retry safety and request-size limits remain active.
240
+ With Fetch, `maxRequestSize` counts stream chunks without buffering and
241
+ cancels the source once the limit is exceeded.
242
+
243
+ Buffered bodies attached to thrown HTTP errors are capped at 10 MiB by
244
+ default. Override `maxErrorResponseSize`, or set it to `Infinity` for trusted
245
+ services that require complete error payloads. This guard preserves
246
+ `HTTP_ERROR`; a stricter `maxResponseSize` remains a hard
247
+ `RESPONSE_TOO_LARGE` limit.
248
+
249
+ Error-body reads and asynchronous JSON parsing are also bounded by `timeout`,
250
+ or by a 10-second error-only fallback when timeout is disabled. The fallback
251
+ keeps `HTTP_ERROR` and omits stalled data; explicit and total timeouts retain
252
+ `TIMEOUT_ERROR`. Malformed or rejected error payloads likewise keep
253
+ `HTTP_ERROR` with unavailable data, so parser failures cannot hide the server
254
+ status. Successful and explicitly non-throwing responses retain strict parser
255
+ errors. Fetch consumes error bodies once; use `error.data` for their payload.
176
256
 
177
257
  ## Request configuration
178
258
 
@@ -196,6 +276,7 @@ Query objects merge with client defaults. Native `searchParams` replace
196
276
  inherited query defaults while preserving repeated keys and order.
197
277
 
198
278
  The body options `body`, `json`, `form`, and `formData` are mutually exclusive.
279
+ `json` accepts complete JSON root values, including primitives and `null`.
199
280
  `GET` and `HEAD` requests cannot contain a body. Invalid configuration throws a
200
281
  `RequestError` before the adapter sends a request.
201
282
 
@@ -222,11 +303,14 @@ isolated to each client.
222
303
  ```ts
223
304
  api.request(config)
224
305
  api.requestResponse(config)
306
+ api.request(nativeRequest, config)
307
+ api.requestResponse(nativeRequest, config)
225
308
 
226
309
  api.get(url, config)
227
310
  api.post(url, config)
228
311
  api.put(url, config)
229
312
  api.patch(url, config)
313
+ api.query(url, config)
230
314
  api.delete(url, config)
231
315
  api.head(url, config)
232
316
  api.options(url, config)
@@ -237,6 +321,7 @@ api.getResponse(url, config)
237
321
  api.postResponse(url, config)
238
322
  api.putResponse(url, config)
239
323
  api.patchResponse(url, config)
324
+ api.queryResponse(url, config)
240
325
  api.deleteResponse(url, config)
241
326
  api.headResponse(url, config)
242
327
  api.optionsResponse(url, config)
@@ -267,6 +352,7 @@ import {
267
352
  circuitBreakerPlugin,
268
353
  concurrencyPlugin,
269
354
  createClient,
355
+ rateLimitPlugin,
270
356
  retryPlugin
271
357
  } from '@npora/request'
272
358
 
@@ -280,6 +366,7 @@ const request = createClient()
280
366
  }))
281
367
  .use(circuitBreakerPlugin())
282
368
  .use(concurrencyPlugin({ maxConcurrent: 20 }))
369
+ .use(rateLimitPlugin({ maxRequests: 100, interval: 1000 }))
283
370
  .use(cache)
284
371
  .use(authPlugin({
285
372
  token: () => accessToken,
@@ -517,6 +604,9 @@ Built-in plugins:
517
604
  - `cachePlugin()`
518
605
  - `circuitBreakerPlugin()`
519
606
  - `concurrencyPlugin()`
607
+ - `rateLimitPlugin()`
608
+ - `openTelemetryPlugin()`
609
+ - `openTelemetryMetricsPlugin()`
520
610
  - `authPlugin()`
521
611
  - `loggerPlugin()`
522
612
  - `uploadPlugin()`
@@ -560,6 +650,61 @@ Limits are isolated by resolved request origin. Queued requests are admitted
560
650
  in FIFO order and remain abortable through their request signal. Full queues
561
651
  and expired queue waits reject with the stable `CONCURRENCY_LIMIT` error code.
562
652
 
653
+ Limit actual transport attempts over a rolling time window independently from
654
+ the number of active logical requests:
655
+
656
+ ```ts
657
+ const limiter = rateLimitPlugin({
658
+ maxRequests: 100,
659
+ interval: 1000,
660
+ maxQueue: 500,
661
+ queueTimeout: 5000,
662
+ sharedRetryAfter: true,
663
+ maxRetryAfter: 60000
664
+ })
665
+
666
+ const request = createClient().use(limiter)
667
+ ```
668
+
669
+ Retry attempts consume permits, while cache hits do not. Full queues and
670
+ expired waits reject with the stable `RATE_LIMIT` error code. A 429 response
671
+ with `Retry-After` pauses the shared origin queue, so concurrent callers do not
672
+ independently retry into the same overloaded upstream.
673
+
674
+ Trace actual transport attempts without adding an OpenTelemetry runtime
675
+ dependency to this package:
676
+
677
+ ```ts
678
+ import { context, propagation, trace } from '@opentelemetry/api'
679
+
680
+ const request = createClient().use(openTelemetryPlugin({
681
+ tracer: trace.getTracer('@npora/request'),
682
+ context,
683
+ trace,
684
+ propagation
685
+ }))
686
+ ```
687
+
688
+ Each retry receives its own CLIENT span and propagated trace context. Cache
689
+ hits do not create transport spans. URLs omit credentials, query strings, and
690
+ fragments by default, and exception events are opt-in.
691
+
692
+ Record low-cardinality OpenTelemetry metrics through a separate optional
693
+ plugin:
694
+
695
+ ```ts
696
+ import { metrics } from '@opentelemetry/api'
697
+
698
+ const request = createClient().use(openTelemetryMetricsPlugin({
699
+ meter: metrics.getMeter('@npora/request'),
700
+ attributes: { 'service.namespace': 'checkout' }
701
+ }))
702
+ ```
703
+
704
+ The plugin records request duration, active requests, retries, cache hit/miss,
705
+ rate-limit waits, and complete ReadableStream/NDJSON/SSE consumption duration.
706
+ It does not bundle an SDK or exporter.
707
+
563
708
  Inject a structured logger when request correlation and timing are needed:
564
709
 
565
710
  ```ts
@@ -613,12 +758,12 @@ const api = createClient({ adapter })
613
758
  ## Errors
614
759
 
615
760
  ```ts
616
- import { RequestError } from '@npora/request'
761
+ import { isRequestError } from '@npora/request'
617
762
 
618
763
  try {
619
764
  await api.get('/users/missing')
620
765
  } catch (error) {
621
- if (error instanceof RequestError) {
766
+ if (isRequestError(error)) {
622
767
  console.error(error.code)
623
768
  console.error(error.status)
624
769
  console.error(error.data)
@@ -644,6 +789,10 @@ Stable request error codes:
644
789
  request failures through the unified base class while still inspecting schema
645
790
  issues when `error.code === 'SCHEMA_ERROR'`.
646
791
 
792
+ Prefer `isRequestError()` and `isSchemaValidationError()` when narrowing an
793
+ unknown caught value. Their non-enumerable shared brands work across iframes
794
+ and duplicated package instances, where `instanceof` can fail.
795
+
647
796
  ## Supply-chain verification
648
797
 
649
798
  The published package contains only the built `dist` artifacts, has no runtime
@@ -658,7 +807,6 @@ allowlist, and size budgets.
658
807
  - [API reference](https://github.com/npora/request/blob/main/docs/api.md)
659
808
  - [Architecture](https://github.com/npora/request/blob/main/docs/architecture.md)
660
809
  - [Migration from 0.x](https://github.com/npora/request/blob/main/docs/migration.md)
661
- - [Migration from Axios or Ky](https://github.com/npora/request/blob/main/docs/migration-from-axios-and-ky.md)
662
810
  - [Security model](https://github.com/npora/request/blob/main/docs/security.md)
663
811
  - [Testing and release gates](https://github.com/npora/request/blob/main/docs/testing.md)
664
812
  - [Performance benchmarks](https://github.com/npora/request/blob/main/docs/benchmark.md)
@@ -1,5 +1,5 @@
1
- import { i as QueryParams, j as HttpMethod, o as RequestConfig, t as NporaResponse } from "./response-BhyS3PAL.js";
2
- import { t as Adapter } from "./adapter-ODzpt_dM.js";
1
+ import { U as HttpMethod, f as RequestConfig, l as QueryParams, t as NporaResponse } from "./response-B6Z3qxyO.js";
2
+ import { t as Adapter } from "./adapter-YnK7Xzw4.js";
3
3
  //#region src/adapters/MockAdapter.d.ts
4
4
  type MockHandler<T = unknown> = (config: RequestConfig) => T | Promise<T>;
5
5
  type MockURLMatcher = string | RegExp;
@@ -1,5 +1,5 @@
1
- import { i as QueryParams, j as HttpMethod, o as RequestConfig, t as NporaResponse } from "./response-BhyS3PAL.cjs";
2
- import { t as Adapter } from "./adapter-BeVVCcNG.cjs";
1
+ import { U as HttpMethod, f as RequestConfig, l as QueryParams, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
2
+ import { t as Adapter } from "./adapter-Bshqh0DY.cjs";
3
3
  //#region src/adapters/MockAdapter.d.ts
4
4
  type MockHandler<T = unknown> = (config: RequestConfig) => T | Promise<T>;
5
5
  type MockURLMatcher = string | RegExp;
@@ -1,4 +1,4 @@
1
- import { o as RequestConfig, t as NporaResponse } from "./response-BhyS3PAL.js";
1
+ import { f as RequestConfig, t as NporaResponse } from "./response-B6Z3qxyO.js";
2
2
  //#region src/interceptors/InterceptorManager.d.ts
3
3
  type Interceptor<T> = (value: T) => T | Promise<T>;
4
4
  interface InterceptorOptions {
@@ -37,6 +37,12 @@ declare class RequestContext<T = unknown> {
37
37
  readonly startTime: number;
38
38
  endTime?: number;
39
39
  attempt: number;
40
+ /** @internal Total time spent waiting for rate-limit admission. */
41
+ rateLimitWaitTime: number;
42
+ /** @internal Whether the rate-limit plugin admitted an attempt. */
43
+ rateLimitApplied: boolean;
44
+ /** @internal Whether the cache plugin supplied the final response. */
45
+ cacheHit: boolean;
40
46
  constructor(config: RequestConfig, preserveRaw?: boolean,
41
47
  /** @internal */
42
48
  background?: boolean);
@@ -1,4 +1,4 @@
1
- import { o as RequestConfig, t as NporaResponse } from "./response-BhyS3PAL.cjs";
1
+ import { f as RequestConfig, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
2
2
  //#region src/interceptors/InterceptorManager.d.ts
3
3
  type Interceptor<T> = (value: T) => T | Promise<T>;
4
4
  interface InterceptorOptions {
@@ -37,6 +37,12 @@ declare class RequestContext<T = unknown> {
37
37
  readonly startTime: number;
38
38
  endTime?: number;
39
39
  attempt: number;
40
+ /** @internal Total time spent waiting for rate-limit admission. */
41
+ rateLimitWaitTime: number;
42
+ /** @internal Whether the rate-limit plugin admitted an attempt. */
43
+ rateLimitApplied: boolean;
44
+ /** @internal Whether the cache plugin supplied the final response. */
45
+ cacheHit: boolean;
40
46
  constructor(config: RequestConfig, preserveRaw?: boolean,
41
47
  /** @internal */
42
48
  background?: boolean);
@@ -0,0 +1 @@
1
+ const e=Symbol.for(`@npora/request/RequestError`);var RequestError=class extends Error{constructor(t,n){super(t),Object.defineProperty(this,e,{value:!0}),this.name=`RequestError`,this.code=n.code,this.status=n.status??n.response?.status,this.data=n.data===null?n.data:n.data??n.response?.data,this.response=n.response,this.config=n.config??n.response?.config,this.cause=n.cause}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status}}};function isRequestError(t){if(typeof t!=`object`&&typeof t!=`function`||t===null)return!1;try{return Reflect.get(t,e)===!0}catch{return!1}}export{isRequestError as n,RequestError as t};
@@ -0,0 +1 @@
1
+ const e=Symbol.for(`@npora/request/RequestError`);var RequestError=class extends Error{constructor(t,n){super(t),Object.defineProperty(this,e,{value:!0}),this.name=`RequestError`,this.code=n.code,this.status=n.status??n.response?.status,this.data=n.data===null?n.data:n.data??n.response?.data,this.response=n.response,this.config=n.config??n.response?.config,this.cause=n.cause}toJSON(){return{name:this.name,message:this.message,code:this.code,status:this.status}}};function isRequestError(t){if(typeof t!=`object`&&typeof t!=`function`||t===null)return!1;try{return Reflect.get(t,e)===!0}catch{return!1}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return isRequestError}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return RequestError}});
@@ -0,0 +1,215 @@
1
+ import { H as StandardSchemaV1, f as RequestConfig, h as RequestURL, m as RequestInputConfig, n as ServerSentEvent, r as StreamingSchemaLocation, t as NporaResponse } from "./response-B6Z3qxyO.cjs";
2
+ import { t as Adapter } from "./adapter-Bshqh0DY.cjs";
3
+ import { s as InterceptorManager, t as Plugin } from "./Plugin-Cxb-obdZ.cjs";
4
+ //#region src/types/client.d.ts
5
+ /**
6
+ * Client creation options.
7
+ */
8
+ interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method' | 'schema' | 'itemSchema'>> {
9
+ /**
10
+ * Request adapter.
11
+ *
12
+ * @default FetchAdapter
13
+ */
14
+ adapter?: Adapter;
15
+ }
16
+ //#endregion
17
+ //#region src/client/Client.d.ts
18
+ type MethodConfig = Omit<RequestConfig, 'url' | 'method'>;
19
+ type SchemaMethodConfig<Schema extends StandardSchemaV1> = Omit<MethodConfig, 'schema'> & {
20
+ schema: Schema;
21
+ };
22
+ type StreamingMethodConfig = Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>;
23
+ type ItemSchemaMethodConfig<Schema extends StandardSchemaV1> = Omit<StreamingMethodConfig, 'itemSchema'> & {
24
+ itemSchema: Schema;
25
+ };
26
+ declare class Client {
27
+ private readonly defaults;
28
+ private readonly adapter;
29
+ private readonly installedPlugins;
30
+ private readonly hooks;
31
+ readonly interceptors: {
32
+ request: InterceptorManager<RequestConfig>;
33
+ response: InterceptorManager<NporaResponse<unknown>>;
34
+ error: InterceptorManager<unknown>;
35
+ };
36
+ private readonly pipeline;
37
+ constructor(options?: ClientOptions);
38
+ /**
39
+ * Create an isolated client that inherits this client's defaults.
40
+ */
41
+ extend(options?: ClientOptions): Client;
42
+ use(plugin: Plugin): this;
43
+ unuse(pluginName: string): this;
44
+ hasPlugin(pluginName: string): boolean;
45
+ request<Schema extends StandardSchemaV1>(config: RequestConfig & {
46
+ schema: Schema;
47
+ }): Promise<StandardSchemaV1.InferOutput<Schema>>;
48
+ request<Schema extends StandardSchemaV1>(input: Request, config: RequestInputConfig & {
49
+ schema: Schema;
50
+ }): Promise<StandardSchemaV1.InferOutput<Schema>>;
51
+ request<T = unknown>(config: RequestConfig): Promise<T>;
52
+ request<T = unknown>(input: Request, config?: RequestInputConfig): Promise<T>;
53
+ requestResponse<Schema extends StandardSchemaV1>(config: RequestConfig & {
54
+ schema: Schema;
55
+ }): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
56
+ requestResponse<Schema extends StandardSchemaV1>(input: Request, config: RequestInputConfig & {
57
+ schema: Schema;
58
+ }): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
59
+ requestResponse<T = unknown>(config: RequestConfig): Promise<NporaResponse<T>>;
60
+ requestResponse<T = unknown>(input: Request, config?: RequestInputConfig): Promise<NporaResponse<T>>;
61
+ get<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
62
+ get<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
63
+ getResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
64
+ getResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
65
+ post<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
66
+ post<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
67
+ postResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
68
+ postResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
69
+ put<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
70
+ put<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
71
+ putResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
72
+ putResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
73
+ patch<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
74
+ patch<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
75
+ patchResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
76
+ patchResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
77
+ query<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
78
+ query<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
79
+ queryResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
80
+ queryResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
81
+ delete<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
82
+ delete<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
83
+ deleteResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
84
+ deleteResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
85
+ head(url: RequestURL, config?: Omit<MethodConfig, 'schema'>): Promise<void>;
86
+ headResponse(url: RequestURL, config?: Omit<MethodConfig, 'schema'>): Promise<NporaResponse<void>>;
87
+ options<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
88
+ options<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<T>;
89
+ optionsResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
90
+ optionsResponse<T = unknown>(url: RequestURL, config?: MethodConfig): Promise<NporaResponse<T>>;
91
+ /**
92
+ * Consume a server-sent event response as a lazy async iterable.
93
+ */
94
+ sse<Schema extends StandardSchemaV1>(url: RequestURL, config: ItemSchemaMethodConfig<Schema>): Promise<AsyncIterable<StandardSchemaV1.InferOutput<Schema>>>;
95
+ sse(url: RequestURL, config?: StreamingMethodConfig): Promise<AsyncIterable<ServerSentEvent>>;
96
+ /**
97
+ * Consume a server-sent event response with complete response metadata.
98
+ */
99
+ sseResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: ItemSchemaMethodConfig<Schema>): Promise<NporaResponse<AsyncIterable<StandardSchemaV1.InferOutput<Schema>>>>;
100
+ sseResponse(url: RequestURL, config?: StreamingMethodConfig): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
101
+ /**
102
+ * Consume newline-delimited JSON records as a lazy async iterable.
103
+ */
104
+ ndjson<Schema extends StandardSchemaV1>(url: RequestURL, config: ItemSchemaMethodConfig<Schema>): Promise<AsyncIterable<StandardSchemaV1.InferOutput<Schema>>>;
105
+ ndjson<T = unknown>(url: RequestURL, config?: StreamingMethodConfig): Promise<AsyncIterable<T>>;
106
+ /**
107
+ * Consume newline-delimited JSON with complete response metadata.
108
+ */
109
+ ndjsonResponse<Schema extends StandardSchemaV1>(url: RequestURL, config: ItemSchemaMethodConfig<Schema>): Promise<NporaResponse<AsyncIterable<StandardSchemaV1.InferOutput<Schema>>>>;
110
+ ndjsonResponse<T = unknown>(url: RequestURL, config?: StreamingMethodConfig): Promise<NporaResponse<AsyncIterable<T>>>;
111
+ private requestMethod;
112
+ private requestMethodResponse;
113
+ private mergeMethodConfig;
114
+ private mergeRequestInput;
115
+ private createPipeline;
116
+ private validatePlugin;
117
+ private findDependent;
118
+ }
119
+ //#endregion
120
+ //#region src/client/createClient.d.ts
121
+ /**
122
+ * Create an HTTP client instance.
123
+ */
124
+ declare function createClient(options?: ClientOptions): Client;
125
+ //#endregion
126
+ //#region src/adapters/FetchAdapter.d.ts
127
+ declare class FetchAdapter implements Adapter {
128
+ request<T = unknown>(config: RequestConfig): Promise<NporaResponse<T>>;
129
+ requestValidated<T = unknown>(config: RequestConfig, validatedHeaders: Headers, preserveRaw?: boolean): Promise<NporaResponse<T>>;
130
+ private execute;
131
+ }
132
+ //#endregion
133
+ //#region src/errors/RequestError.d.ts
134
+ /**
135
+ * Public request error codes.
136
+ */
137
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'SCHEMA_ERROR' | 'REQUEST_TOO_LARGE' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT' | 'RATE_LIMIT';
138
+ interface RequestErrorOptions<T = unknown> {
139
+ /**
140
+ * Stable machine-readable error code.
141
+ */
142
+ code: RequestErrorCode;
143
+ /**
144
+ * HTTP response status when available.
145
+ */
146
+ status?: number;
147
+ /**
148
+ * Parsed response body when the server returned a response.
149
+ */
150
+ data?: T;
151
+ /**
152
+ * Complete response metadata when the server returned a response.
153
+ */
154
+ response?: NporaResponse<T>;
155
+ /**
156
+ * Effective request configuration.
157
+ */
158
+ config?: RequestConfig;
159
+ /**
160
+ * Original error.
161
+ */
162
+ cause?: unknown;
163
+ }
164
+ /**
165
+ * Unified public error for all request failures.
166
+ */
167
+ declare class RequestError<T = unknown> extends Error {
168
+ readonly code: RequestErrorCode;
169
+ readonly status?: number;
170
+ readonly data?: T;
171
+ readonly response?: NporaResponse<T>;
172
+ readonly config?: RequestConfig;
173
+ readonly cause?: unknown;
174
+ constructor(message: string, options: RequestErrorOptions<T>);
175
+ /**
176
+ * Return a privacy-reduced representation for logs and telemetry.
177
+ *
178
+ * Request configuration, response bodies and causes are deliberately
179
+ * excluded because they can contain credentials or application data.
180
+ */
181
+ toJSON(): {
182
+ name: string;
183
+ message: string;
184
+ code: RequestErrorCode;
185
+ status?: number;
186
+ };
187
+ }
188
+ /**
189
+ * Identify request errors across realms and duplicated package instances.
190
+ */
191
+ declare function isRequestError<T = unknown>(value: unknown): value is RequestError<T>;
192
+ //#endregion
193
+ //#region src/errors/SchemaValidationError.d.ts
194
+ /**
195
+ * Response failure reported by a Standard Schema compatible validator.
196
+ */
197
+ declare class SchemaValidationError<T = unknown> extends RequestError<T> {
198
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
199
+ readonly schemaVendor: string;
200
+ /** Zero-based streaming item index when `itemSchema` failed. */
201
+ readonly itemIndex?: number;
202
+ /** One-based physical NDJSON line number when available. */
203
+ readonly lineNumber?: number;
204
+ /** SSE event type when available. */
205
+ readonly event?: string;
206
+ /** SSE event identifier when available. */
207
+ readonly eventId?: string;
208
+ constructor(message: string, response: NporaResponse<T>, schemaVendor: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, cause?: unknown, location?: StreamingSchemaLocation);
209
+ }
210
+ /**
211
+ * Identify schema validation errors across realms and package instances.
212
+ */
213
+ declare function isSchemaValidationError<T = unknown>(value: unknown): value is SchemaValidationError<T>;
214
+ //#endregion
215
+ export { RequestErrorOptions as a, createClient as c, RequestErrorCode as i, Client as l, isSchemaValidationError as n, isRequestError as o, RequestError as r, FetchAdapter as s, SchemaValidationError as t, ClientOptions as u };