@zayne-labs/callapi 1.8.8 → 1.8.10
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 +3 -3
- package/dist/esm/{common-D7kwLndy.d.ts → common-CmLbOQH8.d.ts} +54 -27
- package/dist/esm/index.d.ts +4 -4
- package/dist/esm/index.js +64 -79
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/utils/index.d.ts +1 -1
- package/dist/esm/utils/index.js +1 -1
- package/dist/esm/{utils-BbmhntpS.js → utils-BMQYfuNI.js} +17 -4
- package/dist/esm/utils-BMQYfuNI.js.map +1 -0
- package/package.json +10 -11
- package/dist/esm/utils-BbmhntpS.js.map +0 -1
package/README.md
CHANGED
@@ -7,8 +7,8 @@
|
|
7
7
|
<p align="center">
|
8
8
|
<!-- <a href="https://deno.bundlejs.com/badge?q=@zayne-labs/callapi,@zayne-labs/callapi&treeshake=%5B*%5D,%5B%7B+createFetchClient+%7D%5D&config=%7B%22compression%22:%7B%22type%22:%22brotli%22,%22quality%22:11%7D%7D"><img src="https://deno.bundlejs.com/badge?q=@zayne-labs/callapi,@zayne-labs/callapi&treeshake=%5B*%5D,%5B%7B+createFetchClient+%7D%5D&config=%7B%22compression%22:%7B%22type%22:%22brotli%22,%22quality%22:11%7D%7D" alt="bundle size"></a> -->
|
9
9
|
<a href="https://www.npmjs.com/package/@zayne-labs/callapi"><img src="https://img.shields.io/npm/v/@zayne-labs/callapi?style=flat&color=EFBA5F" alt="npm version"></a>
|
10
|
-
<a href="https://github.com/zayne-labs/
|
11
|
-
<a href="https://github.com/zayne-labs/
|
10
|
+
<a href="https://github.com/zayne-labs/callapi/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/@zayne-labs/callapi?style=flat&color=EFBA5F" alt="license"></a>
|
11
|
+
<a href="https://github.com/zayne-labs/callapi/graphs/commit-activity"><img src="https://img.shields.io/github/commit-activity/m/zayne-labs/callapi?style=flat&color=EFBA5F" alt="commit activity"></a>
|
12
12
|
<a href="https://www.npmjs.com/package/@zayne-labs/callapi"><img src="https://img.shields.io/npm/dm/@zayne-labs/callapi?style=flat&color=EFBA5F" alt="downloads per month"></a>
|
13
13
|
</p>
|
14
14
|
|
@@ -52,6 +52,6 @@ To do this, you first need to set your `script`'s type to `module`, then import
|
|
52
52
|
|
53
53
|
<!-- Locked to a specific version -->
|
54
54
|
<script type="module">
|
55
|
-
import { callApi } from "https://esm.run/@zayne-labs/callapi@
|
55
|
+
import { callApi } from "https://esm.run/@zayne-labs/callapi@1.8.9";
|
56
56
|
</script>
|
57
57
|
```
|
@@ -175,8 +175,7 @@ declare namespace StandardSchemaV1 {
|
|
175
175
|
}
|
176
176
|
//#endregion
|
177
177
|
//#region src/error.d.ts
|
178
|
-
type HTTPErrorDetails<TErrorData> = {
|
179
|
-
defaultErrorMessage: CallApiExtraOptions["defaultErrorMessage"];
|
178
|
+
type HTTPErrorDetails<TErrorData> = Pick<CallApiExtraOptions, "defaultHTTPErrorMessage"> & {
|
180
179
|
errorData: TErrorData;
|
181
180
|
response: Response;
|
182
181
|
};
|
@@ -236,6 +235,8 @@ interface URLOptions {
|
|
236
235
|
readonly initURLNormalized?: string;
|
237
236
|
/**
|
238
237
|
* Parameters to be appended to the URL (i.e: /:id)
|
238
|
+
*
|
239
|
+
* If url is defined as `/path/:id`, params will be `{ id: string }`
|
239
240
|
*/
|
240
241
|
params?: Params;
|
241
242
|
/**
|
@@ -245,7 +246,7 @@ interface URLOptions {
|
|
245
246
|
}
|
246
247
|
//#endregion
|
247
248
|
//#region src/validation.d.ts
|
248
|
-
type InferSchemaResult<TSchema, TFallbackResult =
|
249
|
+
type InferSchemaResult<TSchema, TFallbackResult = unknown> = undefined extends TSchema ? TFallbackResult : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TSchema extends AnyFunction<infer TResult> ? Awaited<TResult> : TFallbackResult;
|
249
250
|
interface CallApiSchemaConfig {
|
250
251
|
/**
|
251
252
|
* The base url of the schema. By default it's the baseURL of the fetch instance.
|
@@ -263,13 +264,13 @@ interface CallApiSchemaConfig {
|
|
263
264
|
*/
|
264
265
|
disableValidationOutputApplication?: boolean;
|
265
266
|
/**
|
266
|
-
*
|
267
|
+
*Determines the inference or requirement of the method option based on the route modifiers (`@get/`, `@post/`, `@put/`, `@patch/`, `@delete/`).
|
267
268
|
*
|
268
269
|
* - When `true`, the method option is made required on the type level and is not automatically added to the request options.
|
269
270
|
* - When `false` or `undefined` (default), the method option is not required on the type level, and is automatically added to the request options.
|
270
271
|
*
|
271
272
|
*/
|
272
|
-
|
273
|
+
requireMethodProvision?: boolean;
|
273
274
|
/**
|
274
275
|
* Controls the strictness of API route validation.
|
275
276
|
*
|
@@ -282,7 +283,6 @@ interface CallApiSchemaConfig {
|
|
282
283
|
* - All routes will be allowed, whether they are defined in the schema or not
|
283
284
|
* - Provides more flexibility but less type safety
|
284
285
|
*
|
285
|
-
* @default false
|
286
286
|
*/
|
287
287
|
strict?: boolean;
|
288
288
|
}
|
@@ -521,7 +521,6 @@ type RequestContext = {
|
|
521
521
|
*/
|
522
522
|
request: CallApiRequestOptionsForHooks;
|
523
523
|
};
|
524
|
-
type ResponseContext<TData, TErrorData> = UnmaskType<RequestContext & (CallApiResultErrorVariant<TErrorData> | CallApiResultSuccessVariant<TData>)>;
|
525
524
|
type ValidationErrorContext = UnmaskType<RequestContext & {
|
526
525
|
error: ValidationError;
|
527
526
|
response: Response | null;
|
@@ -530,6 +529,9 @@ type SuccessContext<TData> = UnmaskType<RequestContext & {
|
|
530
529
|
data: TData;
|
531
530
|
response: Response;
|
532
531
|
}>;
|
532
|
+
type ResponseContext<TData, TErrorData> = UnmaskType<RequestContext & (Prettify<CallApiResultSuccessVariant<TData>> | Prettify<Extract<CallApiResultErrorVariant<TErrorData>, {
|
533
|
+
error: PossibleHTTPError<TErrorData>;
|
534
|
+
}>>)>;
|
533
535
|
type RequestErrorContext = RequestContext & {
|
534
536
|
error: PossibleJavaScriptOrValidationError;
|
535
537
|
response: null;
|
@@ -634,37 +636,38 @@ interface RetryOptions<TErrorData> {
|
|
634
636
|
//#endregion
|
635
637
|
//#region src/types/conditional-types.d.ts
|
636
638
|
/**
|
637
|
-
* @description Makes a type
|
639
|
+
* @description Makes a type partial if the output type of TSchema contains undefined, otherwise makes it required
|
638
640
|
*/
|
639
|
-
type
|
641
|
+
type MakeSchemaOptionPartialOrRequired<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaResult<TSchemaOption> ? Partial<TObject> : Required<TObject>;
|
640
642
|
type ApplyURLBasedConfig<TSchemaConfig extends CallApiSchemaConfig, TCurrentRouteKeys extends string> = TSchemaConfig["baseURL"] extends string ? `${TSchemaConfig["baseURL"]}${TCurrentRouteKeys}` : TCurrentRouteKeys;
|
641
643
|
type ApplyStrictConfig<TSchemaConfig extends CallApiSchemaConfig, TCurrentRouteKeys extends string> = TSchemaConfig["strict"] extends true ? TCurrentRouteKeys : TCurrentRouteKeys | AnyString;
|
642
644
|
type ApplySchemaConfiguration<TSchemaConfig extends CallApiSchemaConfig, TCurrentRouteKeys extends string> = ApplyStrictConfig<TSchemaConfig, ApplyURLBasedConfig<TSchemaConfig, TCurrentRouteKeys>>;
|
643
645
|
type InferAllRouteKeys<TBaseSchema extends BaseCallApiSchema, TSchemaConfig extends CallApiSchemaConfig> = ApplySchemaConfiguration<TSchemaConfig, keyof TBaseSchema extends string ? keyof TBaseSchema : never>;
|
644
646
|
type InferInitURL<TBaseSchema extends BaseCallApiSchema, TSchemaConfig extends CallApiSchemaConfig> = InferAllRouteKeys<TBaseSchema, TSchemaConfig> | URL;
|
645
647
|
type GetCurrentRouteKey<TSchemaConfig extends CallApiSchemaConfig, TPath> = TSchemaConfig["baseURL"] extends string ? TPath extends `${TSchemaConfig["baseURL"]}${infer TCurrentRoute}` ? TCurrentRoute extends string ? TCurrentRoute : string : string : TPath extends URL ? string : TPath;
|
648
|
+
type GetCurrentRouteSchema<TBaseSchema extends BaseCallApiSchema, TCurrentRouteKey extends string> = NonNullable<Writeable<TBaseSchema[TCurrentRouteKey], "deep">>;
|
646
649
|
type JsonPrimitive = boolean | number | string | null | undefined;
|
647
650
|
type SerializableObject = Record<keyof object, unknown>;
|
648
651
|
type SerializableArray = Array<JsonPrimitive | SerializableArray | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableArray | SerializableObject>;
|
649
652
|
type Body = UnmaskType<RequestInit["body"] | SerializableArray | SerializableObject>;
|
650
|
-
type InferBodyOption<TSchema extends CallApiSchema> =
|
653
|
+
type InferBodyOption<TSchema extends CallApiSchema> = MakeSchemaOptionPartialOrRequired<TSchema["body"], {
|
651
654
|
/**
|
652
655
|
* Body of the request, can be a object or any other supported body type.
|
653
656
|
*/
|
654
657
|
body?: InferSchemaResult<TSchema["body"], Body>;
|
655
658
|
}>;
|
656
659
|
type MethodUnion = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
|
657
|
-
type InferMethodFromURL<TInitURL> = TInitURL extends `@${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
|
658
|
-
type MakeMethodOptionRequired<TInitURL, TSchemaConfig extends CallApiSchemaConfig, TObject> = undefined extends TSchemaConfig ? TObject : TInitURL extends `@${string}/${string}` ? TSchemaConfig["
|
659
|
-
type InferMethodOption<TSchema extends CallApiSchema, TSchemaConfig extends CallApiSchemaConfig, TInitURL> =
|
660
|
+
type InferMethodFromURL<TInitURL> = string extends TInitURL ? MethodUnion : TInitURL extends `@${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
|
661
|
+
type MakeMethodOptionRequired<TMethodSchemaOption extends CallApiSchema["method"], TInitURL, TSchemaConfig extends CallApiSchemaConfig, TObject> = MakeSchemaOptionPartialOrRequired<TMethodSchemaOption, undefined extends TSchemaConfig ? TObject : TInitURL extends `@${string}/${string}` ? TSchemaConfig["requireMethodProvision"] extends true ? Required<TObject> : TObject : TObject>;
|
662
|
+
type InferMethodOption<TSchema extends CallApiSchema, TSchemaConfig extends CallApiSchemaConfig, TInitURL> = MakeMethodOptionRequired<TSchema["method"], TInitURL, TSchemaConfig, {
|
660
663
|
/**
|
661
664
|
* HTTP method for the request.
|
662
665
|
* @default "GET"
|
663
666
|
*/
|
664
667
|
method?: InferSchemaResult<TSchema["method"], InferMethodFromURL<TInitURL>>;
|
665
|
-
}
|
668
|
+
}>;
|
666
669
|
type HeadersOption = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders | undefined> | Record<"Content-Type", CommonContentTypes | undefined> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | Array<[string, string]>>;
|
667
|
-
type InferHeadersOption<TSchema extends CallApiSchema> =
|
670
|
+
type InferHeadersOption<TSchema extends CallApiSchema> = MakeSchemaOptionPartialOrRequired<TSchema["headers"], {
|
668
671
|
/**
|
669
672
|
* Headers to be used in the request.
|
670
673
|
*/
|
@@ -677,25 +680,49 @@ interface Register {}
|
|
677
680
|
type GlobalMeta = Register extends {
|
678
681
|
meta?: infer TMeta extends Record<string, unknown>;
|
679
682
|
} ? TMeta : never;
|
680
|
-
type InferMetaOption<TSchema extends CallApiSchema> =
|
683
|
+
type InferMetaOption<TSchema extends CallApiSchema> = MakeSchemaOptionPartialOrRequired<TSchema["meta"], {
|
684
|
+
/**
|
685
|
+
* - An optional field you can fill with additional information,
|
686
|
+
* to associate with the request, typically used for logging or tracing.
|
687
|
+
*
|
688
|
+
* - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
|
689
|
+
*
|
690
|
+
* @example
|
691
|
+
* ```ts
|
692
|
+
* const callMainApi = callApi.create({
|
693
|
+
* baseURL: "https://main-api.com",
|
694
|
+
* onResponseError: ({ response, options }) => {
|
695
|
+
* if (options.meta?.userId) {
|
696
|
+
* console.error(`User ${options.meta.userId} made an error`);
|
697
|
+
* }
|
698
|
+
* },
|
699
|
+
* });
|
700
|
+
*
|
701
|
+
* const response = await callMainApi({
|
702
|
+
* url: "https://example.com/api/data",
|
703
|
+
* meta: { userId: "123" },
|
704
|
+
* });
|
705
|
+
* ```
|
706
|
+
*/
|
681
707
|
meta?: InferSchemaResult<TSchema["meta"], GlobalMeta>;
|
682
708
|
}>;
|
683
|
-
type InferQueryOption<TSchema extends CallApiSchema> =
|
709
|
+
type InferQueryOption<TSchema extends CallApiSchema> = MakeSchemaOptionPartialOrRequired<TSchema["query"], {
|
684
710
|
/**
|
685
711
|
* Parameters to be appended to the URL (i.e: /:id)
|
686
712
|
*/
|
687
713
|
query?: InferSchemaResult<TSchema["query"], Query>;
|
688
714
|
}>;
|
689
715
|
type EmptyString = "";
|
690
|
-
type InferParamFromRoute<
|
691
|
-
type
|
716
|
+
type InferParamFromRoute<TCurrentRoute> = TCurrentRoute extends `${infer IgnoredPrefix}:${infer TCurrentParam}/${infer TRemainingPath}` ? TCurrentParam extends EmptyString ? InferParamFromRoute<TRemainingPath> : Prettify<Record<TCurrentParam | (Params extends InferParamFromRoute<TRemainingPath> ? never : keyof Extract<InferParamFromRoute<TRemainingPath>, Record<string, unknown>>), AllowedQueryParamValues>> | [AllowedQueryParamValues, ...(Params extends InferParamFromRoute<TRemainingPath> ? [] : Extract<InferParamFromRoute<TRemainingPath>, unknown[]>)] : TCurrentRoute extends `${infer IgnoredPrefix}:${infer TCurrentParam}` ? TCurrentParam extends EmptyString ? Params : Prettify<Record<TCurrentParam, AllowedQueryParamValues>> | [AllowedQueryParamValues] : Params;
|
717
|
+
type MakeParamsOptionRequired<TParamsSchemaOption extends CallApiSchema["params"], TBaseSchema extends BaseCallApiSchema, TCurrentRouteKey extends string, TObject> = MakeSchemaOptionPartialOrRequired<TParamsSchemaOption, TCurrentRouteKey extends `${string}:${string}${"" | "/"}${"" | AnyString}` ? TCurrentRouteKey extends Extract<keyof TBaseSchema, TCurrentRouteKey> ? Required<TObject> : TObject : TObject>;
|
718
|
+
type InferParamsOption<TSchema extends CallApiSchema, TBaseSchema extends BaseCallApiSchema, TCurrentRouteKey extends string> = MakeParamsOptionRequired<TSchema["params"], TBaseSchema, TCurrentRouteKey, {
|
692
719
|
/**
|
693
720
|
* Parameters to be appended to the URL (i.e: /:id)
|
694
721
|
*/
|
695
722
|
params?: InferSchemaResult<TSchema["params"], InferParamFromRoute<TCurrentRouteKey>>;
|
696
723
|
}>;
|
697
|
-
type InferExtraOptions<TSchema extends CallApiSchema, TCurrentRouteKey> = InferMetaOption<TSchema> & InferParamsOption<TSchema, TCurrentRouteKey> & InferQueryOption<TSchema>;
|
698
|
-
type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction<infer
|
724
|
+
type InferExtraOptions<TSchema extends CallApiSchema, TBaseSchema extends BaseCallApiSchema, TCurrentRouteKey extends string> = InferMetaOption<TSchema> & InferParamsOption<TSchema, TBaseSchema, TCurrentRouteKey> & InferQueryOption<TSchema>;
|
725
|
+
type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction<infer TReturnedSchema> ? InferSchemaResult<TReturnedSchema> : never : never : never>;
|
699
726
|
type ExtractKeys<TUnion, TSelectedUnion extends TUnion> = Extract<TUnion, TSelectedUnion>;
|
700
727
|
type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
|
701
728
|
resultMode: "onlySuccessWithException";
|
@@ -765,10 +792,10 @@ type SharedExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, T
|
|
765
792
|
*/
|
766
793
|
customFetchImpl?: FetchImpl;
|
767
794
|
/**
|
768
|
-
* Default error message to use if none is provided from a response.
|
795
|
+
* Default HTTP error message to use if none is provided from a response.
|
769
796
|
* @default "Failed to fetch data from server!"
|
770
797
|
*/
|
771
|
-
|
798
|
+
defaultHTTPErrorMessage?: string | ((context: Pick<HTTPError<TErrorData>, "errorData" | "response">) => string);
|
772
799
|
/**
|
773
800
|
* If true, forces the calculation of the total byte size from the request or response body, in case the content-length header is not present or is incorrect.
|
774
801
|
* @default false
|
@@ -886,7 +913,7 @@ type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType,
|
|
886
913
|
*/
|
887
914
|
schema?: Writeable<TSchema, "deep"> | ((context: {
|
888
915
|
baseSchema: Writeable<TBaseSchema, "deep">;
|
889
|
-
currentRouteSchema:
|
916
|
+
currentRouteSchema: GetCurrentRouteSchema<TBaseSchema, TCurrentRouteKey>;
|
890
917
|
}) => Writeable<TSchema, "deep">);
|
891
918
|
/**
|
892
919
|
* Schema config for the callapi instance
|
@@ -901,9 +928,9 @@ type BaseCallApiConfig<TBaseData = DefaultDataType, TBaseErrorData = DefaultData
|
|
901
928
|
options: CallApiExtraOptions;
|
902
929
|
request: CallApiRequestOptions;
|
903
930
|
}) => CallApiRequestOptions & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchema, TBaseSchemaConfig>);
|
904
|
-
type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<BaseCallApiSchema, TSchemaConfig> = InferInitURL<BaseCallApiSchema, TSchemaConfig>, TCurrentRouteKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = InferExtraOptions<TSchema, TCurrentRouteKey> & InferRequestOptions<TSchema, TSchemaConfig, TInitURL> & Omit<CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBasePluginArray, TPluginArray, TBaseSchema, TSchema, TBaseSchemaConfig, TSchemaConfig, TCurrentRouteKey>, keyof InferExtraOptions<CallApiSchema, string>> & Omit<CallApiRequestOptions, keyof InferRequestOptions<CallApiSchema, CallApiSchemaConfig, string>>;
|
931
|
+
type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<BaseCallApiSchema, TSchemaConfig> = InferInitURL<BaseCallApiSchema, TSchemaConfig>, TCurrentRouteKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = InferExtraOptions<TSchema, TBaseSchema, TCurrentRouteKey> & InferRequestOptions<TSchema, TSchemaConfig, TInitURL> & Omit<CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBasePluginArray, TPluginArray, TBaseSchema, TSchema, TBaseSchemaConfig, TSchemaConfig, TCurrentRouteKey>, keyof InferExtraOptions<CallApiSchema, BaseCallApiSchema, string>> & Omit<CallApiRequestOptions, keyof InferRequestOptions<CallApiSchema, CallApiSchemaConfig, string>>;
|
905
932
|
type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<BaseCallApiSchema, TSchemaConfig> = InferInitURL<BaseCallApiSchema, TSchemaConfig>, TCurrentRouteKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = [initURL: TInitURL, config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBaseSchema, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteKey, TBasePluginArray, TPluginArray>];
|
906
933
|
type CallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion, TResponseType extends ResponseTypeUnion> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;
|
907
934
|
//#endregion
|
908
|
-
export { AnyString, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchema, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteKey, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamFromRoute, InferSchemaResult, PluginHooks, PluginHooksWithMoreOptions, PluginInitContext, PossibleHTTPError, PossibleJavaScriptError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, definePlugin, defineSchema };
|
909
|
-
//# sourceMappingURL=common-
|
935
|
+
export { AnyString, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchema, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteKey, GetCurrentRouteSchema, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamFromRoute, InferSchemaResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginInitContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, definePlugin, defineSchema };
|
936
|
+
//# sourceMappingURL=common-CmLbOQH8.d.ts.map
|
package/dist/esm/index.d.ts
CHANGED
@@ -1,12 +1,12 @@
|
|
1
|
-
import { AnyString, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchema, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteKey, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamFromRoute, InferSchemaResult, PluginHooks, PluginHooksWithMoreOptions, PluginInitContext, PossibleHTTPError, PossibleJavaScriptError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, definePlugin, defineSchema } from "./common-
|
1
|
+
import { AnyString, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchema, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteKey, GetCurrentRouteSchema, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamFromRoute, InferSchemaResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginInitContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, definePlugin, defineSchema } from "./common-CmLbOQH8.js";
|
2
2
|
|
3
3
|
//#region src/createFetchClient.d.ts
|
4
4
|
|
5
|
-
declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema, const TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchema, TBaseSchemaConfig, TBasePluginArray>) => <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = TBaseResponseType, TSchemaConfig extends CallApiSchemaConfig = TBaseSchemaConfig, TInitURL extends InferInitURL<TBaseSchema, TSchemaConfig> = InferInitURL<TBaseSchema, TSchemaConfig>, TCurrentRouteKey extends GetCurrentRouteKey<TSchemaConfig, TInitURL> = GetCurrentRouteKey<TSchemaConfig, TInitURL>, TSchema extends CallApiSchema =
|
6
|
-
declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = boolean, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<Partial<Record<"@delete/" | "@get/" | "@patch/" | "@post/" | "@put/" | AnyString, CallApiSchema>>, TSchemaConfig> = InferInitURL<Partial<Record<"@delete/" | "@get/" | "@patch/" | "@post/" | "@put/" | AnyString, CallApiSchema>>, TSchemaConfig>, TCurrentRouteKey extends GetCurrentRouteKey<TSchemaConfig, TInitURL> = GetCurrentRouteKey<TSchemaConfig, TInitURL>, TSchema extends CallApiSchema =
|
5
|
+
declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema, const TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchema, TBaseSchemaConfig, TBasePluginArray>) => <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = TBaseResponseType, TSchemaConfig extends CallApiSchemaConfig = TBaseSchemaConfig, TInitURL extends InferInitURL<TBaseSchema, TSchemaConfig> = InferInitURL<TBaseSchema, TSchemaConfig>, TCurrentRouteKey extends GetCurrentRouteKey<TSchemaConfig, TInitURL> = GetCurrentRouteKey<TSchemaConfig, TInitURL>, TSchema extends CallApiSchema = GetCurrentRouteSchema<TBaseSchema, TCurrentRouteKey>, TPluginArray extends CallApiPlugin[] = TBasePluginArray>(initURL: TInitURL, config?: CallApiConfig<InferSchemaResult<TSchema["data"], TData>, InferSchemaResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType, TBaseSchema, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteKey, TBasePluginArray, TPluginArray> | undefined) => CallApiResult<InferSchemaResult<TSchema["data"], TData>, InferSchemaResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
|
6
|
+
declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = boolean, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<Partial<Record<"@delete/" | "@get/" | "@patch/" | "@post/" | "@put/" | AnyString, CallApiSchema>>, TSchemaConfig> = InferInitURL<Partial<Record<"@delete/" | "@get/" | "@patch/" | "@post/" | "@put/" | AnyString, CallApiSchema>>, TSchemaConfig>, TCurrentRouteKey extends GetCurrentRouteKey<TSchemaConfig, TInitURL> = GetCurrentRouteKey<TSchemaConfig, TInitURL>, TSchema extends CallApiSchema = GetCurrentRouteSchema<Partial<Record<"@delete/" | "@get/" | "@patch/" | "@post/" | "@put/" | AnyString, CallApiSchema>>, TCurrentRouteKey>, TPluginArray extends CallApiPlugin[] = DefaultPluginArray>(initURL: TInitURL, config?: CallApiConfig<InferSchemaResult<TSchema["data"], TData>, InferSchemaResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType, Partial<Record<"@delete/" | "@get/" | "@patch/" | "@post/" | "@put/" | AnyString, CallApiSchema>>, TSchema, CallApiSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteKey, DefaultPluginArray, TPluginArray> | undefined) => CallApiResult<InferSchemaResult<TSchema["data"], TData>, InferSchemaResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
|
7
7
|
//#endregion
|
8
8
|
//#region src/defineParameters.d.ts
|
9
9
|
declare const defineParameters: <TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchema extends BaseCallApiSchema = BaseCallApiSchema, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<BaseCallApiSchema, TSchemaConfig> = InferInitURL<BaseCallApiSchema, TSchemaConfig>, TCurrentRouteKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray>(...parameters: CallApiParameters<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBaseSchema, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteKey, TBasePluginArray, TPluginArray>) => CallApiParameters<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBaseSchema, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteKey, TBasePluginArray, TPluginArray>;
|
10
10
|
//#endregion
|
11
|
-
export { BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchema, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, ErrorContext, HTTPError, Hooks, HooksOrHooksArray, InferParamFromRoute, InferSchemaResult, PluginHooks, PluginHooksWithMoreOptions, PluginInitContext, PossibleHTTPError, PossibleJavaScriptError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, URLOptions, ValidationError, callApi, createFetchClient, defineParameters, definePlugin, defineSchema };
|
11
|
+
export { BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchema, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, ErrorContext, HTTPError, Hooks, HooksOrHooksArray, InferParamFromRoute, InferSchemaResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginInitContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, URLOptions, ValidationError, callApi, createFetchClient, defineParameters, definePlugin, defineSchema };
|
12
12
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/esm/index.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import { HTTPError, ValidationError,
|
1
|
+
import { HTTPError, ValidationError, createCombinedSignal, createTimeoutSignal, dedupeDefaults, defineEnum, deterministicHashFn, getBody, getFetchImpl, getHeaders, hookDefaults, isArray, isFunction, isHTTPErrorInstance, isObject, isPlainObject, isReadableStream, isString, isValidationErrorInstance, requestOptionDefaults, responseDefaults, retryDefaults, splitBaseConfig, splitConfig, toQueryString, waitFor } from "./utils-BMQYfuNI.js";
|
2
2
|
|
3
3
|
//#region src/result.ts
|
4
4
|
const getResponseType = (response, parser) => ({
|
@@ -40,7 +40,7 @@ const resolveSuccessResult = (data, info) => {
|
|
40
40
|
return successResult;
|
41
41
|
};
|
42
42
|
const resolveErrorResult = (error, info) => {
|
43
|
-
const { cloneResponse,
|
43
|
+
const { cloneResponse, message: customErrorMessage, resultMode } = info;
|
44
44
|
let details = {
|
45
45
|
data: null,
|
46
46
|
error: {
|
@@ -65,8 +65,7 @@ const resolveErrorResult = (error, info) => {
|
|
65
65
|
};
|
66
66
|
}
|
67
67
|
if (isHTTPErrorInstance(error)) {
|
68
|
-
const
|
69
|
-
const { errorData, message = selectedDefaultErrorMessage, name, response } = error;
|
68
|
+
const { errorData, message, name, response } = error;
|
70
69
|
details = {
|
71
70
|
data: null,
|
72
71
|
error: {
|
@@ -151,47 +150,52 @@ const calculateTotalBytesFromBody = async (requestBody, existingTotalBytes) => {
|
|
151
150
|
return totalBytes;
|
152
151
|
};
|
153
152
|
const toStreamableRequest = async (context) => {
|
154
|
-
const { baseConfig, config, options, request
|
155
|
-
if (!options.onRequestStream || !
|
156
|
-
const
|
153
|
+
const { baseConfig, config, options, request } = context;
|
154
|
+
if (!options.onRequestStream || !isReadableStream(request.body)) return request;
|
155
|
+
const requestInstance = new Request(options.fullURL, {
|
156
|
+
...request,
|
157
|
+
duplex: "half"
|
158
|
+
});
|
159
|
+
const contentLength = requestInstance.headers.get("content-length");
|
157
160
|
let totalBytes = Number(contentLength ?? 0);
|
158
161
|
const shouldForcefullyCalcStreamSize = isObject(options.forcefullyCalculateStreamSize) ? options.forcefullyCalculateStreamSize.request : options.forcefullyCalculateStreamSize;
|
159
162
|
if (!contentLength && shouldForcefullyCalcStreamSize) totalBytes = await calculateTotalBytesFromBody(requestInstance.clone().body, totalBytes);
|
160
163
|
let transferredBytes = 0;
|
161
|
-
|
162
|
-
|
163
|
-
config,
|
164
|
-
event: createProgressEvent({
|
165
|
-
chunk: new Uint8Array(),
|
166
|
-
totalBytes,
|
167
|
-
transferredBytes
|
168
|
-
}),
|
169
|
-
options,
|
170
|
-
request,
|
171
|
-
requestInstance
|
172
|
-
}));
|
173
|
-
const body = requestInstance.body;
|
174
|
-
new ReadableStream({ start: async (controller) => {
|
164
|
+
const stream = new ReadableStream({ start: async (controller) => {
|
165
|
+
const body = requestInstance.body;
|
175
166
|
if (!body) return;
|
167
|
+
const requestStreamContext = {
|
168
|
+
baseConfig,
|
169
|
+
config,
|
170
|
+
event: createProgressEvent({
|
171
|
+
chunk: new Uint8Array(),
|
172
|
+
totalBytes,
|
173
|
+
transferredBytes
|
174
|
+
}),
|
175
|
+
options,
|
176
|
+
request,
|
177
|
+
requestInstance
|
178
|
+
};
|
179
|
+
await executeHooksInTryBlock(options.onRequestStream?.(requestStreamContext));
|
176
180
|
for await (const chunk of body) {
|
177
181
|
transferredBytes += chunk.byteLength;
|
178
182
|
totalBytes = Math.max(totalBytes, transferredBytes);
|
179
183
|
await executeHooksInTryBlock(options.onRequestStream?.({
|
180
|
-
|
181
|
-
config,
|
184
|
+
...requestStreamContext,
|
182
185
|
event: createProgressEvent({
|
183
186
|
chunk,
|
184
187
|
totalBytes,
|
185
188
|
transferredBytes
|
186
|
-
})
|
187
|
-
options,
|
188
|
-
request,
|
189
|
-
requestInstance
|
189
|
+
})
|
190
190
|
}));
|
191
191
|
controller.enqueue(chunk);
|
192
192
|
}
|
193
193
|
controller.close();
|
194
194
|
} });
|
195
|
+
return new Request(requestInstance, {
|
196
|
+
body: stream,
|
197
|
+
duplex: "half"
|
198
|
+
});
|
195
199
|
};
|
196
200
|
const toStreamableResponse = async (context) => {
|
197
201
|
const { baseConfig, config, options, request, response } = context;
|
@@ -201,35 +205,32 @@ const toStreamableResponse = async (context) => {
|
|
201
205
|
const shouldForceContentLengthCalc = isObject(options.forcefullyCalculateStreamSize) ? options.forcefullyCalculateStreamSize.response : options.forcefullyCalculateStreamSize;
|
202
206
|
if (!contentLength && shouldForceContentLengthCalc) totalBytes = await calculateTotalBytesFromBody(response.clone().body, totalBytes);
|
203
207
|
let transferredBytes = 0;
|
204
|
-
await executeHooksInTryBlock(options.onResponseStream({
|
205
|
-
baseConfig,
|
206
|
-
config,
|
207
|
-
event: createProgressEvent({
|
208
|
-
chunk: new Uint8Array(),
|
209
|
-
totalBytes,
|
210
|
-
transferredBytes
|
211
|
-
}),
|
212
|
-
options,
|
213
|
-
request,
|
214
|
-
response
|
215
|
-
}));
|
216
|
-
const body = response.body;
|
217
208
|
const stream = new ReadableStream({ start: async (controller) => {
|
209
|
+
const body = response.body;
|
218
210
|
if (!body) return;
|
211
|
+
const responseStreamContext = {
|
212
|
+
baseConfig,
|
213
|
+
config,
|
214
|
+
event: createProgressEvent({
|
215
|
+
chunk: new Uint8Array(),
|
216
|
+
totalBytes,
|
217
|
+
transferredBytes
|
218
|
+
}),
|
219
|
+
options,
|
220
|
+
request,
|
221
|
+
response
|
222
|
+
};
|
223
|
+
await executeHooksInTryBlock(options.onResponseStream?.(responseStreamContext));
|
219
224
|
for await (const chunk of body) {
|
220
225
|
transferredBytes += chunk.byteLength;
|
221
226
|
totalBytes = Math.max(totalBytes, transferredBytes);
|
222
227
|
await executeHooksInTryBlock(options.onResponseStream?.({
|
223
|
-
|
224
|
-
config,
|
228
|
+
...responseStreamContext,
|
225
229
|
event: createProgressEvent({
|
226
230
|
chunk,
|
227
231
|
totalBytes,
|
228
232
|
transferredBytes
|
229
|
-
})
|
230
|
-
options,
|
231
|
-
request,
|
232
|
-
response
|
233
|
+
})
|
233
234
|
}));
|
234
235
|
controller.enqueue(chunk);
|
235
236
|
}
|
@@ -249,7 +250,7 @@ const createDedupeStrategy = async (context) => {
|
|
249
250
|
const generateDedupeKey = () => {
|
250
251
|
const shouldHaveDedupeKey = dedupeStrategy === "cancel" || dedupeStrategy === "defer";
|
251
252
|
if (!shouldHaveDedupeKey) return null;
|
252
|
-
return `${globalOptions.fullURL}-${
|
253
|
+
return `${globalOptions.fullURL}-${deterministicHashFn({
|
253
254
|
options: globalOptions,
|
254
255
|
request: globalRequest
|
255
256
|
})}`;
|
@@ -279,32 +280,20 @@ const createDedupeStrategy = async (context) => {
|
|
279
280
|
const { options: localOptions, request: localRequest } = deferContext;
|
280
281
|
const fetchApi = getFetchImpl(localOptions.customFetchImpl);
|
281
282
|
const shouldUsePromiseFromCache = prevRequestInfo && dedupeStrategy === "defer";
|
282
|
-
const
|
283
|
-
...localRequest,
|
284
|
-
duplex: localRequest.duplex ?? "half"
|
285
|
-
} : localRequest;
|
286
|
-
const requestInstance = new Request(localOptions.fullURL, requestObjectForStream);
|
287
|
-
await toStreamableRequest({
|
283
|
+
const streamableContext = {
|
288
284
|
baseConfig,
|
289
285
|
config,
|
290
286
|
options: localOptions,
|
291
|
-
request: localRequest
|
292
|
-
requestInstance: requestInstance.clone()
|
293
|
-
});
|
294
|
-
const getFetchApiPromise = () => {
|
295
|
-
if (isReadableStream(localRequest.body)) return fetchApi(requestInstance.clone());
|
296
|
-
return fetchApi(localOptions.fullURL, localRequest);
|
287
|
+
request: localRequest
|
297
288
|
};
|
298
|
-
const
|
289
|
+
const streamableRequest = await toStreamableRequest(streamableContext);
|
290
|
+
const responsePromise = shouldUsePromiseFromCache ? prevRequestInfo.responsePromise : fetchApi(localOptions.fullURL, streamableRequest);
|
299
291
|
$RequestInfoCacheOrNull?.set(dedupeKey, {
|
300
292
|
controller: newFetchController,
|
301
293
|
responsePromise
|
302
294
|
});
|
303
295
|
const streamableResponse = toStreamableResponse({
|
304
|
-
|
305
|
-
config,
|
306
|
-
options: localOptions,
|
307
|
-
request: localRequest,
|
296
|
+
...streamableContext,
|
308
297
|
response: await responsePromise
|
309
298
|
});
|
310
299
|
return streamableResponse;
|
@@ -325,19 +314,14 @@ const createDedupeStrategy = async (context) => {
|
|
325
314
|
const definePlugin = (plugin) => {
|
326
315
|
return plugin;
|
327
316
|
};
|
328
|
-
const resolvePluginArray = (plugins, basePlugins) => {
|
329
|
-
if (!plugins) return [];
|
330
|
-
if (isFunction(plugins)) return plugins({ basePlugins: basePlugins ?? [] });
|
331
|
-
return plugins;
|
332
|
-
};
|
333
317
|
const initializePlugins = async (context) => {
|
334
318
|
const { baseConfig, config, initURL, options, request } = context;
|
335
319
|
const clonedHookRegistries = structuredClone(hookRegistries);
|
336
320
|
const addMainHooks = () => {
|
337
321
|
for (const key of Object.keys(clonedHookRegistries)) {
|
338
|
-
const baseHook = baseConfig;
|
339
|
-
const instanceHook = config[key];
|
340
322
|
const overriddenHook = options[key];
|
323
|
+
const baseHook = baseConfig[key];
|
324
|
+
const instanceHook = config[key];
|
341
325
|
const mainHook = isArray(baseHook) && Boolean(instanceHook) ? [baseHook, instanceHook].flat() : overriddenHook;
|
342
326
|
if (!mainHook) continue;
|
343
327
|
clonedHookRegistries[key].add(mainHook);
|
@@ -352,7 +336,7 @@ const initializePlugins = async (context) => {
|
|
352
336
|
};
|
353
337
|
const mergedHooksExecutionOrder = options.mergedHooksExecutionOrder ?? hookDefaults.mergedHooksExecutionOrder;
|
354
338
|
if (mergedHooksExecutionOrder === "mainHooksBeforePlugins") addMainHooks();
|
355
|
-
const resolvedPlugins =
|
339
|
+
const resolvedPlugins = isFunction(options.plugins) ? options.plugins({ basePlugins: baseConfig.plugins ?? [] }) : options.plugins ?? [];
|
356
340
|
let resolvedInitURL = initURL;
|
357
341
|
let resolvedOptions = options;
|
358
342
|
let resolvedRequestOptions = request;
|
@@ -427,7 +411,7 @@ const createRetryStrategy = (ctx) => {
|
|
427
411
|
if (!baseShouldRetry) return false;
|
428
412
|
const retryMethods = new Set(options.retryMethods ?? options.retry?.methods ?? retryDefaults.methods);
|
429
413
|
const resolvedMethod = ctx.request.method ?? requestOptionDefaults.method;
|
430
|
-
const includesMethod =
|
414
|
+
const includesMethod = retryMethods.has(resolvedMethod);
|
431
415
|
const retryStatusCodes = new Set(options.retryStatusCodes ?? options.retry?.statusCodes ?? []);
|
432
416
|
const includesStatusCodes = Boolean(ctx.response?.status) && (retryStatusCodes.size > 0 ? retryStatusCodes.has(ctx.response.status) : true);
|
433
417
|
const shouldRetry = includesMethod && includesStatusCodes;
|
@@ -587,7 +571,7 @@ const extractMethodFromURL = (initURL) => {
|
|
587
571
|
};
|
588
572
|
const getMethod = (options) => {
|
589
573
|
const { initURL, method, schemaConfig } = options;
|
590
|
-
if (schemaConfig?.
|
574
|
+
if (schemaConfig?.requireMethodProvision === true) return method?.toUpperCase() ?? requestOptionDefaults.method;
|
591
575
|
return method?.toUpperCase() ?? extractMethodFromURL(initURL)?.toUpperCase() ?? requestOptionDefaults.method;
|
592
576
|
};
|
593
577
|
const normalizeURL = (initURL) => {
|
@@ -621,13 +605,16 @@ const createFetchClient = (initBaseConfig = {}) => {
|
|
621
605
|
const baseConfig = resolvedBaseConfig;
|
622
606
|
const config = initConfig;
|
623
607
|
const [baseFetchOptions, baseExtraOptions] = splitBaseConfig(baseConfig);
|
608
|
+
const shouldSkipAutoMergeForOptions = baseExtraOptions.skipAutoMergeFor === "all" || baseExtraOptions.skipAutoMergeFor === "options";
|
609
|
+
const shouldSkipAutoMergeForRequest = baseExtraOptions.skipAutoMergeFor === "all" || baseExtraOptions.skipAutoMergeFor === "request";
|
624
610
|
const mergedExtraOptions = {
|
625
611
|
...baseExtraOptions,
|
626
|
-
|
612
|
+
...!shouldSkipAutoMergeForOptions && extraOptions
|
627
613
|
};
|
628
614
|
const mergedRequestOptions = {
|
615
|
+
headers: {},
|
629
616
|
...baseFetchOptions,
|
630
|
-
|
617
|
+
...!shouldSkipAutoMergeForRequest && fetchOptions
|
631
618
|
};
|
632
619
|
const { resolvedHooks, resolvedInitURL, resolvedOptions, resolvedRequestOptions } = await initializePlugins({
|
633
620
|
baseConfig,
|
@@ -661,7 +648,6 @@ const createFetchClient = (initBaseConfig = {}) => {
|
|
661
648
|
const combinedSignal = createCombinedSignal(resolvedRequestOptions.signal, timeoutSignal, newFetchController.signal);
|
662
649
|
let request = {
|
663
650
|
...resolvedRequestOptions,
|
664
|
-
headers: resolvedRequestOptions.headers ?? {},
|
665
651
|
signal: combinedSignal
|
666
652
|
};
|
667
653
|
const { dedupeStrategy, handleRequestCancelStrategy, handleRequestDeferStrategy, removeDedupeKeyFromCache } = await createDedupeStrategy({
|
@@ -727,7 +713,7 @@ const createFetchClient = (initBaseConfig = {}) => {
|
|
727
713
|
schemaConfig: resolvedSchemaConfig
|
728
714
|
});
|
729
715
|
throw new HTTPError({
|
730
|
-
|
716
|
+
defaultHTTPErrorMessage: options.defaultHTTPErrorMessage,
|
731
717
|
errorData: validErrorData,
|
732
718
|
response
|
733
719
|
}, { cause: validErrorData });
|
@@ -758,7 +744,6 @@ const createFetchClient = (initBaseConfig = {}) => {
|
|
758
744
|
} catch (error) {
|
759
745
|
const errorInfo = {
|
760
746
|
cloneResponse: options.cloneResponse,
|
761
|
-
defaultErrorMessage: options.defaultErrorMessage,
|
762
747
|
resultMode: options.resultMode
|
763
748
|
};
|
764
749
|
const generalErrorResult = resolveErrorResult(error, errorInfo);
|