@scalemule/sdk 0.0.22 → 0.0.24

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
@@ -326,6 +326,7 @@ __export(index_exports, {
326
326
  PhotoService: () => PhotoService,
327
327
  QueueService: () => QueueService,
328
328
  RealtimeService: () => RealtimeService,
329
+ ReferralsService: () => ReferralsService,
329
330
  ScaleMule: () => ScaleMule,
330
331
  ScaleMuleClient: () => ScaleMuleClient,
331
332
  SchedulerService: () => SchedulerService,
@@ -337,6 +338,8 @@ __export(index_exports, {
337
338
  UploadResumeStore: () => UploadResumeStore,
338
339
  UploadTelemetry: () => UploadTelemetry,
339
340
  VideoService: () => VideoService,
341
+ WEB_PUSH_SERVICE_WORKER: () => WEB_PUSH_SERVICE_WORKER,
342
+ WebPushManager: () => WebPushManager,
340
343
  WebhooksService: () => WebhooksService,
341
344
  WorkspacesService: () => WorkspacesService,
342
345
  buildClientContextHeaders: () => buildClientContextHeaders,
@@ -4066,6 +4069,44 @@ var SocialService = class extends ServiceModule {
4066
4069
  }
4067
4070
  };
4068
4071
 
4072
+ // src/services/referrals.ts
4073
+ var ReferralsService = class extends ServiceModule {
4074
+ constructor() {
4075
+ super(...arguments);
4076
+ this.basePath = "/v1/referrals";
4077
+ }
4078
+ /**
4079
+ * Get current user's referral code, share link, campaign, and stats.
4080
+ * Requires member auth.
4081
+ */
4082
+ async getMyReferral(options) {
4083
+ return this._get("/me", options);
4084
+ }
4085
+ /**
4086
+ * Generate a tracked share link. The `channel` param records where
4087
+ * the share was initiated (e.g., 'whatsapp', 'email', 'copy').
4088
+ * Requires member auth.
4089
+ */
4090
+ async createShareLink(channel, options) {
4091
+ return this.post("/links", channel ? { channel } : void 0, options);
4092
+ }
4093
+ /**
4094
+ * Get referral analytics for the current user over the last N days.
4095
+ * Requires member auth.
4096
+ */
4097
+ async getMyAnalytics(days, options) {
4098
+ const query = days ? `?days=${days}` : "";
4099
+ return this._get(`/me/analytics${query}`, options);
4100
+ }
4101
+ /**
4102
+ * Resolve a referral code to its campaign info.
4103
+ * Public endpoint — no member auth required, only API key.
4104
+ */
4105
+ async resolveCode(code, options) {
4106
+ return this._get(`/public?rc=${encodeURIComponent(code)}`, options);
4107
+ }
4108
+ };
4109
+
4069
4110
  // src/services/billing.ts
4070
4111
  var BillingService = class extends ServiceModule {
4071
4112
  constructor() {
@@ -4450,17 +4491,68 @@ var CommunicationService = class extends ServiceModule {
4450
4491
  return this.post(`/sms/templates/${template}/send`, data, options);
4451
4492
  }
4452
4493
  // --------------------------------------------------------------------------
4453
- // Push Notifications
4494
+ // Push Notifications — Send
4454
4495
  // --------------------------------------------------------------------------
4455
4496
  async sendPush(data, options) {
4456
4497
  return this.post("/push/send", data, options);
4457
4498
  }
4499
+ // --------------------------------------------------------------------------
4500
+ // Push Notifications — Token Management
4501
+ // --------------------------------------------------------------------------
4458
4502
  async registerPushToken(data, options) {
4459
4503
  return this.post("/push/register", data, options);
4460
4504
  }
4505
+ /** @deprecated Use unregisterPushTokenById() for web push tokens */
4461
4506
  async unregisterPushToken(token, options) {
4462
4507
  return this.del(`/push/tokens/${token}`, options);
4463
4508
  }
4509
+ async unregisterPushTokenById(id, options) {
4510
+ const result = await this.del(`/push/tokens/by-id/${id}`, options);
4511
+ if (result.data && typeof result.data === "object" && !("id" in result.data)) {
4512
+ return { data: void 0, error: null };
4513
+ }
4514
+ return result;
4515
+ }
4516
+ async associatePushTokenUserById(id, options) {
4517
+ return this.put(`/push/tokens/by-id/${id}/user`, {}, options);
4518
+ }
4519
+ async disassociatePushTokenUser(id, options) {
4520
+ const result = await this.del(`/push/tokens/by-id/${id}/user`, options);
4521
+ if (result.data && typeof result.data === "object" && !("id" in result.data)) {
4522
+ return { data: void 0, error: null };
4523
+ }
4524
+ return result;
4525
+ }
4526
+ // --------------------------------------------------------------------------
4527
+ // Push Notifications — Settings
4528
+ // --------------------------------------------------------------------------
4529
+ async getMyPushSettings(options) {
4530
+ return this._get("/push/settings/me", options);
4531
+ }
4532
+ // --------------------------------------------------------------------------
4533
+ // Push Notifications — Topics & Subscriptions
4534
+ // --------------------------------------------------------------------------
4535
+ async listTopics(options) {
4536
+ return this._get("/push/topics", options);
4537
+ }
4538
+ async subscribeTopic(topicId, data, options) {
4539
+ return this.post(`/push/topics/${topicId}/subscribe`, data || {}, options);
4540
+ }
4541
+ async unsubscribeTopic(topicId, options) {
4542
+ return this.del(`/push/topics/${topicId}/subscribe`, options);
4543
+ }
4544
+ async listSubscriptions(options) {
4545
+ return this._get("/push/subscriptions", options);
4546
+ }
4547
+ // --------------------------------------------------------------------------
4548
+ // Push Notifications — Preferences
4549
+ // --------------------------------------------------------------------------
4550
+ async getPushPreferences(options) {
4551
+ return this._get("/push/preferences", options);
4552
+ }
4553
+ async updatePushPreferences(data, options) {
4554
+ return this.put("/push/preferences", data, options);
4555
+ }
4464
4556
  // --------------------------------------------------------------------------
4465
4557
  // Message Status
4466
4558
  // --------------------------------------------------------------------------
@@ -4480,6 +4572,258 @@ var CommunicationService = class extends ServiceModule {
4480
4572
  }
4481
4573
  };
4482
4574
 
4575
+ // src/web-push.ts
4576
+ var STORAGE_KEY = "scalemule_push_state";
4577
+ var WebPushManager = class {
4578
+ constructor(options) {
4579
+ this.state = null;
4580
+ this.registration = null;
4581
+ if (typeof window === "undefined") {
4582
+ throw new Error("WebPushManager can only be used in a browser environment");
4583
+ }
4584
+ this.fetcher = options.fetcher;
4585
+ this.swUrl = options.serviceWorkerUrl || "/sw.js";
4586
+ try {
4587
+ const stored = localStorage.getItem(STORAGE_KEY);
4588
+ if (stored) {
4589
+ this.state = JSON.parse(stored);
4590
+ }
4591
+ } catch {
4592
+ }
4593
+ }
4594
+ /** Whether the browser supports Web Push */
4595
+ isSupported() {
4596
+ return typeof window !== "undefined" && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
4597
+ }
4598
+ /** Current notification permission state */
4599
+ getPermissionState() {
4600
+ if (!this.isSupported()) return "unsupported";
4601
+ return Notification.permission;
4602
+ }
4603
+ /** Request notification permission from the user */
4604
+ async requestPermission() {
4605
+ if (!this.isSupported()) return "denied";
4606
+ return Notification.requestPermission();
4607
+ }
4608
+ /**
4609
+ * Full subscribe flow:
4610
+ * 1. Check browser support
4611
+ * 2. Request notification permission
4612
+ * 3. Register service worker
4613
+ * 4. Fetch VAPID public key from backend
4614
+ * 5. PushManager.subscribe() with VAPID key
4615
+ * 6. Register token with backend
4616
+ *
4617
+ * @param deviceId Optional device identifier for anonymous users.
4618
+ * If not provided, generates a random UUID stored in localStorage.
4619
+ */
4620
+ async subscribe(deviceId) {
4621
+ if (!this.isSupported()) return null;
4622
+ const permission = await this.requestPermission();
4623
+ if (permission !== "granted") return null;
4624
+ this.registration = await navigator.serviceWorker.register(this.swUrl);
4625
+ await navigator.serviceWorker.ready;
4626
+ const settings = await this.fetcher.getSettings();
4627
+ if (!settings.webpush_enabled || !settings.vapid_public_key) {
4628
+ throw new Error("Web Push is not enabled for this application");
4629
+ }
4630
+ const applicationServerKey = urlBase64ToUint8Array(settings.vapid_public_key);
4631
+ const pushSubscription = await this.registration.pushManager.subscribe({
4632
+ userVisibleOnly: true,
4633
+ applicationServerKey: applicationServerKey.buffer
4634
+ });
4635
+ const endpoint = pushSubscription.endpoint;
4636
+ const p256dh = arrayBufferToBase64url(pushSubscription.getKey("p256dh"));
4637
+ const auth = arrayBufferToBase64url(pushSubscription.getKey("auth"));
4638
+ const subscription = {
4639
+ endpoint,
4640
+ keys: { p256dh, auth }
4641
+ };
4642
+ const resolvedDeviceId = deviceId || this.state?.deviceId || generateDeviceId();
4643
+ const result = await this.fetcher.registerToken({
4644
+ token: endpoint,
4645
+ platform: "web",
4646
+ device_id: resolvedDeviceId,
4647
+ subscription
4648
+ });
4649
+ this.state = {
4650
+ endpoint,
4651
+ tokenId: result.id,
4652
+ deviceId: resolvedDeviceId
4653
+ };
4654
+ this.persistState();
4655
+ return { tokenId: result.id, endpoint };
4656
+ }
4657
+ /** Unsubscribe from browser push and deregister token */
4658
+ async unsubscribe() {
4659
+ const sub = await this.getSubscription();
4660
+ if (sub) {
4661
+ await sub.unsubscribe();
4662
+ }
4663
+ if (this.state?.tokenId) {
4664
+ try {
4665
+ await this.fetcher.unregisterToken(this.state.tokenId);
4666
+ } catch {
4667
+ }
4668
+ }
4669
+ this.state = null;
4670
+ this.clearState();
4671
+ }
4672
+ /** Link push token to the currently authenticated user (call after login) */
4673
+ async associateUser() {
4674
+ if (!this.state?.tokenId) return;
4675
+ await this.fetcher.associateUser(this.state.tokenId);
4676
+ }
4677
+ /** Clear user association from push token (call before logout) */
4678
+ async disassociateUser() {
4679
+ if (!this.state?.tokenId) return;
4680
+ await this.fetcher.disassociateUser(this.state.tokenId);
4681
+ }
4682
+ /** Check if currently subscribed to push notifications */
4683
+ async isSubscribed() {
4684
+ if (!this.isSupported()) return false;
4685
+ const sub = await this.getSubscription();
4686
+ return sub !== null && this.state !== null;
4687
+ }
4688
+ /** Get the active PushSubscription from the service worker */
4689
+ async getSubscription() {
4690
+ if (!this.isSupported()) return null;
4691
+ try {
4692
+ const reg = await navigator.serviceWorker.getRegistration(this.swUrl);
4693
+ if (!reg) return null;
4694
+ return reg.pushManager.getSubscription();
4695
+ } catch {
4696
+ return null;
4697
+ }
4698
+ }
4699
+ /** Get the stored token ID (for external use) */
4700
+ getTokenId() {
4701
+ return this.state?.tokenId || null;
4702
+ }
4703
+ persistState() {
4704
+ if (this.state) {
4705
+ try {
4706
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this.state));
4707
+ } catch {
4708
+ }
4709
+ }
4710
+ }
4711
+ clearState() {
4712
+ try {
4713
+ localStorage.removeItem(STORAGE_KEY);
4714
+ } catch {
4715
+ }
4716
+ }
4717
+ };
4718
+ function urlBase64ToUint8Array(base64String) {
4719
+ const padding = "=".repeat((4 - base64String.length % 4) % 4);
4720
+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
4721
+ const rawData = atob(base64);
4722
+ const outputArray = new Uint8Array(rawData.length);
4723
+ for (let i = 0; i < rawData.length; ++i) {
4724
+ outputArray[i] = rawData.charCodeAt(i);
4725
+ }
4726
+ return outputArray;
4727
+ }
4728
+ function arrayBufferToBase64url(buffer) {
4729
+ const bytes = new Uint8Array(buffer);
4730
+ const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join("");
4731
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4732
+ }
4733
+ function generateDeviceId() {
4734
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
4735
+ return crypto.randomUUID();
4736
+ }
4737
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
4738
+ const r = Math.random() * 16 | 0;
4739
+ const v = c === "x" ? r : r & 3 | 8;
4740
+ return v.toString(16);
4741
+ });
4742
+ }
4743
+
4744
+ // src/web-push-sw.ts
4745
+ var WEB_PUSH_SERVICE_WORKER = `
4746
+ // ScaleMule Push Notification Service Worker
4747
+
4748
+ self.addEventListener('push', function(event) {
4749
+ if (!event.data) return;
4750
+
4751
+ var data;
4752
+ try {
4753
+ data = event.data.json();
4754
+ } catch (e) {
4755
+ data = { title: 'New Notification', body: event.data.text() };
4756
+ }
4757
+
4758
+ var title = data.title || 'Notification';
4759
+ var options = {
4760
+ body: data.body || '',
4761
+ icon: data.icon || undefined,
4762
+ image: data.image || undefined,
4763
+ badge: data.badge || undefined,
4764
+ data: data.data || data,
4765
+ tag: data.tag || undefined,
4766
+ actions: data.actions || undefined,
4767
+ requireInteraction: data.requireInteraction || false,
4768
+ };
4769
+
4770
+ // Show the notification
4771
+ event.waitUntil(
4772
+ self.registration.showNotification(title, options)
4773
+ .then(function() {
4774
+ // Post message to all client pages for foreground handling
4775
+ return self.clients.matchAll({ type: 'window', includeUncontrolled: true });
4776
+ })
4777
+ .then(function(clients) {
4778
+ clients.forEach(function(client) {
4779
+ client.postMessage({
4780
+ type: 'push-received',
4781
+ payload: data,
4782
+ });
4783
+ });
4784
+ })
4785
+ );
4786
+ });
4787
+
4788
+ self.addEventListener('notificationclick', function(event) {
4789
+ event.notification.close();
4790
+
4791
+ var url = '/';
4792
+ if (event.notification.data && event.notification.data.url) {
4793
+ url = event.notification.data.url;
4794
+ }
4795
+
4796
+ // Handle action button clicks
4797
+ if (event.action && event.notification.data && event.notification.data.actions) {
4798
+ var action = event.notification.data.actions.find(function(a) {
4799
+ return a.action === event.action;
4800
+ });
4801
+ if (action && action.url) {
4802
+ url = action.url;
4803
+ }
4804
+ }
4805
+
4806
+ event.waitUntil(
4807
+ self.clients.matchAll({ type: 'window', includeUncontrolled: true })
4808
+ .then(function(clientList) {
4809
+ // Try to focus an existing window
4810
+ for (var i = 0; i < clientList.length; i++) {
4811
+ var client = clientList[i];
4812
+ if (client.url.indexOf(self.registration.scope) !== -1 && 'focus' in client) {
4813
+ client.focus();
4814
+ client.navigate(url);
4815
+ return;
4816
+ }
4817
+ }
4818
+ // Open a new window if none exists
4819
+ if (self.clients.openWindow) {
4820
+ return self.clients.openWindow(url);
4821
+ }
4822
+ })
4823
+ );
4824
+ });
4825
+ `;
4826
+
4483
4827
  // src/services/scheduler.ts
4484
4828
  var SchedulerService = class extends ServiceModule {
4485
4829
  constructor() {
@@ -5915,6 +6259,7 @@ var ScaleMule = class {
5915
6259
  this.data = new DataService(this._client);
5916
6260
  this.chat = new ChatService(this._client);
5917
6261
  this.social = new SocialService(this._client);
6262
+ this.referrals = new ReferralsService(this._client);
5918
6263
  this.billing = new BillingService(this._client);
5919
6264
  this.analytics = new AnalyticsService(this._client);
5920
6265
  this.flags = new FlagsService(this._client);
@@ -6069,6 +6414,7 @@ var index_default = ScaleMule;
6069
6414
  PhotoService,
6070
6415
  QueueService,
6071
6416
  RealtimeService,
6417
+ ReferralsService,
6072
6418
  ScaleMule,
6073
6419
  ScaleMuleClient,
6074
6420
  SchedulerService,
@@ -6080,6 +6426,8 @@ var index_default = ScaleMule;
6080
6426
  UploadResumeStore,
6081
6427
  UploadTelemetry,
6082
6428
  VideoService,
6429
+ WEB_PUSH_SERVICE_WORKER,
6430
+ WebPushManager,
6083
6431
  WebhooksService,
6084
6432
  WorkspacesService,
6085
6433
  buildClientContextHeaders,