@sagepilot-ai/react-native-sdk 0.4.3 → 0.5.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/README.md CHANGED
@@ -6,6 +6,8 @@ The SDK opens the Sagepilot-hosted chat experience inside a React Native WebView
6
6
 
7
7
  For full integration docs, see [React Native SDK docs](https://docs.sagepilot.ai/sdks/react-native/overview).
8
8
 
9
+ For automatic app observations, initialize the [React Native events add-on](../react-native-events-addon/README.md) separately with an SDK installation key.
10
+
9
11
  ## Requirements
10
12
 
11
13
  - React 18+
@@ -16,7 +18,7 @@ For full integration docs, see [React Native SDK docs](https://docs.sagepilot.ai
16
18
 
17
19
  ## Install
18
20
 
19
- Base SDK **0.4.3** adds the optional native URL handler. Camera and push add-ons remain at **0.4.2** and retain their existing peer compatibility; chat-only apps do not need either add-on.
21
+ The base SDK, camera add-on and push add-on share release **0.4.2**. Install matching versions of the add-ons your app uses; chat-only apps do not need either add-on.
20
22
 
21
23
  ```bash
22
24
  npm install @sagepilot-ai/react-native-sdk@latest react-native-webview
@@ -91,8 +93,6 @@ export function SagepilotProvider({ children }: { children: ReactNode }) {
91
93
  }
92
94
  ```
93
95
 
94
- For native product navigation, pass `onOpenURL` to `SagepilotChatProvider`. It receives external top-level destinations; return `true` (or a promise resolving to `true`) when your native router handles the URL. Returning `false`, omitting the callback, or throwing preserves the existing `Linking.openURL` fallback. Same-origin widget pages, including `/cta` click tracking, load normally before their final destination is offered to the callback. A handled destination resets the hosted WebView so reopening chat does not leave it on a tracking page.
95
-
96
96
  ```tsx
97
97
  export function App() {
98
98
  return (
package/dist/index.js CHANGED
@@ -54,7 +54,7 @@ var import_react_native2 = require("react-native");
54
54
 
55
55
  // package.json
56
56
  var name = "@sagepilot-ai/react-native-sdk";
57
- var version = "0.4.3";
57
+ var version = "0.5.1";
58
58
 
59
59
  // src/core/config/constants.ts
60
60
  var SDK_NAME = name;
@@ -167,18 +167,26 @@ var SagepilotPush = class {
167
167
  if (this.started) return;
168
168
  this.started = true;
169
169
  const binding = await this.mutate(async (state) => state.binding);
170
+ if (this.stopped) return;
170
171
  const adapter = this.config.adapter;
171
172
  if (adapter) {
172
- if (adapter.start) this.subscriptions.push(await adapter.start({
173
- workspaceId: this.context.workspaceId,
174
- channelId: this.context.channelId,
175
- sdkVersion: SDK_VERSION,
176
- storage: this.config.storage,
177
- owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
178
- customerId: this.context.customerId,
179
- upload: (event) => this.context.request("/push/events", "POST", event),
180
- onOpen: (message) => this.config.onOpen?.(message)
181
- }));
173
+ if (adapter.start) {
174
+ const unsubscribe = await adapter.start({
175
+ workspaceId: this.context.workspaceId,
176
+ channelId: this.context.channelId,
177
+ sdkVersion: SDK_VERSION,
178
+ storage: this.config.storage,
179
+ owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
180
+ customerId: this.context.customerId,
181
+ upload: (event) => this.context.request("/push/events", "POST", event),
182
+ onOpen: (message) => this.config.onOpen?.(message)
183
+ });
184
+ if (this.stopped) {
185
+ unsubscribe();
186
+ return;
187
+ }
188
+ this.subscriptions.push(unsubscribe);
189
+ }
182
190
  this.subscriptions.push(
183
191
  adapter.onTokenRefresh((token) => {
184
192
  void this.sync(token).catch(this.context.onError);
@@ -191,8 +199,10 @@ var SagepilotPush = class {
191
199
  })
192
200
  );
193
201
  const initial = await adapter.getInitialNotification();
202
+ if (this.stopped) return;
194
203
  if (initial) await this.handleOpened(initial);
195
204
  }
205
+ if (this.stopped) return;
196
206
  void this.sync().catch(this.context.onError);
197
207
  void this.flush().catch(this.context.onError);
198
208
  }
@@ -563,6 +573,14 @@ var SagepilotTokenManager = class {
563
573
  function normalizeHost(host = DEFAULT_HOST) {
564
574
  return host.replace(/\/+$/, "");
565
575
  }
576
+ function isHttpUrl(value) {
577
+ try {
578
+ const url = new URL(value);
579
+ return (url.protocol === "https:" || url.protocol === "http:") && Boolean(url.hostname);
580
+ } catch {
581
+ return false;
582
+ }
583
+ }
566
584
  function readRuntimeEnv(name2) {
567
585
  return globalThis.process?.env?.[name2]?.trim();
568
586
  }
@@ -911,6 +929,8 @@ var SagepilotReactNativeChat = class {
911
929
  this.identified = false;
912
930
  this.identifyPending = false;
913
931
  this.isConfigured = false;
932
+ this.configuring = false;
933
+ this.runtimeGeneration = 0;
914
934
  this.presented = false;
915
935
  this.hostedChatView = { screen: "home" };
916
936
  this.unreadCount = 0;
@@ -929,11 +949,12 @@ var SagepilotReactNativeChat = class {
929
949
  if (!this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push with durable storage before using the push API.");
930
950
  return this.pushClient;
931
951
  }
952
+ /** Initializes one runtime; destruction invalidates all unfinished work from this attempt. */
932
953
  async configure(config) {
933
- if (this.isConfigured) {
954
+ if (this.isConfigured || this.configuring) {
934
955
  throw new SagepilotChatError(
935
956
  "already_initialized",
936
- `${SDK_NAME} is already configured. Call destroy() before configuring again.`
957
+ `${SDK_NAME} is already configured or configuring. Call destroy() before configuring again.`
937
958
  );
938
959
  }
939
960
  if (!config?.key || typeof config.key !== "string") {
@@ -943,33 +964,39 @@ var SagepilotReactNativeChat = class {
943
964
  );
944
965
  }
945
966
  const { workspaceId, channelId } = parseKey(config.key);
946
- this.runtimeOptions = {
947
- anonymousId: config.anonymousId,
948
- behavior: config.behavior,
949
- cacheStorage: config.cacheStorage,
950
- deviceInfo: config.deviceInfo,
951
- filePicker: config.filePicker,
952
- fileStore: config.fileStore,
953
- metadata: config.metadata,
954
- presentation: config.presentation,
955
- theme: config.theme,
956
- hostedClaimsStorageKeyPrefix: config.hostedClaimsStorageKeyPrefix || DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX
957
- };
958
- const fetchImpl = resolveFetch(config.fetch);
959
- const publicHost = resolveSagepilotHost(config.host);
960
- this.widgetHost = normalizeHost(config.widgetHost || DEFAULT_WIDGET_HOST);
961
- this.apiHost = resolveCustomerApiHost(config.apiHost, publicHost);
962
- this.workspaceId = workspaceId;
963
- this.channelId = channelId;
964
- this.http = new SagepilotHttpClient({
965
- fetch: fetchImpl,
966
- headers: config.headers
967
- });
968
- this.sessionManager = new SagepilotSessionManager(
969
- new SagepilotTokenManager(this.channelId, config.tokenStorage ?? createMemoryTokenStorage())
970
- );
967
+ const generation = ++this.runtimeGeneration;
968
+ this.configuring = true;
971
969
  try {
970
+ this.runtimeOptions = {
971
+ anonymousId: config.anonymousId,
972
+ behavior: config.behavior,
973
+ cacheStorage: config.cacheStorage,
974
+ deviceInfo: config.deviceInfo,
975
+ filePicker: config.filePicker,
976
+ fileStore: config.fileStore,
977
+ metadata: config.metadata,
978
+ presentation: config.presentation,
979
+ theme: config.theme,
980
+ hostedClaimsStorageKeyPrefix: config.hostedClaimsStorageKeyPrefix || DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX
981
+ };
982
+ const fetchImpl = resolveFetch(config.fetch);
983
+ const publicHost = resolveSagepilotHost(config.host);
984
+ this.widgetHost = normalizeHost(config.widgetHost || DEFAULT_WIDGET_HOST);
985
+ this.apiHost = resolveCustomerApiHost(config.apiHost, publicHost);
986
+ this.workspaceId = workspaceId;
987
+ this.channelId = channelId;
988
+ this.http = new SagepilotHttpClient({
989
+ fetch: fetchImpl,
990
+ headers: config.headers
991
+ });
992
+ this.sessionManager = new SagepilotSessionManager(
993
+ new SagepilotTokenManager(this.channelId, config.tokenStorage ?? createMemoryTokenStorage())
994
+ );
995
+ if (!isHttpUrl(this.widgetHost)) {
996
+ throw new SagepilotChatError("invalid_config", `${SDK_NAME} widgetHost must be an absolute HTTP(S) URL.`);
997
+ }
972
998
  const channel = await bootstrapChannel(this.requireHttp(), this.apiHost, this.channelId);
999
+ this.assertRuntimeGeneration(generation);
973
1000
  if (channel.workspace_id !== this.workspaceId) {
974
1001
  throw new SagepilotChatError(
975
1002
  "forbidden",
@@ -977,7 +1004,8 @@ var SagepilotReactNativeChat = class {
977
1004
  { details: { channel_id: this.channelId } }
978
1005
  );
979
1006
  }
980
- const session = await this.resolveCustomerSession(config);
1007
+ const session = await this.resolveCustomerSession(config, generation);
1008
+ this.assertRuntimeGeneration(generation);
981
1009
  this.channel = channel;
982
1010
  this.session = session;
983
1011
  if (config.push) this.legacyWidgetJwt = session.legacy_jwt ?? null;
@@ -1005,6 +1033,7 @@ var SagepilotReactNativeChat = class {
1005
1033
  onError: (error) => this.emitError(error)
1006
1034
  });
1007
1035
  await this.pushClient.start();
1036
+ this.assertRuntimeGeneration(generation);
1008
1037
  this.pushAppStateSubscription = import_react_native2.AppState.addEventListener("change", (state) => {
1009
1038
  if (state === "active") {
1010
1039
  void this.pushClient?.sync().catch((error) => this.emitError(error));
@@ -1012,17 +1041,25 @@ var SagepilotReactNativeChat = class {
1012
1041
  }
1013
1042
  });
1014
1043
  }
1015
- await this.restorePresentationFromCache();
1044
+ await this.restorePresentationFromCache(generation);
1045
+ this.assertRuntimeGeneration(generation);
1016
1046
  this.emitReady();
1047
+ this.assertRuntimeGeneration(generation);
1017
1048
  this.emitState();
1049
+ this.assertRuntimeGeneration(generation);
1018
1050
  if (config.behavior?.enableUnreadPolling ?? true) {
1019
1051
  this.startUnreadPolling(config.behavior?.unreadPollIntervalMs);
1020
1052
  }
1021
1053
  return { channel, session: toPublicSessionState(session) };
1022
1054
  } catch (error) {
1023
- this.resetRuntimeState();
1024
- this.emitError(error);
1055
+ if (generation === this.runtimeGeneration) {
1056
+ this.resetRuntimeState();
1057
+ this.emitError(error);
1058
+ this.emitState();
1059
+ }
1025
1060
  throw error;
1061
+ } finally {
1062
+ if (generation === this.runtimeGeneration) this.configuring = false;
1026
1063
  }
1027
1064
  }
1028
1065
  async getSession() {
@@ -1377,8 +1414,10 @@ var SagepilotReactNativeChat = class {
1377
1414
  getConfig() {
1378
1415
  return this.runtimeOptions;
1379
1416
  }
1417
+ /** Returns no navigation target when the hosted runtime is incomplete or invalid. */
1380
1418
  getConversationUrl() {
1381
1419
  this.requireConfigured();
1420
+ if (!this.runtimeOptions || !this.channelId || !isHttpUrl(this.widgetHost)) return null;
1382
1421
  const session = this.requireSession();
1383
1422
  const path = this.hostedChatView.screen === "home" ? `/chat-widget/${encodeURIComponent(this.channelId)}` : `/chat-widget/${encodeURIComponent(this.channelId)}/conversations`;
1384
1423
  const url = new URL(`${this.widgetHost}${path}`);
@@ -1694,9 +1733,11 @@ var SagepilotReactNativeChat = class {
1694
1733
  }
1695
1734
  return this.runtimeOptions;
1696
1735
  }
1697
- async resolveCustomerSession(config) {
1736
+ /** Restores a session only while the configuration that requested it is still active. */
1737
+ async resolveCustomerSession(config, generation) {
1698
1738
  const sessionManager = this.requireSessionManager();
1699
1739
  const storedSession = await sessionManager.hydrate();
1740
+ this.assertRuntimeGeneration(generation);
1700
1741
  if (storedSession?.session_id && storedSession.session_token) {
1701
1742
  try {
1702
1743
  const liveSession = await getSession(
@@ -1705,25 +1746,31 @@ var SagepilotReactNativeChat = class {
1705
1746
  storedSession.session_id,
1706
1747
  sessionManager.getAuthorizationHeader(storedSession.session_token)
1707
1748
  );
1749
+ this.assertRuntimeGeneration(generation);
1708
1750
  const session = await sessionManager.setSession({
1709
1751
  ...storedSession,
1710
1752
  customer_id: liveSession.customer_id,
1711
1753
  conversation_id: liveSession.conversation_id,
1712
1754
  authenticated: liveSession.authenticated ?? storedSession.authenticated ?? false
1713
1755
  });
1756
+ this.assertRuntimeGeneration(generation);
1714
1757
  return {
1715
1758
  ...liveSession,
1716
1759
  session_token: session.session_token
1717
1760
  };
1718
1761
  } catch {
1762
+ this.assertRuntimeGeneration(generation);
1719
1763
  await sessionManager.clearSession();
1764
+ this.assertRuntimeGeneration(generation);
1720
1765
  }
1721
1766
  }
1722
- return this.createCustomerSession(config);
1767
+ return this.createCustomerSession(config, generation);
1723
1768
  }
1724
- async createCustomerSession(config) {
1769
+ /** Creates and saves a session without allowing stale work to adopt a newer runtime. */
1770
+ async createCustomerSession(config, generation = this.runtimeGeneration) {
1725
1771
  const sessionManager = this.requireSessionManager();
1726
1772
  const deviceInfo = await resolveDeviceInfo(config.deviceInfo);
1773
+ this.assertRuntimeGeneration(generation);
1727
1774
  const session = await createSession(
1728
1775
  this.requireHttp(),
1729
1776
  this.apiHost,
@@ -1739,7 +1786,9 @@ var SagepilotReactNativeChat = class {
1739
1786
  }
1740
1787
  }
1741
1788
  );
1789
+ this.assertRuntimeGeneration(generation);
1742
1790
  await sessionManager.setSession(session);
1791
+ this.assertRuntimeGeneration(generation);
1743
1792
  return session;
1744
1793
  }
1745
1794
  getHostedClaimsStorageKey() {
@@ -1780,7 +1829,17 @@ var SagepilotReactNativeChat = class {
1780
1829
  this.setUnreadCount(response.unread_count || 0);
1781
1830
  return this.unreadCount;
1782
1831
  }
1832
+ /** Rejects continuations belonging to a destroyed or superseded runtime. */
1833
+ assertRuntimeGeneration(generation) {
1834
+ if (generation !== this.runtimeGeneration) {
1835
+ throw new SagepilotChatError("not_initialized", `${SDK_NAME} configuration was cancelled because its runtime was destroyed.`);
1836
+ }
1837
+ }
1838
+ /** Invalidates pending initialization before releasing listeners, timers and runtime state. */
1783
1839
  resetRuntimeState() {
1840
+ this.runtimeGeneration++;
1841
+ this.configuring = false;
1842
+ this.stopUnreadPolling();
1784
1843
  this.pushClient?.stop();
1785
1844
  this.pushClient = null;
1786
1845
  this.pushChannelId = null;
@@ -1880,10 +1939,11 @@ var SagepilotReactNativeChat = class {
1880
1939
  void cache.set(PRESENTATION_CACHE_KEY, state).catch(() => void 0);
1881
1940
  }
1882
1941
  /** Restores Android presentation state after configure without resetting the hosted route to Home. */
1883
- async restorePresentationFromCache() {
1942
+ async restorePresentationFromCache(generation) {
1884
1943
  const cache = this.getPresentationCache();
1885
1944
  if (!cache || import_react_native2.Platform.OS !== "android") return;
1886
1945
  const persisted = await cache.get(PRESENTATION_CACHE_KEY).catch(() => null);
1946
+ this.assertRuntimeGeneration(generation);
1887
1947
  if (persisted?.cleanShutdown) return;
1888
1948
  if (!isFreshPresentationState(persisted?.updatedAt)) return;
1889
1949
  if (!persisted?.presented) return;
@@ -2416,14 +2476,16 @@ var SagepilotInsetsViewNativeComponent_default = (0, import_codegenNativeCompone
2416
2476
 
2417
2477
  // src/ui/SagepilotChatProvider.ts
2418
2478
  function readPresentationState() {
2479
+ const config = internalSagepilotChat.getConfig();
2480
+ const configured = internalSagepilotChat.getState().configured && config !== null;
2419
2481
  return {
2420
2482
  isPresented: internalSagepilotChat.isPresented(),
2421
- configured: internalSagepilotChat.getState().configured,
2422
- conversationUrl: internalSagepilotChat.getState().configured ? internalSagepilotChat.getConversationUrl() : null,
2423
- preloadUrl: internalSagepilotChat.getState().configured ? internalSagepilotChat.getPreloadUrl() : null,
2424
- shouldPreload: internalSagepilotChat.getConfig()?.behavior?.preloadWebView ?? true,
2483
+ configured,
2484
+ conversationUrl: configured ? internalSagepilotChat.getConversationUrl() : null,
2485
+ preloadUrl: configured ? internalSagepilotChat.getPreloadUrl() : null,
2486
+ shouldPreload: configured && (config?.behavior?.preloadWebView ?? true),
2425
2487
  hostedIdentityLogoutVersion: internalSagepilotChat.getHostedIdentityLogoutVersion(),
2426
- presentation: internalSagepilotChat.getConfig()?.presentation
2488
+ presentation: config?.presentation
2427
2489
  };
2428
2490
  }
2429
2491
  function getBridgeCapabilities() {
@@ -3139,6 +3201,8 @@ function SagepilotChatProvider({
3139
3201
  key: `sagepilot-preload-webview-${preloadWebViewKey}`,
3140
3202
  source: { uri: state.preloadUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
3141
3203
  style: styles.preloadWebview,
3204
+ containerStyle: styles.preloadWebview,
3205
+ renderError: () => null,
3142
3206
  injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
3143
3207
  onMessage: handleWebViewMessage,
3144
3208
  onShouldStartLoadWithRequest: handleShouldStartLoadWithRequest,
@@ -3283,6 +3347,7 @@ var styles = import_react_native4.StyleSheet.create({
3283
3347
  flex: 1
3284
3348
  },
3285
3349
  preloadWebview: {
3350
+ flex: 0,
3286
3351
  position: "absolute",
3287
3352
  width: 1,
3288
3353
  height: 1,
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { AppState as AppState2, Platform } from "react-native";
3
3
 
4
4
  // package.json
5
5
  var name = "@sagepilot-ai/react-native-sdk";
6
- var version = "0.4.3";
6
+ var version = "0.5.1";
7
7
 
8
8
  // src/core/config/constants.ts
9
9
  var SDK_NAME = name;
@@ -116,18 +116,26 @@ var SagepilotPush = class {
116
116
  if (this.started) return;
117
117
  this.started = true;
118
118
  const binding = await this.mutate(async (state) => state.binding);
119
+ if (this.stopped) return;
119
120
  const adapter = this.config.adapter;
120
121
  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
- storage: this.config.storage,
126
- owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
127
- customerId: this.context.customerId,
128
- upload: (event) => this.context.request("/push/events", "POST", event),
129
- onOpen: (message) => this.config.onOpen?.(message)
130
- }));
122
+ if (adapter.start) {
123
+ const unsubscribe = await adapter.start({
124
+ workspaceId: this.context.workspaceId,
125
+ channelId: this.context.channelId,
126
+ sdkVersion: SDK_VERSION,
127
+ storage: this.config.storage,
128
+ owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
129
+ customerId: this.context.customerId,
130
+ upload: (event) => this.context.request("/push/events", "POST", event),
131
+ onOpen: (message) => this.config.onOpen?.(message)
132
+ });
133
+ if (this.stopped) {
134
+ unsubscribe();
135
+ return;
136
+ }
137
+ this.subscriptions.push(unsubscribe);
138
+ }
131
139
  this.subscriptions.push(
132
140
  adapter.onTokenRefresh((token) => {
133
141
  void this.sync(token).catch(this.context.onError);
@@ -140,8 +148,10 @@ var SagepilotPush = class {
140
148
  })
141
149
  );
142
150
  const initial = await adapter.getInitialNotification();
151
+ if (this.stopped) return;
143
152
  if (initial) await this.handleOpened(initial);
144
153
  }
154
+ if (this.stopped) return;
145
155
  void this.sync().catch(this.context.onError);
146
156
  void this.flush().catch(this.context.onError);
147
157
  }
@@ -512,6 +522,14 @@ var SagepilotTokenManager = class {
512
522
  function normalizeHost(host = DEFAULT_HOST) {
513
523
  return host.replace(/\/+$/, "");
514
524
  }
525
+ function isHttpUrl(value) {
526
+ try {
527
+ const url = new URL(value);
528
+ return (url.protocol === "https:" || url.protocol === "http:") && Boolean(url.hostname);
529
+ } catch {
530
+ return false;
531
+ }
532
+ }
515
533
  function readRuntimeEnv(name2) {
516
534
  return globalThis.process?.env?.[name2]?.trim();
517
535
  }
@@ -860,6 +878,8 @@ var SagepilotReactNativeChat = class {
860
878
  this.identified = false;
861
879
  this.identifyPending = false;
862
880
  this.isConfigured = false;
881
+ this.configuring = false;
882
+ this.runtimeGeneration = 0;
863
883
  this.presented = false;
864
884
  this.hostedChatView = { screen: "home" };
865
885
  this.unreadCount = 0;
@@ -878,11 +898,12 @@ var SagepilotReactNativeChat = class {
878
898
  if (!this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push with durable storage before using the push API.");
879
899
  return this.pushClient;
880
900
  }
901
+ /** Initializes one runtime; destruction invalidates all unfinished work from this attempt. */
881
902
  async configure(config) {
882
- if (this.isConfigured) {
903
+ if (this.isConfigured || this.configuring) {
883
904
  throw new SagepilotChatError(
884
905
  "already_initialized",
885
- `${SDK_NAME} is already configured. Call destroy() before configuring again.`
906
+ `${SDK_NAME} is already configured or configuring. Call destroy() before configuring again.`
886
907
  );
887
908
  }
888
909
  if (!config?.key || typeof config.key !== "string") {
@@ -892,33 +913,39 @@ var SagepilotReactNativeChat = class {
892
913
  );
893
914
  }
894
915
  const { workspaceId, channelId } = parseKey(config.key);
895
- this.runtimeOptions = {
896
- anonymousId: config.anonymousId,
897
- behavior: config.behavior,
898
- cacheStorage: config.cacheStorage,
899
- deviceInfo: config.deviceInfo,
900
- filePicker: config.filePicker,
901
- fileStore: config.fileStore,
902
- metadata: config.metadata,
903
- presentation: config.presentation,
904
- theme: config.theme,
905
- hostedClaimsStorageKeyPrefix: config.hostedClaimsStorageKeyPrefix || DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX
906
- };
907
- const fetchImpl = resolveFetch(config.fetch);
908
- const publicHost = resolveSagepilotHost(config.host);
909
- this.widgetHost = normalizeHost(config.widgetHost || DEFAULT_WIDGET_HOST);
910
- this.apiHost = resolveCustomerApiHost(config.apiHost, publicHost);
911
- this.workspaceId = workspaceId;
912
- this.channelId = channelId;
913
- this.http = new SagepilotHttpClient({
914
- fetch: fetchImpl,
915
- headers: config.headers
916
- });
917
- this.sessionManager = new SagepilotSessionManager(
918
- new SagepilotTokenManager(this.channelId, config.tokenStorage ?? createMemoryTokenStorage())
919
- );
916
+ const generation = ++this.runtimeGeneration;
917
+ this.configuring = true;
920
918
  try {
919
+ this.runtimeOptions = {
920
+ anonymousId: config.anonymousId,
921
+ behavior: config.behavior,
922
+ cacheStorage: config.cacheStorage,
923
+ deviceInfo: config.deviceInfo,
924
+ filePicker: config.filePicker,
925
+ fileStore: config.fileStore,
926
+ metadata: config.metadata,
927
+ presentation: config.presentation,
928
+ theme: config.theme,
929
+ hostedClaimsStorageKeyPrefix: config.hostedClaimsStorageKeyPrefix || DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX
930
+ };
931
+ const fetchImpl = resolveFetch(config.fetch);
932
+ const publicHost = resolveSagepilotHost(config.host);
933
+ this.widgetHost = normalizeHost(config.widgetHost || DEFAULT_WIDGET_HOST);
934
+ this.apiHost = resolveCustomerApiHost(config.apiHost, publicHost);
935
+ this.workspaceId = workspaceId;
936
+ this.channelId = channelId;
937
+ this.http = new SagepilotHttpClient({
938
+ fetch: fetchImpl,
939
+ headers: config.headers
940
+ });
941
+ this.sessionManager = new SagepilotSessionManager(
942
+ new SagepilotTokenManager(this.channelId, config.tokenStorage ?? createMemoryTokenStorage())
943
+ );
944
+ if (!isHttpUrl(this.widgetHost)) {
945
+ throw new SagepilotChatError("invalid_config", `${SDK_NAME} widgetHost must be an absolute HTTP(S) URL.`);
946
+ }
921
947
  const channel = await bootstrapChannel(this.requireHttp(), this.apiHost, this.channelId);
948
+ this.assertRuntimeGeneration(generation);
922
949
  if (channel.workspace_id !== this.workspaceId) {
923
950
  throw new SagepilotChatError(
924
951
  "forbidden",
@@ -926,7 +953,8 @@ var SagepilotReactNativeChat = class {
926
953
  { details: { channel_id: this.channelId } }
927
954
  );
928
955
  }
929
- const session = await this.resolveCustomerSession(config);
956
+ const session = await this.resolveCustomerSession(config, generation);
957
+ this.assertRuntimeGeneration(generation);
930
958
  this.channel = channel;
931
959
  this.session = session;
932
960
  if (config.push) this.legacyWidgetJwt = session.legacy_jwt ?? null;
@@ -954,6 +982,7 @@ var SagepilotReactNativeChat = class {
954
982
  onError: (error) => this.emitError(error)
955
983
  });
956
984
  await this.pushClient.start();
985
+ this.assertRuntimeGeneration(generation);
957
986
  this.pushAppStateSubscription = AppState2.addEventListener("change", (state) => {
958
987
  if (state === "active") {
959
988
  void this.pushClient?.sync().catch((error) => this.emitError(error));
@@ -961,17 +990,25 @@ var SagepilotReactNativeChat = class {
961
990
  }
962
991
  });
963
992
  }
964
- await this.restorePresentationFromCache();
993
+ await this.restorePresentationFromCache(generation);
994
+ this.assertRuntimeGeneration(generation);
965
995
  this.emitReady();
996
+ this.assertRuntimeGeneration(generation);
966
997
  this.emitState();
998
+ this.assertRuntimeGeneration(generation);
967
999
  if (config.behavior?.enableUnreadPolling ?? true) {
968
1000
  this.startUnreadPolling(config.behavior?.unreadPollIntervalMs);
969
1001
  }
970
1002
  return { channel, session: toPublicSessionState(session) };
971
1003
  } catch (error) {
972
- this.resetRuntimeState();
973
- this.emitError(error);
1004
+ if (generation === this.runtimeGeneration) {
1005
+ this.resetRuntimeState();
1006
+ this.emitError(error);
1007
+ this.emitState();
1008
+ }
974
1009
  throw error;
1010
+ } finally {
1011
+ if (generation === this.runtimeGeneration) this.configuring = false;
975
1012
  }
976
1013
  }
977
1014
  async getSession() {
@@ -1326,8 +1363,10 @@ var SagepilotReactNativeChat = class {
1326
1363
  getConfig() {
1327
1364
  return this.runtimeOptions;
1328
1365
  }
1366
+ /** Returns no navigation target when the hosted runtime is incomplete or invalid. */
1329
1367
  getConversationUrl() {
1330
1368
  this.requireConfigured();
1369
+ if (!this.runtimeOptions || !this.channelId || !isHttpUrl(this.widgetHost)) return null;
1331
1370
  const session = this.requireSession();
1332
1371
  const path = this.hostedChatView.screen === "home" ? `/chat-widget/${encodeURIComponent(this.channelId)}` : `/chat-widget/${encodeURIComponent(this.channelId)}/conversations`;
1333
1372
  const url = new URL(`${this.widgetHost}${path}`);
@@ -1643,9 +1682,11 @@ var SagepilotReactNativeChat = class {
1643
1682
  }
1644
1683
  return this.runtimeOptions;
1645
1684
  }
1646
- async resolveCustomerSession(config) {
1685
+ /** Restores a session only while the configuration that requested it is still active. */
1686
+ async resolveCustomerSession(config, generation) {
1647
1687
  const sessionManager = this.requireSessionManager();
1648
1688
  const storedSession = await sessionManager.hydrate();
1689
+ this.assertRuntimeGeneration(generation);
1649
1690
  if (storedSession?.session_id && storedSession.session_token) {
1650
1691
  try {
1651
1692
  const liveSession = await getSession(
@@ -1654,25 +1695,31 @@ var SagepilotReactNativeChat = class {
1654
1695
  storedSession.session_id,
1655
1696
  sessionManager.getAuthorizationHeader(storedSession.session_token)
1656
1697
  );
1698
+ this.assertRuntimeGeneration(generation);
1657
1699
  const session = await sessionManager.setSession({
1658
1700
  ...storedSession,
1659
1701
  customer_id: liveSession.customer_id,
1660
1702
  conversation_id: liveSession.conversation_id,
1661
1703
  authenticated: liveSession.authenticated ?? storedSession.authenticated ?? false
1662
1704
  });
1705
+ this.assertRuntimeGeneration(generation);
1663
1706
  return {
1664
1707
  ...liveSession,
1665
1708
  session_token: session.session_token
1666
1709
  };
1667
1710
  } catch {
1711
+ this.assertRuntimeGeneration(generation);
1668
1712
  await sessionManager.clearSession();
1713
+ this.assertRuntimeGeneration(generation);
1669
1714
  }
1670
1715
  }
1671
- return this.createCustomerSession(config);
1716
+ return this.createCustomerSession(config, generation);
1672
1717
  }
1673
- async createCustomerSession(config) {
1718
+ /** Creates and saves a session without allowing stale work to adopt a newer runtime. */
1719
+ async createCustomerSession(config, generation = this.runtimeGeneration) {
1674
1720
  const sessionManager = this.requireSessionManager();
1675
1721
  const deviceInfo = await resolveDeviceInfo(config.deviceInfo);
1722
+ this.assertRuntimeGeneration(generation);
1676
1723
  const session = await createSession(
1677
1724
  this.requireHttp(),
1678
1725
  this.apiHost,
@@ -1688,7 +1735,9 @@ var SagepilotReactNativeChat = class {
1688
1735
  }
1689
1736
  }
1690
1737
  );
1738
+ this.assertRuntimeGeneration(generation);
1691
1739
  await sessionManager.setSession(session);
1740
+ this.assertRuntimeGeneration(generation);
1692
1741
  return session;
1693
1742
  }
1694
1743
  getHostedClaimsStorageKey() {
@@ -1729,7 +1778,17 @@ var SagepilotReactNativeChat = class {
1729
1778
  this.setUnreadCount(response.unread_count || 0);
1730
1779
  return this.unreadCount;
1731
1780
  }
1781
+ /** Rejects continuations belonging to a destroyed or superseded runtime. */
1782
+ assertRuntimeGeneration(generation) {
1783
+ if (generation !== this.runtimeGeneration) {
1784
+ throw new SagepilotChatError("not_initialized", `${SDK_NAME} configuration was cancelled because its runtime was destroyed.`);
1785
+ }
1786
+ }
1787
+ /** Invalidates pending initialization before releasing listeners, timers and runtime state. */
1732
1788
  resetRuntimeState() {
1789
+ this.runtimeGeneration++;
1790
+ this.configuring = false;
1791
+ this.stopUnreadPolling();
1733
1792
  this.pushClient?.stop();
1734
1793
  this.pushClient = null;
1735
1794
  this.pushChannelId = null;
@@ -1829,10 +1888,11 @@ var SagepilotReactNativeChat = class {
1829
1888
  void cache.set(PRESENTATION_CACHE_KEY, state).catch(() => void 0);
1830
1889
  }
1831
1890
  /** Restores Android presentation state after configure without resetting the hosted route to Home. */
1832
- async restorePresentationFromCache() {
1891
+ async restorePresentationFromCache(generation) {
1833
1892
  const cache = this.getPresentationCache();
1834
1893
  if (!cache || Platform.OS !== "android") return;
1835
1894
  const persisted = await cache.get(PRESENTATION_CACHE_KEY).catch(() => null);
1895
+ this.assertRuntimeGeneration(generation);
1836
1896
  if (persisted?.cleanShutdown) return;
1837
1897
  if (!isFreshPresentationState(persisted?.updatedAt)) return;
1838
1898
  if (!persisted?.presented) return;
@@ -2377,14 +2437,16 @@ var SagepilotInsetsViewNativeComponent_default = codegenNativeComponent("Sagepil
2377
2437
 
2378
2438
  // src/ui/SagepilotChatProvider.ts
2379
2439
  function readPresentationState() {
2440
+ const config = internalSagepilotChat.getConfig();
2441
+ const configured = internalSagepilotChat.getState().configured && config !== null;
2380
2442
  return {
2381
2443
  isPresented: internalSagepilotChat.isPresented(),
2382
- configured: internalSagepilotChat.getState().configured,
2383
- conversationUrl: internalSagepilotChat.getState().configured ? internalSagepilotChat.getConversationUrl() : null,
2384
- preloadUrl: internalSagepilotChat.getState().configured ? internalSagepilotChat.getPreloadUrl() : null,
2385
- shouldPreload: internalSagepilotChat.getConfig()?.behavior?.preloadWebView ?? true,
2444
+ configured,
2445
+ conversationUrl: configured ? internalSagepilotChat.getConversationUrl() : null,
2446
+ preloadUrl: configured ? internalSagepilotChat.getPreloadUrl() : null,
2447
+ shouldPreload: configured && (config?.behavior?.preloadWebView ?? true),
2386
2448
  hostedIdentityLogoutVersion: internalSagepilotChat.getHostedIdentityLogoutVersion(),
2387
- presentation: internalSagepilotChat.getConfig()?.presentation
2449
+ presentation: config?.presentation
2388
2450
  };
2389
2451
  }
2390
2452
  function getBridgeCapabilities() {
@@ -3100,6 +3162,8 @@ function SagepilotChatProvider({
3100
3162
  key: `sagepilot-preload-webview-${preloadWebViewKey}`,
3101
3163
  source: { uri: state.preloadUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
3102
3164
  style: styles.preloadWebview,
3165
+ containerStyle: styles.preloadWebview,
3166
+ renderError: () => null,
3103
3167
  injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
3104
3168
  onMessage: handleWebViewMessage,
3105
3169
  onShouldStartLoadWithRequest: handleShouldStartLoadWithRequest,
@@ -3244,6 +3308,7 @@ var styles = StyleSheet.create({
3244
3308
  flex: 1
3245
3309
  },
3246
3310
  preloadWebview: {
3311
+ flex: 0,
3247
3312
  position: "absolute",
3248
3313
  width: 1,
3249
3314
  height: 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagepilot-ai/react-native-sdk",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "description": "Sagepilot AI React Native chat SDK",
5
5
  "keywords": [
6
6
  "sagepilot",