@npora/request 1.9.0 → 1.10.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
@@ -3,9 +3,22 @@
3
3
  A TypeScript-first HTTP client built on the standard Fetch API.
4
4
 
5
5
  Npora Request adds typed configuration, a predictable request lifecycle,
6
- interceptors, plugins, unified errors, retries, caching, authentication, and
6
+ runtime response validation, streaming, interceptors, plugins, unified errors,
7
+ retries, caching, concurrency control, circuit breaking, authentication, and
7
8
  upload/download progress without adding runtime dependencies.
8
9
 
10
+ ## Features
11
+
12
+ - Data-first and complete-response APIs with TypeScript inference.
13
+ - Standard Schema v1 validation and transformation for untrusted responses.
14
+ - Incremental SSE and NDJSON async iterables with cancellation and size limits.
15
+ - Unified errors across Fetch, XHR, parsing, validation, timeouts, and aborts.
16
+ - Request/response/error interceptors with deterministic priority ordering.
17
+ - Official retry, cache, circuit-breaker, concurrency, authentication, logger,
18
+ upload, and download plugins.
19
+ - Method-aware `MockAdapter` routing, matching, delays, failures, and history.
20
+ - Browser, Web Worker, ESM, and CommonJS support with zero runtime dependencies.
21
+
9
22
  ## Install
10
23
 
11
24
  ```sh
@@ -20,6 +33,18 @@ Node.js 22 or newer is required. Modern Chromium-based browsers, Firefox,
20
33
  Safari/WebKit, and Web Workers are supported through their native Fetch
21
34
  implementations.
22
35
 
36
+ ## Version support
37
+
38
+ | Version | Status | Guidance |
39
+ | --- | --- | --- |
40
+ | `latest` | Current | Recommended for all new and existing applications. |
41
+ | Earlier releases `>=1.0.0` | Historical stable | Upgrade to `latest` for current fixes and security hardening. |
42
+ | `<1.0.0` | Deprecated and unsupported | Upgrade immediately; 0.x receives no fixes or security updates. |
43
+
44
+ All published releases before `1.0.0` are deprecated by project policy. Do not
45
+ use a 0.x release in production, documentation examples, dependency templates,
46
+ or new lockfiles.
47
+
23
48
  ## Quick start
24
49
 
25
50
  ```ts
@@ -53,6 +78,33 @@ console.log(response.headers)
53
78
  console.log(response.raw)
54
79
  ```
55
80
 
81
+ ## Response validation
82
+
83
+ Validate untrusted response data with any Standard Schema v1 compatible
84
+ library, including Zod 3.24+, Valibot, or ArkType. The schema output type is
85
+ inferred automatically and schemas may transform the parsed value:
86
+
87
+ ```ts
88
+ import { z } from 'zod'
89
+
90
+ const userSchema = z.object({
91
+ id: z.number(),
92
+ name: z.string()
93
+ })
94
+
95
+ const user = await api.get('/users/1', {
96
+ schema: userSchema
97
+ })
98
+
99
+ console.log(user.name)
100
+ ```
101
+
102
+ Validation failures throw `SchemaValidationError` with the stable
103
+ `SCHEMA_ERROR` code, validation issues, schema vendor, parsed response data,
104
+ and complete response metadata. Standard Schema support adds no runtime
105
+ dependency to Npora Request. Schemas are configured per endpoint so one
106
+ endpoint contract cannot be inherited by unrelated requests.
107
+
56
108
  ## Streaming responses
57
109
 
58
110
  SSE and NDJSON responses are decoded incrementally as async iterables. The
@@ -77,7 +129,8 @@ for await (const user of records) {
77
129
 
78
130
  Iteration is lazy and does not buffer the complete response. Breaking out of
79
131
  the loop cancels the response reader. `maxResponseSize` remains enforced while
80
- the stream is consumed.
132
+ the stream is consumed. A response schema validates the parsed response value
133
+ once; it does not validate individual SSE events or NDJSON records.
81
134
 
82
135
  ## Request configuration
83
136
 
@@ -126,6 +179,8 @@ api.patch(url, config)
126
179
  api.delete(url, config)
127
180
  api.head(url, config)
128
181
  api.options(url, config)
182
+ api.sse(url, config)
183
+ api.ndjson(url, config)
129
184
 
130
185
  api.getResponse(url, config)
131
186
  api.postResponse(url, config)
@@ -134,6 +189,8 @@ api.patchResponse(url, config)
134
189
  api.deleteResponse(url, config)
135
190
  api.headResponse(url, config)
136
191
  api.optionsResponse(url, config)
192
+ api.sseResponse(url, config)
193
+ api.ndjsonResponse(url, config)
137
194
  ```
138
195
 
139
196
  ## Plugins
@@ -314,10 +371,23 @@ Stable request error codes:
314
371
  - `TIMEOUT_ERROR`
315
372
  - `ABORT_ERROR`
316
373
  - `PARSER_ERROR`
374
+ - `SCHEMA_ERROR`
317
375
  - `RESPONSE_TOO_LARGE`
318
376
  - `CIRCUIT_OPEN`
319
377
  - `CONCURRENCY_LIMIT`
320
378
 
379
+ `SchemaValidationError` extends `RequestError`, so applications can handle all
380
+ request failures through the unified base class while still inspecting schema
381
+ issues when `error.code === 'SCHEMA_ERROR'`.
382
+
383
+ ## Supply-chain verification
384
+
385
+ The published package contains only the built `dist` artifacts, has no runtime
386
+ dependencies, and is released through npm trusted publishing with provenance.
387
+ Repository release gates verify the exact dependency tree against malware
388
+ advisories, npm registry signatures, known vulnerabilities, the package file
389
+ allowlist, and size budgets.
390
+
321
391
  ## Documentation
322
392
 
323
393
  - [API reference](https://github.com/npora/request/blob/main/docs/api.md)
package/dist/index.cjs CHANGED
@@ -17,6 +17,24 @@ var RequestError = class extends Error {
17
17
  }
18
18
  };
19
19
  //#endregion
20
+ //#region src/errors/SchemaValidationError.ts
21
+ /**
22
+ * Response failure reported by a Standard Schema compatible validator.
23
+ */
24
+ var SchemaValidationError = class extends RequestError {
25
+ constructor(message, response, schemaVendor, issues = [], cause) {
26
+ super(message, {
27
+ code: "SCHEMA_ERROR",
28
+ response,
29
+ cause
30
+ });
31
+ this.name = "SchemaValidationError";
32
+ this.issues = issues;
33
+ this.schemaVendor = schemaVendor;
34
+ Object.setPrototypeOf(this, new.target.prototype);
35
+ }
36
+ };
37
+ //#endregion
20
38
  //#region src/utils/createTimeoutSignal.ts
21
39
  function createTimeoutSignal(signal, timeout) {
22
40
  if (!timeout || timeout <= 0) return {
@@ -592,11 +610,18 @@ function copyResponseMetadata(source, target) {
592
610
  }
593
611
  function detectResponseType(response) {
594
612
  const contentType = response.headers.get("content-type") ?? "";
595
- if (contentType.includes("text/event-stream")) return "sse";
596
- if (contentType.includes("application/x-ndjson") || contentType.includes("application/ndjson") || contentType.includes("+ndjson")) return "ndjson";
597
- if (contentType.includes("application/json") || contentType.includes("+json")) return "json";
613
+ const parameterStart = contentType.indexOf(";");
614
+ const mediaType = contentType.slice(0, parameterStart === -1 ? void 0 : parameterStart).trim().toLowerCase();
615
+ if (mediaType === "text/event-stream") return "sse";
616
+ if (mediaType === "application/x-ndjson" || mediaType === "application/ndjson" || hasStructuredSuffix(mediaType, "+ndjson")) return "ndjson";
617
+ if (mediaType === "application/json" || hasStructuredSuffix(mediaType, "+json")) return "json";
598
618
  return "text";
599
619
  }
620
+ function hasStructuredSuffix(mediaType, suffix) {
621
+ const slashIndex = mediaType.indexOf("/");
622
+ const suffixStart = mediaType.length - suffix.length;
623
+ return slashIndex > 0 && suffixStart > slashIndex + 1 && mediaType.endsWith(suffix);
624
+ }
600
625
  //#endregion
601
626
  //#region src/utils/validateRequestConfig.ts
602
627
  const BODY_FIELDS = [
@@ -612,10 +637,22 @@ function validateRequestConfig(config) {
612
637
  validateURL(config);
613
638
  validateTimeout(config);
614
639
  validateLimits(config);
640
+ validateSchema(config);
615
641
  const headers = validateHeaders(config);
616
642
  validateBody(config);
617
643
  return headers;
618
644
  }
645
+ function validateSchema(config) {
646
+ if (config.schema === void 0) return;
647
+ try {
648
+ const candidate = config.schema;
649
+ if (typeof candidate !== "object" && typeof candidate !== "function" || candidate === null) throw new TypeError("Schema must be an object or function");
650
+ const standard = candidate["~standard"];
651
+ if (typeof standard !== "object" || standard === null || standard.version !== 1 || typeof standard.vendor !== "string" || typeof standard.validate !== "function") throw new TypeError("Schema does not implement Standard Schema v1");
652
+ } catch (error) {
653
+ throw configError("Request schema must implement Standard Schema v1", config, error);
654
+ }
655
+ }
619
656
  function validateLimits(config) {
620
657
  validateLimit(config.maxResponseSize, "Request maxResponseSize", config);
621
658
  validateLimit(config.maxFormDataDepth, "Request maxFormDataDepth", config);
@@ -1210,9 +1247,35 @@ var Pipeline = class {
1210
1247
  }
1211
1248
  async processResponse(context) {
1212
1249
  if (this.hooks.hasResponseHooks) await this.hooks.runResponse(context);
1250
+ await this.validateResponseSchema(context);
1213
1251
  if (this.interceptors.response.active) context.response = await this.interceptors.response.run(context.response);
1214
1252
  return context.response;
1215
1253
  }
1254
+ async validateResponseSchema(context) {
1255
+ const schema = context.config.schema;
1256
+ const response = context.response;
1257
+ if (!schema || !response) return;
1258
+ let result;
1259
+ let schemaVendor = "unknown";
1260
+ try {
1261
+ const standard = schema["~standard"];
1262
+ schemaVendor = standard.vendor;
1263
+ result = await standard.validate(response.data);
1264
+ } catch (error) {
1265
+ throw new SchemaValidationError("Response schema validator failed", response, schemaVendor, [], error);
1266
+ }
1267
+ if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema result"));
1268
+ const issues = "issues" in result ? result.issues : void 0;
1269
+ if (issues !== void 0) {
1270
+ if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected Standard Schema issues to be an array"));
1271
+ throw new SchemaValidationError("Response schema validation failed", response, schemaVendor, issues);
1272
+ }
1273
+ if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema value"));
1274
+ context.response = {
1275
+ ...response,
1276
+ data: result.value
1277
+ };
1278
+ }
1216
1279
  async notifyError(context, error) {
1217
1280
  context.error = error;
1218
1281
  if (this.hooks.hasErrorHooks) try {
@@ -1962,7 +2025,7 @@ function cachePlugin(options = {}) {
1962
2025
  }
1963
2026
  const record = completedRecords.get(requestContext);
1964
2027
  completedRecords.delete(requestContext);
1965
- if (record && requestContext.response && !requestContext.error) {
2028
+ if (record && requestContext.response && (!requestContext.error || isSchemaValidationFailure(requestContext.error))) {
1966
2029
  pending.resolve(record);
1967
2030
  return;
1968
2031
  }
@@ -2096,6 +2159,9 @@ function isCacheableRequest(config, methods) {
2096
2159
  function isAsyncIterable(value) {
2097
2160
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
2098
2161
  }
2162
+ function isSchemaValidationFailure(error) {
2163
+ return error instanceof RequestError && error.code === "SCHEMA_ERROR";
2164
+ }
2099
2165
  function allowsPersistentCaching(response) {
2100
2166
  if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
2101
2167
  return !response.headers.get("vary")?.split(",").some((name) => name.trim() === "*");
@@ -3179,6 +3245,7 @@ exports.MemoryCacheStore = MemoryCacheStore;
3179
3245
  exports.MockAdapter = MockAdapter;
3180
3246
  exports.PluginError = PluginError;
3181
3247
  exports.RequestError = RequestError;
3248
+ exports.SchemaValidationError = SchemaValidationError;
3182
3249
  exports.authPlugin = authPlugin;
3183
3250
  exports.cachePlugin = cachePlugin;
3184
3251
  exports.circuitBreakerPlugin = circuitBreakerPlugin;
package/dist/index.d.cts CHANGED
@@ -4,6 +4,49 @@
4
4
  */
5
5
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
6
  //#endregion
7
+ //#region src/types/standardSchema.d.ts
8
+ /**
9
+ * Standard Schema v1 interface.
10
+ *
11
+ * Compatible schema libraries can be consumed without a runtime dependency on
12
+ * `@standard-schema/spec`.
13
+ */
14
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
15
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
16
+ }
17
+ declare namespace StandardSchemaV1 {
18
+ interface Props<Input = unknown, Output = Input> {
19
+ readonly version: 1;
20
+ readonly vendor: string;
21
+ readonly validate: (value: unknown, options?: Options) => Result<Output> | Promise<Result<Output>>;
22
+ readonly types?: Types<Input, Output>;
23
+ }
24
+ interface Options {
25
+ readonly libraryOptions?: Record<string, unknown>;
26
+ }
27
+ type Result<Output> = SuccessResult<Output> | FailureResult;
28
+ interface SuccessResult<Output> {
29
+ readonly value: Output;
30
+ readonly issues?: undefined;
31
+ }
32
+ interface FailureResult {
33
+ readonly issues: ReadonlyArray<Issue>;
34
+ }
35
+ interface Issue {
36
+ readonly message: string;
37
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment>;
38
+ }
39
+ interface PathSegment {
40
+ readonly key: PropertyKey;
41
+ }
42
+ interface Types<Input = unknown, Output = Input> {
43
+ readonly input: Input;
44
+ readonly output: Output;
45
+ }
46
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
47
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
48
+ }
49
+ //#endregion
7
50
  //#region src/types/extensions.d.ts
8
51
  type CircuitState = 'closed' | 'open' | 'half-open';
9
52
  interface CircuitBreakerOptions {
@@ -274,6 +317,12 @@ interface RequestConfig {
274
317
  */
275
318
  maxFormDataDepth?: number;
276
319
  responseType?: ResponseType;
320
+ /**
321
+ * Validate and optionally transform the parsed response value.
322
+ *
323
+ * Accepts any Standard Schema v1 compatible validator.
324
+ */
325
+ schema?: StandardSchemaV1;
277
326
  validateStatus?: (status: number) => boolean;
278
327
  extensions?: RequestExtensions;
279
328
  }
@@ -353,7 +402,7 @@ interface Adapter {
353
402
  /**
354
403
  * Client creation options.
355
404
  */
356
- interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method'>> {
405
+ interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method' | 'schema'>> {
357
406
  /**
358
407
  * Request adapter.
359
408
  *
@@ -533,6 +582,10 @@ interface Plugin {
533
582
  }
534
583
  //#endregion
535
584
  //#region src/client/Client.d.ts
585
+ type MethodConfig = Omit<RequestConfig, 'url' | 'method'>;
586
+ type SchemaMethodConfig<Schema extends StandardSchemaV1> = Omit<MethodConfig, 'schema'> & {
587
+ schema: Schema;
588
+ };
536
589
  declare class Client {
537
590
  private readonly defaults;
538
591
  private readonly adapter;
@@ -552,38 +605,56 @@ declare class Client {
552
605
  use(plugin: Plugin): this;
553
606
  unuse(pluginName: string): this;
554
607
  hasPlugin(pluginName: string): boolean;
608
+ request<Schema extends StandardSchemaV1>(config: RequestConfig & {
609
+ schema: Schema;
610
+ }): Promise<StandardSchemaV1.InferOutput<Schema>>;
555
611
  request<T = unknown>(config: RequestConfig): Promise<T>;
612
+ requestResponse<Schema extends StandardSchemaV1>(config: RequestConfig & {
613
+ schema: Schema;
614
+ }): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
556
615
  requestResponse<T = unknown>(config: RequestConfig): Promise<NporaResponse<T>>;
557
- get<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
558
- getResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
559
- post<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
560
- postResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
561
- put<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
562
- putResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
563
- patch<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
564
- patchResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
565
- delete<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
566
- deleteResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
567
- head(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<void>;
568
- headResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<void>>;
569
- options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
570
- optionsResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
616
+ get<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
617
+ get<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
618
+ getResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
619
+ getResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
620
+ post<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
621
+ post<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
622
+ postResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
623
+ postResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
624
+ put<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
625
+ put<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
626
+ putResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
627
+ putResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
628
+ patch<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
629
+ patch<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
630
+ patchResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
631
+ patchResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
632
+ delete<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
633
+ delete<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
634
+ deleteResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
635
+ deleteResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
636
+ head(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<void>;
637
+ headResponse(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<NporaResponse<void>>;
638
+ options<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
639
+ options<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
640
+ optionsResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
641
+ optionsResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
571
642
  /**
572
643
  * Consume a server-sent event response as a lazy async iterable.
573
644
  */
574
- sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<ServerSentEvent>>;
645
+ sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<ServerSentEvent>>;
575
646
  /**
576
647
  * Consume a server-sent event response with complete response metadata.
577
648
  */
578
- sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
649
+ sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
579
650
  /**
580
651
  * Consume newline-delimited JSON records as a lazy async iterable.
581
652
  */
582
- ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<T>>;
653
+ ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<T>>;
583
654
  /**
584
655
  * Consume newline-delimited JSON with complete response metadata.
585
656
  */
586
- ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<T>>>;
657
+ ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<T>>>;
587
658
  private createPipeline;
588
659
  private validatePlugin;
589
660
  private findDependent;
@@ -599,7 +670,7 @@ declare function createClient(options?: ClientOptions): Client;
599
670
  /**
600
671
  * Public request error codes.
601
672
  */
602
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
673
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'SCHEMA_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
603
674
  interface RequestErrorOptions<T = unknown> {
604
675
  /**
605
676
  * Stable machine-readable error code.
@@ -639,6 +710,16 @@ declare class RequestError<T = unknown> extends Error {
639
710
  constructor(message: string, options: RequestErrorOptions<T>);
640
711
  }
641
712
  //#endregion
713
+ //#region src/errors/SchemaValidationError.d.ts
714
+ /**
715
+ * Response failure reported by a Standard Schema compatible validator.
716
+ */
717
+ declare class SchemaValidationError<T = unknown> extends RequestError<T> {
718
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
719
+ readonly schemaVendor: string;
720
+ constructor(message: string, response: NporaResponse<T>, schemaVendor: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, cause?: unknown);
721
+ }
722
+ //#endregion
642
723
  //#region src/plugins/PluginError.d.ts
643
724
  type PluginErrorCode = 'MISSING_DEPENDENCY' | 'PLUGIN_CONFLICT' | 'DEPENDENCY_IN_USE';
644
725
  interface PluginErrorOptions {
@@ -905,4 +986,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
905
986
  //#region src/plugins/uploadPlugin.d.ts
906
987
  declare function uploadPlugin(): Plugin;
907
988
  //#endregion
908
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, ServerSentEvent, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
989
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,49 @@
4
4
  */
5
5
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
6
6
  //#endregion
7
+ //#region src/types/standardSchema.d.ts
8
+ /**
9
+ * Standard Schema v1 interface.
10
+ *
11
+ * Compatible schema libraries can be consumed without a runtime dependency on
12
+ * `@standard-schema/spec`.
13
+ */
14
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
15
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
16
+ }
17
+ declare namespace StandardSchemaV1 {
18
+ interface Props<Input = unknown, Output = Input> {
19
+ readonly version: 1;
20
+ readonly vendor: string;
21
+ readonly validate: (value: unknown, options?: Options) => Result<Output> | Promise<Result<Output>>;
22
+ readonly types?: Types<Input, Output>;
23
+ }
24
+ interface Options {
25
+ readonly libraryOptions?: Record<string, unknown>;
26
+ }
27
+ type Result<Output> = SuccessResult<Output> | FailureResult;
28
+ interface SuccessResult<Output> {
29
+ readonly value: Output;
30
+ readonly issues?: undefined;
31
+ }
32
+ interface FailureResult {
33
+ readonly issues: ReadonlyArray<Issue>;
34
+ }
35
+ interface Issue {
36
+ readonly message: string;
37
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment>;
38
+ }
39
+ interface PathSegment {
40
+ readonly key: PropertyKey;
41
+ }
42
+ interface Types<Input = unknown, Output = Input> {
43
+ readonly input: Input;
44
+ readonly output: Output;
45
+ }
46
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
47
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
48
+ }
49
+ //#endregion
7
50
  //#region src/types/extensions.d.ts
8
51
  type CircuitState = 'closed' | 'open' | 'half-open';
9
52
  interface CircuitBreakerOptions {
@@ -274,6 +317,12 @@ interface RequestConfig {
274
317
  */
275
318
  maxFormDataDepth?: number;
276
319
  responseType?: ResponseType;
320
+ /**
321
+ * Validate and optionally transform the parsed response value.
322
+ *
323
+ * Accepts any Standard Schema v1 compatible validator.
324
+ */
325
+ schema?: StandardSchemaV1;
277
326
  validateStatus?: (status: number) => boolean;
278
327
  extensions?: RequestExtensions;
279
328
  }
@@ -353,7 +402,7 @@ interface Adapter {
353
402
  /**
354
403
  * Client creation options.
355
404
  */
356
- interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method'>> {
405
+ interface ClientOptions extends Partial<Omit<RequestConfig, 'url' | 'method' | 'schema'>> {
357
406
  /**
358
407
  * Request adapter.
359
408
  *
@@ -533,6 +582,10 @@ interface Plugin {
533
582
  }
534
583
  //#endregion
535
584
  //#region src/client/Client.d.ts
585
+ type MethodConfig = Omit<RequestConfig, 'url' | 'method'>;
586
+ type SchemaMethodConfig<Schema extends StandardSchemaV1> = Omit<MethodConfig, 'schema'> & {
587
+ schema: Schema;
588
+ };
536
589
  declare class Client {
537
590
  private readonly defaults;
538
591
  private readonly adapter;
@@ -552,38 +605,56 @@ declare class Client {
552
605
  use(plugin: Plugin): this;
553
606
  unuse(pluginName: string): this;
554
607
  hasPlugin(pluginName: string): boolean;
608
+ request<Schema extends StandardSchemaV1>(config: RequestConfig & {
609
+ schema: Schema;
610
+ }): Promise<StandardSchemaV1.InferOutput<Schema>>;
555
611
  request<T = unknown>(config: RequestConfig): Promise<T>;
612
+ requestResponse<Schema extends StandardSchemaV1>(config: RequestConfig & {
613
+ schema: Schema;
614
+ }): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
556
615
  requestResponse<T = unknown>(config: RequestConfig): Promise<NporaResponse<T>>;
557
- get<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
558
- getResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
559
- post<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
560
- postResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
561
- put<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
562
- putResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
563
- patch<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
564
- patchResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
565
- delete<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
566
- deleteResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
567
- head(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<void>;
568
- headResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<void>>;
569
- options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
570
- optionsResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
616
+ get<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
617
+ get<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
618
+ getResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
619
+ getResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
620
+ post<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
621
+ post<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
622
+ postResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
623
+ postResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
624
+ put<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
625
+ put<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
626
+ putResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
627
+ putResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
628
+ patch<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
629
+ patch<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
630
+ patchResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
631
+ patchResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
632
+ delete<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
633
+ delete<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
634
+ deleteResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
635
+ deleteResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
636
+ head(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<void>;
637
+ headResponse(url: string, config?: Omit<MethodConfig, 'schema'>): Promise<NporaResponse<void>>;
638
+ options<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<StandardSchemaV1.InferOutput<Schema>>;
639
+ options<T = unknown>(url: string, config?: MethodConfig): Promise<T>;
640
+ optionsResponse<Schema extends StandardSchemaV1>(url: string, config: SchemaMethodConfig<Schema>): Promise<NporaResponse<StandardSchemaV1.InferOutput<Schema>>>;
641
+ optionsResponse<T = unknown>(url: string, config?: MethodConfig): Promise<NporaResponse<T>>;
571
642
  /**
572
643
  * Consume a server-sent event response as a lazy async iterable.
573
644
  */
574
- sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<ServerSentEvent>>;
645
+ sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<ServerSentEvent>>;
575
646
  /**
576
647
  * Consume a server-sent event response with complete response metadata.
577
648
  */
578
- sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
649
+ sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
579
650
  /**
580
651
  * Consume newline-delimited JSON records as a lazy async iterable.
581
652
  */
582
- ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<T>>;
653
+ ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<AsyncIterable<T>>;
583
654
  /**
584
655
  * Consume newline-delimited JSON with complete response metadata.
585
656
  */
586
- ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<T>>>;
657
+ ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType' | 'schema'>): Promise<NporaResponse<AsyncIterable<T>>>;
587
658
  private createPipeline;
588
659
  private validatePlugin;
589
660
  private findDependent;
@@ -599,7 +670,7 @@ declare function createClient(options?: ClientOptions): Client;
599
670
  /**
600
671
  * Public request error codes.
601
672
  */
602
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
673
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'SCHEMA_ERROR' | 'RESPONSE_TOO_LARGE' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
603
674
  interface RequestErrorOptions<T = unknown> {
604
675
  /**
605
676
  * Stable machine-readable error code.
@@ -639,6 +710,16 @@ declare class RequestError<T = unknown> extends Error {
639
710
  constructor(message: string, options: RequestErrorOptions<T>);
640
711
  }
641
712
  //#endregion
713
+ //#region src/errors/SchemaValidationError.d.ts
714
+ /**
715
+ * Response failure reported by a Standard Schema compatible validator.
716
+ */
717
+ declare class SchemaValidationError<T = unknown> extends RequestError<T> {
718
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
719
+ readonly schemaVendor: string;
720
+ constructor(message: string, response: NporaResponse<T>, schemaVendor: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, cause?: unknown);
721
+ }
722
+ //#endregion
642
723
  //#region src/plugins/PluginError.d.ts
643
724
  type PluginErrorCode = 'MISSING_DEPENDENCY' | 'PLUGIN_CONFLICT' | 'DEPENDENCY_IN_USE';
644
725
  interface PluginErrorOptions {
@@ -905,4 +986,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
905
986
  //#region src/plugins/uploadPlugin.d.ts
906
987
  declare function uploadPlugin(): Plugin;
907
988
  //#endregion
908
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, ServerSentEvent, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
989
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -16,6 +16,24 @@ var RequestError = class extends Error {
16
16
  }
17
17
  };
18
18
  //#endregion
19
+ //#region src/errors/SchemaValidationError.ts
20
+ /**
21
+ * Response failure reported by a Standard Schema compatible validator.
22
+ */
23
+ var SchemaValidationError = class extends RequestError {
24
+ constructor(message, response, schemaVendor, issues = [], cause) {
25
+ super(message, {
26
+ code: "SCHEMA_ERROR",
27
+ response,
28
+ cause
29
+ });
30
+ this.name = "SchemaValidationError";
31
+ this.issues = issues;
32
+ this.schemaVendor = schemaVendor;
33
+ Object.setPrototypeOf(this, new.target.prototype);
34
+ }
35
+ };
36
+ //#endregion
19
37
  //#region src/utils/createTimeoutSignal.ts
20
38
  function createTimeoutSignal(signal, timeout) {
21
39
  if (!timeout || timeout <= 0) return {
@@ -591,11 +609,18 @@ function copyResponseMetadata(source, target) {
591
609
  }
592
610
  function detectResponseType(response) {
593
611
  const contentType = response.headers.get("content-type") ?? "";
594
- if (contentType.includes("text/event-stream")) return "sse";
595
- if (contentType.includes("application/x-ndjson") || contentType.includes("application/ndjson") || contentType.includes("+ndjson")) return "ndjson";
596
- if (contentType.includes("application/json") || contentType.includes("+json")) return "json";
612
+ const parameterStart = contentType.indexOf(";");
613
+ const mediaType = contentType.slice(0, parameterStart === -1 ? void 0 : parameterStart).trim().toLowerCase();
614
+ if (mediaType === "text/event-stream") return "sse";
615
+ if (mediaType === "application/x-ndjson" || mediaType === "application/ndjson" || hasStructuredSuffix(mediaType, "+ndjson")) return "ndjson";
616
+ if (mediaType === "application/json" || hasStructuredSuffix(mediaType, "+json")) return "json";
597
617
  return "text";
598
618
  }
619
+ function hasStructuredSuffix(mediaType, suffix) {
620
+ const slashIndex = mediaType.indexOf("/");
621
+ const suffixStart = mediaType.length - suffix.length;
622
+ return slashIndex > 0 && suffixStart > slashIndex + 1 && mediaType.endsWith(suffix);
623
+ }
599
624
  //#endregion
600
625
  //#region src/utils/validateRequestConfig.ts
601
626
  const BODY_FIELDS = [
@@ -611,10 +636,22 @@ function validateRequestConfig(config) {
611
636
  validateURL(config);
612
637
  validateTimeout(config);
613
638
  validateLimits(config);
639
+ validateSchema(config);
614
640
  const headers = validateHeaders(config);
615
641
  validateBody(config);
616
642
  return headers;
617
643
  }
644
+ function validateSchema(config) {
645
+ if (config.schema === void 0) return;
646
+ try {
647
+ const candidate = config.schema;
648
+ if (typeof candidate !== "object" && typeof candidate !== "function" || candidate === null) throw new TypeError("Schema must be an object or function");
649
+ const standard = candidate["~standard"];
650
+ if (typeof standard !== "object" || standard === null || standard.version !== 1 || typeof standard.vendor !== "string" || typeof standard.validate !== "function") throw new TypeError("Schema does not implement Standard Schema v1");
651
+ } catch (error) {
652
+ throw configError("Request schema must implement Standard Schema v1", config, error);
653
+ }
654
+ }
618
655
  function validateLimits(config) {
619
656
  validateLimit(config.maxResponseSize, "Request maxResponseSize", config);
620
657
  validateLimit(config.maxFormDataDepth, "Request maxFormDataDepth", config);
@@ -1209,9 +1246,35 @@ var Pipeline = class {
1209
1246
  }
1210
1247
  async processResponse(context) {
1211
1248
  if (this.hooks.hasResponseHooks) await this.hooks.runResponse(context);
1249
+ await this.validateResponseSchema(context);
1212
1250
  if (this.interceptors.response.active) context.response = await this.interceptors.response.run(context.response);
1213
1251
  return context.response;
1214
1252
  }
1253
+ async validateResponseSchema(context) {
1254
+ const schema = context.config.schema;
1255
+ const response = context.response;
1256
+ if (!schema || !response) return;
1257
+ let result;
1258
+ let schemaVendor = "unknown";
1259
+ try {
1260
+ const standard = schema["~standard"];
1261
+ schemaVendor = standard.vendor;
1262
+ result = await standard.validate(response.data);
1263
+ } catch (error) {
1264
+ throw new SchemaValidationError("Response schema validator failed", response, schemaVendor, [], error);
1265
+ }
1266
+ if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema result"));
1267
+ const issues = "issues" in result ? result.issues : void 0;
1268
+ if (issues !== void 0) {
1269
+ if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected Standard Schema issues to be an array"));
1270
+ throw new SchemaValidationError("Response schema validation failed", response, schemaVendor, issues);
1271
+ }
1272
+ if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema value"));
1273
+ context.response = {
1274
+ ...response,
1275
+ data: result.value
1276
+ };
1277
+ }
1215
1278
  async notifyError(context, error) {
1216
1279
  context.error = error;
1217
1280
  if (this.hooks.hasErrorHooks) try {
@@ -1961,7 +2024,7 @@ function cachePlugin(options = {}) {
1961
2024
  }
1962
2025
  const record = completedRecords.get(requestContext);
1963
2026
  completedRecords.delete(requestContext);
1964
- if (record && requestContext.response && !requestContext.error) {
2027
+ if (record && requestContext.response && (!requestContext.error || isSchemaValidationFailure(requestContext.error))) {
1965
2028
  pending.resolve(record);
1966
2029
  return;
1967
2030
  }
@@ -2095,6 +2158,9 @@ function isCacheableRequest(config, methods) {
2095
2158
  function isAsyncIterable(value) {
2096
2159
  return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
2097
2160
  }
2161
+ function isSchemaValidationFailure(error) {
2162
+ return error instanceof RequestError && error.code === "SCHEMA_ERROR";
2163
+ }
2098
2164
  function allowsPersistentCaching(response) {
2099
2165
  if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
2100
2166
  return !response.headers.get("vary")?.split(",").some((name) => name.trim() === "*");
@@ -3171,4 +3237,4 @@ function uploadPlugin() {
3171
3237
  };
3172
3238
  }
3173
3239
  //#endregion
3174
- export { Client, FetchAdapter, InterceptorManager, MemoryCacheStore, MockAdapter, PluginError, RequestError, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
3240
+ export { Client, FetchAdapter, InterceptorManager, MemoryCacheStore, MockAdapter, PluginError, RequestError, SchemaValidationError, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",