wallaby-cash 3.6.0 → 3.7.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/dist/base.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AuthType, WallabyConfig, RequestOptions, RequestRoute, WallabyConfigOptions } from './types';
1
+ import { AuthType, WallabyConfig, RequestOptions, RequestRoute, WallabyConfigOptions, WallabyError, WallabyErrorPayload } from './types';
2
2
  import { StorageService } from './lib/utils/storage.service';
3
3
  import { LocalStorage } from './types/storage';
4
4
  import { LockManagerService } from './helpers/lock-manager.service';
@@ -43,16 +43,29 @@ export declare abstract class Base {
43
43
  * All concurrent callers share the same in-flight promise via the module-level
44
44
  * `refreshDedupeManager` so only one network request is issued per user/environment scope.
45
45
  */
46
- protected _performTokenRefresh(): Promise<void>;
46
+ protected _performTokenRefresh(opts?: {
47
+ silent?: boolean;
48
+ }): Promise<void>;
49
+ /**
50
+ * Single chokepoint for surfacing transport failures. Every WallabyError raised
51
+ * by a transport path is built here so `options.onError` fires exactly once per
52
+ * logical failure. Retry paths must decide to retry BEFORE calling this so a
53
+ * retried request does not double-fire.
54
+ */
55
+ protected toWallabyError(payload: WallabyErrorPayload): WallabyError;
47
56
  /**
48
57
  * Main request method for making API calls to the Wallaby API.
49
58
  * @param route - Route configuration object containing the endpoint path and HTTP method
50
59
  * @param options - Optional request options including payload and query parameters
51
60
  * @param retried - Internal flag; set to true when retrying after a 401 to prevent loops
61
+ * @param silent - Internal flag; when true the resulting WallabyError does NOT fire
62
+ * `options.onError`. Used for best-effort refreshes whose failure is
63
+ * swallowed by the caller (e.g. proactive refresh in securityWorker),
64
+ * so an internal request never surfaces a consumer-facing error.
52
65
  * @returns Promise resolving to the typed response data
53
66
  * @throws Error if the API returns an error response or network failure occurs
54
67
  */
55
- protected request<T>(route: RequestRoute, options?: RequestOptions, retried?: boolean): Promise<T>;
68
+ protected request<T>(route: RequestRoute, options?: RequestOptions, retried?: boolean, silent?: boolean): Promise<T>;
56
69
  private _getRequestHeaders;
57
70
  protected securityWorker(securityData: any): Promise<any>;
58
71
  }
package/dist/index.cjs.js CHANGED
@@ -625,7 +625,7 @@ const env = {
625
625
  isNative: !isWeb,
626
626
  isWeb,
627
627
  };
628
- const currentPackageVersion = "3.6.0" ;
628
+ const currentPackageVersion = "3.7.0" ;
629
629
 
630
630
  /**
631
631
  * Storage keys adapter for Storage interface across different platforms.
@@ -7556,32 +7556,41 @@ class Base {
7556
7556
  return await originalRequest(params);
7557
7557
  }
7558
7558
  catch (error) {
7559
- // Reactive 401 handling for the generated client: refresh once and retry
7559
+ // Reactive 401 handling for the generated client: refresh once and retry.
7560
+ // The retry recurses and surfaces its own final error, so the intermediate
7561
+ // 401 must not be routed through toWallabyError (would double-fire onError).
7560
7562
  if (!retried && shouldAttemptTokenRefresh(error)) {
7561
7563
  await this._performTokenRefresh();
7562
7564
  // securityWorker will re-fetch the new access token on retry
7563
7565
  return attemptRequest(true);
7564
7566
  }
7565
- // Transform the generated API error format into WallabyError
7567
+ // Transform the generated API error format into WallabyError.
7568
+ // `error.error` is the parsed response body (no statusCode); the HTTP
7569
+ // status lives on the HttpResponse itself (`error.status`).
7566
7570
  if (error === null || error === void 0 ? void 0 : error.error) {
7567
7571
  const apiError = error.error;
7568
- throw new WallabyError({
7572
+ throw this.toWallabyError({
7569
7573
  message: apiError.message || 'API request failed',
7570
- statusCode: apiError.statusCode || 500,
7574
+ statusCode: apiError.statusCode || error.status || 500,
7571
7575
  errorCode: apiError.errorCode,
7572
7576
  data: apiError,
7573
7577
  });
7574
7578
  }
7575
- // Re-throw if already a WallabyError
7579
+ // Already a WallabyError (e.g. a pre-send guard from securityWorker) — propagate as-is.
7576
7580
  if (error instanceof WallabyError) {
7577
7581
  throw error;
7578
7582
  }
7579
- // Wrap any other errors
7580
- throw new WallabyError({
7581
- message: error.message || 'Unknown error occurred',
7582
- statusCode: error.statusCode || 500,
7583
- errorCode: error.errorCode,
7584
- data: error,
7583
+ // No HTTP response reached us: treat as a network failure, mirroring the
7584
+ // custom request() path so both transports surface the same shape.
7585
+ throw this.toWallabyError({
7586
+ message: error.message || 'Network request failed',
7587
+ statusCode: 0,
7588
+ errorCode: 'NETWORK_ERROR',
7589
+ data: {
7590
+ code: error.code || error.name,
7591
+ originalError: error,
7592
+ },
7593
+ cause: error.cause,
7585
7594
  });
7586
7595
  }
7587
7596
  };
@@ -7674,17 +7683,16 @@ class Base {
7674
7683
  * All concurrent callers share the same in-flight promise via the module-level
7675
7684
  * `refreshDedupeManager` so only one network request is issued per user/environment scope.
7676
7685
  */
7677
- async _performTokenRefresh() {
7686
+ async _performTokenRefresh(opts) {
7678
7687
  const refreshDedupeKey = `refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;
7679
7688
  await refreshDedupeManager.withDedupe(refreshDedupeKey, async () => {
7689
+ var _a;
7680
7690
  const refreshToken = await this.localStorageService.fetch(exports.LocalStorageItems.RefreshToken);
7681
7691
  if (!refreshToken) {
7682
7692
  return;
7683
7693
  }
7684
7694
  try {
7685
- const response = await this.request(AuthRoutes.refreshAccessToken, {
7686
- payload: { refreshToken },
7687
- });
7695
+ const response = await this.request(AuthRoutes.refreshAccessToken, { payload: { refreshToken } }, false, (_a = opts === null || opts === void 0 ? void 0 : opts.silent) !== null && _a !== void 0 ? _a : false);
7688
7696
  await this.localStorageService.save(exports.LocalStorageItems.AccessToken, response.accessToken);
7689
7697
  await this.localStorageService.save(exports.LocalStorageItems.RefreshToken, response.refreshToken);
7690
7698
  }
@@ -7697,16 +7705,44 @@ class Base {
7697
7705
  }
7698
7706
  });
7699
7707
  }
7708
+ /**
7709
+ * Single chokepoint for surfacing transport failures. Every WallabyError raised
7710
+ * by a transport path is built here so `options.onError` fires exactly once per
7711
+ * logical failure. Retry paths must decide to retry BEFORE calling this so a
7712
+ * retried request does not double-fire.
7713
+ */
7714
+ toWallabyError(payload) {
7715
+ var _a, _b;
7716
+ const error = new WallabyError(payload);
7717
+ try {
7718
+ (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
7719
+ }
7720
+ catch (onErrorException) {
7721
+ // A throwing consumer callback must not replace the WallabyError being surfaced.
7722
+ logger.error('SDK::Base::toWallabyError::onError handler threw', { error: onErrorException });
7723
+ }
7724
+ return error;
7725
+ }
7700
7726
  /**
7701
7727
  * Main request method for making API calls to the Wallaby API.
7702
7728
  * @param route - Route configuration object containing the endpoint path and HTTP method
7703
7729
  * @param options - Optional request options including payload and query parameters
7704
7730
  * @param retried - Internal flag; set to true when retrying after a 401 to prevent loops
7731
+ * @param silent - Internal flag; when true the resulting WallabyError does NOT fire
7732
+ * `options.onError`. Used for best-effort refreshes whose failure is
7733
+ * swallowed by the caller (e.g. proactive refresh in securityWorker),
7734
+ * so an internal request never surfaces a consumer-facing error.
7705
7735
  * @returns Promise resolving to the typed response data
7706
7736
  * @throws Error if the API returns an error response or network failure occurs
7707
7737
  */
7708
- async request(route, options, retried = false) {
7738
+ async request(route, options, retried = false, silent = false) {
7709
7739
  var _a;
7740
+ // `silent` suppresses onError for swallowed internal refreshes. Note: refresh
7741
+ // requests dedupe by user/env/network, so under concurrent mixed-path refreshes
7742
+ // the winning call's `silent` value applies to all sharers — a narrow edge that
7743
+ // does not affect the retry no-double-fire guarantee. A fully race-free fix would
7744
+ // require idempotent (per-error) firing.
7745
+ const emitError = (payload) => silent ? new WallabyError(payload) : this.toWallabyError(payload);
7710
7746
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7711
7747
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7712
7748
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
@@ -7757,7 +7793,16 @@ class Base {
7757
7793
  });
7758
7794
  // Handle error responses (status >= 400)
7759
7795
  if (!response.ok) {
7760
- throw new WallabyError({
7796
+ // Reactive token refresh: on a refreshable 401, refresh once and retry the
7797
+ // original request. Decided here (before constructing the WallabyError) so the
7798
+ // retried attempt surfaces the single onError; the intermediate 401 never fires.
7799
+ if (!retried &&
7800
+ route !== AuthRoutes.refreshAccessToken &&
7801
+ shouldAttemptTokenRefresh({ status: response.status, errorCode: data === null || data === void 0 ? void 0 : data.errorCode })) {
7802
+ await this._performTokenRefresh();
7803
+ return this.request(route, options, true);
7804
+ }
7805
+ throw emitError({
7761
7806
  message: (data === null || data === void 0 ? void 0 : data.message) || response.statusText || 'Request failed',
7762
7807
  statusCode: response.status,
7763
7808
  errorCode: data === null || data === void 0 ? void 0 : data.errorCode,
@@ -7767,36 +7812,33 @@ class Base {
7767
7812
  return data;
7768
7813
  }
7769
7814
  catch (error) {
7770
- // Reactive token refresh: on 401, refresh once and retry the original request
7771
- if (!retried && route !== AuthRoutes.refreshAccessToken && shouldAttemptTokenRefresh(error)) {
7772
- await this._performTokenRefresh();
7773
- return this.request(route, options, true);
7815
+ // Already surfaced through toWallabyError (the !response.ok branch above), or a
7816
+ // pre-send guard error from before the fetch — propagate without re-firing onError.
7817
+ if (error instanceof WallabyError) {
7818
+ throw error;
7774
7819
  }
7775
7820
  if (error === null || error === void 0 ? void 0 : error.error) {
7776
7821
  logger.error('SDK::Base::handleApiCall::API Error', { error });
7777
7822
  const apiError = error.error;
7778
- throw new WallabyError({
7823
+ throw emitError({
7779
7824
  message: apiError.message || 'API request failed',
7780
7825
  statusCode: apiError.statusCode || 500,
7781
7826
  errorCode: apiError.errorCode,
7782
7827
  data: apiError,
7783
7828
  });
7784
7829
  }
7785
- if (error instanceof WallabyError) {
7786
- throw error;
7787
- }
7788
7830
  // Handle network errors, fetch failures, etc.
7789
7831
  logger.error(`SDK::Base::${route.method}::NetworkError`, {
7790
7832
  message: error.message,
7791
7833
  name: error.name,
7792
7834
  error,
7793
7835
  });
7794
- throw new WallabyError({
7836
+ throw emitError({
7795
7837
  message: error.message || 'Network request failed',
7796
7838
  statusCode: 0,
7797
7839
  errorCode: 'NETWORK_ERROR',
7798
7840
  data: {
7799
- code: error.name,
7841
+ code: error.code || error.name,
7800
7842
  originalError: error,
7801
7843
  },
7802
7844
  cause: error.cause,
@@ -7824,11 +7866,13 @@ class Base {
7824
7866
  return headers;
7825
7867
  }
7826
7868
  async securityWorker(securityData) {
7827
- // Proactive token refresh before building headers for the generated client
7869
+ // Proactive token refresh before building headers for the generated client.
7870
+ // Best-effort and swallowed below, so it must NOT surface onError — otherwise a
7871
+ // failed internal refresh would fire even when the actual request later succeeds.
7828
7872
  try {
7829
7873
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7830
7874
  if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7831
- await this._performTokenRefresh();
7875
+ await this._performTokenRefresh({ silent: true });
7832
7876
  }
7833
7877
  }
7834
7878
  catch (_a) {