@sagepilot-ai/react-native-sdk 0.3.6 → 0.4.1

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.mjs CHANGED
@@ -1,5 +1,21 @@
1
1
  // src/public/SdkClient.ts
2
- import { Platform } from "react-native";
2
+ import { AppState as AppState2, Platform } from "react-native";
3
+
4
+ // package.json
5
+ var name = "@sagepilot-ai/react-native-sdk";
6
+ var version = "0.4.1";
7
+
8
+ // src/core/config/constants.ts
9
+ var SDK_NAME = name;
10
+ var SDK_VERSION = version;
11
+ var DEFAULT_HOST = "https://app.sagepilot.ai";
12
+ var DEFAULT_WIDGET_HOST = "https://app.sagepilot.ai";
13
+ var CUSTOMER_API_PREFIX = "/customer-api/v1";
14
+ var DEFAULT_UNREAD_POLL_INTERVAL_MS = 3e4;
15
+ var DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX = "sg_chat_claims";
16
+
17
+ // src/push.ts
18
+ import { AppState } from "react-native";
3
19
 
4
20
  // src/core/errors/SagepilotChatError.ts
5
21
  var SagepilotChatError = class extends Error {
@@ -16,14 +32,335 @@ var SagepilotChatError = class extends Error {
16
32
  }
17
33
  };
18
34
 
19
- // src/core/config/constants.ts
20
- var SDK_NAME = "@sagepilot-ai/react-native-sdk";
21
- var SDK_VERSION = "0.3.6";
22
- var DEFAULT_HOST = "https://app.sagepilot.ai";
23
- var DEFAULT_WIDGET_HOST = "https://app.sagepilot.ai";
24
- var CUSTOMER_API_PREFIX = "/customer-api/v1";
25
- var DEFAULT_UNREAD_POLL_INTERVAL_MS = 3e4;
26
- var DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX = "sg_chat_claims";
35
+ // src/core/storage/cache.ts
36
+ function createAsyncStorageCacheStorage(asyncStorage) {
37
+ return {
38
+ getItem: (key) => asyncStorage.getItem(key),
39
+ setItem: (key, value) => asyncStorage.setItem(key, value),
40
+ removeItem: (key) => asyncStorage.removeItem(key)
41
+ };
42
+ }
43
+ function createJsonCache(storage, namespace, strict = false) {
44
+ return {
45
+ async get(key) {
46
+ const value = await storage.getItem(`${namespace}:${key}`);
47
+ if (!value) return null;
48
+ try {
49
+ return JSON.parse(value);
50
+ } catch (error) {
51
+ if (strict) throw error;
52
+ return null;
53
+ }
54
+ },
55
+ async set(key, value) {
56
+ await storage.setItem(`${namespace}:${key}`, JSON.stringify(value));
57
+ },
58
+ async remove(key) {
59
+ await storage.removeItem(`${namespace}:${key}`);
60
+ }
61
+ };
62
+ }
63
+
64
+ // src/push.ts
65
+ var INSTALLATION_ID = /^\S{1,255}$/;
66
+ var MAX_EVENTS = 200;
67
+ var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
68
+ function createId() {
69
+ return "10000000-1000-4000-8000-100000000000".replace(
70
+ /[018]/g,
71
+ (value) => (Number(value) ^ Math.floor(Math.random() * 16) >> Number(value) / 4).toString(16)
72
+ );
73
+ }
74
+ function eventKey(event) {
75
+ return JSON.stringify([event.message_id, event.endpoint_id, event.event_type, ["action", "conversion"].includes(event.event_type) ? event.action_id ?? "" : ""]);
76
+ }
77
+ var SagepilotPush = class {
78
+ /** Reuses a channel-specific durable cache and the SDK's authenticated request gateway. */
79
+ constructor(config, context) {
80
+ this.config = config;
81
+ this.context = context;
82
+ this.pending = Promise.resolve();
83
+ this.paused = false;
84
+ this.stopped = false;
85
+ this.started = false;
86
+ this.flushPromise = null;
87
+ this.retryTimer = null;
88
+ this.retryAttempt = 0;
89
+ this.subscriptions = [];
90
+ if (config.installationId !== void 0 && !INSTALLATION_ID.test(config.installationId)) {
91
+ throw new SagepilotChatError("invalid_config", "Push installationId must contain 1\u2013255 non-whitespace characters.");
92
+ }
93
+ this.cache = createJsonCache(config.storage, `sagepilot_push:${context.workspaceId}:${context.channelId}`, true);
94
+ }
95
+ /** Serializes state changes so registration, revocation and outbox writes cannot overwrite one another. */
96
+ mutate(operation) {
97
+ const next = this.pending.then(async () => {
98
+ if (this.stopped) throw new Error("Push has been stopped. Configure the SDK again.");
99
+ const saved = await this.cache.get("state");
100
+ if (this.stopped) throw new Error("Push has been stopped.");
101
+ if (saved && (!INSTALLATION_ID.test(saved.installationId) || !Array.isArray(saved.outbox) || !Array.isArray(saved.recent))) {
102
+ throw new Error("Invalid persisted push state; refusing to discard a possible device binding.");
103
+ }
104
+ if (saved && this.config.installationId && saved.installationId !== this.config.installationId) {
105
+ throw new Error("Reuse the persisted installationId; revoke and clear push storage before replacing it.");
106
+ }
107
+ const state = saved ?? { installationId: this.config.installationId || createId(), outbox: [], recent: [] };
108
+ if (!saved) await this.cache.set("state", state);
109
+ return operation(state);
110
+ });
111
+ this.pending = next.catch(() => void 0);
112
+ return next;
113
+ }
114
+ /** Starts optional native listeners without prompting for notification permission. */
115
+ async start() {
116
+ if (this.started) return;
117
+ this.started = true;
118
+ const binding = await this.mutate(async (state) => state.binding);
119
+ const adapter = this.config.adapter;
120
+ if (adapter) {
121
+ if (adapter.start) this.subscriptions.push(await adapter.start({
122
+ workspaceId: this.context.workspaceId,
123
+ channelId: this.context.channelId,
124
+ sdkVersion: SDK_VERSION,
125
+ owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
126
+ customerId: this.context.customerId,
127
+ upload: (event) => this.context.request("/push/events", "POST", event),
128
+ onOpen: (message) => this.config.onOpen?.(message)
129
+ }));
130
+ this.subscriptions.push(
131
+ adapter.onTokenRefresh((token) => {
132
+ void this.sync(token).catch(this.context.onError);
133
+ }),
134
+ adapter.onMessage((message) => {
135
+ void this.handleReceived(message, true).catch(this.context.onError);
136
+ }),
137
+ adapter.onOpened((message) => {
138
+ void this.handleOpened(message).catch(this.context.onError);
139
+ })
140
+ );
141
+ const initial = await adapter.getInitialNotification();
142
+ if (initial) await this.handleOpened(initial);
143
+ }
144
+ void this.sync().catch(this.context.onError);
145
+ void this.flush().catch(this.context.onError);
146
+ }
147
+ /** Requests native permission only following an explicit host action, then resynchronizes the token. */
148
+ async requestPermission() {
149
+ if (!this.config.adapter) throw new Error("Configure a push adapter to request native permission.");
150
+ const permission = await this.config.adapter.requestPermission();
151
+ await this.sync();
152
+ return permission;
153
+ }
154
+ /** Refreshes an existing authorized installation after identity, token or permission changes. */
155
+ async sync(token) {
156
+ if (this.paused || this.stopped || !this.context.customerId() || !this.config.adapter) return;
157
+ const adapter = this.config.adapter;
158
+ const permission = await adapter.getPermission();
159
+ if (permission !== "authorized" && permission !== "provisional") {
160
+ await this.unregister();
161
+ return;
162
+ }
163
+ await this.register({ token: token ?? await adapter.getToken(), provider: adapter.provider, permission, app_id: this.config.appId });
164
+ }
165
+ /** Registers a native token only for the current identified customer; the server verifies identity. */
166
+ async register(input) {
167
+ if (!input.token.trim() || !["authorized", "provisional"].includes(input.permission)) {
168
+ throw new SagepilotChatError("invalid_request", "Push registration requires a token and notification permission.");
169
+ }
170
+ return this.mutate(async (state) => {
171
+ const customerId = this.context.customerId();
172
+ if (this.paused || !customerId) throw new SagepilotChatError("forbidden", "Identify a verified customer before registering push.");
173
+ if (state.binding && state.binding.customerId !== customerId) {
174
+ throw new SagepilotChatError("forbidden", "Revoke the previous customer's push binding before switching accounts.");
175
+ }
176
+ const previousBinding = state.binding;
177
+ state.binding = { ...state.binding, customerId };
178
+ await this.cache.set("state", state);
179
+ let result;
180
+ try {
181
+ result = await this.context.request("/push/endpoints", "POST", {
182
+ token: input.token,
183
+ provider: input.provider,
184
+ permission: input.permission,
185
+ app_id: input.app_id ?? this.config.appId,
186
+ installation_id: state.installationId,
187
+ platform: this.context.platform,
188
+ metadata: {
189
+ sdk: SDK_NAME,
190
+ sdk_version: SDK_VERSION,
191
+ app_version: this.config.appVersion,
192
+ capabilities: input.capabilities ?? this.config.adapter?.capabilities ?? { version: 1, display_modes: ["provider"], media: [] }
193
+ }
194
+ });
195
+ } catch (error) {
196
+ if (!this.stopped && error instanceof SagepilotChatError && [400, 401, 403, 422].includes(error.status ?? 0)) {
197
+ state.binding = previousBinding;
198
+ await this.cache.set("state", state);
199
+ }
200
+ throw error;
201
+ }
202
+ if (!result.endpoint_id) throw new Error("Push registration returned no endpoint_id.");
203
+ if (this.stopped) return result;
204
+ state.binding = { customerId, endpointId: result.endpoint_id };
205
+ await this.cache.set("state", state);
206
+ await this.config.adapter?.setOwner?.({ customerId, endpointId: result.endpoint_id });
207
+ return result;
208
+ });
209
+ }
210
+ /** Revokes this installation before credentials are discarded; failures retain the binding for retry. */
211
+ async unregister() {
212
+ await this.mutate(async (state) => {
213
+ if (!state.binding) {
214
+ await this.config.adapter?.setOwner?.(null);
215
+ return;
216
+ }
217
+ await this.context.request("/push/endpoints", "DELETE", { installation_id: state.installationId });
218
+ if (this.stopped) return;
219
+ delete state.binding;
220
+ await this.cache.set("state", state);
221
+ await this.config.adapter?.setOwner?.(null);
222
+ });
223
+ }
224
+ /** Pauses refresh callbacks and revokes the installation before logout or identity replacement. */
225
+ async pauseAndRevoke() {
226
+ this.paused = true;
227
+ await this.unregister();
228
+ }
229
+ /** Allows token refresh again after the identity transition has finished. */
230
+ resume() {
231
+ this.paused = false;
232
+ void this.sync().catch(this.context.onError);
233
+ void this.flush().catch(this.context.onError);
234
+ }
235
+ /** Reads notification preferences for the current verified customer. */
236
+ getPreferences() {
237
+ return this.context.request("/push/preferences", "GET");
238
+ }
239
+ /** Saves customer consent independently of the device's notification permission. */
240
+ setPreferences(preferences) {
241
+ return this.context.request("/push/preferences", "PUT", preferences);
242
+ }
243
+ /** Persists actual callback receipt and presents only foreground messages when the host opted in. */
244
+ async handleReceived(message, foreground = false) {
245
+ const recorded = await this.track("received", message);
246
+ if (recorded && foreground && this.config.presentForeground) {
247
+ if (await this.track("presentation_requested", message)) {
248
+ try {
249
+ await this.config.presentForeground(message);
250
+ } catch (error) {
251
+ await this.track("presentation_failed", message);
252
+ throw error;
253
+ }
254
+ }
255
+ }
256
+ return recorded;
257
+ }
258
+ /** Persists a real tap before invoking host navigation, including cold-start taps. */
259
+ async handleOpened(message) {
260
+ const recorded = await this.track("opened", message);
261
+ if (recorded && !this.config.adapter?.track) this.config.onOpen?.(message);
262
+ return recorded;
263
+ }
264
+ /** Records SDK engagement; reuse actionId for duplicate callbacks and distinct IDs for separate conversions. */
265
+ async track(type, message, metadata = {}, actionId) {
266
+ if (this.config.adapter?.track) return this.config.adapter.track(type, message, metadata, actionId);
267
+ const data = message.data;
268
+ if (this.context.brand && data?.sp_channel_id !== this.context.channelId) return false;
269
+ if (data?.sp_source_channel_id && data.sp_source_channel_id !== this.context.channelId) return false;
270
+ if (!data || data.sp_workspace_id !== this.context.workspaceId || !data.sp_message_id || !data.sp_endpoint_id || !data.sp_event_token) return false;
271
+ const event = {
272
+ event_id: createId(),
273
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
274
+ sdk_version: SDK_VERSION,
275
+ event_type: type,
276
+ message_id: data.sp_message_id,
277
+ endpoint_id: data.sp_endpoint_id,
278
+ event_token: data.sp_event_token,
279
+ ...actionId ? { action_id: actionId } : {},
280
+ metadata: {
281
+ platform: this.context.platform,
282
+ app_id: this.config.appId,
283
+ app_version: this.config.appVersion,
284
+ app_state: AppState.currentState ?? "unknown",
285
+ ...metadata,
286
+ sdk: SDK_NAME,
287
+ sdk_version: SDK_VERSION
288
+ }
289
+ };
290
+ const recorded = await this.mutate(async (state) => {
291
+ const key = eventKey(event);
292
+ if (state.recent.includes(key) || state.outbox.some((item) => eventKey(item) === key)) return false;
293
+ if (state.outbox.length >= MAX_EVENTS) throw new Error("Push analytics outbox is full; retry after connectivity is restored.");
294
+ state.outbox.push(event);
295
+ await this.cache.set("state", state);
296
+ return true;
297
+ });
298
+ if (recorded) void this.flush().catch(this.context.onError);
299
+ return recorded;
300
+ }
301
+ /** Uploads preserved event metadata with the current request version and bounded exponential retries. */
302
+ async flush() {
303
+ if (this.stopped) return;
304
+ if (this.config.adapter?.flush) await this.config.adapter.flush();
305
+ if (this.flushPromise) return this.flushPromise;
306
+ this.flushPromise = (async () => {
307
+ while (!this.stopped) {
308
+ const event = await this.mutate(async (state) => state.outbox[0]);
309
+ if (!event) break;
310
+ if (Date.now() - Date.parse(event.occurred_at) > MAX_AGE_MS) {
311
+ this.context.onError(new Error(`Push event ${event.event_id} expired before upload.`));
312
+ } else {
313
+ try {
314
+ await this.context.request("/push/events", "POST", event);
315
+ } catch (error) {
316
+ const status = error instanceof SagepilotChatError ? error.status : void 0;
317
+ const terminalTokenError = status === 401 && error instanceof SagepilotChatError && error.details?.terminal === true;
318
+ if (!terminalTokenError && ![400, 403, 404, 410, 422].includes(status ?? 0)) throw error;
319
+ this.context.onError(error);
320
+ }
321
+ }
322
+ if (this.stopped) return;
323
+ await this.mutate(async (state) => {
324
+ state.outbox = state.outbox.filter((queued) => queued.event_id !== event.event_id);
325
+ state.recent = [...state.recent, eventKey(event)].slice(-MAX_EVENTS);
326
+ await this.cache.set("state", state);
327
+ });
328
+ }
329
+ this.retryAttempt = 0;
330
+ })().catch((error) => {
331
+ if (!this.stopped && !this.retryTimer) {
332
+ this.retryTimer = setTimeout(() => {
333
+ this.retryTimer = null;
334
+ void this.flush().catch(this.context.onError);
335
+ }, Math.min(6e4, 1e3 * 2 ** Math.min(this.retryAttempt++, 6)));
336
+ }
337
+ throw error;
338
+ }).finally(() => {
339
+ this.flushPromise = null;
340
+ });
341
+ return this.flushPromise;
342
+ }
343
+ /** Removes listeners and timers without revoking an installation merely because its UI was destroyed. */
344
+ stop() {
345
+ this.stopped = true;
346
+ this.subscriptions.forEach((unsubscribe) => unsubscribe());
347
+ this.subscriptions = [];
348
+ if (this.retryTimer) clearTimeout(this.retryTimer);
349
+ this.retryTimer = null;
350
+ }
351
+ };
352
+ function createFirebasePushAdapter(firebase, permissions) {
353
+ return {
354
+ provider: "fcm",
355
+ getToken: () => firebase.getToken(),
356
+ getPermission: () => permissions.getPermission(),
357
+ requestPermission: () => permissions.requestPermission(),
358
+ onTokenRefresh: (callback) => firebase.onTokenRefresh(callback),
359
+ onMessage: (callback) => firebase.onMessage(callback),
360
+ onOpened: (callback) => firebase.onNotificationOpenedApp(callback),
361
+ getInitialNotification: () => firebase.getInitialNotification()
362
+ };
363
+ }
27
364
 
28
365
  // src/core/auth/sessionManager.ts
29
366
  var SagepilotSessionManager = class {
@@ -48,7 +385,7 @@ var SagepilotSessionManager = class {
48
385
  return this.currentSession;
49
386
  }
50
387
  async setSession(session) {
51
- this.currentSession = {
388
+ const nextSession = {
52
389
  session_id: session.session_id,
53
390
  session_token: session.session_token,
54
391
  customer_id: session.customer_id ?? null,
@@ -56,7 +393,8 @@ var SagepilotSessionManager = class {
56
393
  authenticated: session.authenticated ?? false,
57
394
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
58
395
  };
59
- await this.tokenManager.setSession(this.currentSession);
396
+ await this.tokenManager.setSession(nextSession);
397
+ this.currentSession = nextSession;
60
398
  return this.currentSession;
61
399
  }
62
400
  async updateSession(updates) {
@@ -173,8 +511,8 @@ var SagepilotTokenManager = class {
173
511
  function normalizeHost(host = DEFAULT_HOST) {
174
512
  return host.replace(/\/+$/, "");
175
513
  }
176
- function readRuntimeEnv(name) {
177
- return globalThis.process?.env?.[name]?.trim();
514
+ function readRuntimeEnv(name2) {
515
+ return globalThis.process?.env?.[name2]?.trim();
178
516
  }
179
517
  function resolveSagepilotHost(configuredHost) {
180
518
  const envHost = readRuntimeEnv("EXPO_PUBLIC_SAGEPILOT_HOST") || readRuntimeEnv("SAGEPILOT_HOST") || readRuntimeEnv("EXPO_PUBLIC_SAGEPILOT_CUSTOMER_API_BASE_URL") || readRuntimeEnv("SAGEPILOT_CUSTOMER_API_BASE_URL");
@@ -277,6 +615,9 @@ var SagepilotHttpClient = class {
277
615
  this.retryPolicy = resolveRetryPolicy(options.retryPolicy);
278
616
  }
279
617
  async request(url, init) {
618
+ const headers = mergeHeaders(this.baseHeaders, init.headers);
619
+ headers.set("X-Sagepilot-Sdk-Name", SDK_NAME);
620
+ headers.set("X-Sagepilot-Sdk-Version", SDK_VERSION);
280
621
  const policy = resolveRetryPolicy(init.retryPolicy ?? this.retryPolicy);
281
622
  const method = (init.method ?? "GET").toUpperCase();
282
623
  const canRetry = RETRYABLE_METHODS.has(method);
@@ -286,7 +627,7 @@ var SagepilotHttpClient = class {
286
627
  try {
287
628
  response = await this.fetchImpl(url, {
288
629
  ...init,
289
- headers: mergeHeaders(this.baseHeaders, init.headers)
630
+ headers
290
631
  });
291
632
  } catch (error) {
292
633
  lastNetworkError = error;
@@ -327,34 +668,6 @@ async function resolveDeviceInfo(adapter) {
327
668
  return adapter.getDeviceInfo();
328
669
  }
329
670
 
330
- // src/core/storage/cache.ts
331
- function createAsyncStorageCacheStorage(asyncStorage) {
332
- return {
333
- getItem: (key) => asyncStorage.getItem(key),
334
- setItem: (key, value) => asyncStorage.setItem(key, value),
335
- removeItem: (key) => asyncStorage.removeItem(key)
336
- };
337
- }
338
- function createJsonCache(storage, namespace) {
339
- return {
340
- async get(key) {
341
- const value = await storage.getItem(`${namespace}:${key}`);
342
- if (!value) return null;
343
- try {
344
- return JSON.parse(value);
345
- } catch {
346
- return null;
347
- }
348
- },
349
- async set(key, value) {
350
- await storage.setItem(`${namespace}:${key}`, JSON.stringify(value));
351
- },
352
- async remove(key) {
353
- await storage.removeItem(`${namespace}:${key}`);
354
- }
355
- };
356
- }
357
-
358
671
  // src/resources/channels.ts
359
672
  function bootstrapChannel(http, host, channelId) {
360
673
  return http.request(
@@ -378,9 +691,9 @@ function createSession(http, host, channelId, input) {
378
691
  anonymous_id: input.anonymousId,
379
692
  metadata: {
380
693
  platform: "react_native",
694
+ ...input.metadata,
381
695
  sdk: SDK_NAME,
382
- sdk_version: SDK_VERSION,
383
- ...input.metadata
696
+ sdk_version: SDK_VERSION
384
697
  }
385
698
  }),
386
699
  errorMessage: `${SDK_NAME} Failed to create customer session.`
@@ -527,6 +840,9 @@ function toPublicSessionState(session) {
527
840
  var SagepilotReactNativeChat = class {
528
841
  constructor() {
529
842
  this.sdkName = SDK_NAME;
843
+ this.pushClient = null;
844
+ this.pushChannelId = null;
845
+ this.pushAppStateSubscription = null;
530
846
  this.runtimeOptions = null;
531
847
  this.http = null;
532
848
  this.sessionManager = null;
@@ -556,6 +872,11 @@ var SagepilotReactNativeChat = class {
556
872
  this.dismissCallbacks = /* @__PURE__ */ new Set();
557
873
  this.errorCallbacks = /* @__PURE__ */ new Set();
558
874
  }
875
+ /** Returns the configured push lifecycle and analytics API. */
876
+ get push() {
877
+ if (!this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push with durable storage before using the push API.");
878
+ return this.pushClient;
879
+ }
559
880
  async configure(config) {
560
881
  if (this.isConfigured) {
561
882
  throw new SagepilotChatError(
@@ -607,7 +928,38 @@ var SagepilotReactNativeChat = class {
607
928
  const session = await this.resolveCustomerSession(config);
608
929
  this.channel = channel;
609
930
  this.session = session;
931
+ if (config.push) this.legacyWidgetJwt = session.legacy_jwt ?? null;
610
932
  this.isConfigured = true;
933
+ if (config.push) {
934
+ if (Platform.OS !== "ios" && Platform.OS !== "android") {
935
+ throw new SagepilotChatError("invalid_config", "Push is supported on Android and iOS.");
936
+ }
937
+ this.pushChannelId = config.push.channelId ?? null;
938
+ this.pushClient = new SagepilotPush(config.push, {
939
+ workspaceId,
940
+ channelId: this.pushChannelId ?? channelId,
941
+ platform: Platform.OS,
942
+ brand: Boolean(this.pushChannelId),
943
+ customerId: () => this.session?.authenticated ? this.session.customer_id ?? null : null,
944
+ request: (path, method, body) => this.requireHttp().request(
945
+ `${this.apiHost}${CUSTOMER_API_PREFIX}${path}`,
946
+ {
947
+ method,
948
+ headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
949
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
950
+ errorMessage: `${SDK_NAME} Push request failed.`
951
+ }
952
+ ),
953
+ onError: (error) => this.emitError(error)
954
+ });
955
+ await this.pushClient.start();
956
+ this.pushAppStateSubscription = AppState2.addEventListener("change", (state) => {
957
+ if (state === "active") {
958
+ void this.pushClient?.sync().catch((error) => this.emitError(error));
959
+ void this.pushClient?.flush().catch((error) => this.emitError(error));
960
+ }
961
+ });
962
+ }
611
963
  await this.restorePresentationFromCache();
612
964
  this.emitReady();
613
965
  this.emitState();
@@ -639,9 +991,11 @@ var SagepilotReactNativeChat = class {
639
991
  async identify(identity) {
640
992
  const session = this.requireSession();
641
993
  const apiIdentity = normalizeIdentity(identity);
994
+ if (this.pushClient && this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
642
995
  this.identifyPending = true;
643
996
  this.emitState();
644
997
  try {
998
+ if (this.pushClient) await this.pushClient.pauseAndRevoke();
645
999
  const result = await identifySession(
646
1000
  this.requireHttp(),
647
1001
  this.apiHost,
@@ -677,16 +1031,58 @@ var SagepilotReactNativeChat = class {
677
1031
  this.lastIdentifyResult = publicResult;
678
1032
  this.identifyCallbacks.forEach((callback) => callback(publicResult));
679
1033
  this.emitState();
1034
+ this.pushClient?.resume();
680
1035
  return publicResult;
681
1036
  } catch (error) {
682
1037
  this.identifyPending = false;
1038
+ this.pushClient?.resume();
683
1039
  this.emitState();
684
1040
  this.emitError(error);
685
1041
  throw error;
686
1042
  }
687
1043
  }
1044
+ /** Adds verified brand permission to the existing session; the host never manages another stored token. */
1045
+ async authorizePush(identityToken) {
1046
+ if (typeof identityToken !== "string" || !identityToken.trim()) {
1047
+ throw new SagepilotChatError("invalid_request", "A signed brand identity proof is required.");
1048
+ }
1049
+ const session = this.requireSession();
1050
+ if (!this.pushChannelId || !this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push.channelId first.");
1051
+ if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
1052
+ this.identifyPending = true;
1053
+ try {
1054
+ const result = await this.requireHttp().request(
1055
+ `${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`,
1056
+ {
1057
+ method: "POST",
1058
+ headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
1059
+ body: JSON.stringify({ channel_id: this.pushChannelId, identity_token: identityToken }),
1060
+ errorMessage: "Brand authorization failed."
1061
+ }
1062
+ );
1063
+ if (result.session_id !== session.session_id || result.customer_id !== session.customer_id || result.channel_id !== this.pushChannelId || result.workspace_id !== this.workspaceId || !result.session_token || !result.authenticated || this.session !== session) {
1064
+ throw new SagepilotChatError("forbidden", "Brand session scope changed.");
1065
+ }
1066
+ this.session = await this.requireSessionManager().setSession({ ...session, session_token: result.session_token });
1067
+ this.legacyWidgetJwt = result.legacy_jwt ?? this.legacyWidgetJwt;
1068
+ this.pushClient.resume();
1069
+ } finally {
1070
+ this.identifyPending = false;
1071
+ }
1072
+ }
688
1073
  async logout() {
689
1074
  const session = this.requireSession();
1075
+ if (this.pushClient) {
1076
+ if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
1077
+ this.identifyPending = true;
1078
+ try {
1079
+ await this.pushClient.pauseAndRevoke();
1080
+ } catch (error) {
1081
+ this.identifyPending = false;
1082
+ this.emitState();
1083
+ throw error;
1084
+ }
1085
+ }
690
1086
  const wasUnreadPolling = this.unreadPollTimer !== null;
691
1087
  let result = null;
692
1088
  let logoutError = null;
@@ -726,6 +1122,7 @@ var SagepilotReactNativeChat = class {
726
1122
  throw error;
727
1123
  }
728
1124
  this.session = freshSession;
1125
+ this.pushClient?.resume();
729
1126
  this.setUnreadCount(0);
730
1127
  this.emitState();
731
1128
  this.persistPresentationState();
@@ -934,6 +1331,8 @@ var SagepilotReactNativeChat = class {
934
1331
  const path = this.hostedChatView.screen === "home" ? `/chat-widget/${encodeURIComponent(this.channelId)}` : `/chat-widget/${encodeURIComponent(this.channelId)}/conversations`;
935
1332
  const url = new URL(`${this.widgetHost}${path}`);
936
1333
  url.searchParams.set("sdk", "react-native");
1334
+ url.searchParams.set("sdk_name", SDK_NAME);
1335
+ url.searchParams.set("sdk_version", SDK_VERSION);
937
1336
  if (this.runtimeOptions?.presentation?.mobile ?? true) {
938
1337
  url.searchParams.set("mobile", "1");
939
1338
  }
@@ -1055,6 +1454,10 @@ var SagepilotReactNativeChat = class {
1055
1454
  }
1056
1455
  return true;
1057
1456
  }
1457
+ if (message.type === "sagepilot:session_updated") {
1458
+ if (this.pushClient) void this.acceptHostedSession(message).catch((error) => this.emitError(error));
1459
+ return true;
1460
+ }
1058
1461
  if (message.type === "sagepilot:conversation_created") {
1059
1462
  this.handleConversationCreated(message);
1060
1463
  return true;
@@ -1065,6 +1468,54 @@ var SagepilotReactNativeChat = class {
1065
1468
  }
1066
1469
  return true;
1067
1470
  }
1471
+ /** Verifies an OTP-issued token with the Customer API before accepting a hosted identity change. */
1472
+ async acceptHostedSession(message) {
1473
+ const session = this.requireSession();
1474
+ const sessionToken = readStringField(message, "session_token");
1475
+ if (!sessionToken || readStringField(message, "session_id") !== session.session_id) return;
1476
+ if (message.workspace_id && message.workspace_id !== this.workspaceId) return;
1477
+ if (message.channel_id && message.channel_id !== this.channelId) return;
1478
+ if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
1479
+ this.identifyPending = true;
1480
+ this.emitState();
1481
+ try {
1482
+ const verified = await getSession(
1483
+ this.requireHttp(),
1484
+ this.apiHost,
1485
+ session.session_id,
1486
+ this.requireSessionManager().getAuthorizationHeader(sessionToken)
1487
+ );
1488
+ if (verified.session_id !== session.session_id || verified.channel_id && verified.channel_id !== this.channelId || !verified.authenticated) {
1489
+ throw new SagepilotChatError("forbidden", "Hosted token does not identify this customer session.");
1490
+ }
1491
+ if (this.session?.session_id !== session.session_id || this.session.session_token !== session.session_token) return;
1492
+ if (verified.customer_id !== session.customer_id) await this.pushClient?.pauseAndRevoke();
1493
+ let adoptedToken = sessionToken;
1494
+ let legacyJwt = verified.legacy_jwt ?? null;
1495
+ if (this.pushChannelId && verified.customer_id === session.customer_id) {
1496
+ const renewed = await this.requireHttp().request(`${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`, {
1497
+ method: "POST",
1498
+ headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
1499
+ body: JSON.stringify({ replacement_session_token: sessionToken }),
1500
+ errorMessage: "Shared push session refresh failed."
1501
+ });
1502
+ if (renewed.session_id !== session.session_id || renewed.customer_id !== session.customer_id || !renewed.session_token) {
1503
+ throw new SagepilotChatError("forbidden", "Shared session refresh scope changed.");
1504
+ }
1505
+ adoptedToken = renewed.session_token;
1506
+ legacyJwt = renewed.legacy_jwt ?? legacyJwt;
1507
+ }
1508
+ this.session = await this.requireSessionManager().setSession({ ...verified, session_token: adoptedToken });
1509
+ this.legacyWidgetJwt = legacyJwt;
1510
+ this.hostedIdentityLogoutVersion = 0;
1511
+ this.identified = true;
1512
+ this.customer = verified.customer_id ? { id: verified.customer_id } : null;
1513
+ this.pushClient?.resume();
1514
+ } finally {
1515
+ this.identifyPending = false;
1516
+ this.emitState();
1517
+ }
1518
+ }
1068
1519
  handleConversationCreated(message) {
1069
1520
  const chatId = readStringField(message, "chat_id") ?? readStringField(message, "conversation_id");
1070
1521
  if (!chatId) return;
@@ -1118,10 +1569,12 @@ var SagepilotReactNativeChat = class {
1118
1569
  this.dismissCallbacks.clear();
1119
1570
  this.errorCallbacks.clear();
1120
1571
  }
1572
+ /** Updates both unread subscribers and the state used by React launchers. */
1121
1573
  setUnreadCount(count) {
1122
1574
  if (count === this.unreadCount) return;
1123
1575
  this.unreadCount = count;
1124
1576
  this.emitUnreadChange();
1577
+ this.emitState();
1125
1578
  }
1126
1579
  emitUnreadChange() {
1127
1580
  const state = this.getUnreadState();
@@ -1276,6 +1729,11 @@ var SagepilotReactNativeChat = class {
1276
1729
  return this.unreadCount;
1277
1730
  }
1278
1731
  resetRuntimeState() {
1732
+ this.pushClient?.stop();
1733
+ this.pushClient = null;
1734
+ this.pushChannelId = null;
1735
+ this.pushAppStateSubscription?.remove();
1736
+ this.pushAppStateSubscription = null;
1279
1737
  this.runtimeOptions = null;
1280
1738
  this.http = null;
1281
1739
  this.sessionManager = null;
@@ -1386,9 +1844,15 @@ var SagepilotReactNativeChat = class {
1386
1844
  };
1387
1845
  var internalSagepilotChat = new SagepilotReactNativeChat();
1388
1846
  var SagepilotChat = {
1847
+ /** Provides push registration, preferences and SDK engagement callbacks. */
1848
+ get push() {
1849
+ return internalSagepilotChat.push;
1850
+ },
1389
1851
  configure: (config) => internalSagepilotChat.configure(config),
1390
1852
  getSession: () => internalSagepilotChat.getSession(),
1391
1853
  identify: (identity) => internalSagepilotChat.identify(identity),
1854
+ /** Authorizes the configured brand on the same customer session used by chat. */
1855
+ authorizePush: (identityToken) => internalSagepilotChat.authorizePush(identityToken),
1392
1856
  logout: () => internalSagepilotChat.logout(),
1393
1857
  getIdentityState: () => internalSagepilotChat.getIdentityState(),
1394
1858
  onIdentify: (callback) => internalSagepilotChat.onIdentify(callback),
@@ -1418,6 +1882,7 @@ var SagepilotChat = {
1418
1882
  getChannel: () => internalSagepilotChat.getChannel(),
1419
1883
  destroy: () => internalSagepilotChat.destroy()
1420
1884
  };
1885
+ Object.defineProperty(SagepilotChat, "push", { enumerable: false });
1421
1886
 
1422
1887
  // src/core/storage/fileStore.ts
1423
1888
  var DEFAULT_DIRECTORY_NAME = "sagepilot-attachments";
@@ -1720,7 +2185,7 @@ function createSagepilotFilePicker(options) {
1720
2185
  import { createElement, useCallback, useEffect, useRef, useState } from "react";
1721
2186
  import {
1722
2187
  ActivityIndicator,
1723
- AppState,
2188
+ AppState as AppState3,
1724
2189
  KeyboardAvoidingView,
1725
2190
  Linking as Linking2,
1726
2191
  Modal,
@@ -1736,7 +2201,7 @@ import { WebView } from "react-native-webview";
1736
2201
  // src/core/webview/mobileBridge.ts
1737
2202
  var FILE_PICKER_PROTOCOL_VERSION = 2;
1738
2203
  function buildBridgeCapabilitiesPayload(capabilities) {
1739
- return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION };
2204
+ return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION, sdk: SDK_NAME, sdk_version: SDK_VERSION };
1740
2205
  }
1741
2206
  function buildBridgeCapabilitiesScript(capabilities) {
1742
2207
  const payload = buildBridgeCapabilitiesPayload(capabilities);
@@ -2062,7 +2527,7 @@ function SagepilotChatProvider({
2062
2527
  const livenessPausedUntilRef = useRef(0);
2063
2528
  const pickerInFlightRef = useRef(false);
2064
2529
  const livenessRemountCountRef = useRef(0);
2065
- const appStateRef = useRef(AppState.currentState);
2530
+ const appStateRef = useRef(AppState3.currentState);
2066
2531
  const didReconcileRef = useRef(false);
2067
2532
  const [androidRepaintTick, setAndroidRepaintTick] = useState(0);
2068
2533
  const [sourceChooser, setSourceChooser] = useState(null);
@@ -2403,7 +2868,7 @@ function SagepilotChatProvider({
2403
2868
  }, LIVENESS_PONG_TIMEOUT_MS);
2404
2869
  }, [clearDeferredLivenessProbe, clearPing, recoverNativeWebView]);
2405
2870
  useEffect(() => {
2406
- const subscription = AppState.addEventListener("change", (nextState) => {
2871
+ const subscription = AppState3.addEventListener("change", (nextState) => {
2407
2872
  const prev = appStateRef.current;
2408
2873
  appStateRef.current = nextState;
2409
2874
  if (nextState === "active" && (prev === "background" || prev === "inactive")) {
@@ -2450,6 +2915,8 @@ function SagepilotChatProvider({
2450
2915
  ].filter(Boolean)
2451
2916
  };
2452
2917
  const handleWebViewMessage = (event) => {
2918
+ const origin = readUrlOrigin(state.conversationUrl ?? state.preloadUrl);
2919
+ if (event.nativeEvent?.url && (!origin || readUrlOrigin(event.nativeEvent.url) !== origin)) return;
2453
2920
  const message = parseHostedBridgeMessage(event.nativeEvent?.data);
2454
2921
  if (message?.type === "sagepilot:open_file_picker") {
2455
2922
  logNativeFilePicker("bridge_message_open_file_picker", {
@@ -2540,7 +3007,7 @@ function SagepilotChatProvider({
2540
3007
  const trustedWidgetOrigin = readUrlOrigin(state.conversationUrl);
2541
3008
  if (!trustedWidgetOrigin) return;
2542
3009
  const handleWindowMessage = (event) => {
2543
- if (event.origin !== trustedWidgetOrigin) return;
3010
+ if (event.origin !== trustedWidgetOrigin || event.source !== webFrameRef.current?.contentWindow) return;
2544
3011
  internalSagepilotChat.handleHostedBridgeMessage(parseHostedBridgeMessage(event.data));
2545
3012
  };
2546
3013
  window.addEventListener("message", handleWindowMessage);
@@ -2614,7 +3081,7 @@ function SagepilotChatProvider({
2614
3081
  // disrupt an in-flight delivery). onRenderProcessGone must still be
2615
3082
  // handled here or an unhandled renderer kill crashes the whole app.
2616
3083
  key: `sagepilot-preload-webview-${preloadWebViewKey}`,
2617
- source: { uri: state.preloadUrl },
3084
+ source: { uri: state.preloadUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
2618
3085
  style: styles.preloadWebview,
2619
3086
  injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
2620
3087
  onMessage: handleWebViewMessage,
@@ -2656,7 +3123,7 @@ function SagepilotChatProvider({
2656
3123
  ...hostedChatWebViewProps,
2657
3124
  key: `sagepilot-hosted-webview-${nativeWebViewKey}`,
2658
3125
  ref: nativeWebViewRef,
2659
- source: { uri: state.conversationUrl },
3126
+ source: { uri: state.conversationUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
2660
3127
  // The imperceptible opacity toggle forces the Android WebView
2661
3128
  // surface to re-composite on resume, clearing the blank-but-alive
2662
3129
  // surface bug without a reload (see runLivenessProbe).
@@ -2912,15 +3379,113 @@ function useSagepilotChat() {
2912
3379
  onConversationCreated
2913
3380
  };
2914
3381
  }
3382
+
3383
+ // src/brandPush.ts
3384
+ import { AppState as AppState4, Platform as Platform4 } from "react-native";
3385
+ var SagepilotBrandPush = class {
3386
+ /** Keeps brand credentials separate from chat and other workspace/channel sessions. */
3387
+ constructor(config) {
3388
+ this.config = config;
3389
+ this.session = null;
3390
+ this.pending = Promise.resolve();
3391
+ this.started = false;
3392
+ this.appStateSubscription = null;
3393
+ this.scope = parseKey(config.key);
3394
+ if (Platform4.OS !== "android" && Platform4.OS !== "ios") throw new Error("Brand push requires Android or iOS.");
3395
+ this.tokens = new SagepilotTokenManager(`push_${this.scope.workspaceId}_${this.scope.channelId}`, config.tokenStorage);
3396
+ this.http = new SagepilotHttpClient({ fetch: resolveFetch(config.fetch) });
3397
+ this.host = resolveCustomerApiHost(config.host);
3398
+ this.push = new SagepilotPush(config.push, {
3399
+ ...this.scope,
3400
+ platform: Platform4.OS,
3401
+ brand: true,
3402
+ customerId: () => this.session?.customer_id ?? null,
3403
+ onError: config.onError,
3404
+ request: (path, method, body) => this.request(path, method, body)
3405
+ });
3406
+ }
3407
+ /** Serializes identity transitions so an old installation is revoked with its original credentials. */
3408
+ transition(operation) {
3409
+ const next = this.pending.then(operation);
3410
+ this.pending = next.catch(() => void 0);
3411
+ return next;
3412
+ }
3413
+ /** Sends through the shared version-stamped transport using the current brand credential. */
3414
+ request(path, method, body) {
3415
+ if (!this.session) return Promise.reject(new Error("Identify a brand customer before using push."));
3416
+ return this.http.request(`${this.host}${CUSTOMER_API_PREFIX}${path}`, {
3417
+ method,
3418
+ headers: withJsonHeaders(this.tokens.createAuthorizationHeader(this.session.session_token)),
3419
+ body: body === void 0 ? void 0 : JSON.stringify(body),
3420
+ errorMessage: "Push request failed"
3421
+ });
3422
+ }
3423
+ /** Restores durable credentials before registering listeners; never prompts for permission. */
3424
+ start() {
3425
+ return this.transition(async () => {
3426
+ if (this.started) return;
3427
+ this.session = await this.tokens.getSession();
3428
+ await this.push.start();
3429
+ this.appStateSubscription = AppState4.addEventListener("change", (state) => {
3430
+ if (state === "active") {
3431
+ void this.push.sync().catch(this.config.onError);
3432
+ void this.push.flush().catch(this.config.onError);
3433
+ }
3434
+ });
3435
+ this.started = true;
3436
+ });
3437
+ }
3438
+ /** Exchanges a host-server proof, then revokes old ownership before adopting the new session. */
3439
+ identify(identityToken) {
3440
+ return this.transition(async () => {
3441
+ if (!this.started) throw new Error("Call start before identify.");
3442
+ if (typeof identityToken !== "string" || !identityToken.trim()) throw new Error("A signed brand identity proof is required.");
3443
+ const next = await this.http.request(
3444
+ `${this.host}${CUSTOMER_API_PREFIX}/push/sessions`,
3445
+ {
3446
+ method: "POST",
3447
+ headers: withJsonHeaders(void 0),
3448
+ body: JSON.stringify({ channel_id: this.scope.channelId, identity_token: identityToken }),
3449
+ errorMessage: "Brand identity verification failed"
3450
+ }
3451
+ );
3452
+ if (next.workspace_id !== this.scope.workspaceId || next.channel_id !== this.scope.channelId || !next.customer_id || !next.session_token || !next.session_id || !next.authenticated) {
3453
+ throw new Error("Brand session scope mismatch.");
3454
+ }
3455
+ if (this.session?.customer_id !== next.customer_id) await this.push.pauseAndRevoke();
3456
+ await this.tokens.setSession(next);
3457
+ this.session = next;
3458
+ this.push.resume();
3459
+ });
3460
+ }
3461
+ /** Retains credentials on failed revocation so logout can be retried safely. */
3462
+ logout() {
3463
+ return this.transition(async () => {
3464
+ if (!this.started) throw new Error("Call start before logout.");
3465
+ await this.push.pauseAndRevoke();
3466
+ await this.tokens.clearSession();
3467
+ this.session = null;
3468
+ });
3469
+ }
3470
+ /** Stops listeners; call logout first when the customer is signing out. */
3471
+ destroy() {
3472
+ return this.transition(async () => {
3473
+ this.appStateSubscription?.remove();
3474
+ this.push.stop();
3475
+ });
3476
+ }
3477
+ };
2915
3478
  export {
2916
3479
  SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION,
2917
3480
  SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES,
2918
3481
  SAGEPILOT_DEFAULT_IMAGE_QUALITY,
3482
+ SagepilotBrandPush,
2919
3483
  SagepilotChat,
2920
3484
  SagepilotChatError,
2921
3485
  SagepilotChatProvider,
2922
3486
  SagepilotFilePickerError,
2923
3487
  createAsyncStorageCacheStorage,
3488
+ createFirebasePushAdapter,
2924
3489
  createKeychainTokenStorage,
2925
3490
  createSagepilotFilePicker,
2926
3491
  createSagepilotFileStore,