@scalemule/nextjs 0.1.33 → 0.1.35

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/client.mjs CHANGED
@@ -1,398 +1,6 @@
1
- // node_modules/@scalemule/sdk/dist/index.mjs
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __esm = (fn, res) => function __init() {
5
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
- };
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var upload_resume_exports = {};
12
- __export(upload_resume_exports, {
13
- UploadResumeStore: () => UploadResumeStore
14
- });
15
- var DB_NAME;
16
- var STORE_NAME;
17
- var DB_VERSION;
18
- var MAX_AGE_MS;
19
- var UploadResumeStore;
20
- var init_upload_resume = __esm({
21
- "src/services/upload-resume.ts"() {
22
- DB_NAME = "sm_upload_sessions_v1";
23
- STORE_NAME = "sessions";
24
- DB_VERSION = 1;
25
- MAX_AGE_MS = 24 * 60 * 60 * 1e3;
26
- UploadResumeStore = class {
27
- constructor() {
28
- this.db = null;
29
- }
30
- /** Generate a deterministic resume key from upload identity */
31
- static async generateResumeKey(appId, userId, filename, size, lastModified) {
32
- const raw = `${appId}:${userId}:${filename}:${size}:${lastModified ?? 0}`;
33
- if (typeof crypto !== "undefined" && crypto.subtle) {
34
- const buffer = new TextEncoder().encode(raw);
35
- const hash2 = await crypto.subtle.digest("SHA-256", buffer);
36
- return Array.from(new Uint8Array(hash2)).map((b) => b.toString(16).padStart(2, "0")).join("");
37
- }
38
- let hash = 0;
39
- for (let i = 0; i < raw.length; i++) {
40
- const chr = raw.charCodeAt(i);
41
- hash = (hash << 5) - hash + chr;
42
- hash |= 0;
43
- }
44
- return `fallback_${Math.abs(hash).toString(36)}`;
45
- }
46
- /** Open the IndexedDB store. No-ops if IndexedDB is unavailable. */
47
- async open() {
48
- if (typeof indexedDB === "undefined") return;
49
- return new Promise((resolve, reject) => {
50
- const request = indexedDB.open(DB_NAME, DB_VERSION);
51
- request.onupgradeneeded = () => {
52
- const db = request.result;
53
- if (!db.objectStoreNames.contains(STORE_NAME)) {
54
- const store = db.createObjectStore(STORE_NAME, { keyPath: "key" });
55
- store.createIndex("updated_at", "updated_at");
56
- }
57
- };
58
- request.onsuccess = () => {
59
- this.db = request.result;
60
- resolve();
61
- };
62
- request.onerror = () => {
63
- reject(request.error);
64
- };
65
- });
66
- }
67
- /** Get a resume session by key. Returns null if not found or stale. */
68
- async get(key) {
69
- if (!this.db) return null;
70
- return new Promise((resolve) => {
71
- const tx = this.db.transaction(STORE_NAME, "readonly");
72
- const store = tx.objectStore(STORE_NAME);
73
- const request = store.get(key);
74
- request.onsuccess = () => {
75
- const entry = request.result;
76
- if (!entry) {
77
- resolve(null);
78
- return;
79
- }
80
- if (Date.now() - entry.updated_at > MAX_AGE_MS) {
81
- this.remove(key).catch(() => {
82
- });
83
- resolve(null);
84
- return;
85
- }
86
- resolve(entry.session);
87
- };
88
- request.onerror = () => resolve(null);
89
- });
90
- }
91
- /** Save a new resume session. */
92
- async save(key, session) {
93
- if (!this.db) return;
94
- return new Promise((resolve, reject) => {
95
- const tx = this.db.transaction(STORE_NAME, "readwrite");
96
- const store = tx.objectStore(STORE_NAME);
97
- const entry = {
98
- key,
99
- session: { ...session, created_at: Date.now() },
100
- updated_at: Date.now()
101
- };
102
- const request = store.put(entry);
103
- request.onsuccess = () => resolve();
104
- request.onerror = () => reject(request.error);
105
- });
106
- }
107
- /** Update a single completed part in an existing session. */
108
- async updatePart(key, partNumber, etag) {
109
- if (!this.db) return;
110
- return new Promise((resolve) => {
111
- const tx = this.db.transaction(STORE_NAME, "readwrite");
112
- const store = tx.objectStore(STORE_NAME);
113
- const getRequest = store.get(key);
114
- getRequest.onsuccess = () => {
115
- const entry = getRequest.result;
116
- if (!entry) {
117
- resolve();
118
- return;
119
- }
120
- const existing = entry.session.completed_parts.find((p) => p.part_number === partNumber);
121
- if (!existing) {
122
- entry.session.completed_parts.push({ part_number: partNumber, etag });
123
- }
124
- entry.updated_at = Date.now();
125
- const putRequest = store.put(entry);
126
- putRequest.onsuccess = () => resolve();
127
- putRequest.onerror = () => resolve();
128
- };
129
- getRequest.onerror = () => resolve();
130
- });
131
- }
132
- /** Remove a resume session (e.g., after successful completion). */
133
- async remove(key) {
134
- if (!this.db) return;
135
- return new Promise((resolve) => {
136
- const tx = this.db.transaction(STORE_NAME, "readwrite");
137
- const store = tx.objectStore(STORE_NAME);
138
- const request = store.delete(key);
139
- request.onsuccess = () => resolve();
140
- request.onerror = () => resolve();
141
- });
142
- }
143
- /** Purge all stale entries (older than MAX_AGE_MS). */
144
- async purgeStale() {
145
- if (!this.db) return 0;
146
- return new Promise((resolve) => {
147
- const cutoff = Date.now() - MAX_AGE_MS;
148
- const tx = this.db.transaction(STORE_NAME, "readwrite");
149
- const store = tx.objectStore(STORE_NAME);
150
- const index = store.index("updated_at");
151
- const range = IDBKeyRange.upperBound(cutoff);
152
- const request = index.openCursor(range);
153
- let count = 0;
154
- request.onsuccess = () => {
155
- const cursor = request.result;
156
- if (cursor) {
157
- cursor.delete();
158
- count++;
159
- cursor.continue();
160
- } else {
161
- resolve(count);
162
- }
163
- };
164
- request.onerror = () => resolve(0);
165
- });
166
- }
167
- /** Close the database connection. */
168
- close() {
169
- if (this.db) {
170
- this.db.close();
171
- this.db = null;
172
- }
173
- }
174
- };
175
- }
176
- });
177
- var upload_compression_exports = {};
178
- __export(upload_compression_exports, {
179
- maybeCompressImage: () => maybeCompressImage
180
- });
181
- async function maybeCompressImage(file, userConfig, sessionId, telemetry) {
182
- const type = file.type?.toLowerCase() || "";
183
- if (!type.startsWith("image/")) return null;
184
- if (SKIP_TYPES.has(type)) {
185
- telemetry?.emit(sessionId, "upload.compression.skipped", { reason: "format", type });
186
- return null;
187
- }
188
- if (!COMPRESSIBLE_TYPES.has(type)) {
189
- telemetry?.emit(sessionId, "upload.compression.skipped", { reason: "unsupported_type", type });
190
- return null;
191
- }
192
- if (file.size < MIN_COMPRESS_SIZE) {
193
- telemetry?.emit(sessionId, "upload.compression.skipped", { reason: "too_small", size: file.size });
194
- return null;
195
- }
196
- const networkType = getNetworkEffectiveType();
197
- const defaultProfile = { maxWidth: 3840, maxHeight: 3840, quality: 0.85, maxSizeMB: 5 };
198
- const networkProfile = NETWORK_PROFILES[networkType] ?? defaultProfile;
199
- const config = {
200
- maxWidth: userConfig?.maxWidth ?? networkProfile.maxWidth,
201
- maxHeight: userConfig?.maxHeight ?? networkProfile.maxHeight,
202
- quality: userConfig?.quality ?? networkProfile.quality,
203
- maxSizeMB: userConfig?.maxSizeMB ?? networkProfile.maxSizeMB
204
- };
205
- telemetry?.emit(sessionId, "upload.compression.started", {
206
- original_size: file.size,
207
- network: networkType,
208
- target_quality: config.quality
209
- });
210
- try {
211
- const imageCompression = await loadImageCompression();
212
- if (!imageCompression) {
213
- telemetry?.emit(sessionId, "upload.compression.skipped", { reason: "library_unavailable" });
214
- return null;
215
- }
216
- const compressed = await imageCompression(file, {
217
- maxSizeMB: config.maxSizeMB,
218
- maxWidthOrHeight: Math.max(config.maxWidth, config.maxHeight),
219
- initialQuality: config.quality,
220
- useWebWorker: true,
221
- fileType: type === "image/png" ? "image/webp" : void 0
222
- });
223
- if (compressed.size >= file.size * 0.95) {
224
- telemetry?.emit(sessionId, "upload.compression.skipped", {
225
- reason: "no_size_reduction",
226
- original_size: file.size,
227
- compressed_size: compressed.size
228
- });
229
- return null;
230
- }
231
- telemetry?.emit(sessionId, "upload.compression.completed", {
232
- original_size: file.size,
233
- compressed_size: compressed.size,
234
- ratio: (compressed.size / file.size).toFixed(2)
235
- });
236
- return compressed;
237
- } catch (err) {
238
- telemetry?.emit(sessionId, "upload.compression.skipped", {
239
- reason: "error",
240
- error: err instanceof Error ? err.message : "Unknown compression error"
241
- });
242
- return null;
243
- }
244
- }
245
- async function loadImageCompression() {
246
- if (cachedImport === false) return null;
247
- if (cachedImport) return cachedImport;
248
- try {
249
- const mod = await Function('return import("browser-image-compression")')();
250
- cachedImport = mod.default || mod;
251
- return cachedImport;
252
- } catch {
253
- cachedImport = false;
254
- return null;
255
- }
256
- }
257
- function getNetworkEffectiveType() {
258
- if (typeof navigator !== "undefined" && "connection" in navigator) {
259
- const conn = navigator.connection;
260
- return conn?.effectiveType || "4g";
261
- }
262
- return "4g";
263
- }
264
- var MIN_COMPRESS_SIZE;
265
- var COMPRESSIBLE_TYPES;
266
- var SKIP_TYPES;
267
- var NETWORK_PROFILES;
268
- var cachedImport;
269
- var STORAGE_KEYS = {
270
- SESSION: "scalemule_session",
271
- USER_ID: "scalemule_user_id",
272
- WORKSPACE_ID: "scalemule_workspace_id",
273
- ANONYMOUS_ID: "scalemule_anonymous_id",
274
- SESSION_POOL: "scalemule_session_pool",
275
- ACTIVE_ACCOUNT: "scalemule_active_account",
276
- KNOWN_ACCOUNTS: "scalemule_known_accounts",
277
- OFFLINE_QUEUE: "scalemule_offline_queue"
278
- };
279
- var LEGACY_ANONYMOUS_ID_KEYS = ["sm_anonymous_id"];
280
- function generateAnonymousId() {
281
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
282
- return crypto.randomUUID();
283
- }
284
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
285
- const r = Math.random() * 16 | 0;
286
- const v = c === "x" ? r : r & 3 | 8;
287
- return v.toString(16);
288
- });
289
- }
290
- var inFlight = /* @__PURE__ */ new WeakMap();
291
- function ensureAnonymousId(storage) {
292
- const existing = inFlight.get(storage);
293
- if (existing) return existing;
294
- const promise = (async () => {
295
- try {
296
- return await resolveAnonymousId(storage);
297
- } finally {
298
- inFlight.delete(storage);
299
- }
300
- })();
301
- inFlight.set(storage, promise);
302
- return promise;
303
- }
304
- async function resolveAnonymousId(storage) {
305
- const canonical = await storage.getItem(STORAGE_KEYS.ANONYMOUS_ID);
306
- if (canonical) {
307
- for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
308
- const legacy = await storage.getItem(legacyKey);
309
- if (legacy !== canonical) {
310
- try {
311
- await storage.setItem(legacyKey, canonical);
312
- } catch {
313
- }
314
- }
315
- }
316
- return canonical;
317
- }
318
- for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
319
- const legacy = await storage.getItem(legacyKey);
320
- if (legacy) {
321
- try {
322
- await storage.setItem(STORAGE_KEYS.ANONYMOUS_ID, legacy);
323
- } catch {
324
- }
325
- return legacy;
326
- }
327
- }
328
- const fresh = generateAnonymousId();
329
- try {
330
- await storage.setItem(STORAGE_KEYS.ANONYMOUS_ID, fresh);
331
- } catch {
332
- }
333
- for (const legacyKey of LEGACY_ANONYMOUS_ID_KEYS) {
334
- try {
335
- await storage.setItem(legacyKey, fresh);
336
- } catch {
337
- }
338
- }
339
- return fresh;
340
- }
341
- var PHONE_COUNTRIES = [
342
- { code: "US", name: "United States", dialCode: "+1" },
343
- { code: "CA", name: "Canada", dialCode: "+1" },
344
- { code: "GB", name: "United Kingdom", dialCode: "+44" },
345
- { code: "AU", name: "Australia", dialCode: "+61" },
346
- { code: "DE", name: "Germany", dialCode: "+49" },
347
- { code: "FR", name: "France", dialCode: "+33" },
348
- { code: "IT", name: "Italy", dialCode: "+39" },
349
- { code: "ES", name: "Spain", dialCode: "+34" },
350
- { code: "NL", name: "Netherlands", dialCode: "+31" },
351
- { code: "BE", name: "Belgium", dialCode: "+32" },
352
- { code: "CH", name: "Switzerland", dialCode: "+41" },
353
- { code: "AT", name: "Austria", dialCode: "+43" },
354
- { code: "SE", name: "Sweden", dialCode: "+46" },
355
- { code: "NO", name: "Norway", dialCode: "+47" },
356
- { code: "DK", name: "Denmark", dialCode: "+45" },
357
- { code: "FI", name: "Finland", dialCode: "+358" },
358
- { code: "IE", name: "Ireland", dialCode: "+353" },
359
- { code: "PT", name: "Portugal", dialCode: "+351" },
360
- { code: "PL", name: "Poland", dialCode: "+48" },
361
- { code: "CZ", name: "Czech Republic", dialCode: "+420" },
362
- { code: "GR", name: "Greece", dialCode: "+30" },
363
- { code: "RU", name: "Russia", dialCode: "+7" },
364
- { code: "JP", name: "Japan", dialCode: "+81" },
365
- { code: "KR", name: "South Korea", dialCode: "+82" },
366
- { code: "CN", name: "China", dialCode: "+86" },
367
- { code: "HK", name: "Hong Kong", dialCode: "+852" },
368
- { code: "TW", name: "Taiwan", dialCode: "+886" },
369
- { code: "SG", name: "Singapore", dialCode: "+65" },
370
- { code: "MY", name: "Malaysia", dialCode: "+60" },
371
- { code: "TH", name: "Thailand", dialCode: "+66" },
372
- { code: "VN", name: "Vietnam", dialCode: "+84" },
373
- { code: "PH", name: "Philippines", dialCode: "+63" },
374
- { code: "ID", name: "Indonesia", dialCode: "+62" },
375
- { code: "IN", name: "India", dialCode: "+91" },
376
- { code: "PK", name: "Pakistan", dialCode: "+92" },
377
- { code: "BD", name: "Bangladesh", dialCode: "+880" },
378
- { code: "AE", name: "UAE", dialCode: "+971" },
379
- { code: "SA", name: "Saudi Arabia", dialCode: "+966" },
380
- { code: "IL", name: "Israel", dialCode: "+972" },
381
- { code: "TR", name: "Turkey", dialCode: "+90" },
382
- { code: "EG", name: "Egypt", dialCode: "+20" },
383
- { code: "ZA", name: "South Africa", dialCode: "+27" },
384
- { code: "NG", name: "Nigeria", dialCode: "+234" },
385
- { code: "KE", name: "Kenya", dialCode: "+254" },
386
- { code: "BR", name: "Brazil", dialCode: "+55" },
387
- { code: "MX", name: "Mexico", dialCode: "+52" },
388
- { code: "AR", name: "Argentina", dialCode: "+54" },
389
- { code: "CL", name: "Chile", dialCode: "+56" },
390
- { code: "CO", name: "Colombia", dialCode: "+57" },
391
- { code: "PE", name: "Peru", dialCode: "+51" },
392
- { code: "NZ", name: "New Zealand", dialCode: "+64" }
393
- ];
394
- [...PHONE_COUNTRIES].sort((a, b) => b.dialCode.length - a.dialCode.length);
395
- init_upload_resume();
1
+ import { STORAGE_KEYS, ensureAnonymousId } from '@scalemule/sdk';
2
+
3
+ // src/client.ts
396
4
 
397
5
  // src/types/index.ts
398
6
  var ScaleMuleApiError = class extends Error {
@@ -410,9 +18,9 @@ var GATEWAY_URLS = {
410
18
  dev: "https://api-dev.scalemule.com",
411
19
  prod: "https://api.scalemule.com"
412
20
  };
413
- var SESSION_STORAGE_KEY2 = STORAGE_KEYS.SESSION;
414
- var USER_ID_STORAGE_KEY2 = STORAGE_KEYS.USER_ID;
415
- var WORKSPACE_STORAGE_KEY2 = STORAGE_KEYS.WORKSPACE_ID;
21
+ var SESSION_STORAGE_KEY = STORAGE_KEYS.SESSION;
22
+ var USER_ID_STORAGE_KEY = STORAGE_KEYS.USER_ID;
23
+ var WORKSPACE_STORAGE_KEY = STORAGE_KEYS.WORKSPACE_ID;
416
24
  var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
417
25
  function sleep(ms) {
418
26
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -762,9 +370,9 @@ var ScaleMuleClient = class {
762
370
  setWorkspaceContext(id) {
763
371
  this.workspaceId = id;
764
372
  if (id) {
765
- this.storage.setItem(WORKSPACE_STORAGE_KEY2, id);
373
+ this.storage.setItem(WORKSPACE_STORAGE_KEY, id);
766
374
  } else {
767
- this.storage.removeItem(WORKSPACE_STORAGE_KEY2);
375
+ this.storage.removeItem(WORKSPACE_STORAGE_KEY);
768
376
  }
769
377
  }
770
378
  /**
@@ -811,11 +419,11 @@ var ScaleMuleClient = class {
811
419
  * Initialize client by loading persisted session
812
420
  */
813
421
  async initialize() {
814
- const token = await this.storage.getItem(SESSION_STORAGE_KEY2);
815
- const userId = await this.storage.getItem(USER_ID_STORAGE_KEY2);
422
+ const token = await this.storage.getItem(SESSION_STORAGE_KEY);
423
+ const userId = await this.storage.getItem(USER_ID_STORAGE_KEY);
816
424
  if (token) this.sessionToken = token;
817
425
  if (userId) this.userId = userId;
818
- const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY2);
426
+ const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
819
427
  if (wsId) this.workspaceId = wsId;
820
428
  try {
821
429
  await this.ensureAnonymousId();
@@ -860,8 +468,8 @@ var ScaleMuleClient = class {
860
468
  async setSession(token, userId) {
861
469
  this.sessionToken = token;
862
470
  this.userId = userId;
863
- await this.storage.setItem(SESSION_STORAGE_KEY2, token);
864
- await this.storage.setItem(USER_ID_STORAGE_KEY2, userId);
471
+ await this.storage.setItem(SESSION_STORAGE_KEY, token);
472
+ await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
865
473
  if (this.debug) {
866
474
  console.log("[ScaleMule] Session set for user:", userId);
867
475
  }
@@ -891,9 +499,9 @@ var ScaleMuleClient = class {
891
499
  this.sessionToken = null;
892
500
  this.userId = null;
893
501
  this.workspaceId = null;
894
- await this.storage.removeItem(SESSION_STORAGE_KEY2);
895
- await this.storage.removeItem(USER_ID_STORAGE_KEY2);
896
- await this.storage.removeItem(WORKSPACE_STORAGE_KEY2);
502
+ await this.storage.removeItem(SESSION_STORAGE_KEY);
503
+ await this.storage.removeItem(USER_ID_STORAGE_KEY);
504
+ await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
897
505
  if (this.debug) {
898
506
  console.log("[ScaleMule] Session cleared");
899
507
  }