aspi 1.3.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -75,7 +75,7 @@ var CustomError = class extends Error {
75
75
  }
76
76
  };
77
77
  var isAspiError = (error) => {
78
- return error instanceof AspiError;
78
+ return error instanceof AspiError && error.tag === "aspiError";
79
79
  };
80
80
  var isCustomError = (error) => {
81
81
  return error instanceof CustomError;
@@ -287,19 +287,17 @@ var Request = class {
287
287
  #shouldBeResult = false;
288
288
  #bodySchemaIssues = [];
289
289
  #throwOnError = false;
290
- constructor(method, path, {
291
- requestConfig,
292
- retryConfig,
293
- middlewares,
294
- errorCbs,
295
- throwOnError
296
- }) {
290
+ constructor(method, path, requestOptions) {
297
291
  this.#path = path;
298
- this.#middlewares = middlewares || [];
299
- this.#localRequestInit = { ...requestConfig, method };
300
- this.#retryConfig = retryConfig;
301
- this.#customErrorCbs = errorCbs || {};
302
- this.#throwOnError = throwOnError || false;
292
+ this.#middlewares = requestOptions.middlewares || [];
293
+ this.#localRequestInit = {
294
+ ...requestOptions.requestConfig,
295
+ method
296
+ };
297
+ this.#retryConfig = requestOptions.retryConfig;
298
+ this.#customErrorCbs = requestOptions.errorCbs || {};
299
+ this.#throwOnError = requestOptions.throwOnError || false;
300
+ this.#shouldBeResult = requestOptions.shouldBeResult || false;
303
301
  }
304
302
  /**
305
303
  * Sets the base URL for the request.
@@ -334,18 +332,25 @@ var Request = class {
334
332
  return this;
335
333
  }
336
334
  /**
337
- * Sets multiple headers for the request.
338
- * @param headers An object containing header key-value pairs
339
- * @returns The request instance for chaining
335
+ * Merges the provided headers into the request configuration.
336
+ *
337
+ * @param {HeadersInit} headers - An object or iterable containing header name/value pairs.
338
+ * Existing headers are retained unless a key in this object overwrites them.
339
+ * @returns {this} The current {@link Request} instance for method chaining.
340
+ *
340
341
  * @example
342
+ * // Set common JSON headers
341
343
  * const request = new Request('/users', config);
342
344
  * request.setHeaders({
343
345
  * 'Content-Type': 'application/json',
344
- * 'Accept': 'application/json'
346
+ * 'Accept': 'application/json',
345
347
  * });
346
348
  */
347
349
  setHeaders(headers) {
348
- this.#localRequestInit.headers = headers;
350
+ this.#localRequestInit.headers = {
351
+ ...this.#localRequestInit.headers ?? {},
352
+ ...headers
353
+ };
349
354
  return this;
350
355
  }
351
356
  /**
@@ -359,7 +364,7 @@ var Request = class {
359
364
  */
360
365
  setHeader(key, value) {
361
366
  this.#localRequestInit.headers = {
362
- ...this.#localRequestInit.headers,
367
+ ...this.#localRequestInit.headers ?? {},
363
368
  [key]: value
364
369
  };
365
370
  return this;
@@ -557,29 +562,54 @@ var Request = class {
557
562
  return this.error("internalServerError", "INTERNAL_SERVER_ERROR", cb);
558
563
  }
559
564
  /**
560
- * Sets a custom error handler for a specific HTTP status code.
561
- * @param tag A string identifier for the error type
562
- * @param status The HTTP error status to handle
563
- * @param cb The callback function to handle the error
564
- * @returns The request instance for chaining
565
+ * Register a custom error handler for a specific HTTP status code.
566
+ *
567
+ * When the response matches the provided `status`, the supplied callback `cb`
568
+ * is invoked and its return value is wrapped in a {@link CustomError} with the
569
+ * given `tag`. The method also augments the request's generic `Opts['error']`
570
+ * type so that the custom error is reflected in the resulting `Result`
571
+ * union.
572
+ *
573
+ * @template Tag - A string literal used as the error tag.
574
+ * @template A - The shape of the data returned by the callback.
575
+ *
576
+ * @param {Tag} tag
577
+ * A unique identifier for the custom error. This value becomes the `tag`
578
+ * property of the {@link CustomError} produced by the handler.
579
+ *
580
+ * @param {HttpErrorStatus} status
581
+ * The HTTP status code (e.g. `'BAD_REQUEST'`, `'NOT_FOUND'`) that should
582
+ * trigger the custom handler.
583
+ *
584
+ * @param {CustomErrorCb<TRequest, A>} cb
585
+ * A callback that receives the failing request and response objects and
586
+ * returns an object describing the error payload.
587
+ *
588
+ * @returns {Request<Method, TRequest, Merge<Omit<Opts, 'error'>, { error: { [K in Tag | keyof Opts['error']]: K extends Tag ? CustomError<Tag, A> : Opts['error'][K]; } }>>}
589
+ * The same {@link Request} instance, now typed with the newly added error
590
+ * variant, allowing method‑chaining.
591
+ *
565
592
  * @example
593
+ * ```ts
566
594
  * const request = new Request('/users', config);
595
+ *
596
+ * // Attach a custom handler for a 400 Bad Request response
567
597
  * request
568
- .withResult()
569
- .error('customError', 'BAD_REQUEST', (error) => {
570
- * console.log('Bad request error:', error);
571
- * return {
572
- * message: 'Invalid input',
573
- * details: error.response.responseData
574
- * };
575
- * });
598
+ * withResult()
599
+ * .error('customError', 'BAD_REQUEST', (ctx) => {
600
+ * console.log('Bad request error:', ctx);
601
+ * return {
602
+ * message: 'Invalid input',
603
+ * details: ctx.response.responseData,
604
+ * };
605
+ * });
576
606
  *
577
- * // Later when making the request:
607
+ * // Later, when executing the request:
578
608
  * const result = await request.json();
579
- * if (Result.isErr(result)) {
580
- * if(result.tag === 'customError') {
609
+ * if (Result.isErr(result) && result.tag === 'customError') {
581
610
  * console.log(result.error.data.message); // 'Invalid input'
582
611
  * }
612
+ * ```
583
613
  */
584
614
  error(tag, status, cb) {
585
615
  this.#customErrorCbs[httpErrors[status]] = {
@@ -589,58 +619,106 @@ var Request = class {
589
619
  return this;
590
620
  }
591
621
  /**
592
- * Sets query parameters for the request URL.
593
- * @param params An object containing query parameter key-value pairs
594
- * @returns The request instance for chaining
622
+ * Sets the query parameters for the request URL.
623
+ *
624
+ * Accepts any value that can be passed to the `URLSearchParams` constructor:
625
+ * - an object mapping keys to string values,
626
+ * - an iterable of `[key, value]` tuples,
627
+ * - a raw query string, or
628
+ * - an existing {@link URLSearchParams} instance.
629
+ *
630
+ * The supplied parameters replace any previously defined query parameters.
631
+ *
632
+ * @template T - The concrete type of the supplied parameters.
633
+ * @param {T} params - The query parameters to apply.
634
+ * @returns {this} The request instance for method‑chaining.
635
+ *
595
636
  * @example
596
637
  * const request = new Request('/users', config);
597
638
  * request.setQueryParams({
598
639
  * page: '1',
599
640
  * limit: '10',
600
- * sort: 'desc'
641
+ * sort: 'desc',
601
642
  * });
643
+ *
644
+ * // Using a raw query string
645
+ * request.setQueryParams('page=1&limit=10');
646
+ *
647
+ * // Using an array of entries
648
+ * request.setQueryParams([['page', '1'], ['limit', '10']]);
649
+ *
650
+ * // Using an existing URLSearchParams instance
651
+ * const qp = new URLSearchParams({ page: '1' });
652
+ * request.setQueryParams(qp);
602
653
  */
603
654
  setQueryParams(params) {
604
655
  this.#queryParams = new URLSearchParams(params);
605
656
  return this;
606
657
  }
607
658
  /**
608
- * Sets the output schema for validating the response data using Zod.
609
- * @param schema The Zod schema to validate the response
610
- * @returns The request instance for chaining
659
+ * Sets a validation schema for the response data.
660
+ *
661
+ * The provided {@link StandardSchemaV1} schema will be used to validate the
662
+ * response payload when the request is executed. If validation fails, a
663
+ * `parseError` is added to the request's error type.
664
+ *
665
+ * @template TSchema - A type extending {@link StandardSchemaV1}
666
+ * @param schema - The schema used to validate the response data
667
+ * @returns The request instance for chaining with an updated generic type that
668
+ * includes the schema and a possible `parseError` in the error union
669
+ *
611
670
  * @example
671
+ * ```ts
612
672
  * import { z } from 'zod';
613
673
  *
614
674
  * const userSchema = z.object({
615
675
  * id: z.number(),
616
676
  * name: z.string(),
617
- * email: z.string().email()
677
+ * email: z.string().email(),
618
678
  * });
619
679
  *
620
680
  * const request = new Request('/users', config);
621
681
  * const result = await request
622
682
  * .withResult()
623
- * .output(userSchema)
683
+ * .schema(userSchema)
624
684
  * .json();
625
685
  *
626
686
  * if (Result.isOk(result)) {
627
687
  * const user = result.value; // Typed and validated user data
628
688
  * }
689
+ * ```
629
690
  */
630
691
  schema(schema) {
631
692
  this.#schema = schema;
632
693
  return this;
633
694
  }
634
695
  /**
635
- * Sets the request to throw an error if the response status is not successful.
636
- * @returns The request instance for chaining
696
+ * Configures the request to **throw** an exception when the response status
697
+ * indicates a failure (i.e., `!response.ok`). This disables the “Result”
698
+ * mode (`withResult`) and enables “throwable” mode, causing
699
+ * `await request.json()` (or other response helpers) to either resolve with
700
+ * the successful payload **or** reject with an `AspiError`/`CustomError`.
701
+ *
702
+ * Use this when you prefer traditional `try / catch` error handling over
703
+ * the explicit `Result` type returned by {@link withResult}.
704
+ *
705
+ * @returns This {@link Request} instance, now typed with `throwable: true` and
706
+ * `withResult: false` for proper chaining.
707
+ *
637
708
  * @example
709
+ * ```ts
638
710
  * const request = new Request('/users', config);
639
- * const result = await request
640
- * .withResult()
641
- * .throwable()
642
- * .json();
643
711
  *
712
+ * try {
713
+ * const user = await request
714
+ * .throwable() // Enable throwing on HTTP errors
715
+ * .json<User>(); // Will throw if the response is not ok
716
+ * console.log(user);
717
+ * } catch (err) {
718
+ * // err is either AspiError or a CustomError returned by a custom handler
719
+ * console.error('Request failed:', err);
720
+ * }
721
+ * ```
644
722
  */
645
723
  throwable() {
646
724
  this.#shouldBeResult = false;
@@ -648,43 +726,100 @@ var Request = class {
648
726
  return this;
649
727
  }
650
728
  /**
651
- * Executes the request and returns the JSON response.
652
- * @returns A Promise containing the Result type with either successful data or error information
729
+ * Sends the request and parses the response body as JSON.
730
+ *
731
+ * The resolved value of the returned promise varies based on the request mode:
732
+ *
733
+ * - **Result mode** (`withResult()`): resolves to a {@link Result.Result} that
734
+ * contains either an {@link AspiResultOk} with the parsed payload or a union
735
+ * of possible error types (HTTP errors, custom errors, JSON‑parse errors,
736
+ * schema‑validation errors, etc.).
737
+ *
738
+ * - **Throwable mode** (`throwable()`): resolves directly to the successful
739
+ * payload (`AspiPlainResponse`) and throws a {@link AspiError} or
740
+ * {@link CustomError} on failure.
741
+ *
742
+ * - **Default mode** (no explicit mode): resolves to a tuple
743
+ * `[value, error]` where exactly one element is non‑null.
744
+ *
745
+ * @template T - The inferred output type of the response schema (if a schema
746
+ * was supplied via {@link schema}). When no schema is provided `T` defaults
747
+ * to `any`.
748
+ *
749
+ * @returns A promise whose shape depends on the selected mode (see description).
750
+ * In Result mode it is `Result<ResultOk<…>, …>`, in throwable mode it is
751
+ * `AspiPlainResponse<…>`, and otherwise a tuple
752
+ * `[AspiResultOk<…> | null, Error | null]`.
753
+ *
653
754
  * @example
755
+ * // Using the Result API
654
756
  * const request = new Request('/users', config);
655
757
  * const result = await request
656
758
  * .setQueryParams({ id: '123' })
657
- * .
658
- withResult()
659
- * .notFound((error) => ({ message: 'User not found' }))
759
+ * .withResult()
760
+ * .notFound(() => ({ message: 'User not found' }))
660
761
  * .json<User>();
661
762
  *
662
763
  * if (Result.isOk(result)) {
663
- * const user = result.value; // User data
764
+ * // `result.value` has type `User`
765
+ * console.log(result.value);
664
766
  * } else {
665
- * console.error(result.error); // Error handling
767
+ * console.error(result.error);
666
768
  * }
667
769
  */
668
770
  async json() {
669
- const output = await this.#makeRequest(
670
- async (response) => response.json().catch(
771
+ const output = await this.#makeRequest(async (response) => {
772
+ if (response.status === 204 || response.status >= 300 && response.status < 400) {
773
+ return null;
774
+ }
775
+ return response.json().catch(
671
776
  (e) => new CustomError("jsonParseError", {
672
777
  message: e instanceof Error ? e.message : "Failed to parse JSON"
673
778
  })
674
- ),
675
- true
676
- );
779
+ );
780
+ }, true);
677
781
  return this.#mapResponse(output);
678
782
  }
679
783
  /**
680
- * Executes the request and returns the response as plain text.
681
- * @returns A Promise containing the Result type with either successful text data or error information
784
+ * Executes the request and returns the response body as plain text.
785
+ *
786
+ * The method respects the request mode:
787
+ *
788
+ * - **Result mode** (`withResult()`): resolves to a {@link Result.Result}
789
+ * containing either an {@link AspiResultOk} with the text payload or an
790
+ * error variant.
791
+ * - **Throwable mode** (`throwable()`): resolves directly to the text string
792
+ * and throws on error.
793
+ * - **Default mode**: resolves to a tuple `[value, error]` where exactly one
794
+ * element is `null`.
795
+ *
796
+ * @returns {Promise<
797
+ * Opts['withResult'] extends true
798
+ * ? Result.Result<
799
+ * AspiResultOk<TRequest, string>,
800
+ * AspiError<TRequest> |
801
+ * (Opts extends { error: any } ? Opts['error'][keyof Opts['error']] : never)
802
+ * >
803
+ * : Opts['throwable'] extends true
804
+ * ? AspiPlainResponse<TRequest, string>
805
+ * : [
806
+ * AspiResultOk<TRequest, string> | null,
807
+ * (
808
+ * | AspiError<TRequest>
809
+ * | (Opts extends { error: any } ? Opts['error'][keyof Opts['error']] : never)
810
+ * | null
811
+ * )
812
+ * ]
813
+ * }>
814
+ * A promise that resolves according to the selected request mode.
815
+ *
682
816
  * @example
817
+ * ```ts
683
818
  * const request = new Request('/data.txt', config);
684
819
  * const result = await request
685
820
  * .setQueryParams({ version: '1' })
686
821
  * .withResult()
687
- * .notFound((error) => ({ message: 'Text file not found' }))
822
+ * .notFound(() => ({ message: 'Text file not found' }))
688
823
  * .text();
689
824
  *
690
825
  * if (Result.isOk(result)) {
@@ -692,22 +827,58 @@ var Request = class {
692
827
  * } else {
693
828
  * console.error(result.error); // Error handling
694
829
  * }
830
+ * ```
695
831
  */
696
832
  async text() {
697
- const output = await this.#makeRequest(
698
- (response) => response.text()
699
- );
833
+ const output = await this.#makeRequest((response) => {
834
+ return response.text();
835
+ });
700
836
  return this.#mapResponse(output);
701
837
  }
702
838
  /**
703
- * Executes the request and returns the response as a Blob.
704
- * @returns A Promise containing the Result type with either successful Blob data or error information
839
+ * Executes the request and returns the response body as a {@link Blob}.
840
+ *
841
+ * The shape of the returned {@link Promise} depends on the request mode:
842
+ *
843
+ * - **Result mode** (`withResult()`): resolves to a {@link Result.Result} containing
844
+ * either an {@link AspiResultOk} with `Blob` data or an error variant.
845
+ * - **Throwable mode** (`throwable()`): resolves directly to a {@link Blob}
846
+ * (wrapped in {@link AspiPlainResponse}) and throws on failure.
847
+ * - **Default mode**: resolves to a tuple `[value, error]` where exactly one element
848
+ * is `null`.
849
+ *
850
+ * @returns {Promise<
851
+ * Opts['withResult'] extends true
852
+ * ? Result.Result<
853
+ * AspiResultOk<TRequest, Blob>,
854
+ * | AspiError<TRequest>
855
+ * | (Opts extends { error: any }
856
+ * ? Opts['error'][keyof Opts['error']]
857
+ * : never)
858
+ * >
859
+ * : Opts['throwable'] extends true
860
+ * ? AspiPlainResponse<TRequest, Blob>
861
+ * : [
862
+ * AspiResultOk<TRequest, Blob> | null,
863
+ * (
864
+ * | (
865
+ * | AspiError<TRequest>
866
+ * | (Opts extends { error: any }
867
+ * ? Opts['error'][keyof Opts['error']]
868
+ * : never)
869
+ * )
870
+ * | null
871
+ * ),
872
+ * ]
873
+ * }>
874
+ *
705
875
  * @example
876
+ * ```ts
706
877
  * const request = new Request('/image.jpg', config);
707
878
  * const result = await request
708
879
  * .setQueryParams({ size: 'large' })
709
880
  * .withResult()
710
- * .notFound((error) => ({ message: 'Image not found' }))
881
+ * .notFound(() => ({ message: 'Image not found' }))
711
882
  * .blob();
712
883
  *
713
884
  * if (Result.isOk(result)) {
@@ -715,43 +886,77 @@ var Request = class {
715
886
  * } else {
716
887
  * console.error(result.error); // Error handling
717
888
  * }
889
+ * ```
718
890
  */
719
891
  async blob() {
720
892
  const output = await this.#makeRequest((response) => response.blob());
721
893
  return this.#mapResponse(output);
722
894
  }
723
895
  #url() {
724
- const baseUrl = this.#localRequestInit.baseUrl?.replace(/\/+$/, "") ?? "";
896
+ const passedBaseUrl = typeof this.#localRequestInit.baseUrl === "string" ? this.#localRequestInit.baseUrl : this.#localRequestInit.baseUrl.toString();
897
+ const baseUrl = passedBaseUrl.replace(/\/+$/, "") ?? "";
725
898
  const path = this.#path.replace(/^\/+/, "/");
726
899
  const queryString = this.#queryParams ? `?${this.#queryParams.toString()}` : "";
727
900
  const url = [baseUrl, path, queryString].filter(Boolean).join("");
728
901
  return url;
729
902
  }
730
903
  /**
731
- * Returns the complete URL for the request including base URL, path, and query parameters.
732
- * @returns The complete URL string
904
+ * Returns the fully‑qualified URL that will be used for the request.
905
+ *
906
+ * The URL is constructed from the configured base URL, the request path,
907
+ * and any query parameters added via {@link setQueryParams}.
908
+ *
909
+ * @returns {string} The complete request URL.
910
+ *
733
911
  * @example
912
+ * ```ts
734
913
  * const request = new Request('/users', config);
735
914
  * request.setBaseUrl('https://api.example.com');
736
915
  * request.setQueryParams({ id: '123' });
737
- * console.log(request.url()); // 'https://api.example.com/users?id=123'
916
+ *
917
+ * console.log(request.url());
918
+ * // => 'https://api.example.com/users?id=123'
919
+ * ```
738
920
  */
739
921
  url() {
740
922
  return this.#url();
741
923
  }
742
924
  /**
743
- * Configures the request to return a Result type instead of a tuple.
744
- * @returns The request instance for chaining with Result type return value
925
+ * Switches the request into **Result** mode.
926
+ *
927
+ * In Result mode the response helpers (`json`, `text`, `blob`, …) resolve to a
928
+ * {@link Result.Result} instance instead of the default tuple
929
+ * `[value, error]`. This allows callers to use pattern matching
930
+ * (`Result.isOk`, `Result.isErr`) to handle success and failure.
931
+ *
932
+ * Calling `withResult` disables the “throwable” behaviour (see {@link throwable}).
933
+ *
934
+ * @returns {Request<
935
+ * Method,
936
+ * TRequest,
937
+ * Merge<
938
+ * Omit<Opts, 'withResult' | 'throwable'>,
939
+ * {
940
+ * withResult: true;
941
+ * throwable: false;
942
+ * }
943
+ * >
944
+ * >} The same {@link Request} instance, now typed with `withResult: true` and
945
+ * `throwable: false` for fluent chaining.
946
+ *
745
947
  * @example
948
+ * ```ts
746
949
  * const request = new Request('/users', config);
950
+ *
747
951
  * const result = await request
748
- * .withResult()
952
+ * .withResult() // enable Result mode
749
953
  * .json<User>();
750
954
  *
751
- * // Returns Result type instead of tuple
752
955
  * if (Result.isOk(result)) {
753
- * const user = result.value;
956
+ * // `result.value` is of type `User`
957
+ * console.log(result.value);
754
958
  * }
959
+ * ```
755
960
  */
756
961
  withResult() {
757
962
  this.#throwOnError = false;
@@ -771,6 +976,9 @@ var Request = class {
771
976
  return [null, getErrorOrNull(value)];
772
977
  }
773
978
  }
979
+ #isSuccessResponse(response) {
980
+ return response.ok || response.status >= 300 && response.status < 400;
981
+ }
774
982
  async #makeRequest(responseParser, isJson = false) {
775
983
  if (this.#bodySchemaIssues.length) {
776
984
  return err(new CustomError("parseError", this.#bodySchemaIssues));
@@ -781,20 +989,23 @@ var Request = class {
781
989
  const requestInit = request.requestInit;
782
990
  const url = this.#url();
783
991
  let attempts = 1;
784
- let response;
785
- let responseData;
992
+ let response = new Response(null, {
993
+ status: 500,
994
+ statusText: "Internal Server Error"
995
+ });
996
+ let responseData = null;
786
997
  while (attempts <= retries) {
787
998
  try {
788
999
  response = await fetch(url, requestInit);
789
1000
  responseData = await responseParser(response);
790
- if (responseData instanceof CustomError) {
1001
+ if (responseData instanceof Error) {
791
1002
  return err(responseData);
792
1003
  }
793
1004
  const retryWhileCondition = retryWhile ? await retryWhile(
794
1005
  request,
795
1006
  this.#makeResponse(response, responseData)
796
1007
  ) : false;
797
- if (response.ok || !retryOn.includes(response.status) && !retryWhileCondition) {
1008
+ if (this.#isSuccessResponse(response) || !retryOn.includes(response.status) && !retryWhileCondition) {
798
1009
  break;
799
1010
  }
800
1011
  if (response.status in this.#customErrorCbs && attempts === retries) {
@@ -817,9 +1028,31 @@ var Request = class {
817
1028
  request,
818
1029
  this.#makeResponse(response, responseData)
819
1030
  ) : retryDelay;
820
- await new Promise((resolve) => setTimeout(resolve, delay));
1031
+ await this.#abortDelay(delay, request);
821
1032
  }
822
1033
  } catch (e) {
1034
+ if (e instanceof Error && e.name === "AbortError") {
1035
+ if (500 in this.#customErrorCbs) {
1036
+ const result = this.#customErrorCbs[response.status].cb({
1037
+ request,
1038
+ response: this.#makeResponse(response, responseData)
1039
+ });
1040
+ return err(
1041
+ new CustomError(
1042
+ // @ts-ignore
1043
+ this.#customErrorCbs[response.status].tag,
1044
+ result
1045
+ )
1046
+ );
1047
+ }
1048
+ return err(
1049
+ new AspiError(
1050
+ e.message,
1051
+ this.#request(),
1052
+ this.#makeResponse(response, responseData)
1053
+ )
1054
+ );
1055
+ }
823
1056
  if (attempts === retries) throw e;
824
1057
  const delay = typeof retryDelay === "function" ? await retryDelay(
825
1058
  retries - attempts - 1,
@@ -827,14 +1060,14 @@ var Request = class {
827
1060
  request,
828
1061
  this.#makeResponse(response, responseData)
829
1062
  ) : retryDelay;
830
- await new Promise((resolve) => setTimeout(resolve, delay));
1063
+ await this.#abortDelay(delay, request);
831
1064
  }
832
1065
  if (onRetry) {
833
1066
  onRetry(request, this.#makeResponse(response, responseData));
834
1067
  }
835
1068
  attempts++;
836
1069
  }
837
- if (!response.ok) {
1070
+ if (!this.#isSuccessResponse(response)) {
838
1071
  if (response.status in this.#customErrorCbs) {
839
1072
  const result = this.#customErrorCbs[response.status].cb({
840
1073
  request,
@@ -904,17 +1137,38 @@ var Request = class {
904
1137
  );
905
1138
  }
906
1139
  }
1140
+ #abortDelay(ms, request) {
1141
+ return new Promise((resolve, reject) => {
1142
+ const timer = setTimeout(resolve, ms);
1143
+ const signal = request.requestInit.signal;
1144
+ if (signal) {
1145
+ if (signal.aborted) {
1146
+ clearTimeout(timer);
1147
+ reject(new DOMException("The user aborted a request.", "AbortError"));
1148
+ } else {
1149
+ const abortHandler = () => {
1150
+ clearTimeout(timer);
1151
+ reject(
1152
+ new DOMException("The user aborted a request.", "AbortError")
1153
+ );
1154
+ };
1155
+ signal.addEventListener("abort", abortHandler, { once: true });
1156
+ }
1157
+ }
1158
+ });
1159
+ }
907
1160
  #request() {
908
1161
  let requestInit = this.#localRequestInit;
909
1162
  for (const middleware of this.#middlewares) {
910
- requestInit = middleware(this.#localRequestInit);
1163
+ requestInit = middleware(requestInit);
911
1164
  }
912
1165
  return {
913
- requestInit,
914
- baseUrl: this.#localRequestInit.baseUrl,
1166
+ requestInit: {
1167
+ ...requestInit,
1168
+ retryConfig: this.#sanitisedRetryConfig()
1169
+ },
915
1170
  path: this.#path,
916
- queryParams: this.#queryParams || null,
917
- retryConfig: this.#sanitisedRetryConfig()
1171
+ queryParams: this.#queryParams || null
918
1172
  };
919
1173
  }
920
1174
  #sanitisedRetryConfig() {
@@ -939,6 +1193,68 @@ var Request = class {
939
1193
  responseData
940
1194
  };
941
1195
  }
1196
+ /**
1197
+ * Returns the underlying {@link AspiRequest} object that will be used for the fetch call.
1198
+ *
1199
+ * This method does not perform any network activity; it simply builds and returns the
1200
+ * request configuration, including any applied middlewares, query parameters, etc.
1201
+ *
1202
+ * @returns {AspiRequest<TRequest>} The constructed request object.
1203
+ */
1204
+ getRequest() {
1205
+ return this.#request();
1206
+ }
1207
+ /**
1208
+ * Retrieves the registry of custom error callbacks that have been
1209
+ * registered via {@link error}. The returned object maps HTTP status
1210
+ * codes to their corresponding callback functions and tags.
1211
+ *
1212
+ * @returns {ErrorCallbacks} A shallow copy of the internal error callback registry.
1213
+ */
1214
+ getErrorCallbackRegistry() {
1215
+ return { ...this.#customErrorCbs };
1216
+ }
1217
+ /**
1218
+ * Returns whether the request is configured to return a {@link Result.Result}
1219
+ * instead of the default tuple or throwing.
1220
+ *
1221
+ * @returns {boolean} `true` when {@link withResult} has been called.
1222
+ */
1223
+ isResult() {
1224
+ return this.#shouldBeResult;
1225
+ }
1226
+ /**
1227
+ * Returns whether the request is configured to throw on HTTP errors.
1228
+ *
1229
+ * @returns {boolean} `true` when {@link throwable} has been called.
1230
+ */
1231
+ isThrowable() {
1232
+ return this.#throwOnError;
1233
+ }
1234
+ /**
1235
+ * Returns the effective retry configuration for this request, including defaulted values.
1236
+ *
1237
+ * The returned object contains:
1238
+ * - `retries` – number of retry attempts (default 1)
1239
+ * - `retryDelay` – delay between attempts in milliseconds or a function that returns a delay
1240
+ * - `retryOn` – array of HTTP status codes that should trigger a retry
1241
+ * - `retryWhile` – optional custom predicate executed after each response
1242
+ * - `onRetry` – optional callback invoked after a retry attempt
1243
+ *
1244
+ * A shallow copy is returned to avoid accidental mutation of the internal state.
1245
+ *
1246
+ * @returns {{
1247
+ * retries: number;
1248
+ * retryDelay: number | ((attempt: number, maxAttempts: number, request: AspiRequest<TRequest>, response: AspiResponse<any, true>) => number);
1249
+ * retryOn: number[];
1250
+ * retryWhile?: (request: AspiRequest<TRequest>, response: AspiResponse<any, true>) => boolean | Promise<boolean>;
1251
+ * onRetry?: (request: AspiRequest<TRequest>, response: AspiResponse<any, true>) => void;
1252
+ * }}
1253
+ */
1254
+ getRetryConfig() {
1255
+ const cfg = this.#sanitisedRetryConfig();
1256
+ return { ...cfg };
1257
+ }
942
1258
  };
943
1259
 
944
1260
  // src/aspi.ts
@@ -948,15 +1264,20 @@ var Aspi2 = class {
948
1264
  #retryConfig;
949
1265
  #customErrorCbs = {};
950
1266
  #throwOnError = false;
1267
+ #shouldBeResult = false;
951
1268
  constructor(config) {
952
- const { retryConfig, ...requestConfig } = config;
953
- this.#globalRequestInit = requestConfig;
1269
+ const { retryConfig, ...requestInit } = config;
1270
+ this.#globalRequestInit = requestInit;
954
1271
  this.#retryConfig = retryConfig;
955
1272
  }
956
1273
  /**
957
- * Sets the base URL for all API requests
958
- * @param {string} url - The base URL to be set
959
- * @returns {Aspi} The Aspi instance for chaining
1274
+ * Sets or overrides the base URL used for all subsequent API requests.
1275
+ *
1276
+ * Accepts either a string or a `URL` instance. If a `URL` object is provided,
1277
+ * it is converted to its string representation.
1278
+ *
1279
+ * @param url - The new base URL.
1280
+ * @returns The current {@link Aspi} instance for chaining.
960
1281
  * @example
961
1282
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
962
1283
  * api.setBaseUrl('https://api.newdomain.com');
@@ -985,17 +1306,17 @@ var Aspi2 = class {
985
1306
  };
986
1307
  return this;
987
1308
  }
988
- #createRequest(method, path, body) {
1309
+ #createRequest(method, path) {
989
1310
  return new Request(method, path, {
990
1311
  requestConfig: {
991
1312
  ...this.#globalRequestInit,
992
- method,
993
- body
1313
+ method
994
1314
  },
995
- retryConfig: this.#retryConfig,
996
1315
  middlewares: this.#middlewares,
997
1316
  errorCbs: this.#customErrorCbs,
998
- throwOnError: this.#throwOnError
1317
+ throwOnError: this.#throwOnError,
1318
+ shouldBeResult: this.#shouldBeResult,
1319
+ retryConfig: this.#retryConfig
999
1320
  });
1000
1321
  }
1001
1322
  /**
@@ -1010,40 +1331,39 @@ var Aspi2 = class {
1010
1331
  return this.#createRequest("GET", path);
1011
1332
  }
1012
1333
  /**
1013
- * Makes a POST request to the specified path with an optional body
1014
- * @param {string} path - The path to make the request to
1015
- * @param {BodyInit} [body] - The body of the request
1016
- * @returns {Request} A Request instance for chaining
1334
+ * Makes a POST request to the specified path.
1335
+ *
1336
+ * @param {string} path - The path to make the request to.
1337
+ * @returns {Request} A Request instance for chaining.
1338
+ *
1017
1339
  * @example
1018
1340
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
1019
- * const response = await api.post('/users', { name: 'John' }).json();
1341
+ * const response = await api.post('/users').json();
1020
1342
  */
1021
- post(path, body) {
1022
- return this.#createRequest("POST", path, body);
1343
+ post(path) {
1344
+ return this.#createRequest("POST", path);
1023
1345
  }
1024
1346
  /**
1025
- * Makes a PUT request to the specified path with an optional body
1026
- * @param {string} path - The path to make the request to
1027
- * @param {BodyInit} [body] - The body of the request
1028
- * @returns {Request} A Request instance for chaining
1347
+ * Makes a PUT request to the specified path.
1348
+ * @param {string} path - The path to make the request to.
1349
+ * @returns {Request} A Request instance for chaining.
1029
1350
  * @example
1030
1351
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
1031
- * const response = await api.put('/users/1', { name: 'John' }).json();
1352
+ * const response = await api.put('/users/1').json();
1032
1353
  */
1033
- put(path, body) {
1034
- return this.#createRequest("PUT", path, body);
1354
+ put(path) {
1355
+ return this.#createRequest("PUT", path);
1035
1356
  }
1036
1357
  /**
1037
- * Makes a PATCH request to the specified path with an optional body
1038
- * @param {string} path - The path to make the request to
1039
- * @param {BodyInit} [body] - The body of the request
1040
- * @returns {Request} A Request instance for chaining
1358
+ * Makes a PATCH request to the specified path.
1359
+ * @param {string} path - The path to make the request to.
1360
+ * @returns {Request} A Request instance for chaining.
1041
1361
  * @example
1042
1362
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
1043
- * const response = await api.patch('/users/1', { name: 'John' }).json();
1363
+ * const response = await api.patch('/users/1').json();
1044
1364
  */
1045
- patch(path, body) {
1046
- return this.#createRequest("PATCH", path, body);
1365
+ patch(path) {
1366
+ return this.#createRequest("PATCH", path);
1047
1367
  }
1048
1368
  /**
1049
1369
  * Makes a DELETE request to the specified path
@@ -1079,8 +1399,9 @@ var Aspi2 = class {
1079
1399
  return this.#createRequest("OPTIONS", path);
1080
1400
  }
1081
1401
  /**
1082
- * Sets multiple headers for all API requests
1083
- * @param {Record<string, string>} headers - An object containing header key-value pairs
1402
+ * Sets multiple headers for all API requests. Existing headers are preserved
1403
+ * and new ones are merged, overriding any duplicate keys.
1404
+ * @param {HeadersInit} headers - An object containing header key-value pairs
1084
1405
  * @returns {Aspi} The Aspi instance for chaining
1085
1406
  * @example
1086
1407
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
@@ -1090,21 +1411,26 @@ var Aspi2 = class {
1090
1411
  * });
1091
1412
  */
1092
1413
  setHeaders(headers) {
1093
- this.#globalRequestInit.headers = headers;
1414
+ this.#globalRequestInit.headers = {
1415
+ ...this.#globalRequestInit.headers ?? {},
1416
+ ...headers
1417
+ };
1094
1418
  return this;
1095
1419
  }
1096
1420
  /**
1097
- * Sets a single header for all API requests
1098
- * @param {string} key - The header key
1099
- * @param {string} value - The header value
1100
- * @returns {Aspi} The Aspi instance for chaining
1421
+ * Sets a single header for all API requests.
1422
+ *
1423
+ * @param key - The header name.
1424
+ * @param value - The header value.
1425
+ * @returns This {@link Aspi} instance for chaining.
1426
+ *
1101
1427
  * @example
1102
1428
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
1103
1429
  * api.setHeader('Content-Type', 'application/json');
1104
1430
  */
1105
1431
  setHeader(key, value) {
1106
1432
  this.#globalRequestInit.headers = {
1107
- ...this.#globalRequestInit.headers,
1433
+ ...this.#globalRequestInit.headers ?? {},
1108
1434
  [key]: value
1109
1435
  };
1110
1436
  return this;
@@ -1121,18 +1447,28 @@ var Aspi2 = class {
1121
1447
  return this.setHeader("Authorization", `Bearer ${token}`);
1122
1448
  }
1123
1449
  /**
1124
- * Use a middleware function to transform requests
1125
- * @param {Middleware<T, U>} fn - The middleware function to apply
1126
- * @returns {Aspi<U>} A new Aspi instance with the applied middleware
1450
+ * Register a request‑transformer middleware.
1451
+ *
1452
+ * The supplied function receives the current request initialization object
1453
+ * (`T`) and must return a request initialization of type `U`. The middleware
1454
+ * is added to the internal middleware chain and will be applied to every
1455
+ * request created by this {@link Aspi} instance.
1456
+ *
1457
+ * @template T - The input request type, extending the current {@link Aspi} request init type.
1458
+ * @template U - The output request type after transformation.
1459
+ * @param {RequestTransformer<T, U>} fn - The middleware function that transforms a request configuration.
1460
+ * @returns {Aspi<U>} A new {@link Aspi} instance typed with the transformed request configuration.
1127
1461
  * @example
1128
1462
  * const api = new Aspi({ baseUrl: 'https://api.example.com' });
1129
- * api.use((req) => {
1130
- * // Add custom headers
1131
- * req.headers = {
1132
- * ...req.headers,
1133
- * 'x-custom-header': 'custom-value'
1463
+ * const apiWithHeaders = api.use((req) => {
1464
+ * // Add custom headers to every request
1465
+ * return {
1466
+ * ...req,
1467
+ * headers: {
1468
+ * ...req.headers,
1469
+ * 'x-custom-header': 'custom-value',
1470
+ * },
1134
1471
  * };
1135
- * return req;
1136
1472
  * });
1137
1473
  */
1138
1474
  use(fn) {
@@ -1264,6 +1600,16 @@ var Aspi2 = class {
1264
1600
  */
1265
1601
  throwable() {
1266
1602
  this.#throwOnError = true;
1603
+ this.#shouldBeResult = false;
1604
+ return this;
1605
+ }
1606
+ /**
1607
+ * Configures the request to return a Result object instead of just the response body.
1608
+ * @returns The Aspi instance with result handling enabled.
1609
+ */
1610
+ withResult() {
1611
+ this.#shouldBeResult = true;
1612
+ this.#throwOnError = false;
1267
1613
  return this;
1268
1614
  }
1269
1615
  };