@scalemule/sdk 0.0.47 → 0.0.48

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.d.mts CHANGED
@@ -153,6 +153,12 @@ interface ScaleMuleConfig {
153
153
  * recover stripped fields for existing entries until those accounts log in again.
154
154
  */
155
155
  accountSwitcherPrivacy?: AccountSwitcherPrivacy;
156
+ /** Callback when a 401 auto-refresh starts */
157
+ onRefreshStart?: () => void;
158
+ /** Callback when a 401 auto-refresh finishes */
159
+ onRefreshEnd?: () => void;
160
+ /** Callback when a 401 auto-refresh fails */
161
+ onAutoRefreshFailed?: (error: ApiError) => void;
156
162
  }
157
163
  /**
158
164
  * A session entry in the multi-account session pool.
@@ -233,6 +239,8 @@ interface RequestOptions {
233
239
  headers?: Record<string, string>;
234
240
  /** Client context to forward end-user info (IP, UA, etc.) in server-to-server calls */
235
241
  clientContext?: ClientContext;
242
+ /** Internal flag to prevent infinite refresh loops */
243
+ isAutoRefresh?: boolean;
236
244
  }
237
245
  /**
238
246
  * End-user context for server-to-server calls.
@@ -343,6 +351,10 @@ declare class ScaleMuleClient {
343
351
  private accountSwitcherEnabled;
344
352
  private accountSwitcherPrivacy;
345
353
  private knownAccounts;
354
+ private refreshPromise;
355
+ private onRefreshStart?;
356
+ private onRefreshEnd?;
357
+ private onAutoRefreshFailed?;
346
358
  constructor(config: ScaleMuleConfig);
347
359
  initialize(): Promise<void>;
348
360
  setSession(token: string, userId: string): Promise<void>;
@@ -403,6 +415,8 @@ declare class ScaleMuleClient {
403
415
  retries?: number;
404
416
  skipRetry?: boolean;
405
417
  signal?: AbortSignal;
418
+ isAutoRefresh?: boolean;
419
+ onAutoRefreshFailed?: (error: ApiError) => void;
406
420
  }): Promise<ApiResponse<T>>;
407
421
  get<T>(path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
408
422
  post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
package/dist/index.d.ts CHANGED
@@ -153,6 +153,12 @@ interface ScaleMuleConfig {
153
153
  * recover stripped fields for existing entries until those accounts log in again.
154
154
  */
155
155
  accountSwitcherPrivacy?: AccountSwitcherPrivacy;
156
+ /** Callback when a 401 auto-refresh starts */
157
+ onRefreshStart?: () => void;
158
+ /** Callback when a 401 auto-refresh finishes */
159
+ onRefreshEnd?: () => void;
160
+ /** Callback when a 401 auto-refresh fails */
161
+ onAutoRefreshFailed?: (error: ApiError) => void;
156
162
  }
157
163
  /**
158
164
  * A session entry in the multi-account session pool.
@@ -233,6 +239,8 @@ interface RequestOptions {
233
239
  headers?: Record<string, string>;
234
240
  /** Client context to forward end-user info (IP, UA, etc.) in server-to-server calls */
235
241
  clientContext?: ClientContext;
242
+ /** Internal flag to prevent infinite refresh loops */
243
+ isAutoRefresh?: boolean;
236
244
  }
237
245
  /**
238
246
  * End-user context for server-to-server calls.
@@ -343,6 +351,10 @@ declare class ScaleMuleClient {
343
351
  private accountSwitcherEnabled;
344
352
  private accountSwitcherPrivacy;
345
353
  private knownAccounts;
354
+ private refreshPromise;
355
+ private onRefreshStart?;
356
+ private onRefreshEnd?;
357
+ private onAutoRefreshFailed?;
346
358
  constructor(config: ScaleMuleConfig);
347
359
  initialize(): Promise<void>;
348
360
  setSession(token: string, userId: string): Promise<void>;
@@ -403,6 +415,8 @@ declare class ScaleMuleClient {
403
415
  retries?: number;
404
416
  skipRetry?: boolean;
405
417
  signal?: AbortSignal;
418
+ isAutoRefresh?: boolean;
419
+ onAutoRefreshFailed?: (error: ApiError) => void;
406
420
  }): Promise<ApiResponse<T>>;
407
421
  get<T>(path: string, options?: RequestOptions): Promise<ApiResponse<T>>;
408
422
  post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>>;
package/dist/index.js CHANGED
@@ -722,6 +722,7 @@ var ScaleMuleClient = class {
722
722
  this.anonymousId = null;
723
723
  this.sessionPool = /* @__PURE__ */ new Map();
724
724
  this.knownAccounts = /* @__PURE__ */ new Map();
725
+ this.refreshPromise = null;
725
726
  this.apiKey = config.apiKey;
726
727
  this.applicationId = config.applicationId || null;
727
728
  this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
@@ -740,6 +741,9 @@ var ScaleMuleClient = class {
740
741
  this.multiSessionEnabled = config.enableMultiSession || false;
741
742
  this.accountSwitcherEnabled = config.enableAccountSwitcher || false;
742
743
  this.accountSwitcherPrivacy = config.accountSwitcherPrivacy || "full";
744
+ this.onRefreshStart = config.onRefreshStart;
745
+ this.onRefreshEnd = config.onRefreshEnd;
746
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
743
747
  }
744
748
  // --------------------------------------------------------------------------
745
749
  // Session Management
@@ -1025,34 +1029,28 @@ var ScaleMuleClient = class {
1025
1029
  const method = (init.method || "GET").toUpperCase();
1026
1030
  const timeout = init.timeout || this.defaultTimeout;
1027
1031
  const maxRetries = init.skipRetry ? 0 : init.retries ?? this.maxRetries;
1028
- const headers = {
1029
- "x-api-key": this.apiKey,
1030
- "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
1031
- ...init.headers
1032
- };
1033
- if (!init.skipAuth && this.sessionToken) {
1034
- headers["Authorization"] = `Bearer ${this.sessionToken}`;
1035
- }
1036
- if (this.workspaceId) {
1037
- headers["x-sm-workspace-id"] = this.workspaceId;
1038
- }
1039
- if (!this.sessionToken && this.anonymousId) {
1040
- headers["x-anonymous-id"] = this.anonymousId;
1041
- }
1042
- let bodyStr;
1043
- if (init.body !== void 0 && init.body !== null) {
1044
- bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
1045
- if (!headers["Content-Type"]) {
1046
- headers["Content-Type"] = "application/json";
1047
- }
1048
- }
1049
- if (this.debug) {
1050
- console.log(`[ScaleMule] ${method} ${path}`);
1051
- }
1052
- const idempotencyKey = method === "POST" ? generateIdempotencyKey() : void 0;
1032
+ const bodyStr = init.body ? JSON.stringify(init.body) : void 0;
1053
1033
  let lastError = null;
1034
+ let idempotencyKey = null;
1054
1035
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
1055
- if (attempt > 0 && idempotencyKey) {
1036
+ const headers = {
1037
+ "x-api-key": this.apiKey,
1038
+ "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
1039
+ ...init.headers
1040
+ };
1041
+ if (!init.skipAuth && this.sessionToken) {
1042
+ headers["Authorization"] = `Bearer ${this.sessionToken}`;
1043
+ }
1044
+ if (this.workspaceId) {
1045
+ headers["x-sm-workspace-id"] = this.workspaceId;
1046
+ }
1047
+ if (!this.sessionToken && this.anonymousId) {
1048
+ headers["x-anonymous-id"] = this.anonymousId;
1049
+ }
1050
+ if (attempt > 0 && (method === "POST" || method === "PUT" || method === "PATCH")) {
1051
+ if (!idempotencyKey) {
1052
+ idempotencyKey = generateIdempotencyKey();
1053
+ }
1056
1054
  headers["x-idempotency-key"] = idempotencyKey;
1057
1055
  }
1058
1056
  const controller = new AbortController();
@@ -1072,6 +1070,10 @@ var ScaleMuleClient = class {
1072
1070
  signal: controller.signal
1073
1071
  });
1074
1072
  clearTimeout(timeoutId);
1073
+ const rotatedToken = response.headers.get("x-rotated-session-token");
1074
+ if (rotatedToken && this.sessionToken && this.userId) {
1075
+ this.setSession(rotatedToken, this.userId);
1076
+ }
1075
1077
  if (this.rateLimitQueue) {
1076
1078
  this.rateLimitQueue.updateFromHeaders(response.headers);
1077
1079
  }
@@ -1094,6 +1096,45 @@ var ScaleMuleClient = class {
1094
1096
  status: response.status,
1095
1097
  details: responseData?.error?.details || responseData?.details
1096
1098
  };
1099
+ if (response.status === 401 && this.sessionToken && !init.isAutoRefresh) {
1100
+ if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
1101
+ let isPrimaryRefresh = false;
1102
+ if (!this.refreshPromise) {
1103
+ isPrimaryRefresh = true;
1104
+ this.onRefreshStart?.();
1105
+ this.refreshPromise = this.auth?.refreshSession ? this.auth.refreshSession() : this.post("/auth/refresh", {}, { isAutoRefresh: true });
1106
+ }
1107
+ const currentRefreshPromise = this.refreshPromise;
1108
+ try {
1109
+ const refreshResult = await currentRefreshPromise;
1110
+ if (!refreshResult || refreshResult.error) {
1111
+ if (this.debug) console.log("[ScaleMule] Auto-refresh failed:", refreshResult?.error);
1112
+ const apiError = refreshResult?.error || {
1113
+ code: "refresh_failed",
1114
+ message: "Auto-refresh failed",
1115
+ status: 400
1116
+ };
1117
+ init.onAutoRefreshFailed?.(apiError);
1118
+ this.onAutoRefreshFailed?.(apiError);
1119
+ return { data: null, error };
1120
+ }
1121
+ if (this.debug) console.log("[ScaleMule] Auto-refresh succeeded, retrying original request...");
1122
+ const newToken = refreshResult.data?.session_token || refreshResult.data?.access_token;
1123
+ if (newToken) {
1124
+ this.sessionToken = newToken;
1125
+ if (this.userId) {
1126
+ await this.storage.setItem(SESSION_STORAGE_KEY, newToken);
1127
+ }
1128
+ }
1129
+ attempt--;
1130
+ continue;
1131
+ } finally {
1132
+ if (isPrimaryRefresh && this.refreshPromise === currentRefreshPromise) {
1133
+ this.refreshPromise = null;
1134
+ this.onRefreshEnd?.();
1135
+ }
1136
+ }
1137
+ }
1097
1138
  if (response.status === 429) {
1098
1139
  const retryAfter = response.headers.get("Retry-After");
1099
1140
  if (retryAfter) {
package/dist/index.mjs CHANGED
@@ -352,6 +352,7 @@ var ScaleMuleClient = class {
352
352
  this.anonymousId = null;
353
353
  this.sessionPool = /* @__PURE__ */ new Map();
354
354
  this.knownAccounts = /* @__PURE__ */ new Map();
355
+ this.refreshPromise = null;
355
356
  this.apiKey = config.apiKey;
356
357
  this.applicationId = config.applicationId || null;
357
358
  this.baseUrl = config.baseUrl || GATEWAY_URLS[config.environment || "prod"];
@@ -370,6 +371,9 @@ var ScaleMuleClient = class {
370
371
  this.multiSessionEnabled = config.enableMultiSession || false;
371
372
  this.accountSwitcherEnabled = config.enableAccountSwitcher || false;
372
373
  this.accountSwitcherPrivacy = config.accountSwitcherPrivacy || "full";
374
+ this.onRefreshStart = config.onRefreshStart;
375
+ this.onRefreshEnd = config.onRefreshEnd;
376
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
373
377
  }
374
378
  // --------------------------------------------------------------------------
375
379
  // Session Management
@@ -655,34 +659,28 @@ var ScaleMuleClient = class {
655
659
  const method = (init.method || "GET").toUpperCase();
656
660
  const timeout = init.timeout || this.defaultTimeout;
657
661
  const maxRetries = init.skipRetry ? 0 : init.retries ?? this.maxRetries;
658
- const headers = {
659
- "x-api-key": this.apiKey,
660
- "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
661
- ...init.headers
662
- };
663
- if (!init.skipAuth && this.sessionToken) {
664
- headers["Authorization"] = `Bearer ${this.sessionToken}`;
665
- }
666
- if (this.workspaceId) {
667
- headers["x-sm-workspace-id"] = this.workspaceId;
668
- }
669
- if (!this.sessionToken && this.anonymousId) {
670
- headers["x-anonymous-id"] = this.anonymousId;
671
- }
672
- let bodyStr;
673
- if (init.body !== void 0 && init.body !== null) {
674
- bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
675
- if (!headers["Content-Type"]) {
676
- headers["Content-Type"] = "application/json";
677
- }
678
- }
679
- if (this.debug) {
680
- console.log(`[ScaleMule] ${method} ${path}`);
681
- }
682
- const idempotencyKey = method === "POST" ? generateIdempotencyKey() : void 0;
662
+ const bodyStr = init.body ? JSON.stringify(init.body) : void 0;
683
663
  let lastError = null;
664
+ let idempotencyKey = null;
684
665
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
685
- if (attempt > 0 && idempotencyKey) {
666
+ const headers = {
667
+ "x-api-key": this.apiKey,
668
+ "User-Agent": `ScaleMule-SDK-TypeScript/${SDK_VERSION}`,
669
+ ...init.headers
670
+ };
671
+ if (!init.skipAuth && this.sessionToken) {
672
+ headers["Authorization"] = `Bearer ${this.sessionToken}`;
673
+ }
674
+ if (this.workspaceId) {
675
+ headers["x-sm-workspace-id"] = this.workspaceId;
676
+ }
677
+ if (!this.sessionToken && this.anonymousId) {
678
+ headers["x-anonymous-id"] = this.anonymousId;
679
+ }
680
+ if (attempt > 0 && (method === "POST" || method === "PUT" || method === "PATCH")) {
681
+ if (!idempotencyKey) {
682
+ idempotencyKey = generateIdempotencyKey();
683
+ }
686
684
  headers["x-idempotency-key"] = idempotencyKey;
687
685
  }
688
686
  const controller = new AbortController();
@@ -702,6 +700,10 @@ var ScaleMuleClient = class {
702
700
  signal: controller.signal
703
701
  });
704
702
  clearTimeout(timeoutId);
703
+ const rotatedToken = response.headers.get("x-rotated-session-token");
704
+ if (rotatedToken && this.sessionToken && this.userId) {
705
+ this.setSession(rotatedToken, this.userId);
706
+ }
705
707
  if (this.rateLimitQueue) {
706
708
  this.rateLimitQueue.updateFromHeaders(response.headers);
707
709
  }
@@ -724,6 +726,45 @@ var ScaleMuleClient = class {
724
726
  status: response.status,
725
727
  details: responseData?.error?.details || responseData?.details
726
728
  };
729
+ if (response.status === 401 && this.sessionToken && !init.isAutoRefresh) {
730
+ if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
731
+ let isPrimaryRefresh = false;
732
+ if (!this.refreshPromise) {
733
+ isPrimaryRefresh = true;
734
+ this.onRefreshStart?.();
735
+ this.refreshPromise = this.auth?.refreshSession ? this.auth.refreshSession() : this.post("/auth/refresh", {}, { isAutoRefresh: true });
736
+ }
737
+ const currentRefreshPromise = this.refreshPromise;
738
+ try {
739
+ const refreshResult = await currentRefreshPromise;
740
+ if (!refreshResult || refreshResult.error) {
741
+ if (this.debug) console.log("[ScaleMule] Auto-refresh failed:", refreshResult?.error);
742
+ const apiError = refreshResult?.error || {
743
+ code: "refresh_failed",
744
+ message: "Auto-refresh failed",
745
+ status: 400
746
+ };
747
+ init.onAutoRefreshFailed?.(apiError);
748
+ this.onAutoRefreshFailed?.(apiError);
749
+ return { data: null, error };
750
+ }
751
+ if (this.debug) console.log("[ScaleMule] Auto-refresh succeeded, retrying original request...");
752
+ const newToken = refreshResult.data?.session_token || refreshResult.data?.access_token;
753
+ if (newToken) {
754
+ this.sessionToken = newToken;
755
+ if (this.userId) {
756
+ await this.storage.setItem(SESSION_STORAGE_KEY, newToken);
757
+ }
758
+ }
759
+ attempt--;
760
+ continue;
761
+ } finally {
762
+ if (isPrimaryRefresh && this.refreshPromise === currentRefreshPromise) {
763
+ this.refreshPromise = null;
764
+ this.onRefreshEnd?.();
765
+ }
766
+ }
767
+ }
727
768
  if (response.status === 429) {
728
769
  const retryAfter = response.headers.get("Retry-After");
729
770
  if (retryAfter) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.47",
3
+ "version": "0.0.48",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",