@scalemule/nextjs 0.1.58 → 0.1.61
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/package.json +2 -2
- package/dist/audio.css +0 -857
- package/dist/audio.d.mts +0 -334
- package/dist/audio.d.ts +0 -334
- package/dist/audio.js +0 -2178
- package/dist/audio.mjs +0 -2156
- package/dist/client.d.mts +0 -240
- package/dist/client.d.ts +0 -240
- package/dist/client.js +0 -938
- package/dist/client.mjs +0 -935
- package/dist/index-2PnO4RAF.d.mts +0 -975
- package/dist/index-2PnO4RAF.d.ts +0 -975
- package/dist/index.d.mts +0 -1234
- package/dist/index.d.ts +0 -1234
- package/dist/index.js +0 -5894
- package/dist/index.mjs +0 -5833
- package/dist/ledvery-CxPzZpxP.d.mts +0 -44
- package/dist/ledvery-CxPzZpxP.d.ts +0 -44
- package/dist/listening-hub.global.js +0 -1
- package/dist/server/auth.d.mts +0 -43
- package/dist/server/auth.d.ts +0 -43
- package/dist/server/auth.js +0 -1934
- package/dist/server/auth.mjs +0 -1928
- package/dist/server/index.d.mts +0 -1302
- package/dist/server/index.d.ts +0 -1302
- package/dist/server/index.js +0 -3579
- package/dist/server/index.mjs +0 -3500
- package/dist/server/ledvery.d.mts +0 -1
- package/dist/server/ledvery.d.ts +0 -1
- package/dist/server/ledvery.js +0 -336
- package/dist/server/ledvery.mjs +0 -333
- package/dist/server/webhook-handler.d.mts +0 -3
- package/dist/server/webhook-handler.d.ts +0 -3
- package/dist/server/webhook-handler.js +0 -59
- package/dist/server/webhook-handler.mjs +0 -57
- package/dist/testing.d.mts +0 -109
- package/dist/testing.d.ts +0 -109
- package/dist/testing.js +0 -144
- package/dist/testing.mjs +0 -138
- package/dist/webhook-handler-1nnrmWT0.d.ts +0 -826
- package/dist/webhook-handler-DNpCXDDA.d.mts +0 -826
package/dist/client.js
DELETED
|
@@ -1,938 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var sdk = require('@scalemule/sdk');
|
|
4
|
-
|
|
5
|
-
// src/client.ts
|
|
6
|
-
|
|
7
|
-
// src/types/index.ts
|
|
8
|
-
var ScaleMuleApiError = class extends Error {
|
|
9
|
-
constructor(error, status) {
|
|
10
|
-
super(error.message);
|
|
11
|
-
this.name = "ScaleMuleApiError";
|
|
12
|
-
this.code = error.code;
|
|
13
|
-
this.field = error.field;
|
|
14
|
-
this.status = status;
|
|
15
|
-
this.requestId = error.requestId;
|
|
16
|
-
this.traceId = error.traceId;
|
|
17
|
-
this.problem = error.problem;
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
// src/error-context.ts
|
|
22
|
-
function withErrorContext(error, responseData, headers) {
|
|
23
|
-
const enriched = { ...error };
|
|
24
|
-
const meta = responseData?.meta;
|
|
25
|
-
const requestId = meta?.request_id ?? headers?.get("x-request-id") ?? void 0;
|
|
26
|
-
if (requestId !== void 0 && enriched.requestId === void 0) {
|
|
27
|
-
enriched.requestId = requestId;
|
|
28
|
-
}
|
|
29
|
-
const traceId = meta?.trace_id;
|
|
30
|
-
if (traceId !== void 0 && enriched.traceId === void 0) {
|
|
31
|
-
enriched.traceId = traceId;
|
|
32
|
-
}
|
|
33
|
-
const rawError = responseData?.error;
|
|
34
|
-
if (rawError !== null && typeof rawError === "object" && enriched.problem === void 0) {
|
|
35
|
-
enriched.problem = rawError;
|
|
36
|
-
}
|
|
37
|
-
return enriched;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// src/client.ts
|
|
41
|
-
var GATEWAY_URLS = {
|
|
42
|
-
dev: "https://api-dev.scalemule.com",
|
|
43
|
-
prod: "https://api.scalemule.com"
|
|
44
|
-
};
|
|
45
|
-
var SESSION_STORAGE_KEY = sdk.STORAGE_KEYS.SESSION;
|
|
46
|
-
var USER_ID_STORAGE_KEY = sdk.STORAGE_KEYS.USER_ID;
|
|
47
|
-
var WORKSPACE_STORAGE_KEY = sdk.STORAGE_KEYS.WORKSPACE_ID;
|
|
48
|
-
var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
49
|
-
function sleep(ms) {
|
|
50
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
51
|
-
}
|
|
52
|
-
function getBackoffDelay(attempt, baseDelay = 1e3) {
|
|
53
|
-
const exponentialDelay = baseDelay * Math.pow(2, attempt);
|
|
54
|
-
const jitter = Math.random() * 0.3 * exponentialDelay;
|
|
55
|
-
return Math.min(exponentialDelay + jitter, 3e4);
|
|
56
|
-
}
|
|
57
|
-
function sanitizeFilename(filename) {
|
|
58
|
-
let sanitized = filename.replace(/[\x00-\x1f\x7f]/g, "");
|
|
59
|
-
sanitized = sanitized.replace(/["\\/\n\r]/g, "_").normalize("NFC").replace(/[\u200b-\u200f\ufeff\u2028\u2029]/g, "");
|
|
60
|
-
if (!sanitized || sanitized.trim() === "") {
|
|
61
|
-
sanitized = "unnamed";
|
|
62
|
-
}
|
|
63
|
-
if (sanitized.length > 200) {
|
|
64
|
-
const ext = sanitized.split(".").pop();
|
|
65
|
-
const base = sanitized.substring(0, 190);
|
|
66
|
-
sanitized = ext ? `${base}.${ext}` : base;
|
|
67
|
-
}
|
|
68
|
-
return sanitized.trim();
|
|
69
|
-
}
|
|
70
|
-
var RateLimitQueue = class {
|
|
71
|
-
constructor() {
|
|
72
|
-
this.queue = [];
|
|
73
|
-
this.processing = false;
|
|
74
|
-
this.rateLimitedUntil = 0;
|
|
75
|
-
this.requestsInWindow = 0;
|
|
76
|
-
this.windowStart = Date.now();
|
|
77
|
-
this.maxRequestsPerWindow = 100;
|
|
78
|
-
this.windowDurationMs = 6e4;
|
|
79
|
-
}
|
|
80
|
-
// 1 minute
|
|
81
|
-
/**
|
|
82
|
-
* Add request to queue
|
|
83
|
-
*/
|
|
84
|
-
enqueue(execute, priority = 0) {
|
|
85
|
-
return new Promise((resolve, reject) => {
|
|
86
|
-
this.queue.push({
|
|
87
|
-
execute,
|
|
88
|
-
resolve,
|
|
89
|
-
reject,
|
|
90
|
-
priority
|
|
91
|
-
});
|
|
92
|
-
this.queue.sort((a, b) => b.priority - a.priority);
|
|
93
|
-
this.processQueue();
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Process queued requests
|
|
98
|
-
*/
|
|
99
|
-
async processQueue() {
|
|
100
|
-
if (this.processing || this.queue.length === 0) return;
|
|
101
|
-
this.processing = true;
|
|
102
|
-
while (this.queue.length > 0) {
|
|
103
|
-
const now = Date.now();
|
|
104
|
-
if (now < this.rateLimitedUntil) {
|
|
105
|
-
const waitTime = this.rateLimitedUntil - now;
|
|
106
|
-
await sleep(waitTime);
|
|
107
|
-
}
|
|
108
|
-
if (now - this.windowStart >= this.windowDurationMs) {
|
|
109
|
-
this.windowStart = now;
|
|
110
|
-
this.requestsInWindow = 0;
|
|
111
|
-
}
|
|
112
|
-
if (this.requestsInWindow >= this.maxRequestsPerWindow) {
|
|
113
|
-
const waitTime = this.windowDurationMs - (now - this.windowStart);
|
|
114
|
-
await sleep(waitTime);
|
|
115
|
-
this.windowStart = Date.now();
|
|
116
|
-
this.requestsInWindow = 0;
|
|
117
|
-
}
|
|
118
|
-
const request = this.queue.shift();
|
|
119
|
-
if (!request) continue;
|
|
120
|
-
try {
|
|
121
|
-
this.requestsInWindow++;
|
|
122
|
-
const result = await request.execute();
|
|
123
|
-
request.resolve(result);
|
|
124
|
-
} catch (error) {
|
|
125
|
-
if (error instanceof ScaleMuleApiError && error.code === "RATE_LIMITED") {
|
|
126
|
-
this.queue.unshift(request);
|
|
127
|
-
this.rateLimitedUntil = Date.now() + 6e4;
|
|
128
|
-
} else {
|
|
129
|
-
request.reject(error);
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
this.processing = false;
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Update rate limit from response headers
|
|
137
|
-
*/
|
|
138
|
-
updateFromHeaders(headers) {
|
|
139
|
-
const retryAfter = headers.get("Retry-After");
|
|
140
|
-
if (retryAfter) {
|
|
141
|
-
const seconds = parseInt(retryAfter, 10);
|
|
142
|
-
if (!isNaN(seconds)) {
|
|
143
|
-
this.rateLimitedUntil = Date.now() + seconds * 1e3;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
const remaining = headers.get("X-RateLimit-Remaining");
|
|
147
|
-
if (remaining) {
|
|
148
|
-
const count = parseInt(remaining, 10);
|
|
149
|
-
if (!isNaN(count) && count === 0) {
|
|
150
|
-
const reset = headers.get("X-RateLimit-Reset");
|
|
151
|
-
if (reset) {
|
|
152
|
-
const resetTime = parseInt(reset, 10) * 1e3;
|
|
153
|
-
if (!isNaN(resetTime)) {
|
|
154
|
-
this.rateLimitedUntil = resetTime;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Get queue length
|
|
162
|
-
*/
|
|
163
|
-
get length() {
|
|
164
|
-
return this.queue.length;
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Check if rate limited
|
|
168
|
-
*/
|
|
169
|
-
get isRateLimited() {
|
|
170
|
-
return Date.now() < this.rateLimitedUntil;
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
var OfflineQueue = class {
|
|
174
|
-
constructor(storage) {
|
|
175
|
-
this.queue = [];
|
|
176
|
-
this.storageKey = "scalemule_offline_queue";
|
|
177
|
-
this.isOnline = true;
|
|
178
|
-
this.onOnline = null;
|
|
179
|
-
this.storage = storage;
|
|
180
|
-
this.loadFromStorage();
|
|
181
|
-
this.setupOnlineListener();
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Setup online/offline event listeners
|
|
185
|
-
*/
|
|
186
|
-
setupOnlineListener() {
|
|
187
|
-
if (typeof window === "undefined") return;
|
|
188
|
-
this.isOnline = navigator.onLine;
|
|
189
|
-
window.addEventListener("online", () => {
|
|
190
|
-
this.isOnline = true;
|
|
191
|
-
if (this.onOnline) this.onOnline();
|
|
192
|
-
});
|
|
193
|
-
window.addEventListener("offline", () => {
|
|
194
|
-
this.isOnline = false;
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Load queue from storage
|
|
199
|
-
*/
|
|
200
|
-
async loadFromStorage() {
|
|
201
|
-
try {
|
|
202
|
-
const data = await this.storage.getItem(this.storageKey);
|
|
203
|
-
if (data) {
|
|
204
|
-
this.queue = JSON.parse(data);
|
|
205
|
-
}
|
|
206
|
-
} catch {
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Save queue to storage
|
|
211
|
-
*/
|
|
212
|
-
async saveToStorage() {
|
|
213
|
-
try {
|
|
214
|
-
await this.storage.setItem(this.storageKey, JSON.stringify(this.queue));
|
|
215
|
-
} catch {
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
/**
|
|
219
|
-
* Add request to offline queue
|
|
220
|
-
*/
|
|
221
|
-
async add(method, path, body) {
|
|
222
|
-
const item = {
|
|
223
|
-
id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
224
|
-
method,
|
|
225
|
-
path,
|
|
226
|
-
body: body ? JSON.stringify(body) : void 0,
|
|
227
|
-
timestamp: Date.now()
|
|
228
|
-
};
|
|
229
|
-
this.queue.push(item);
|
|
230
|
-
await this.saveToStorage();
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* Get all queued requests
|
|
234
|
-
*/
|
|
235
|
-
getAll() {
|
|
236
|
-
return [...this.queue];
|
|
237
|
-
}
|
|
238
|
-
/**
|
|
239
|
-
* Remove a request from queue
|
|
240
|
-
*/
|
|
241
|
-
async remove(id) {
|
|
242
|
-
this.queue = this.queue.filter((item) => item.id !== id);
|
|
243
|
-
await this.saveToStorage();
|
|
244
|
-
}
|
|
245
|
-
/**
|
|
246
|
-
* Clear all queued requests
|
|
247
|
-
*/
|
|
248
|
-
async clear() {
|
|
249
|
-
this.queue = [];
|
|
250
|
-
await this.saveToStorage();
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Set callback for when coming back online
|
|
254
|
-
*/
|
|
255
|
-
setOnlineCallback(callback) {
|
|
256
|
-
this.onOnline = callback;
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Check if currently online
|
|
260
|
-
*/
|
|
261
|
-
get online() {
|
|
262
|
-
return this.isOnline;
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Get queue length
|
|
266
|
-
*/
|
|
267
|
-
get length() {
|
|
268
|
-
return this.queue.length;
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
function resolveGatewayUrl(config) {
|
|
272
|
-
if (config.gatewayUrl) {
|
|
273
|
-
return config.gatewayUrl;
|
|
274
|
-
}
|
|
275
|
-
const env = config.environment || "prod";
|
|
276
|
-
return GATEWAY_URLS[env];
|
|
277
|
-
}
|
|
278
|
-
function createDefaultStorage() {
|
|
279
|
-
if (typeof window !== "undefined" && window.localStorage) {
|
|
280
|
-
return {
|
|
281
|
-
getItem: (key) => localStorage.getItem(key),
|
|
282
|
-
setItem: (key, value) => localStorage.setItem(key, value),
|
|
283
|
-
removeItem: (key) => localStorage.removeItem(key)
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
const memoryStorage = /* @__PURE__ */ new Map();
|
|
287
|
-
return {
|
|
288
|
-
getItem: (key) => memoryStorage.get(key) ?? null,
|
|
289
|
-
setItem: (key, value) => {
|
|
290
|
-
memoryStorage.set(key, value);
|
|
291
|
-
},
|
|
292
|
-
removeItem: (key) => {
|
|
293
|
-
memoryStorage.delete(key);
|
|
294
|
-
}
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
var ScaleMuleClient = class {
|
|
298
|
-
constructor(config) {
|
|
299
|
-
this.applicationId = null;
|
|
300
|
-
this.sessionToken = null;
|
|
301
|
-
this.userId = null;
|
|
302
|
-
this.rateLimitQueue = null;
|
|
303
|
-
this.offlineQueue = null;
|
|
304
|
-
this.sessionGate = null;
|
|
305
|
-
this.resolveSessionGate = null;
|
|
306
|
-
this.workspaceId = null;
|
|
307
|
-
// Anonymous visitor ID for identity linking. See `@scalemule/sdk/anonymous-id`
|
|
308
|
-
// for the contract. The base SDK and this client share the same canonical
|
|
309
|
-
// localStorage key so a visitor has exactly one ID across all packages.
|
|
310
|
-
this.anonymousId = null;
|
|
311
|
-
// Per-client single-flight cache for the lazy mint. Concurrent first-use
|
|
312
|
-
// callers receive the same promise — without this, two simultaneous
|
|
313
|
-
// unauthenticated requests on a fresh visitor could mint different IDs.
|
|
314
|
-
// The shared helper also single-flights at the storage-adapter level.
|
|
315
|
-
this.anonymousIdPromise = null;
|
|
316
|
-
this.refreshPromise = null;
|
|
317
|
-
this.cookieSession = config.cookieSession === true;
|
|
318
|
-
this.apiKey = config.apiKey;
|
|
319
|
-
this.applicationId = config.applicationId || null;
|
|
320
|
-
this.gatewayUrl = resolveGatewayUrl(config);
|
|
321
|
-
this.debug = config.debug || false;
|
|
322
|
-
this.storage = config.storage || createDefaultStorage();
|
|
323
|
-
this.enableRateLimitQueue = config.enableRateLimitQueue || false;
|
|
324
|
-
this.enableOfflineQueue = config.enableOfflineQueue || false;
|
|
325
|
-
this.onRefreshStart = config.onRefreshStart;
|
|
326
|
-
this.onRefreshEnd = config.onRefreshEnd;
|
|
327
|
-
this.onAutoRefreshFailed = config.onAutoRefreshFailed;
|
|
328
|
-
if (this.enableRateLimitQueue) {
|
|
329
|
-
this.rateLimitQueue = new RateLimitQueue();
|
|
330
|
-
}
|
|
331
|
-
if (this.enableOfflineQueue) {
|
|
332
|
-
this.offlineQueue = new OfflineQueue(this.storage);
|
|
333
|
-
this.offlineQueue.setOnlineCallback(() => this.syncOfflineQueue());
|
|
334
|
-
}
|
|
335
|
-
if (config.pendingSessionInit) {
|
|
336
|
-
this.setSessionPending();
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Sync offline queue when coming back online
|
|
341
|
-
*/
|
|
342
|
-
async syncOfflineQueue() {
|
|
343
|
-
if (!this.offlineQueue) return;
|
|
344
|
-
const items = this.offlineQueue.getAll();
|
|
345
|
-
if (this.debug && items.length > 0) {
|
|
346
|
-
console.log(`[ScaleMule] Syncing ${items.length} offline requests`);
|
|
347
|
-
}
|
|
348
|
-
for (const item of items) {
|
|
349
|
-
try {
|
|
350
|
-
await this.request(item.path, {
|
|
351
|
-
method: item.method,
|
|
352
|
-
body: item.body,
|
|
353
|
-
skipRetry: true
|
|
354
|
-
});
|
|
355
|
-
await this.offlineQueue.remove(item.id);
|
|
356
|
-
} catch (err) {
|
|
357
|
-
if (this.debug) {
|
|
358
|
-
console.error("[ScaleMule] Failed to sync offline request:", err);
|
|
359
|
-
}
|
|
360
|
-
break;
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
/**
|
|
365
|
-
* Check if client is online
|
|
366
|
-
*/
|
|
367
|
-
isOnline() {
|
|
368
|
-
if (this.offlineQueue) {
|
|
369
|
-
return this.offlineQueue.online;
|
|
370
|
-
}
|
|
371
|
-
return typeof navigator === "undefined" || navigator.onLine;
|
|
372
|
-
}
|
|
373
|
-
/**
|
|
374
|
-
* Get number of pending offline requests
|
|
375
|
-
*/
|
|
376
|
-
getOfflineQueueLength() {
|
|
377
|
-
return this.offlineQueue?.length || 0;
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Get number of pending rate-limited requests
|
|
381
|
-
*/
|
|
382
|
-
getRateLimitQueueLength() {
|
|
383
|
-
return this.rateLimitQueue?.length || 0;
|
|
384
|
-
}
|
|
385
|
-
/**
|
|
386
|
-
* Check if currently rate limited
|
|
387
|
-
*/
|
|
388
|
-
isRateLimited() {
|
|
389
|
-
return this.rateLimitQueue?.isRateLimited || false;
|
|
390
|
-
}
|
|
391
|
-
/**
|
|
392
|
-
* Set the active workspace context. All subsequent requests will include
|
|
393
|
-
* x-sm-workspace-id header. Pass null to clear.
|
|
394
|
-
*/
|
|
395
|
-
setWorkspaceContext(id) {
|
|
396
|
-
this.workspaceId = id;
|
|
397
|
-
if (id) {
|
|
398
|
-
this.storage.setItem(WORKSPACE_STORAGE_KEY, id);
|
|
399
|
-
} else {
|
|
400
|
-
this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
/**
|
|
404
|
-
* Get the current workspace ID
|
|
405
|
-
*/
|
|
406
|
-
getWorkspaceId() {
|
|
407
|
-
return this.workspaceId;
|
|
408
|
-
}
|
|
409
|
-
/**
|
|
410
|
-
* Get the gateway URL
|
|
411
|
-
*/
|
|
412
|
-
getGatewayUrl() {
|
|
413
|
-
return this.gatewayUrl;
|
|
414
|
-
}
|
|
415
|
-
/**
|
|
416
|
-
* Get the application ID (required for realtime features)
|
|
417
|
-
*/
|
|
418
|
-
getApplicationId() {
|
|
419
|
-
return this.applicationId;
|
|
420
|
-
}
|
|
421
|
-
/**
|
|
422
|
-
* Signal that a session is being established asynchronously.
|
|
423
|
-
* API requests will wait until resolveSessionPending() is called.
|
|
424
|
-
*/
|
|
425
|
-
setSessionPending() {
|
|
426
|
-
if (!this.sessionGate) {
|
|
427
|
-
this.sessionGate = new Promise((resolve) => {
|
|
428
|
-
this.resolveSessionGate = resolve;
|
|
429
|
-
});
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
/**
|
|
433
|
-
* Resolve the pending session gate, allowing queued API requests to proceed.
|
|
434
|
-
* Must be called after setSessionPending(), whether session was established or not.
|
|
435
|
-
*/
|
|
436
|
-
resolveSessionPending() {
|
|
437
|
-
if (this.resolveSessionGate) {
|
|
438
|
-
this.resolveSessionGate();
|
|
439
|
-
this.resolveSessionGate = null;
|
|
440
|
-
this.sessionGate = null;
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
/**
|
|
444
|
-
* Initialize client by loading persisted session
|
|
445
|
-
*/
|
|
446
|
-
async initialize() {
|
|
447
|
-
if (this.cookieSession) {
|
|
448
|
-
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
449
|
-
await this.storage.removeItem(sdk.STORAGE_KEYS.SESSION_POOL);
|
|
450
|
-
await this.storage.removeItem(sdk.STORAGE_KEYS.ACTIVE_ACCOUNT);
|
|
451
|
-
}
|
|
452
|
-
const token = this.cookieSession ? null : await this.storage.getItem(SESSION_STORAGE_KEY);
|
|
453
|
-
const userId = this.cookieSession ? null : await this.storage.getItem(USER_ID_STORAGE_KEY);
|
|
454
|
-
if (token) this.sessionToken = token;
|
|
455
|
-
if (userId) this.userId = userId;
|
|
456
|
-
const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
|
|
457
|
-
if (wsId) this.workspaceId = wsId;
|
|
458
|
-
try {
|
|
459
|
-
await this.ensureAnonymousId();
|
|
460
|
-
} catch {
|
|
461
|
-
}
|
|
462
|
-
if (token) {
|
|
463
|
-
this.resolveSessionPending();
|
|
464
|
-
}
|
|
465
|
-
if (this.debug) {
|
|
466
|
-
console.log("[ScaleMule] Initialized with session:", !!token);
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
/**
|
|
470
|
-
* Sync accessor for the cached anonymous ID. Returns `null` until either
|
|
471
|
-
* `initialize()` has run or `ensureAnonymousId()` has been awaited at
|
|
472
|
-
* least once. Use `ensureAnonymousId()` if you need a guaranteed value.
|
|
473
|
-
*/
|
|
474
|
-
getAnonymousId() {
|
|
475
|
-
return this.anonymousId;
|
|
476
|
-
}
|
|
477
|
-
/**
|
|
478
|
-
* Lazy-mint or cache-then-return the anonymous ID via the shared
|
|
479
|
-
* `@scalemule/sdk` helper. Concurrent callers receive the same in-flight
|
|
480
|
-
* promise, so a burst of simultaneous first-use requests all see the
|
|
481
|
-
* same minted value.
|
|
482
|
-
*/
|
|
483
|
-
async ensureAnonymousId() {
|
|
484
|
-
if (this.anonymousId) return this.anonymousId;
|
|
485
|
-
if (!this.anonymousIdPromise) {
|
|
486
|
-
this.anonymousIdPromise = sdk.ensureAnonymousId(this.storage).then((id) => {
|
|
487
|
-
this.anonymousId = id;
|
|
488
|
-
return id;
|
|
489
|
-
}).finally(() => {
|
|
490
|
-
this.anonymousIdPromise = null;
|
|
491
|
-
});
|
|
492
|
-
}
|
|
493
|
-
return this.anonymousIdPromise;
|
|
494
|
-
}
|
|
495
|
-
/**
|
|
496
|
-
* Set session after login
|
|
497
|
-
*/
|
|
498
|
-
async setSession(token, userId) {
|
|
499
|
-
if (this.cookieSession) {
|
|
500
|
-
this.setCookieSession(userId);
|
|
501
|
-
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
502
|
-
return;
|
|
503
|
-
}
|
|
504
|
-
this.sessionToken = token;
|
|
505
|
-
this.userId = userId;
|
|
506
|
-
await this.storage.setItem(SESSION_STORAGE_KEY, token);
|
|
507
|
-
await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
|
|
508
|
-
if (this.debug) {
|
|
509
|
-
console.log("[ScaleMule] Session set for user:", userId);
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
/**
|
|
513
|
-
* Token-only setter for member-auth surfaces.
|
|
514
|
-
*
|
|
515
|
-
* Unlike `setSession(token, userId)`, this does NOT persist a userId or
|
|
516
|
-
* write to local storage — useful when the host platform owns identity
|
|
517
|
-
* (e.g. ScaleMule's member dashboards use `MemberAuthProvider` and the
|
|
518
|
-
* token comes from a `${env}_member_access_token` cookie). The token is
|
|
519
|
-
* applied in-memory and used as a `Bearer` Authorization header on
|
|
520
|
-
* subsequent requests.
|
|
521
|
-
*
|
|
522
|
-
* Pass `null` to clear without touching userId/storage.
|
|
523
|
-
*/
|
|
524
|
-
setCookieSession(userId) {
|
|
525
|
-
if (!this.cookieSession) return;
|
|
526
|
-
this.sessionToken = null;
|
|
527
|
-
this.userId = userId;
|
|
528
|
-
this.resolveSessionPending();
|
|
529
|
-
}
|
|
530
|
-
usesCookieSession() {
|
|
531
|
-
return this.cookieSession;
|
|
532
|
-
}
|
|
533
|
-
setSessionToken(token) {
|
|
534
|
-
this.sessionToken = this.cookieSession ? null : token;
|
|
535
|
-
if (this.debug) {
|
|
536
|
-
console.log("[ScaleMule] Session token", token ? "set (token-only)" : "cleared (token-only)");
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Clear session on logout
|
|
541
|
-
*/
|
|
542
|
-
async clearSession() {
|
|
543
|
-
this.sessionToken = null;
|
|
544
|
-
this.userId = null;
|
|
545
|
-
this.workspaceId = null;
|
|
546
|
-
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
547
|
-
await this.storage.removeItem(USER_ID_STORAGE_KEY);
|
|
548
|
-
await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
|
|
549
|
-
if (this.debug) {
|
|
550
|
-
console.log("[ScaleMule] Session cleared");
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Get current session token
|
|
555
|
-
*/
|
|
556
|
-
getSessionToken() {
|
|
557
|
-
return this.sessionToken;
|
|
558
|
-
}
|
|
559
|
-
/**
|
|
560
|
-
* Get current user ID
|
|
561
|
-
*/
|
|
562
|
-
getUserId() {
|
|
563
|
-
return this.userId;
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* Check if client has an active session
|
|
567
|
-
*/
|
|
568
|
-
isAuthenticated() {
|
|
569
|
-
return (this.cookieSession || this.sessionToken !== null) && this.userId !== null;
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Build headers for a request
|
|
573
|
-
*/
|
|
574
|
-
buildHeaders(options) {
|
|
575
|
-
const headers = new Headers(options?.headers);
|
|
576
|
-
headers.set("x-api-key", this.apiKey);
|
|
577
|
-
if (!options?.skipAuth && this.sessionToken) {
|
|
578
|
-
headers.set("Authorization", `Bearer ${this.sessionToken}`);
|
|
579
|
-
}
|
|
580
|
-
if (this.workspaceId) {
|
|
581
|
-
headers.set("x-sm-workspace-id", this.workspaceId);
|
|
582
|
-
}
|
|
583
|
-
if (!options?.skipAuth && !this.sessionToken && this.anonymousId) {
|
|
584
|
-
headers.set("x-anonymous-id", this.anonymousId);
|
|
585
|
-
}
|
|
586
|
-
if (!headers.has("Content-Type") && options?.body && typeof options.body === "string") {
|
|
587
|
-
headers.set("Content-Type", "application/json");
|
|
588
|
-
}
|
|
589
|
-
return headers;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* Make an HTTP request to the ScaleMule API
|
|
593
|
-
*/
|
|
594
|
-
async request(path, options = {}) {
|
|
595
|
-
if (this.sessionGate) {
|
|
596
|
-
await this.sessionGate;
|
|
597
|
-
}
|
|
598
|
-
if (!options.skipAuth && !this.sessionToken && !this.anonymousId) {
|
|
599
|
-
try {
|
|
600
|
-
await this.ensureAnonymousId();
|
|
601
|
-
} catch {
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
const url = `${this.gatewayUrl}${path}`;
|
|
605
|
-
const headers = this.buildHeaders(options);
|
|
606
|
-
const maxRetries = options.skipRetry ? 0 : options.retries ?? 2;
|
|
607
|
-
const timeout = options.timeout || 3e4;
|
|
608
|
-
if (this.debug) {
|
|
609
|
-
console.log(`[ScaleMule] ${options.method || "GET"} ${path}`);
|
|
610
|
-
}
|
|
611
|
-
let lastError = null;
|
|
612
|
-
const MAX_REFRESH_ATTEMPTS = 1;
|
|
613
|
-
let refreshAttempts = 0;
|
|
614
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
615
|
-
const controller = new AbortController();
|
|
616
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
617
|
-
try {
|
|
618
|
-
const response = await fetch(url, {
|
|
619
|
-
...options,
|
|
620
|
-
headers,
|
|
621
|
-
signal: controller.signal
|
|
622
|
-
});
|
|
623
|
-
clearTimeout(timeoutId);
|
|
624
|
-
const rotatedToken = response.headers.get("x-rotated-session-token");
|
|
625
|
-
if (rotatedToken && this.sessionToken && this.userId) {
|
|
626
|
-
this.setSession(rotatedToken, this.userId);
|
|
627
|
-
}
|
|
628
|
-
const text = await response.text();
|
|
629
|
-
let responseData = null;
|
|
630
|
-
try {
|
|
631
|
-
responseData = text ? JSON.parse(text) : null;
|
|
632
|
-
} catch {
|
|
633
|
-
}
|
|
634
|
-
if (!response.ok || responseData?.success === false) {
|
|
635
|
-
const rawError = responseData?.error;
|
|
636
|
-
const baseError = rawError && typeof rawError === "object" ? rawError : { code: `HTTP_${response.status}`, message: typeof rawError === "string" ? rawError : responseData?.message || text || response.statusText };
|
|
637
|
-
const error = withErrorContext(baseError, responseData, response.headers);
|
|
638
|
-
if (response.status === 401 && this.sessionToken && !options.isAutoRefresh && refreshAttempts < MAX_REFRESH_ATTEMPTS) {
|
|
639
|
-
refreshAttempts++;
|
|
640
|
-
if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
|
|
641
|
-
if (!this.refreshPromise) {
|
|
642
|
-
this.onRefreshStart?.();
|
|
643
|
-
this.refreshPromise = this.post("/api/auth/refresh", {}, { isAutoRefresh: true });
|
|
644
|
-
}
|
|
645
|
-
try {
|
|
646
|
-
await this.refreshPromise;
|
|
647
|
-
if (this.debug) console.log("[ScaleMule] Auto-refresh succeeded, retrying original request...");
|
|
648
|
-
attempt--;
|
|
649
|
-
if (this.sessionToken) {
|
|
650
|
-
headers.set("Authorization", `Bearer ${this.sessionToken}`);
|
|
651
|
-
}
|
|
652
|
-
continue;
|
|
653
|
-
} catch (refreshErr) {
|
|
654
|
-
if (this.debug) console.error("[ScaleMule] Auto-refresh failed:", refreshErr);
|
|
655
|
-
const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message, field: refreshErr.field } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
|
|
656
|
-
this.onAutoRefreshFailed?.(refreshApiError);
|
|
657
|
-
throw new ScaleMuleApiError(error);
|
|
658
|
-
} finally {
|
|
659
|
-
this.refreshPromise = null;
|
|
660
|
-
this.onRefreshEnd?.();
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
if (attempt < maxRetries && RETRYABLE_STATUS_CODES.has(response.status)) {
|
|
664
|
-
lastError = error;
|
|
665
|
-
const delay = getBackoffDelay(attempt);
|
|
666
|
-
if (this.debug) {
|
|
667
|
-
console.log(`[ScaleMule] Retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
|
|
668
|
-
}
|
|
669
|
-
await sleep(delay);
|
|
670
|
-
continue;
|
|
671
|
-
}
|
|
672
|
-
if (this.debug) {
|
|
673
|
-
console.error("[ScaleMule] Request failed:", ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(error.code) ? error.code : error);
|
|
674
|
-
}
|
|
675
|
-
throw new ScaleMuleApiError(error);
|
|
676
|
-
}
|
|
677
|
-
const data = responseData?.data !== void 0 ? responseData.data : responseData;
|
|
678
|
-
return data;
|
|
679
|
-
} catch (err) {
|
|
680
|
-
clearTimeout(timeoutId);
|
|
681
|
-
if (err instanceof ScaleMuleApiError) {
|
|
682
|
-
throw err;
|
|
683
|
-
}
|
|
684
|
-
const error = {
|
|
685
|
-
code: err instanceof Error && err.name === "AbortError" ? "TIMEOUT" : "NETWORK_ERROR",
|
|
686
|
-
message: err instanceof Error ? err.message : "Network request failed"
|
|
687
|
-
};
|
|
688
|
-
if (attempt < maxRetries) {
|
|
689
|
-
lastError = error;
|
|
690
|
-
const delay = getBackoffDelay(attempt);
|
|
691
|
-
if (this.debug) {
|
|
692
|
-
console.log(`[ScaleMule] Retrying after error in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
|
|
693
|
-
}
|
|
694
|
-
await sleep(delay);
|
|
695
|
-
continue;
|
|
696
|
-
}
|
|
697
|
-
if (this.debug) {
|
|
698
|
-
console.error("[ScaleMule] Network error:", err);
|
|
699
|
-
}
|
|
700
|
-
throw new ScaleMuleApiError(error);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
throw new ScaleMuleApiError(lastError || { code: "UNKNOWN", message: "Request failed" });
|
|
704
|
-
}
|
|
705
|
-
/**
|
|
706
|
-
* GET request
|
|
707
|
-
*/
|
|
708
|
-
async get(path, options) {
|
|
709
|
-
return this.request(path, { ...options, method: "GET" });
|
|
710
|
-
}
|
|
711
|
-
/**
|
|
712
|
-
* POST request with JSON body
|
|
713
|
-
*/
|
|
714
|
-
async post(path, body, options) {
|
|
715
|
-
return this.request(path, {
|
|
716
|
-
...options,
|
|
717
|
-
method: "POST",
|
|
718
|
-
body: body ? JSON.stringify(body) : void 0
|
|
719
|
-
});
|
|
720
|
-
}
|
|
721
|
-
/**
|
|
722
|
-
* PUT request with JSON body
|
|
723
|
-
*/
|
|
724
|
-
async put(path, body, options) {
|
|
725
|
-
return this.request(path, {
|
|
726
|
-
...options,
|
|
727
|
-
method: "PUT",
|
|
728
|
-
body: body ? JSON.stringify(body) : void 0
|
|
729
|
-
});
|
|
730
|
-
}
|
|
731
|
-
/**
|
|
732
|
-
* PATCH request with JSON body
|
|
733
|
-
*/
|
|
734
|
-
async patch(path, body, options) {
|
|
735
|
-
return this.request(path, {
|
|
736
|
-
...options,
|
|
737
|
-
method: "PATCH",
|
|
738
|
-
body: body ? JSON.stringify(body) : void 0
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
/**
|
|
742
|
-
* DELETE request
|
|
743
|
-
*/
|
|
744
|
-
async delete(path, options) {
|
|
745
|
-
return this.request(path, { ...options, method: "DELETE" });
|
|
746
|
-
}
|
|
747
|
-
/**
|
|
748
|
-
* Upload a file using multipart/form-data
|
|
749
|
-
*
|
|
750
|
-
* Automatically includes Authorization: Bearer header for user identity.
|
|
751
|
-
* Supports progress callback via XMLHttpRequest when onProgress is provided.
|
|
752
|
-
*/
|
|
753
|
-
async upload(path, file, additionalFields, options) {
|
|
754
|
-
const sanitizedName = sanitizeFilename(file.name);
|
|
755
|
-
const sanitizedFile = sanitizedName !== file.name ? new File([file], sanitizedName, { type: file.type }) : file;
|
|
756
|
-
const formData = new FormData();
|
|
757
|
-
formData.append("file", sanitizedFile);
|
|
758
|
-
if (this.userId) {
|
|
759
|
-
formData.append("sm_user_id", this.userId);
|
|
760
|
-
}
|
|
761
|
-
if (additionalFields) {
|
|
762
|
-
for (const [key, value] of Object.entries(additionalFields)) {
|
|
763
|
-
formData.append(key, value);
|
|
764
|
-
}
|
|
765
|
-
}
|
|
766
|
-
const url = `${this.gatewayUrl}${path}`;
|
|
767
|
-
if (this.debug) {
|
|
768
|
-
console.log(`[ScaleMule] UPLOAD ${path}`);
|
|
769
|
-
}
|
|
770
|
-
if (options?.onProgress && typeof XMLHttpRequest !== "undefined") {
|
|
771
|
-
return this.uploadWithProgress(url, formData, options.onProgress);
|
|
772
|
-
}
|
|
773
|
-
const maxRetries = options?.retries ?? 2;
|
|
774
|
-
const headers = new Headers();
|
|
775
|
-
headers.set("x-api-key", this.apiKey);
|
|
776
|
-
if (this.sessionToken) {
|
|
777
|
-
headers.set("Authorization", `Bearer ${this.sessionToken}`);
|
|
778
|
-
}
|
|
779
|
-
if (this.workspaceId) {
|
|
780
|
-
headers.set("x-sm-workspace-id", this.workspaceId);
|
|
781
|
-
}
|
|
782
|
-
let lastError = null;
|
|
783
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
784
|
-
try {
|
|
785
|
-
const retryFormData = attempt === 0 ? formData : new FormData();
|
|
786
|
-
if (attempt > 0) {
|
|
787
|
-
retryFormData.append("file", sanitizedFile);
|
|
788
|
-
if (this.userId) {
|
|
789
|
-
retryFormData.append("sm_user_id", this.userId);
|
|
790
|
-
}
|
|
791
|
-
if (additionalFields) {
|
|
792
|
-
for (const [key, value] of Object.entries(additionalFields)) {
|
|
793
|
-
retryFormData.append(key, value);
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
const response = await fetch(url, {
|
|
798
|
-
method: "POST",
|
|
799
|
-
headers,
|
|
800
|
-
body: retryFormData
|
|
801
|
-
});
|
|
802
|
-
const uploadText = await response.text();
|
|
803
|
-
let responseData = null;
|
|
804
|
-
try {
|
|
805
|
-
responseData = uploadText ? JSON.parse(uploadText) : null;
|
|
806
|
-
} catch {
|
|
807
|
-
}
|
|
808
|
-
if (!response.ok) {
|
|
809
|
-
const error = responseData?.error || {
|
|
810
|
-
code: `HTTP_${response.status}`,
|
|
811
|
-
message: responseData?.message || uploadText || response.statusText
|
|
812
|
-
};
|
|
813
|
-
if (attempt < maxRetries && RETRYABLE_STATUS_CODES.has(response.status)) {
|
|
814
|
-
lastError = error;
|
|
815
|
-
const delay = getBackoffDelay(attempt);
|
|
816
|
-
if (this.debug) {
|
|
817
|
-
console.log(`[ScaleMule] Upload retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
|
|
818
|
-
}
|
|
819
|
-
await sleep(delay);
|
|
820
|
-
continue;
|
|
821
|
-
}
|
|
822
|
-
throw new ScaleMuleApiError(error);
|
|
823
|
-
}
|
|
824
|
-
const data = responseData?.data !== void 0 ? responseData.data : responseData;
|
|
825
|
-
return data;
|
|
826
|
-
} catch (err) {
|
|
827
|
-
if (err instanceof ScaleMuleApiError) {
|
|
828
|
-
throw err;
|
|
829
|
-
}
|
|
830
|
-
lastError = {
|
|
831
|
-
code: "UPLOAD_ERROR",
|
|
832
|
-
message: err instanceof Error ? err.message : "Upload failed"
|
|
833
|
-
};
|
|
834
|
-
if (attempt < maxRetries) {
|
|
835
|
-
const delay = getBackoffDelay(attempt);
|
|
836
|
-
if (this.debug) {
|
|
837
|
-
console.log(`[ScaleMule] Upload retry ${attempt + 1}/${maxRetries} after ${delay}ms (network error)`);
|
|
838
|
-
}
|
|
839
|
-
await sleep(delay);
|
|
840
|
-
continue;
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
throw new ScaleMuleApiError(lastError || { code: "UPLOAD_ERROR", message: "Upload failed after retries" });
|
|
845
|
-
}
|
|
846
|
-
/**
|
|
847
|
-
* Upload with progress using XMLHttpRequest (with retry)
|
|
848
|
-
*/
|
|
849
|
-
async uploadWithProgress(url, formData, onProgress, maxRetries = 2) {
|
|
850
|
-
let lastError = null;
|
|
851
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
852
|
-
try {
|
|
853
|
-
return await this.singleUploadWithProgress(url, formData, onProgress);
|
|
854
|
-
} catch (err) {
|
|
855
|
-
if (!(err instanceof ScaleMuleApiError)) {
|
|
856
|
-
throw err;
|
|
857
|
-
}
|
|
858
|
-
const errorCode = err.code;
|
|
859
|
-
const isNetworkError = errorCode === "UPLOAD_ERROR" || errorCode === "NETWORK_ERROR";
|
|
860
|
-
const isRetryableHttp = errorCode.startsWith("HTTP_") && RETRYABLE_STATUS_CODES.has(parseInt(errorCode.replace("HTTP_", ""), 10));
|
|
861
|
-
if (attempt < maxRetries && (isNetworkError || isRetryableHttp)) {
|
|
862
|
-
lastError = { code: err.code, message: err.message };
|
|
863
|
-
const delay = getBackoffDelay(attempt);
|
|
864
|
-
if (this.debug) {
|
|
865
|
-
console.log(`[ScaleMule] Upload retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
|
|
866
|
-
}
|
|
867
|
-
await sleep(delay);
|
|
868
|
-
onProgress(0);
|
|
869
|
-
continue;
|
|
870
|
-
}
|
|
871
|
-
throw err;
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
throw new ScaleMuleApiError(lastError || { code: "UPLOAD_ERROR", message: "Upload failed after retries" });
|
|
875
|
-
}
|
|
876
|
-
/**
|
|
877
|
-
* Single upload attempt with progress using XMLHttpRequest
|
|
878
|
-
*/
|
|
879
|
-
singleUploadWithProgress(url, formData, onProgress) {
|
|
880
|
-
return new Promise((resolve, reject) => {
|
|
881
|
-
const xhr = new XMLHttpRequest();
|
|
882
|
-
xhr.upload.addEventListener("progress", (event) => {
|
|
883
|
-
if (event.lengthComputable) {
|
|
884
|
-
const progress = Math.round(event.loaded / event.total * 100);
|
|
885
|
-
onProgress(progress);
|
|
886
|
-
}
|
|
887
|
-
});
|
|
888
|
-
xhr.addEventListener("load", () => {
|
|
889
|
-
try {
|
|
890
|
-
let data = null;
|
|
891
|
-
try {
|
|
892
|
-
data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
|
|
893
|
-
} catch {
|
|
894
|
-
}
|
|
895
|
-
if (xhr.status >= 200 && xhr.status < 300) {
|
|
896
|
-
const unwrapped = data?.data !== void 0 ? data.data : data;
|
|
897
|
-
resolve(unwrapped);
|
|
898
|
-
} else {
|
|
899
|
-
const uploadError = data?.error || {
|
|
900
|
-
code: `HTTP_${xhr.status}`,
|
|
901
|
-
message: data?.message || xhr.responseText || "Upload failed"
|
|
902
|
-
};
|
|
903
|
-
reject(
|
|
904
|
-
new ScaleMuleApiError(
|
|
905
|
-
withErrorContext(uploadError, data, {
|
|
906
|
-
get: (name) => xhr.getResponseHeader(name)
|
|
907
|
-
})
|
|
908
|
-
)
|
|
909
|
-
);
|
|
910
|
-
}
|
|
911
|
-
} catch {
|
|
912
|
-
reject(new ScaleMuleApiError({ code: "PARSE_ERROR", message: "Failed to parse response" }));
|
|
913
|
-
}
|
|
914
|
-
});
|
|
915
|
-
xhr.addEventListener("error", () => {
|
|
916
|
-
reject(new ScaleMuleApiError({ code: "UPLOAD_ERROR", message: "Upload failed" }));
|
|
917
|
-
});
|
|
918
|
-
xhr.addEventListener("abort", () => {
|
|
919
|
-
reject(new ScaleMuleApiError({ code: "UPLOAD_ABORTED", message: "Upload cancelled" }));
|
|
920
|
-
});
|
|
921
|
-
xhr.open("POST", url);
|
|
922
|
-
xhr.setRequestHeader("x-api-key", this.apiKey);
|
|
923
|
-
if (this.sessionToken) {
|
|
924
|
-
xhr.setRequestHeader("Authorization", `Bearer ${this.sessionToken}`);
|
|
925
|
-
}
|
|
926
|
-
if (this.workspaceId) {
|
|
927
|
-
xhr.setRequestHeader("x-sm-workspace-id", this.workspaceId);
|
|
928
|
-
}
|
|
929
|
-
xhr.send(formData);
|
|
930
|
-
});
|
|
931
|
-
}
|
|
932
|
-
};
|
|
933
|
-
function createClient(config) {
|
|
934
|
-
return new ScaleMuleClient(config);
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
exports.ScaleMuleClient = ScaleMuleClient;
|
|
938
|
-
exports.createClient = createClient;
|