@sagepilot-ai/react-native-sdk 0.3.5 → 0.4.0

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.0";
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.4";
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,55 @@ 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
+ const session = this.requireSession();
1047
+ if (!this.pushChannelId || !this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push.channelId first.");
1048
+ if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
1049
+ this.identifyPending = true;
1050
+ try {
1051
+ const result = await this.requireHttp().request(
1052
+ `${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`,
1053
+ {
1054
+ method: "POST",
1055
+ headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
1056
+ body: JSON.stringify({ channel_id: this.pushChannelId, identity_token: identityToken }),
1057
+ errorMessage: "Brand authorization failed."
1058
+ }
1059
+ );
1060
+ 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) {
1061
+ throw new SagepilotChatError("forbidden", "Brand session scope changed.");
1062
+ }
1063
+ this.session = await this.requireSessionManager().setSession({ ...session, session_token: result.session_token });
1064
+ this.legacyWidgetJwt = result.legacy_jwt ?? this.legacyWidgetJwt;
1065
+ this.pushClient.resume();
1066
+ } finally {
1067
+ this.identifyPending = false;
1068
+ }
1069
+ }
688
1070
  async logout() {
689
1071
  const session = this.requireSession();
1072
+ if (this.pushClient) {
1073
+ if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
1074
+ this.identifyPending = true;
1075
+ try {
1076
+ await this.pushClient.pauseAndRevoke();
1077
+ } catch (error) {
1078
+ this.identifyPending = false;
1079
+ this.emitState();
1080
+ throw error;
1081
+ }
1082
+ }
690
1083
  const wasUnreadPolling = this.unreadPollTimer !== null;
691
1084
  let result = null;
692
1085
  let logoutError = null;
@@ -726,6 +1119,7 @@ var SagepilotReactNativeChat = class {
726
1119
  throw error;
727
1120
  }
728
1121
  this.session = freshSession;
1122
+ this.pushClient?.resume();
729
1123
  this.setUnreadCount(0);
730
1124
  this.emitState();
731
1125
  this.persistPresentationState();
@@ -934,6 +1328,8 @@ var SagepilotReactNativeChat = class {
934
1328
  const path = this.hostedChatView.screen === "home" ? `/chat-widget/${encodeURIComponent(this.channelId)}` : `/chat-widget/${encodeURIComponent(this.channelId)}/conversations`;
935
1329
  const url = new URL(`${this.widgetHost}${path}`);
936
1330
  url.searchParams.set("sdk", "react-native");
1331
+ url.searchParams.set("sdk_name", SDK_NAME);
1332
+ url.searchParams.set("sdk_version", SDK_VERSION);
937
1333
  if (this.runtimeOptions?.presentation?.mobile ?? true) {
938
1334
  url.searchParams.set("mobile", "1");
939
1335
  }
@@ -1055,6 +1451,10 @@ var SagepilotReactNativeChat = class {
1055
1451
  }
1056
1452
  return true;
1057
1453
  }
1454
+ if (message.type === "sagepilot:session_updated") {
1455
+ if (this.pushClient) void this.acceptHostedSession(message).catch((error) => this.emitError(error));
1456
+ return true;
1457
+ }
1058
1458
  if (message.type === "sagepilot:conversation_created") {
1059
1459
  this.handleConversationCreated(message);
1060
1460
  return true;
@@ -1065,6 +1465,54 @@ var SagepilotReactNativeChat = class {
1065
1465
  }
1066
1466
  return true;
1067
1467
  }
1468
+ /** Verifies an OTP-issued token with the Customer API before accepting a hosted identity change. */
1469
+ async acceptHostedSession(message) {
1470
+ const session = this.requireSession();
1471
+ const sessionToken = readStringField(message, "session_token");
1472
+ if (!sessionToken || readStringField(message, "session_id") !== session.session_id) return;
1473
+ if (message.workspace_id && message.workspace_id !== this.workspaceId) return;
1474
+ if (message.channel_id && message.channel_id !== this.channelId) return;
1475
+ if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
1476
+ this.identifyPending = true;
1477
+ this.emitState();
1478
+ try {
1479
+ const verified = await getSession(
1480
+ this.requireHttp(),
1481
+ this.apiHost,
1482
+ session.session_id,
1483
+ this.requireSessionManager().getAuthorizationHeader(sessionToken)
1484
+ );
1485
+ if (verified.session_id !== session.session_id || verified.channel_id && verified.channel_id !== this.channelId || !verified.authenticated) {
1486
+ throw new SagepilotChatError("forbidden", "Hosted token does not identify this customer session.");
1487
+ }
1488
+ if (this.session?.session_id !== session.session_id || this.session.session_token !== session.session_token) return;
1489
+ if (verified.customer_id !== session.customer_id) await this.pushClient?.pauseAndRevoke();
1490
+ let adoptedToken = sessionToken;
1491
+ let legacyJwt = verified.legacy_jwt ?? null;
1492
+ if (this.pushChannelId && verified.customer_id === session.customer_id) {
1493
+ const renewed = await this.requireHttp().request(`${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`, {
1494
+ method: "POST",
1495
+ headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
1496
+ body: JSON.stringify({ replacement_session_token: sessionToken }),
1497
+ errorMessage: "Shared push session refresh failed."
1498
+ });
1499
+ if (renewed.session_id !== session.session_id || renewed.customer_id !== session.customer_id || !renewed.session_token) {
1500
+ throw new SagepilotChatError("forbidden", "Shared session refresh scope changed.");
1501
+ }
1502
+ adoptedToken = renewed.session_token;
1503
+ legacyJwt = renewed.legacy_jwt ?? legacyJwt;
1504
+ }
1505
+ this.session = await this.requireSessionManager().setSession({ ...verified, session_token: adoptedToken });
1506
+ this.legacyWidgetJwt = legacyJwt;
1507
+ this.hostedIdentityLogoutVersion = 0;
1508
+ this.identified = true;
1509
+ this.customer = verified.customer_id ? { id: verified.customer_id } : null;
1510
+ this.pushClient?.resume();
1511
+ } finally {
1512
+ this.identifyPending = false;
1513
+ this.emitState();
1514
+ }
1515
+ }
1068
1516
  handleConversationCreated(message) {
1069
1517
  const chatId = readStringField(message, "chat_id") ?? readStringField(message, "conversation_id");
1070
1518
  if (!chatId) return;
@@ -1118,10 +1566,12 @@ var SagepilotReactNativeChat = class {
1118
1566
  this.dismissCallbacks.clear();
1119
1567
  this.errorCallbacks.clear();
1120
1568
  }
1569
+ /** Updates both unread subscribers and the state used by React launchers. */
1121
1570
  setUnreadCount(count) {
1122
1571
  if (count === this.unreadCount) return;
1123
1572
  this.unreadCount = count;
1124
1573
  this.emitUnreadChange();
1574
+ this.emitState();
1125
1575
  }
1126
1576
  emitUnreadChange() {
1127
1577
  const state = this.getUnreadState();
@@ -1276,6 +1726,11 @@ var SagepilotReactNativeChat = class {
1276
1726
  return this.unreadCount;
1277
1727
  }
1278
1728
  resetRuntimeState() {
1729
+ this.pushClient?.stop();
1730
+ this.pushClient = null;
1731
+ this.pushChannelId = null;
1732
+ this.pushAppStateSubscription?.remove();
1733
+ this.pushAppStateSubscription = null;
1279
1734
  this.runtimeOptions = null;
1280
1735
  this.http = null;
1281
1736
  this.sessionManager = null;
@@ -1386,9 +1841,15 @@ var SagepilotReactNativeChat = class {
1386
1841
  };
1387
1842
  var internalSagepilotChat = new SagepilotReactNativeChat();
1388
1843
  var SagepilotChat = {
1844
+ /** Provides push registration, preferences and SDK engagement callbacks. */
1845
+ get push() {
1846
+ return internalSagepilotChat.push;
1847
+ },
1389
1848
  configure: (config) => internalSagepilotChat.configure(config),
1390
1849
  getSession: () => internalSagepilotChat.getSession(),
1391
1850
  identify: (identity) => internalSagepilotChat.identify(identity),
1851
+ /** Authorizes the configured brand on the same customer session used by chat. */
1852
+ authorizePush: (identityToken) => internalSagepilotChat.authorizePush(identityToken),
1392
1853
  logout: () => internalSagepilotChat.logout(),
1393
1854
  getIdentityState: () => internalSagepilotChat.getIdentityState(),
1394
1855
  onIdentify: (callback) => internalSagepilotChat.onIdentify(callback),
@@ -1418,6 +1879,7 @@ var SagepilotChat = {
1418
1879
  getChannel: () => internalSagepilotChat.getChannel(),
1419
1880
  destroy: () => internalSagepilotChat.destroy()
1420
1881
  };
1882
+ Object.defineProperty(SagepilotChat, "push", { enumerable: false });
1421
1883
 
1422
1884
  // src/core/storage/fileStore.ts
1423
1885
  var DEFAULT_DIRECTORY_NAME = "sagepilot-attachments";
@@ -1720,7 +2182,7 @@ function createSagepilotFilePicker(options) {
1720
2182
  import { createElement, useCallback, useEffect, useRef, useState } from "react";
1721
2183
  import {
1722
2184
  ActivityIndicator,
1723
- AppState,
2185
+ AppState as AppState3,
1724
2186
  KeyboardAvoidingView,
1725
2187
  Linking as Linking2,
1726
2188
  Modal,
@@ -1736,7 +2198,7 @@ import { WebView } from "react-native-webview";
1736
2198
  // src/core/webview/mobileBridge.ts
1737
2199
  var FILE_PICKER_PROTOCOL_VERSION = 2;
1738
2200
  function buildBridgeCapabilitiesPayload(capabilities) {
1739
- return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION };
2201
+ return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION, sdk: SDK_NAME, sdk_version: SDK_VERSION };
1740
2202
  }
1741
2203
  function buildBridgeCapabilitiesScript(capabilities) {
1742
2204
  const payload = buildBridgeCapabilitiesPayload(capabilities);
@@ -2062,7 +2524,7 @@ function SagepilotChatProvider({
2062
2524
  const livenessPausedUntilRef = useRef(0);
2063
2525
  const pickerInFlightRef = useRef(false);
2064
2526
  const livenessRemountCountRef = useRef(0);
2065
- const appStateRef = useRef(AppState.currentState);
2527
+ const appStateRef = useRef(AppState3.currentState);
2066
2528
  const didReconcileRef = useRef(false);
2067
2529
  const [androidRepaintTick, setAndroidRepaintTick] = useState(0);
2068
2530
  const [sourceChooser, setSourceChooser] = useState(null);
@@ -2403,7 +2865,7 @@ function SagepilotChatProvider({
2403
2865
  }, LIVENESS_PONG_TIMEOUT_MS);
2404
2866
  }, [clearDeferredLivenessProbe, clearPing, recoverNativeWebView]);
2405
2867
  useEffect(() => {
2406
- const subscription = AppState.addEventListener("change", (nextState) => {
2868
+ const subscription = AppState3.addEventListener("change", (nextState) => {
2407
2869
  const prev = appStateRef.current;
2408
2870
  appStateRef.current = nextState;
2409
2871
  if (nextState === "active" && (prev === "background" || prev === "inactive")) {
@@ -2450,6 +2912,8 @@ function SagepilotChatProvider({
2450
2912
  ].filter(Boolean)
2451
2913
  };
2452
2914
  const handleWebViewMessage = (event) => {
2915
+ const origin = readUrlOrigin(state.conversationUrl ?? state.preloadUrl);
2916
+ if (event.nativeEvent?.url && (!origin || readUrlOrigin(event.nativeEvent.url) !== origin)) return;
2453
2917
  const message = parseHostedBridgeMessage(event.nativeEvent?.data);
2454
2918
  if (message?.type === "sagepilot:open_file_picker") {
2455
2919
  logNativeFilePicker("bridge_message_open_file_picker", {
@@ -2540,7 +3004,7 @@ function SagepilotChatProvider({
2540
3004
  const trustedWidgetOrigin = readUrlOrigin(state.conversationUrl);
2541
3005
  if (!trustedWidgetOrigin) return;
2542
3006
  const handleWindowMessage = (event) => {
2543
- if (event.origin !== trustedWidgetOrigin) return;
3007
+ if (event.origin !== trustedWidgetOrigin || event.source !== webFrameRef.current?.contentWindow) return;
2544
3008
  internalSagepilotChat.handleHostedBridgeMessage(parseHostedBridgeMessage(event.data));
2545
3009
  };
2546
3010
  window.addEventListener("message", handleWindowMessage);
@@ -2614,7 +3078,7 @@ function SagepilotChatProvider({
2614
3078
  // disrupt an in-flight delivery). onRenderProcessGone must still be
2615
3079
  // handled here or an unhandled renderer kill crashes the whole app.
2616
3080
  key: `sagepilot-preload-webview-${preloadWebViewKey}`,
2617
- source: { uri: state.preloadUrl },
3081
+ source: { uri: state.preloadUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
2618
3082
  style: styles.preloadWebview,
2619
3083
  injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
2620
3084
  onMessage: handleWebViewMessage,
@@ -2656,7 +3120,7 @@ function SagepilotChatProvider({
2656
3120
  ...hostedChatWebViewProps,
2657
3121
  key: `sagepilot-hosted-webview-${nativeWebViewKey}`,
2658
3122
  ref: nativeWebViewRef,
2659
- source: { uri: state.conversationUrl },
3123
+ source: { uri: state.conversationUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
2660
3124
  // The imperceptible opacity toggle forces the Android WebView
2661
3125
  // surface to re-composite on resume, clearing the blank-but-alive
2662
3126
  // surface bug without a reload (see runLivenessProbe).
@@ -2912,15 +3376,112 @@ function useSagepilotChat() {
2912
3376
  onConversationCreated
2913
3377
  };
2914
3378
  }
3379
+
3380
+ // src/brandPush.ts
3381
+ import { AppState as AppState4, Platform as Platform4 } from "react-native";
3382
+ var SagepilotBrandPush = class {
3383
+ /** Keeps brand credentials separate from chat and other workspace/channel sessions. */
3384
+ constructor(config) {
3385
+ this.config = config;
3386
+ this.session = null;
3387
+ this.pending = Promise.resolve();
3388
+ this.started = false;
3389
+ this.appStateSubscription = null;
3390
+ this.scope = parseKey(config.key);
3391
+ if (Platform4.OS !== "android" && Platform4.OS !== "ios") throw new Error("Brand push requires Android or iOS.");
3392
+ this.tokens = new SagepilotTokenManager(`push_${this.scope.workspaceId}_${this.scope.channelId}`, config.tokenStorage);
3393
+ this.http = new SagepilotHttpClient({ fetch: resolveFetch(config.fetch) });
3394
+ this.host = resolveCustomerApiHost(config.host);
3395
+ this.push = new SagepilotPush(config.push, {
3396
+ ...this.scope,
3397
+ platform: Platform4.OS,
3398
+ brand: true,
3399
+ customerId: () => this.session?.customer_id ?? null,
3400
+ onError: config.onError,
3401
+ request: (path, method, body) => this.request(path, method, body)
3402
+ });
3403
+ }
3404
+ /** Serializes identity transitions so an old installation is revoked with its original credentials. */
3405
+ transition(operation) {
3406
+ const next = this.pending.then(operation);
3407
+ this.pending = next.catch(() => void 0);
3408
+ return next;
3409
+ }
3410
+ /** Sends through the shared version-stamped transport using the current brand credential. */
3411
+ request(path, method, body) {
3412
+ if (!this.session) return Promise.reject(new Error("Identify a brand customer before using push."));
3413
+ return this.http.request(`${this.host}${CUSTOMER_API_PREFIX}${path}`, {
3414
+ method,
3415
+ headers: withJsonHeaders(this.tokens.createAuthorizationHeader(this.session.session_token)),
3416
+ body: body === void 0 ? void 0 : JSON.stringify(body),
3417
+ errorMessage: "Push request failed"
3418
+ });
3419
+ }
3420
+ /** Restores durable credentials before registering listeners; never prompts for permission. */
3421
+ start() {
3422
+ return this.transition(async () => {
3423
+ if (this.started) return;
3424
+ this.session = await this.tokens.getSession();
3425
+ await this.push.start();
3426
+ this.appStateSubscription = AppState4.addEventListener("change", (state) => {
3427
+ if (state === "active") {
3428
+ void this.push.sync().catch(this.config.onError);
3429
+ void this.push.flush().catch(this.config.onError);
3430
+ }
3431
+ });
3432
+ this.started = true;
3433
+ });
3434
+ }
3435
+ /** Exchanges a host-server proof, then revokes old ownership before adopting the new session. */
3436
+ identify(identityToken) {
3437
+ return this.transition(async () => {
3438
+ if (!this.started) throw new Error("Call start before identify.");
3439
+ const next = await this.http.request(
3440
+ `${this.host}${CUSTOMER_API_PREFIX}/push/sessions`,
3441
+ {
3442
+ method: "POST",
3443
+ headers: withJsonHeaders(void 0),
3444
+ body: JSON.stringify({ channel_id: this.scope.channelId, identity_token: identityToken }),
3445
+ errorMessage: "Brand identity verification failed"
3446
+ }
3447
+ );
3448
+ if (next.workspace_id !== this.scope.workspaceId || next.channel_id !== this.scope.channelId || !next.customer_id || !next.session_token || !next.session_id || !next.authenticated) {
3449
+ throw new Error("Brand session scope mismatch.");
3450
+ }
3451
+ if (this.session?.customer_id !== next.customer_id) await this.push.pauseAndRevoke();
3452
+ await this.tokens.setSession(next);
3453
+ this.session = next;
3454
+ this.push.resume();
3455
+ });
3456
+ }
3457
+ /** Retains credentials on failed revocation so logout can be retried safely. */
3458
+ logout() {
3459
+ return this.transition(async () => {
3460
+ if (!this.started) throw new Error("Call start before logout.");
3461
+ await this.push.pauseAndRevoke();
3462
+ await this.tokens.clearSession();
3463
+ this.session = null;
3464
+ });
3465
+ }
3466
+ /** Stops listeners; call logout first when the customer is signing out. */
3467
+ destroy() {
3468
+ return this.transition(async () => {
3469
+ this.appStateSubscription?.remove();
3470
+ this.push.stop();
3471
+ });
3472
+ }
3473
+ };
2915
3474
  export {
2916
3475
  SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION,
2917
3476
  SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES,
2918
3477
  SAGEPILOT_DEFAULT_IMAGE_QUALITY,
3478
+ SagepilotBrandPush,
2919
3479
  SagepilotChat,
2920
3480
  SagepilotChatError,
2921
3481
  SagepilotChatProvider,
2922
3482
  SagepilotFilePickerError,
2923
3483
  createAsyncStorageCacheStorage,
3484
+ createFirebasePushAdapter,
2924
3485
  createKeychainTokenStorage,
2925
3486
  createSagepilotFilePicker,
2926
3487
  createSagepilotFileStore,