@sagepilot-ai/react-native-sdk 0.3.6 → 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/README.md +41 -0
- package/dist/index.d.mts +208 -1
- package/dist/index.d.ts +208 -1
- package/dist/index.js +668 -105
- package/dist/index.mjs +612 -51
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -6,8 +6,8 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
8
|
var __export = (target, all) => {
|
|
9
|
-
for (var
|
|
10
|
-
__defProp(target,
|
|
9
|
+
for (var name2 in all)
|
|
10
|
+
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
11
11
|
};
|
|
12
12
|
var __copyProps = (to, from, except, desc) => {
|
|
13
13
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -33,11 +33,13 @@ __export(index_exports, {
|
|
|
33
33
|
SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION: () => SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION,
|
|
34
34
|
SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES: () => SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES,
|
|
35
35
|
SAGEPILOT_DEFAULT_IMAGE_QUALITY: () => SAGEPILOT_DEFAULT_IMAGE_QUALITY,
|
|
36
|
+
SagepilotBrandPush: () => SagepilotBrandPush,
|
|
36
37
|
SagepilotChat: () => SagepilotChat,
|
|
37
38
|
SagepilotChatError: () => SagepilotChatError,
|
|
38
39
|
SagepilotChatProvider: () => SagepilotChatProvider,
|
|
39
40
|
SagepilotFilePickerError: () => SagepilotFilePickerError,
|
|
40
41
|
createAsyncStorageCacheStorage: () => createAsyncStorageCacheStorage,
|
|
42
|
+
createFirebasePushAdapter: () => createFirebasePushAdapter,
|
|
41
43
|
createKeychainTokenStorage: () => createKeychainTokenStorage,
|
|
42
44
|
createSagepilotFilePicker: () => createSagepilotFilePicker,
|
|
43
45
|
createSagepilotFileStore: () => createSagepilotFileStore,
|
|
@@ -48,6 +50,22 @@ __export(index_exports, {
|
|
|
48
50
|
module.exports = __toCommonJS(index_exports);
|
|
49
51
|
|
|
50
52
|
// src/public/SdkClient.ts
|
|
53
|
+
var import_react_native2 = require("react-native");
|
|
54
|
+
|
|
55
|
+
// package.json
|
|
56
|
+
var name = "@sagepilot-ai/react-native-sdk";
|
|
57
|
+
var version = "0.4.0";
|
|
58
|
+
|
|
59
|
+
// src/core/config/constants.ts
|
|
60
|
+
var SDK_NAME = name;
|
|
61
|
+
var SDK_VERSION = version;
|
|
62
|
+
var DEFAULT_HOST = "https://app.sagepilot.ai";
|
|
63
|
+
var DEFAULT_WIDGET_HOST = "https://app.sagepilot.ai";
|
|
64
|
+
var CUSTOMER_API_PREFIX = "/customer-api/v1";
|
|
65
|
+
var DEFAULT_UNREAD_POLL_INTERVAL_MS = 3e4;
|
|
66
|
+
var DEFAULT_HOSTED_CLAIMS_STORAGE_KEY_PREFIX = "sg_chat_claims";
|
|
67
|
+
|
|
68
|
+
// src/push.ts
|
|
51
69
|
var import_react_native = require("react-native");
|
|
52
70
|
|
|
53
71
|
// src/core/errors/SagepilotChatError.ts
|
|
@@ -65,14 +83,335 @@ var SagepilotChatError = class extends Error {
|
|
|
65
83
|
}
|
|
66
84
|
};
|
|
67
85
|
|
|
68
|
-
// src/core/
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
86
|
+
// src/core/storage/cache.ts
|
|
87
|
+
function createAsyncStorageCacheStorage(asyncStorage) {
|
|
88
|
+
return {
|
|
89
|
+
getItem: (key) => asyncStorage.getItem(key),
|
|
90
|
+
setItem: (key, value) => asyncStorage.setItem(key, value),
|
|
91
|
+
removeItem: (key) => asyncStorage.removeItem(key)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function createJsonCache(storage, namespace, strict = false) {
|
|
95
|
+
return {
|
|
96
|
+
async get(key) {
|
|
97
|
+
const value = await storage.getItem(`${namespace}:${key}`);
|
|
98
|
+
if (!value) return null;
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(value);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (strict) throw error;
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
async set(key, value) {
|
|
107
|
+
await storage.setItem(`${namespace}:${key}`, JSON.stringify(value));
|
|
108
|
+
},
|
|
109
|
+
async remove(key) {
|
|
110
|
+
await storage.removeItem(`${namespace}:${key}`);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// src/push.ts
|
|
116
|
+
var INSTALLATION_ID = /^\S{1,255}$/;
|
|
117
|
+
var MAX_EVENTS = 200;
|
|
118
|
+
var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
119
|
+
function createId() {
|
|
120
|
+
return "10000000-1000-4000-8000-100000000000".replace(
|
|
121
|
+
/[018]/g,
|
|
122
|
+
(value) => (Number(value) ^ Math.floor(Math.random() * 16) >> Number(value) / 4).toString(16)
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
function eventKey(event) {
|
|
126
|
+
return JSON.stringify([event.message_id, event.endpoint_id, event.event_type, ["action", "conversion"].includes(event.event_type) ? event.action_id ?? "" : ""]);
|
|
127
|
+
}
|
|
128
|
+
var SagepilotPush = class {
|
|
129
|
+
/** Reuses a channel-specific durable cache and the SDK's authenticated request gateway. */
|
|
130
|
+
constructor(config, context) {
|
|
131
|
+
this.config = config;
|
|
132
|
+
this.context = context;
|
|
133
|
+
this.pending = Promise.resolve();
|
|
134
|
+
this.paused = false;
|
|
135
|
+
this.stopped = false;
|
|
136
|
+
this.started = false;
|
|
137
|
+
this.flushPromise = null;
|
|
138
|
+
this.retryTimer = null;
|
|
139
|
+
this.retryAttempt = 0;
|
|
140
|
+
this.subscriptions = [];
|
|
141
|
+
if (config.installationId !== void 0 && !INSTALLATION_ID.test(config.installationId)) {
|
|
142
|
+
throw new SagepilotChatError("invalid_config", "Push installationId must contain 1\u2013255 non-whitespace characters.");
|
|
143
|
+
}
|
|
144
|
+
this.cache = createJsonCache(config.storage, `sagepilot_push:${context.workspaceId}:${context.channelId}`, true);
|
|
145
|
+
}
|
|
146
|
+
/** Serializes state changes so registration, revocation and outbox writes cannot overwrite one another. */
|
|
147
|
+
mutate(operation) {
|
|
148
|
+
const next = this.pending.then(async () => {
|
|
149
|
+
if (this.stopped) throw new Error("Push has been stopped. Configure the SDK again.");
|
|
150
|
+
const saved = await this.cache.get("state");
|
|
151
|
+
if (this.stopped) throw new Error("Push has been stopped.");
|
|
152
|
+
if (saved && (!INSTALLATION_ID.test(saved.installationId) || !Array.isArray(saved.outbox) || !Array.isArray(saved.recent))) {
|
|
153
|
+
throw new Error("Invalid persisted push state; refusing to discard a possible device binding.");
|
|
154
|
+
}
|
|
155
|
+
if (saved && this.config.installationId && saved.installationId !== this.config.installationId) {
|
|
156
|
+
throw new Error("Reuse the persisted installationId; revoke and clear push storage before replacing it.");
|
|
157
|
+
}
|
|
158
|
+
const state = saved ?? { installationId: this.config.installationId || createId(), outbox: [], recent: [] };
|
|
159
|
+
if (!saved) await this.cache.set("state", state);
|
|
160
|
+
return operation(state);
|
|
161
|
+
});
|
|
162
|
+
this.pending = next.catch(() => void 0);
|
|
163
|
+
return next;
|
|
164
|
+
}
|
|
165
|
+
/** Starts optional native listeners without prompting for notification permission. */
|
|
166
|
+
async start() {
|
|
167
|
+
if (this.started) return;
|
|
168
|
+
this.started = true;
|
|
169
|
+
const binding = await this.mutate(async (state) => state.binding);
|
|
170
|
+
const adapter = this.config.adapter;
|
|
171
|
+
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
|
+
owner: binding?.endpointId && binding.customerId === this.context.customerId() ? { customerId: binding.customerId, endpointId: binding.endpointId } : null,
|
|
177
|
+
customerId: this.context.customerId,
|
|
178
|
+
upload: (event) => this.context.request("/push/events", "POST", event),
|
|
179
|
+
onOpen: (message) => this.config.onOpen?.(message)
|
|
180
|
+
}));
|
|
181
|
+
this.subscriptions.push(
|
|
182
|
+
adapter.onTokenRefresh((token) => {
|
|
183
|
+
void this.sync(token).catch(this.context.onError);
|
|
184
|
+
}),
|
|
185
|
+
adapter.onMessage((message) => {
|
|
186
|
+
void this.handleReceived(message, true).catch(this.context.onError);
|
|
187
|
+
}),
|
|
188
|
+
adapter.onOpened((message) => {
|
|
189
|
+
void this.handleOpened(message).catch(this.context.onError);
|
|
190
|
+
})
|
|
191
|
+
);
|
|
192
|
+
const initial = await adapter.getInitialNotification();
|
|
193
|
+
if (initial) await this.handleOpened(initial);
|
|
194
|
+
}
|
|
195
|
+
void this.sync().catch(this.context.onError);
|
|
196
|
+
void this.flush().catch(this.context.onError);
|
|
197
|
+
}
|
|
198
|
+
/** Requests native permission only following an explicit host action, then resynchronizes the token. */
|
|
199
|
+
async requestPermission() {
|
|
200
|
+
if (!this.config.adapter) throw new Error("Configure a push adapter to request native permission.");
|
|
201
|
+
const permission = await this.config.adapter.requestPermission();
|
|
202
|
+
await this.sync();
|
|
203
|
+
return permission;
|
|
204
|
+
}
|
|
205
|
+
/** Refreshes an existing authorized installation after identity, token or permission changes. */
|
|
206
|
+
async sync(token) {
|
|
207
|
+
if (this.paused || this.stopped || !this.context.customerId() || !this.config.adapter) return;
|
|
208
|
+
const adapter = this.config.adapter;
|
|
209
|
+
const permission = await adapter.getPermission();
|
|
210
|
+
if (permission !== "authorized" && permission !== "provisional") {
|
|
211
|
+
await this.unregister();
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
await this.register({ token: token ?? await adapter.getToken(), provider: adapter.provider, permission, app_id: this.config.appId });
|
|
215
|
+
}
|
|
216
|
+
/** Registers a native token only for the current identified customer; the server verifies identity. */
|
|
217
|
+
async register(input) {
|
|
218
|
+
if (!input.token.trim() || !["authorized", "provisional"].includes(input.permission)) {
|
|
219
|
+
throw new SagepilotChatError("invalid_request", "Push registration requires a token and notification permission.");
|
|
220
|
+
}
|
|
221
|
+
return this.mutate(async (state) => {
|
|
222
|
+
const customerId = this.context.customerId();
|
|
223
|
+
if (this.paused || !customerId) throw new SagepilotChatError("forbidden", "Identify a verified customer before registering push.");
|
|
224
|
+
if (state.binding && state.binding.customerId !== customerId) {
|
|
225
|
+
throw new SagepilotChatError("forbidden", "Revoke the previous customer's push binding before switching accounts.");
|
|
226
|
+
}
|
|
227
|
+
const previousBinding = state.binding;
|
|
228
|
+
state.binding = { ...state.binding, customerId };
|
|
229
|
+
await this.cache.set("state", state);
|
|
230
|
+
let result;
|
|
231
|
+
try {
|
|
232
|
+
result = await this.context.request("/push/endpoints", "POST", {
|
|
233
|
+
token: input.token,
|
|
234
|
+
provider: input.provider,
|
|
235
|
+
permission: input.permission,
|
|
236
|
+
app_id: input.app_id ?? this.config.appId,
|
|
237
|
+
installation_id: state.installationId,
|
|
238
|
+
platform: this.context.platform,
|
|
239
|
+
metadata: {
|
|
240
|
+
sdk: SDK_NAME,
|
|
241
|
+
sdk_version: SDK_VERSION,
|
|
242
|
+
app_version: this.config.appVersion,
|
|
243
|
+
capabilities: input.capabilities ?? this.config.adapter?.capabilities ?? { version: 1, display_modes: ["provider"], media: [] }
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (!this.stopped && error instanceof SagepilotChatError && [400, 401, 403, 422].includes(error.status ?? 0)) {
|
|
248
|
+
state.binding = previousBinding;
|
|
249
|
+
await this.cache.set("state", state);
|
|
250
|
+
}
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
253
|
+
if (!result.endpoint_id) throw new Error("Push registration returned no endpoint_id.");
|
|
254
|
+
if (this.stopped) return result;
|
|
255
|
+
state.binding = { customerId, endpointId: result.endpoint_id };
|
|
256
|
+
await this.cache.set("state", state);
|
|
257
|
+
await this.config.adapter?.setOwner?.({ customerId, endpointId: result.endpoint_id });
|
|
258
|
+
return result;
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
/** Revokes this installation before credentials are discarded; failures retain the binding for retry. */
|
|
262
|
+
async unregister() {
|
|
263
|
+
await this.mutate(async (state) => {
|
|
264
|
+
if (!state.binding) {
|
|
265
|
+
await this.config.adapter?.setOwner?.(null);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
await this.context.request("/push/endpoints", "DELETE", { installation_id: state.installationId });
|
|
269
|
+
if (this.stopped) return;
|
|
270
|
+
delete state.binding;
|
|
271
|
+
await this.cache.set("state", state);
|
|
272
|
+
await this.config.adapter?.setOwner?.(null);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
/** Pauses refresh callbacks and revokes the installation before logout or identity replacement. */
|
|
276
|
+
async pauseAndRevoke() {
|
|
277
|
+
this.paused = true;
|
|
278
|
+
await this.unregister();
|
|
279
|
+
}
|
|
280
|
+
/** Allows token refresh again after the identity transition has finished. */
|
|
281
|
+
resume() {
|
|
282
|
+
this.paused = false;
|
|
283
|
+
void this.sync().catch(this.context.onError);
|
|
284
|
+
void this.flush().catch(this.context.onError);
|
|
285
|
+
}
|
|
286
|
+
/** Reads notification preferences for the current verified customer. */
|
|
287
|
+
getPreferences() {
|
|
288
|
+
return this.context.request("/push/preferences", "GET");
|
|
289
|
+
}
|
|
290
|
+
/** Saves customer consent independently of the device's notification permission. */
|
|
291
|
+
setPreferences(preferences) {
|
|
292
|
+
return this.context.request("/push/preferences", "PUT", preferences);
|
|
293
|
+
}
|
|
294
|
+
/** Persists actual callback receipt and presents only foreground messages when the host opted in. */
|
|
295
|
+
async handleReceived(message, foreground = false) {
|
|
296
|
+
const recorded = await this.track("received", message);
|
|
297
|
+
if (recorded && foreground && this.config.presentForeground) {
|
|
298
|
+
if (await this.track("presentation_requested", message)) {
|
|
299
|
+
try {
|
|
300
|
+
await this.config.presentForeground(message);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
await this.track("presentation_failed", message);
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return recorded;
|
|
308
|
+
}
|
|
309
|
+
/** Persists a real tap before invoking host navigation, including cold-start taps. */
|
|
310
|
+
async handleOpened(message) {
|
|
311
|
+
const recorded = await this.track("opened", message);
|
|
312
|
+
if (recorded && !this.config.adapter?.track) this.config.onOpen?.(message);
|
|
313
|
+
return recorded;
|
|
314
|
+
}
|
|
315
|
+
/** Records SDK engagement; reuse actionId for duplicate callbacks and distinct IDs for separate conversions. */
|
|
316
|
+
async track(type, message, metadata = {}, actionId) {
|
|
317
|
+
if (this.config.adapter?.track) return this.config.adapter.track(type, message, metadata, actionId);
|
|
318
|
+
const data = message.data;
|
|
319
|
+
if (this.context.brand && data?.sp_channel_id !== this.context.channelId) return false;
|
|
320
|
+
if (data?.sp_source_channel_id && data.sp_source_channel_id !== this.context.channelId) return false;
|
|
321
|
+
if (!data || data.sp_workspace_id !== this.context.workspaceId || !data.sp_message_id || !data.sp_endpoint_id || !data.sp_event_token) return false;
|
|
322
|
+
const event = {
|
|
323
|
+
event_id: createId(),
|
|
324
|
+
occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
325
|
+
sdk_version: SDK_VERSION,
|
|
326
|
+
event_type: type,
|
|
327
|
+
message_id: data.sp_message_id,
|
|
328
|
+
endpoint_id: data.sp_endpoint_id,
|
|
329
|
+
event_token: data.sp_event_token,
|
|
330
|
+
...actionId ? { action_id: actionId } : {},
|
|
331
|
+
metadata: {
|
|
332
|
+
platform: this.context.platform,
|
|
333
|
+
app_id: this.config.appId,
|
|
334
|
+
app_version: this.config.appVersion,
|
|
335
|
+
app_state: import_react_native.AppState.currentState ?? "unknown",
|
|
336
|
+
...metadata,
|
|
337
|
+
sdk: SDK_NAME,
|
|
338
|
+
sdk_version: SDK_VERSION
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
const recorded = await this.mutate(async (state) => {
|
|
342
|
+
const key = eventKey(event);
|
|
343
|
+
if (state.recent.includes(key) || state.outbox.some((item) => eventKey(item) === key)) return false;
|
|
344
|
+
if (state.outbox.length >= MAX_EVENTS) throw new Error("Push analytics outbox is full; retry after connectivity is restored.");
|
|
345
|
+
state.outbox.push(event);
|
|
346
|
+
await this.cache.set("state", state);
|
|
347
|
+
return true;
|
|
348
|
+
});
|
|
349
|
+
if (recorded) void this.flush().catch(this.context.onError);
|
|
350
|
+
return recorded;
|
|
351
|
+
}
|
|
352
|
+
/** Uploads preserved event metadata with the current request version and bounded exponential retries. */
|
|
353
|
+
async flush() {
|
|
354
|
+
if (this.stopped) return;
|
|
355
|
+
if (this.config.adapter?.flush) await this.config.adapter.flush();
|
|
356
|
+
if (this.flushPromise) return this.flushPromise;
|
|
357
|
+
this.flushPromise = (async () => {
|
|
358
|
+
while (!this.stopped) {
|
|
359
|
+
const event = await this.mutate(async (state) => state.outbox[0]);
|
|
360
|
+
if (!event) break;
|
|
361
|
+
if (Date.now() - Date.parse(event.occurred_at) > MAX_AGE_MS) {
|
|
362
|
+
this.context.onError(new Error(`Push event ${event.event_id} expired before upload.`));
|
|
363
|
+
} else {
|
|
364
|
+
try {
|
|
365
|
+
await this.context.request("/push/events", "POST", event);
|
|
366
|
+
} catch (error) {
|
|
367
|
+
const status = error instanceof SagepilotChatError ? error.status : void 0;
|
|
368
|
+
const terminalTokenError = status === 401 && error instanceof SagepilotChatError && error.details?.terminal === true;
|
|
369
|
+
if (!terminalTokenError && ![400, 403, 404, 410, 422].includes(status ?? 0)) throw error;
|
|
370
|
+
this.context.onError(error);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (this.stopped) return;
|
|
374
|
+
await this.mutate(async (state) => {
|
|
375
|
+
state.outbox = state.outbox.filter((queued) => queued.event_id !== event.event_id);
|
|
376
|
+
state.recent = [...state.recent, eventKey(event)].slice(-MAX_EVENTS);
|
|
377
|
+
await this.cache.set("state", state);
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
this.retryAttempt = 0;
|
|
381
|
+
})().catch((error) => {
|
|
382
|
+
if (!this.stopped && !this.retryTimer) {
|
|
383
|
+
this.retryTimer = setTimeout(() => {
|
|
384
|
+
this.retryTimer = null;
|
|
385
|
+
void this.flush().catch(this.context.onError);
|
|
386
|
+
}, Math.min(6e4, 1e3 * 2 ** Math.min(this.retryAttempt++, 6)));
|
|
387
|
+
}
|
|
388
|
+
throw error;
|
|
389
|
+
}).finally(() => {
|
|
390
|
+
this.flushPromise = null;
|
|
391
|
+
});
|
|
392
|
+
return this.flushPromise;
|
|
393
|
+
}
|
|
394
|
+
/** Removes listeners and timers without revoking an installation merely because its UI was destroyed. */
|
|
395
|
+
stop() {
|
|
396
|
+
this.stopped = true;
|
|
397
|
+
this.subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
398
|
+
this.subscriptions = [];
|
|
399
|
+
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
400
|
+
this.retryTimer = null;
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
function createFirebasePushAdapter(firebase, permissions) {
|
|
404
|
+
return {
|
|
405
|
+
provider: "fcm",
|
|
406
|
+
getToken: () => firebase.getToken(),
|
|
407
|
+
getPermission: () => permissions.getPermission(),
|
|
408
|
+
requestPermission: () => permissions.requestPermission(),
|
|
409
|
+
onTokenRefresh: (callback) => firebase.onTokenRefresh(callback),
|
|
410
|
+
onMessage: (callback) => firebase.onMessage(callback),
|
|
411
|
+
onOpened: (callback) => firebase.onNotificationOpenedApp(callback),
|
|
412
|
+
getInitialNotification: () => firebase.getInitialNotification()
|
|
413
|
+
};
|
|
414
|
+
}
|
|
76
415
|
|
|
77
416
|
// src/core/auth/sessionManager.ts
|
|
78
417
|
var SagepilotSessionManager = class {
|
|
@@ -97,7 +436,7 @@ var SagepilotSessionManager = class {
|
|
|
97
436
|
return this.currentSession;
|
|
98
437
|
}
|
|
99
438
|
async setSession(session) {
|
|
100
|
-
|
|
439
|
+
const nextSession = {
|
|
101
440
|
session_id: session.session_id,
|
|
102
441
|
session_token: session.session_token,
|
|
103
442
|
customer_id: session.customer_id ?? null,
|
|
@@ -105,7 +444,8 @@ var SagepilotSessionManager = class {
|
|
|
105
444
|
authenticated: session.authenticated ?? false,
|
|
106
445
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
107
446
|
};
|
|
108
|
-
await this.tokenManager.setSession(
|
|
447
|
+
await this.tokenManager.setSession(nextSession);
|
|
448
|
+
this.currentSession = nextSession;
|
|
109
449
|
return this.currentSession;
|
|
110
450
|
}
|
|
111
451
|
async updateSession(updates) {
|
|
@@ -222,8 +562,8 @@ var SagepilotTokenManager = class {
|
|
|
222
562
|
function normalizeHost(host = DEFAULT_HOST) {
|
|
223
563
|
return host.replace(/\/+$/, "");
|
|
224
564
|
}
|
|
225
|
-
function readRuntimeEnv(
|
|
226
|
-
return globalThis.process?.env?.[
|
|
565
|
+
function readRuntimeEnv(name2) {
|
|
566
|
+
return globalThis.process?.env?.[name2]?.trim();
|
|
227
567
|
}
|
|
228
568
|
function resolveSagepilotHost(configuredHost) {
|
|
229
569
|
const envHost = readRuntimeEnv("EXPO_PUBLIC_SAGEPILOT_HOST") || readRuntimeEnv("SAGEPILOT_HOST") || readRuntimeEnv("EXPO_PUBLIC_SAGEPILOT_CUSTOMER_API_BASE_URL") || readRuntimeEnv("SAGEPILOT_CUSTOMER_API_BASE_URL");
|
|
@@ -326,6 +666,9 @@ var SagepilotHttpClient = class {
|
|
|
326
666
|
this.retryPolicy = resolveRetryPolicy(options.retryPolicy);
|
|
327
667
|
}
|
|
328
668
|
async request(url, init) {
|
|
669
|
+
const headers = mergeHeaders(this.baseHeaders, init.headers);
|
|
670
|
+
headers.set("X-Sagepilot-Sdk-Name", SDK_NAME);
|
|
671
|
+
headers.set("X-Sagepilot-Sdk-Version", SDK_VERSION);
|
|
329
672
|
const policy = resolveRetryPolicy(init.retryPolicy ?? this.retryPolicy);
|
|
330
673
|
const method = (init.method ?? "GET").toUpperCase();
|
|
331
674
|
const canRetry = RETRYABLE_METHODS.has(method);
|
|
@@ -335,7 +678,7 @@ var SagepilotHttpClient = class {
|
|
|
335
678
|
try {
|
|
336
679
|
response = await this.fetchImpl(url, {
|
|
337
680
|
...init,
|
|
338
|
-
headers
|
|
681
|
+
headers
|
|
339
682
|
});
|
|
340
683
|
} catch (error) {
|
|
341
684
|
lastNetworkError = error;
|
|
@@ -376,34 +719,6 @@ async function resolveDeviceInfo(adapter) {
|
|
|
376
719
|
return adapter.getDeviceInfo();
|
|
377
720
|
}
|
|
378
721
|
|
|
379
|
-
// src/core/storage/cache.ts
|
|
380
|
-
function createAsyncStorageCacheStorage(asyncStorage) {
|
|
381
|
-
return {
|
|
382
|
-
getItem: (key) => asyncStorage.getItem(key),
|
|
383
|
-
setItem: (key, value) => asyncStorage.setItem(key, value),
|
|
384
|
-
removeItem: (key) => asyncStorage.removeItem(key)
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
function createJsonCache(storage, namespace) {
|
|
388
|
-
return {
|
|
389
|
-
async get(key) {
|
|
390
|
-
const value = await storage.getItem(`${namespace}:${key}`);
|
|
391
|
-
if (!value) return null;
|
|
392
|
-
try {
|
|
393
|
-
return JSON.parse(value);
|
|
394
|
-
} catch {
|
|
395
|
-
return null;
|
|
396
|
-
}
|
|
397
|
-
},
|
|
398
|
-
async set(key, value) {
|
|
399
|
-
await storage.setItem(`${namespace}:${key}`, JSON.stringify(value));
|
|
400
|
-
},
|
|
401
|
-
async remove(key) {
|
|
402
|
-
await storage.removeItem(`${namespace}:${key}`);
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
|
|
407
722
|
// src/resources/channels.ts
|
|
408
723
|
function bootstrapChannel(http, host, channelId) {
|
|
409
724
|
return http.request(
|
|
@@ -427,9 +742,9 @@ function createSession(http, host, channelId, input) {
|
|
|
427
742
|
anonymous_id: input.anonymousId,
|
|
428
743
|
metadata: {
|
|
429
744
|
platform: "react_native",
|
|
745
|
+
...input.metadata,
|
|
430
746
|
sdk: SDK_NAME,
|
|
431
|
-
sdk_version: SDK_VERSION
|
|
432
|
-
...input.metadata
|
|
747
|
+
sdk_version: SDK_VERSION
|
|
433
748
|
}
|
|
434
749
|
}),
|
|
435
750
|
errorMessage: `${SDK_NAME} Failed to create customer session.`
|
|
@@ -576,6 +891,9 @@ function toPublicSessionState(session) {
|
|
|
576
891
|
var SagepilotReactNativeChat = class {
|
|
577
892
|
constructor() {
|
|
578
893
|
this.sdkName = SDK_NAME;
|
|
894
|
+
this.pushClient = null;
|
|
895
|
+
this.pushChannelId = null;
|
|
896
|
+
this.pushAppStateSubscription = null;
|
|
579
897
|
this.runtimeOptions = null;
|
|
580
898
|
this.http = null;
|
|
581
899
|
this.sessionManager = null;
|
|
@@ -605,6 +923,11 @@ var SagepilotReactNativeChat = class {
|
|
|
605
923
|
this.dismissCallbacks = /* @__PURE__ */ new Set();
|
|
606
924
|
this.errorCallbacks = /* @__PURE__ */ new Set();
|
|
607
925
|
}
|
|
926
|
+
/** Returns the configured push lifecycle and analytics API. */
|
|
927
|
+
get push() {
|
|
928
|
+
if (!this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push with durable storage before using the push API.");
|
|
929
|
+
return this.pushClient;
|
|
930
|
+
}
|
|
608
931
|
async configure(config) {
|
|
609
932
|
if (this.isConfigured) {
|
|
610
933
|
throw new SagepilotChatError(
|
|
@@ -656,7 +979,38 @@ var SagepilotReactNativeChat = class {
|
|
|
656
979
|
const session = await this.resolveCustomerSession(config);
|
|
657
980
|
this.channel = channel;
|
|
658
981
|
this.session = session;
|
|
982
|
+
if (config.push) this.legacyWidgetJwt = session.legacy_jwt ?? null;
|
|
659
983
|
this.isConfigured = true;
|
|
984
|
+
if (config.push) {
|
|
985
|
+
if (import_react_native2.Platform.OS !== "ios" && import_react_native2.Platform.OS !== "android") {
|
|
986
|
+
throw new SagepilotChatError("invalid_config", "Push is supported on Android and iOS.");
|
|
987
|
+
}
|
|
988
|
+
this.pushChannelId = config.push.channelId ?? null;
|
|
989
|
+
this.pushClient = new SagepilotPush(config.push, {
|
|
990
|
+
workspaceId,
|
|
991
|
+
channelId: this.pushChannelId ?? channelId,
|
|
992
|
+
platform: import_react_native2.Platform.OS,
|
|
993
|
+
brand: Boolean(this.pushChannelId),
|
|
994
|
+
customerId: () => this.session?.authenticated ? this.session.customer_id ?? null : null,
|
|
995
|
+
request: (path, method, body) => this.requireHttp().request(
|
|
996
|
+
`${this.apiHost}${CUSTOMER_API_PREFIX}${path}`,
|
|
997
|
+
{
|
|
998
|
+
method,
|
|
999
|
+
headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
|
|
1000
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
1001
|
+
errorMessage: `${SDK_NAME} Push request failed.`
|
|
1002
|
+
}
|
|
1003
|
+
),
|
|
1004
|
+
onError: (error) => this.emitError(error)
|
|
1005
|
+
});
|
|
1006
|
+
await this.pushClient.start();
|
|
1007
|
+
this.pushAppStateSubscription = import_react_native2.AppState.addEventListener("change", (state) => {
|
|
1008
|
+
if (state === "active") {
|
|
1009
|
+
void this.pushClient?.sync().catch((error) => this.emitError(error));
|
|
1010
|
+
void this.pushClient?.flush().catch((error) => this.emitError(error));
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
660
1014
|
await this.restorePresentationFromCache();
|
|
661
1015
|
this.emitReady();
|
|
662
1016
|
this.emitState();
|
|
@@ -688,9 +1042,11 @@ var SagepilotReactNativeChat = class {
|
|
|
688
1042
|
async identify(identity) {
|
|
689
1043
|
const session = this.requireSession();
|
|
690
1044
|
const apiIdentity = normalizeIdentity(identity);
|
|
1045
|
+
if (this.pushClient && this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
691
1046
|
this.identifyPending = true;
|
|
692
1047
|
this.emitState();
|
|
693
1048
|
try {
|
|
1049
|
+
if (this.pushClient) await this.pushClient.pauseAndRevoke();
|
|
694
1050
|
const result = await identifySession(
|
|
695
1051
|
this.requireHttp(),
|
|
696
1052
|
this.apiHost,
|
|
@@ -726,16 +1082,55 @@ var SagepilotReactNativeChat = class {
|
|
|
726
1082
|
this.lastIdentifyResult = publicResult;
|
|
727
1083
|
this.identifyCallbacks.forEach((callback) => callback(publicResult));
|
|
728
1084
|
this.emitState();
|
|
1085
|
+
this.pushClient?.resume();
|
|
729
1086
|
return publicResult;
|
|
730
1087
|
} catch (error) {
|
|
731
1088
|
this.identifyPending = false;
|
|
1089
|
+
this.pushClient?.resume();
|
|
732
1090
|
this.emitState();
|
|
733
1091
|
this.emitError(error);
|
|
734
1092
|
throw error;
|
|
735
1093
|
}
|
|
736
1094
|
}
|
|
1095
|
+
/** Adds verified brand permission to the existing session; the host never manages another stored token. */
|
|
1096
|
+
async authorizePush(identityToken) {
|
|
1097
|
+
const session = this.requireSession();
|
|
1098
|
+
if (!this.pushChannelId || !this.pushClient) throw new SagepilotChatError("invalid_config", "Configure push.channelId first.");
|
|
1099
|
+
if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
1100
|
+
this.identifyPending = true;
|
|
1101
|
+
try {
|
|
1102
|
+
const result = await this.requireHttp().request(
|
|
1103
|
+
`${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`,
|
|
1104
|
+
{
|
|
1105
|
+
method: "POST",
|
|
1106
|
+
headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
|
|
1107
|
+
body: JSON.stringify({ channel_id: this.pushChannelId, identity_token: identityToken }),
|
|
1108
|
+
errorMessage: "Brand authorization failed."
|
|
1109
|
+
}
|
|
1110
|
+
);
|
|
1111
|
+
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) {
|
|
1112
|
+
throw new SagepilotChatError("forbidden", "Brand session scope changed.");
|
|
1113
|
+
}
|
|
1114
|
+
this.session = await this.requireSessionManager().setSession({ ...session, session_token: result.session_token });
|
|
1115
|
+
this.legacyWidgetJwt = result.legacy_jwt ?? this.legacyWidgetJwt;
|
|
1116
|
+
this.pushClient.resume();
|
|
1117
|
+
} finally {
|
|
1118
|
+
this.identifyPending = false;
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
737
1121
|
async logout() {
|
|
738
1122
|
const session = this.requireSession();
|
|
1123
|
+
if (this.pushClient) {
|
|
1124
|
+
if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
1125
|
+
this.identifyPending = true;
|
|
1126
|
+
try {
|
|
1127
|
+
await this.pushClient.pauseAndRevoke();
|
|
1128
|
+
} catch (error) {
|
|
1129
|
+
this.identifyPending = false;
|
|
1130
|
+
this.emitState();
|
|
1131
|
+
throw error;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
739
1134
|
const wasUnreadPolling = this.unreadPollTimer !== null;
|
|
740
1135
|
let result = null;
|
|
741
1136
|
let logoutError = null;
|
|
@@ -775,6 +1170,7 @@ var SagepilotReactNativeChat = class {
|
|
|
775
1170
|
throw error;
|
|
776
1171
|
}
|
|
777
1172
|
this.session = freshSession;
|
|
1173
|
+
this.pushClient?.resume();
|
|
778
1174
|
this.setUnreadCount(0);
|
|
779
1175
|
this.emitState();
|
|
780
1176
|
this.persistPresentationState();
|
|
@@ -983,6 +1379,8 @@ var SagepilotReactNativeChat = class {
|
|
|
983
1379
|
const path = this.hostedChatView.screen === "home" ? `/chat-widget/${encodeURIComponent(this.channelId)}` : `/chat-widget/${encodeURIComponent(this.channelId)}/conversations`;
|
|
984
1380
|
const url = new URL(`${this.widgetHost}${path}`);
|
|
985
1381
|
url.searchParams.set("sdk", "react-native");
|
|
1382
|
+
url.searchParams.set("sdk_name", SDK_NAME);
|
|
1383
|
+
url.searchParams.set("sdk_version", SDK_VERSION);
|
|
986
1384
|
if (this.runtimeOptions?.presentation?.mobile ?? true) {
|
|
987
1385
|
url.searchParams.set("mobile", "1");
|
|
988
1386
|
}
|
|
@@ -1071,7 +1469,7 @@ var SagepilotReactNativeChat = class {
|
|
|
1071
1469
|
}
|
|
1072
1470
|
/** Restores the hosted route for a queued attachment batch before delivery. */
|
|
1073
1471
|
restoreHostedAttachmentTarget(target) {
|
|
1074
|
-
if (
|
|
1472
|
+
if (import_react_native2.Platform.OS !== "android") return false;
|
|
1075
1473
|
if (!target) return false;
|
|
1076
1474
|
const hostedChatView = this.readPersistedHostedChatView(target.hostedChatView);
|
|
1077
1475
|
if (!hostedChatView) return false;
|
|
@@ -1104,6 +1502,10 @@ var SagepilotReactNativeChat = class {
|
|
|
1104
1502
|
}
|
|
1105
1503
|
return true;
|
|
1106
1504
|
}
|
|
1505
|
+
if (message.type === "sagepilot:session_updated") {
|
|
1506
|
+
if (this.pushClient) void this.acceptHostedSession(message).catch((error) => this.emitError(error));
|
|
1507
|
+
return true;
|
|
1508
|
+
}
|
|
1107
1509
|
if (message.type === "sagepilot:conversation_created") {
|
|
1108
1510
|
this.handleConversationCreated(message);
|
|
1109
1511
|
return true;
|
|
@@ -1114,6 +1516,54 @@ var SagepilotReactNativeChat = class {
|
|
|
1114
1516
|
}
|
|
1115
1517
|
return true;
|
|
1116
1518
|
}
|
|
1519
|
+
/** Verifies an OTP-issued token with the Customer API before accepting a hosted identity change. */
|
|
1520
|
+
async acceptHostedSession(message) {
|
|
1521
|
+
const session = this.requireSession();
|
|
1522
|
+
const sessionToken = readStringField(message, "session_token");
|
|
1523
|
+
if (!sessionToken || readStringField(message, "session_id") !== session.session_id) return;
|
|
1524
|
+
if (message.workspace_id && message.workspace_id !== this.workspaceId) return;
|
|
1525
|
+
if (message.channel_id && message.channel_id !== this.channelId) return;
|
|
1526
|
+
if (this.identifyPending) throw new SagepilotChatError("invalid_request", "Another identity change is in progress.");
|
|
1527
|
+
this.identifyPending = true;
|
|
1528
|
+
this.emitState();
|
|
1529
|
+
try {
|
|
1530
|
+
const verified = await getSession(
|
|
1531
|
+
this.requireHttp(),
|
|
1532
|
+
this.apiHost,
|
|
1533
|
+
session.session_id,
|
|
1534
|
+
this.requireSessionManager().getAuthorizationHeader(sessionToken)
|
|
1535
|
+
);
|
|
1536
|
+
if (verified.session_id !== session.session_id || verified.channel_id && verified.channel_id !== this.channelId || !verified.authenticated) {
|
|
1537
|
+
throw new SagepilotChatError("forbidden", "Hosted token does not identify this customer session.");
|
|
1538
|
+
}
|
|
1539
|
+
if (this.session?.session_id !== session.session_id || this.session.session_token !== session.session_token) return;
|
|
1540
|
+
if (verified.customer_id !== session.customer_id) await this.pushClient?.pauseAndRevoke();
|
|
1541
|
+
let adoptedToken = sessionToken;
|
|
1542
|
+
let legacyJwt = verified.legacy_jwt ?? null;
|
|
1543
|
+
if (this.pushChannelId && verified.customer_id === session.customer_id) {
|
|
1544
|
+
const renewed = await this.requireHttp().request(`${this.apiHost}${CUSTOMER_API_PREFIX}/push/sessions`, {
|
|
1545
|
+
method: "POST",
|
|
1546
|
+
headers: withJsonHeaders(this.requireSessionManager().getAuthorizationHeader()),
|
|
1547
|
+
body: JSON.stringify({ replacement_session_token: sessionToken }),
|
|
1548
|
+
errorMessage: "Shared push session refresh failed."
|
|
1549
|
+
});
|
|
1550
|
+
if (renewed.session_id !== session.session_id || renewed.customer_id !== session.customer_id || !renewed.session_token) {
|
|
1551
|
+
throw new SagepilotChatError("forbidden", "Shared session refresh scope changed.");
|
|
1552
|
+
}
|
|
1553
|
+
adoptedToken = renewed.session_token;
|
|
1554
|
+
legacyJwt = renewed.legacy_jwt ?? legacyJwt;
|
|
1555
|
+
}
|
|
1556
|
+
this.session = await this.requireSessionManager().setSession({ ...verified, session_token: adoptedToken });
|
|
1557
|
+
this.legacyWidgetJwt = legacyJwt;
|
|
1558
|
+
this.hostedIdentityLogoutVersion = 0;
|
|
1559
|
+
this.identified = true;
|
|
1560
|
+
this.customer = verified.customer_id ? { id: verified.customer_id } : null;
|
|
1561
|
+
this.pushClient?.resume();
|
|
1562
|
+
} finally {
|
|
1563
|
+
this.identifyPending = false;
|
|
1564
|
+
this.emitState();
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1117
1567
|
handleConversationCreated(message) {
|
|
1118
1568
|
const chatId = readStringField(message, "chat_id") ?? readStringField(message, "conversation_id");
|
|
1119
1569
|
if (!chatId) return;
|
|
@@ -1167,10 +1617,12 @@ var SagepilotReactNativeChat = class {
|
|
|
1167
1617
|
this.dismissCallbacks.clear();
|
|
1168
1618
|
this.errorCallbacks.clear();
|
|
1169
1619
|
}
|
|
1620
|
+
/** Updates both unread subscribers and the state used by React launchers. */
|
|
1170
1621
|
setUnreadCount(count) {
|
|
1171
1622
|
if (count === this.unreadCount) return;
|
|
1172
1623
|
this.unreadCount = count;
|
|
1173
1624
|
this.emitUnreadChange();
|
|
1625
|
+
this.emitState();
|
|
1174
1626
|
}
|
|
1175
1627
|
emitUnreadChange() {
|
|
1176
1628
|
const state = this.getUnreadState();
|
|
@@ -1325,6 +1777,11 @@ var SagepilotReactNativeChat = class {
|
|
|
1325
1777
|
return this.unreadCount;
|
|
1326
1778
|
}
|
|
1327
1779
|
resetRuntimeState() {
|
|
1780
|
+
this.pushClient?.stop();
|
|
1781
|
+
this.pushClient = null;
|
|
1782
|
+
this.pushChannelId = null;
|
|
1783
|
+
this.pushAppStateSubscription?.remove();
|
|
1784
|
+
this.pushAppStateSubscription = null;
|
|
1328
1785
|
this.runtimeOptions = null;
|
|
1329
1786
|
this.http = null;
|
|
1330
1787
|
this.sessionManager = null;
|
|
@@ -1421,7 +1878,7 @@ var SagepilotReactNativeChat = class {
|
|
|
1421
1878
|
/** Restores Android presentation state after configure without resetting the hosted route to Home. */
|
|
1422
1879
|
async restorePresentationFromCache() {
|
|
1423
1880
|
const cache = this.getPresentationCache();
|
|
1424
|
-
if (!cache ||
|
|
1881
|
+
if (!cache || import_react_native2.Platform.OS !== "android") return;
|
|
1425
1882
|
const persisted = await cache.get(PRESENTATION_CACHE_KEY).catch(() => null);
|
|
1426
1883
|
if (persisted?.cleanShutdown) return;
|
|
1427
1884
|
if (!isFreshPresentationState(persisted?.updatedAt)) return;
|
|
@@ -1435,9 +1892,15 @@ var SagepilotReactNativeChat = class {
|
|
|
1435
1892
|
};
|
|
1436
1893
|
var internalSagepilotChat = new SagepilotReactNativeChat();
|
|
1437
1894
|
var SagepilotChat = {
|
|
1895
|
+
/** Provides push registration, preferences and SDK engagement callbacks. */
|
|
1896
|
+
get push() {
|
|
1897
|
+
return internalSagepilotChat.push;
|
|
1898
|
+
},
|
|
1438
1899
|
configure: (config) => internalSagepilotChat.configure(config),
|
|
1439
1900
|
getSession: () => internalSagepilotChat.getSession(),
|
|
1440
1901
|
identify: (identity) => internalSagepilotChat.identify(identity),
|
|
1902
|
+
/** Authorizes the configured brand on the same customer session used by chat. */
|
|
1903
|
+
authorizePush: (identityToken) => internalSagepilotChat.authorizePush(identityToken),
|
|
1441
1904
|
logout: () => internalSagepilotChat.logout(),
|
|
1442
1905
|
getIdentityState: () => internalSagepilotChat.getIdentityState(),
|
|
1443
1906
|
onIdentify: (callback) => internalSagepilotChat.onIdentify(callback),
|
|
@@ -1467,6 +1930,7 @@ var SagepilotChat = {
|
|
|
1467
1930
|
getChannel: () => internalSagepilotChat.getChannel(),
|
|
1468
1931
|
destroy: () => internalSagepilotChat.destroy()
|
|
1469
1932
|
};
|
|
1933
|
+
Object.defineProperty(SagepilotChat, "push", { enumerable: false });
|
|
1470
1934
|
|
|
1471
1935
|
// src/core/storage/fileStore.ts
|
|
1472
1936
|
var DEFAULT_DIRECTORY_NAME = "sagepilot-attachments";
|
|
@@ -1525,7 +1989,7 @@ function createSagepilotFileStore(blobUtil, options = {}) {
|
|
|
1525
1989
|
}
|
|
1526
1990
|
|
|
1527
1991
|
// src/core/native/filePicker.ts
|
|
1528
|
-
var
|
|
1992
|
+
var import_react_native3 = require("react-native");
|
|
1529
1993
|
|
|
1530
1994
|
// src/core/native/filePickerShared.ts
|
|
1531
1995
|
var SagepilotFilePickerError = class extends Error {
|
|
@@ -1558,9 +2022,9 @@ function stripFileScheme(uri) {
|
|
|
1558
2022
|
return uri.startsWith("file://") ? uri.replace("file://", "") : uri;
|
|
1559
2023
|
}
|
|
1560
2024
|
async function promptOpenSagepilotCameraSettings() {
|
|
1561
|
-
if (
|
|
2025
|
+
if (import_react_native3.Platform.OS !== "android") return;
|
|
1562
2026
|
await new Promise((resolve) => {
|
|
1563
|
-
|
|
2027
|
+
import_react_native3.Alert.alert(
|
|
1564
2028
|
"Camera access is off",
|
|
1565
2029
|
"Enable camera access for this app in Settings to take a photo.",
|
|
1566
2030
|
[
|
|
@@ -1572,7 +2036,7 @@ async function promptOpenSagepilotCameraSettings() {
|
|
|
1572
2036
|
{
|
|
1573
2037
|
text: "Open Settings",
|
|
1574
2038
|
onPress: () => {
|
|
1575
|
-
|
|
2039
|
+
import_react_native3.Linking.openSettings().finally(resolve);
|
|
1576
2040
|
}
|
|
1577
2041
|
}
|
|
1578
2042
|
]
|
|
@@ -1580,21 +2044,21 @@ async function promptOpenSagepilotCameraSettings() {
|
|
|
1580
2044
|
});
|
|
1581
2045
|
}
|
|
1582
2046
|
async function ensureSagepilotAndroidCameraPermission() {
|
|
1583
|
-
if (
|
|
2047
|
+
if (import_react_native3.Platform.OS !== "android") return;
|
|
1584
2048
|
let result;
|
|
1585
2049
|
try {
|
|
1586
|
-
result = await
|
|
2050
|
+
result = await import_react_native3.PermissionsAndroid.request(import_react_native3.PermissionsAndroid.PERMISSIONS.CAMERA);
|
|
1587
2051
|
} catch {
|
|
1588
2052
|
return;
|
|
1589
2053
|
}
|
|
1590
|
-
if (result ===
|
|
2054
|
+
if (result === import_react_native3.PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
|
|
1591
2055
|
await promptOpenSagepilotCameraSettings();
|
|
1592
2056
|
throw new SagepilotFilePickerError(
|
|
1593
2057
|
"permission_denied",
|
|
1594
2058
|
"Camera access is turned off. Enable it for this app in Settings to take a photo."
|
|
1595
2059
|
);
|
|
1596
2060
|
}
|
|
1597
|
-
if (result ===
|
|
2061
|
+
if (result === import_react_native3.PermissionsAndroid.RESULTS.DENIED) {
|
|
1598
2062
|
throw new SagepilotFilePickerError(
|
|
1599
2063
|
"permission_denied",
|
|
1600
2064
|
"Camera permission is required to take a photo."
|
|
@@ -1767,13 +2231,13 @@ function createSagepilotFilePicker(options) {
|
|
|
1767
2231
|
|
|
1768
2232
|
// src/ui/SagepilotChatProvider.ts
|
|
1769
2233
|
var import_react = require("react");
|
|
1770
|
-
var
|
|
2234
|
+
var import_react_native4 = require("react-native");
|
|
1771
2235
|
var import_react_native_webview = require("react-native-webview");
|
|
1772
2236
|
|
|
1773
2237
|
// src/core/webview/mobileBridge.ts
|
|
1774
2238
|
var FILE_PICKER_PROTOCOL_VERSION = 2;
|
|
1775
2239
|
function buildBridgeCapabilitiesPayload(capabilities) {
|
|
1776
|
-
return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION };
|
|
2240
|
+
return { ...capabilities, filePickerProtocol: FILE_PICKER_PROTOCOL_VERSION, sdk: SDK_NAME, sdk_version: SDK_VERSION };
|
|
1777
2241
|
}
|
|
1778
2242
|
function buildBridgeCapabilitiesScript(capabilities) {
|
|
1779
2243
|
const payload = buildBridgeCapabilitiesPayload(capabilities);
|
|
@@ -2061,7 +2525,7 @@ function isInternalWebViewScheme(url) {
|
|
|
2061
2525
|
var hostedChatWebViewProps = {
|
|
2062
2526
|
allowFileAccess: true,
|
|
2063
2527
|
allowFileAccessFromFileURLs: true,
|
|
2064
|
-
...
|
|
2528
|
+
...import_react_native4.Platform.OS === "ios" ? {
|
|
2065
2529
|
automaticallyAdjustContentInsets: false,
|
|
2066
2530
|
contentInsetAdjustmentBehavior: "never",
|
|
2067
2531
|
hideKeyboardAccessoryView: true
|
|
@@ -2076,7 +2540,7 @@ var hostedChatWebViewProps = {
|
|
|
2076
2540
|
sharedCookiesEnabled: true,
|
|
2077
2541
|
thirdPartyCookiesEnabled: true
|
|
2078
2542
|
};
|
|
2079
|
-
var AndroidInsetsView =
|
|
2543
|
+
var AndroidInsetsView = import_react_native4.Platform.OS === "android" ? SagepilotInsetsViewNativeComponent_default : import_react_native4.View;
|
|
2080
2544
|
var emptyAndroidInsets = { top: 0, bottom: 0 };
|
|
2081
2545
|
function SagepilotChatProvider({
|
|
2082
2546
|
children,
|
|
@@ -2099,7 +2563,7 @@ function SagepilotChatProvider({
|
|
|
2099
2563
|
const livenessPausedUntilRef = (0, import_react.useRef)(0);
|
|
2100
2564
|
const pickerInFlightRef = (0, import_react.useRef)(false);
|
|
2101
2565
|
const livenessRemountCountRef = (0, import_react.useRef)(0);
|
|
2102
|
-
const appStateRef = (0, import_react.useRef)(
|
|
2566
|
+
const appStateRef = (0, import_react.useRef)(import_react_native4.AppState.currentState);
|
|
2103
2567
|
const didReconcileRef = (0, import_react.useRef)(false);
|
|
2104
2568
|
const [androidRepaintTick, setAndroidRepaintTick] = (0, import_react.useState)(0);
|
|
2105
2569
|
const [sourceChooser, setSourceChooser] = (0, import_react.useState)(null);
|
|
@@ -2241,7 +2705,7 @@ function SagepilotChatProvider({
|
|
|
2241
2705
|
setPreloadWebViewKey((key) => key + 1);
|
|
2242
2706
|
}, []);
|
|
2243
2707
|
const pauseLivenessAfterPicker = (0, import_react.useCallback)((durationMs) => {
|
|
2244
|
-
if (
|
|
2708
|
+
if (import_react_native4.Platform.OS !== "android") return;
|
|
2245
2709
|
livenessPausedUntilRef.current = Math.max(livenessPausedUntilRef.current, Date.now() + durationMs);
|
|
2246
2710
|
}, []);
|
|
2247
2711
|
const runNativeFilePicker = (0, import_react.useCallback)((source, multiple) => {
|
|
@@ -2411,7 +2875,7 @@ function SagepilotChatProvider({
|
|
|
2411
2875
|
};
|
|
2412
2876
|
}, [clearDeferredLivenessProbe]);
|
|
2413
2877
|
const runLivenessProbe = (0, import_react.useCallback)(() => {
|
|
2414
|
-
if (
|
|
2878
|
+
if (import_react_native4.Platform.OS !== "android") return;
|
|
2415
2879
|
const ref = nativeWebViewRef.current;
|
|
2416
2880
|
if (!ref || !internalSagepilotChat.isPresented()) return;
|
|
2417
2881
|
const pauseRemainingMs = livenessPausedUntilRef.current - Date.now();
|
|
@@ -2440,7 +2904,7 @@ function SagepilotChatProvider({
|
|
|
2440
2904
|
}, LIVENESS_PONG_TIMEOUT_MS);
|
|
2441
2905
|
}, [clearDeferredLivenessProbe, clearPing, recoverNativeWebView]);
|
|
2442
2906
|
(0, import_react.useEffect)(() => {
|
|
2443
|
-
const subscription =
|
|
2907
|
+
const subscription = import_react_native4.AppState.addEventListener("change", (nextState) => {
|
|
2444
2908
|
const prev = appStateRef.current;
|
|
2445
2909
|
appStateRef.current = nextState;
|
|
2446
2910
|
if (nextState === "active" && (prev === "background" || prev === "inactive")) {
|
|
@@ -2468,11 +2932,11 @@ function SagepilotChatProvider({
|
|
|
2468
2932
|
const presentationStyle = state.presentation?.style ?? "sheet";
|
|
2469
2933
|
const isFullScreenModal = presentationStyle === "fullScreen";
|
|
2470
2934
|
const animationType = presentationStyle === "fullScreen" || presentationStyle === "push" ? "slide" : "fade";
|
|
2471
|
-
const ModalContainer =
|
|
2472
|
-
const NativeModalContainer =
|
|
2473
|
-
const ChatContentContainer =
|
|
2474
|
-
const nativeModalContainerProps =
|
|
2475
|
-
const chatContentContainerProps =
|
|
2935
|
+
const ModalContainer = import_react_native4.Platform.OS === "ios" && isFullScreenModal ? import_react_native4.SafeAreaView : import_react_native4.View;
|
|
2936
|
+
const NativeModalContainer = import_react_native4.Platform.OS === "android" ? AndroidInsetsView : ModalContainer;
|
|
2937
|
+
const ChatContentContainer = import_react_native4.Platform.OS === "ios" ? import_react_native4.KeyboardAvoidingView : import_react_native4.View;
|
|
2938
|
+
const nativeModalContainerProps = import_react_native4.Platform.OS === "android" ? { style: styles.container, onInsetsChange: handleAndroidInsetsChange } : { style: styles.container };
|
|
2939
|
+
const chatContentContainerProps = import_react_native4.Platform.OS === "ios" ? {
|
|
2476
2940
|
behavior: "padding",
|
|
2477
2941
|
enabled: true,
|
|
2478
2942
|
keyboardVerticalOffset: 0,
|
|
@@ -2480,13 +2944,15 @@ function SagepilotChatProvider({
|
|
|
2480
2944
|
} : {
|
|
2481
2945
|
style: [
|
|
2482
2946
|
styles.modalContent,
|
|
2483
|
-
|
|
2947
|
+
import_react_native4.Platform.OS === "android" ? {
|
|
2484
2948
|
paddingTop: androidModalInsets.top,
|
|
2485
2949
|
paddingBottom: androidModalInsets.bottom
|
|
2486
2950
|
} : null
|
|
2487
2951
|
].filter(Boolean)
|
|
2488
2952
|
};
|
|
2489
2953
|
const handleWebViewMessage = (event) => {
|
|
2954
|
+
const origin = readUrlOrigin(state.conversationUrl ?? state.preloadUrl);
|
|
2955
|
+
if (event.nativeEvent?.url && (!origin || readUrlOrigin(event.nativeEvent.url) !== origin)) return;
|
|
2490
2956
|
const message = parseHostedBridgeMessage(event.nativeEvent?.data);
|
|
2491
2957
|
if (message?.type === "sagepilot:open_file_picker") {
|
|
2492
2958
|
logNativeFilePicker("bridge_message_open_file_picker", {
|
|
@@ -2569,43 +3035,43 @@ function SagepilotChatProvider({
|
|
|
2569
3035
|
if (widgetOrigin && readUrlOrigin(url) === widgetOrigin) {
|
|
2570
3036
|
return true;
|
|
2571
3037
|
}
|
|
2572
|
-
|
|
3038
|
+
import_react_native4.Linking.openURL(url).catch(() => void 0);
|
|
2573
3039
|
return false;
|
|
2574
3040
|
}, [state.conversationUrl, state.preloadUrl]);
|
|
2575
3041
|
(0, import_react.useEffect)(() => {
|
|
2576
|
-
if (
|
|
3042
|
+
if (import_react_native4.Platform.OS !== "web" || typeof window === "undefined") return;
|
|
2577
3043
|
const trustedWidgetOrigin = readUrlOrigin(state.conversationUrl);
|
|
2578
3044
|
if (!trustedWidgetOrigin) return;
|
|
2579
3045
|
const handleWindowMessage = (event) => {
|
|
2580
|
-
if (event.origin !== trustedWidgetOrigin) return;
|
|
3046
|
+
if (event.origin !== trustedWidgetOrigin || event.source !== webFrameRef.current?.contentWindow) return;
|
|
2581
3047
|
internalSagepilotChat.handleHostedBridgeMessage(parseHostedBridgeMessage(event.data));
|
|
2582
3048
|
};
|
|
2583
3049
|
window.addEventListener("message", handleWindowMessage);
|
|
2584
3050
|
return () => window.removeEventListener("message", handleWindowMessage);
|
|
2585
3051
|
}, [state.conversationUrl]);
|
|
2586
3052
|
(0, import_react.useEffect)(() => {
|
|
2587
|
-
if (
|
|
3053
|
+
if (import_react_native4.Platform.OS !== "web" || !state.isPresented) return;
|
|
2588
3054
|
postIdentityToWebFrame();
|
|
2589
3055
|
}, [state.isPresented, state.conversationUrl, state.configured]);
|
|
2590
3056
|
(0, import_react.useEffect)(() => {
|
|
2591
|
-
if (
|
|
3057
|
+
if (import_react_native4.Platform.OS !== "web" || !state.isPresented) return;
|
|
2592
3058
|
postIdentityLogoutToWebFrame();
|
|
2593
3059
|
}, [state.hostedIdentityLogoutVersion, state.isPresented, state.conversationUrl, state.configured]);
|
|
2594
3060
|
(0, import_react.useEffect)(() => {
|
|
2595
|
-
if (
|
|
3061
|
+
if (import_react_native4.Platform.OS === "web" || !state.isPresented) return;
|
|
2596
3062
|
postIdentityToNativeWebView();
|
|
2597
3063
|
}, [state.isPresented, state.conversationUrl, state.configured]);
|
|
2598
3064
|
(0, import_react.useEffect)(() => {
|
|
2599
|
-
if (
|
|
3065
|
+
if (import_react_native4.Platform.OS === "web" || !state.isPresented) return;
|
|
2600
3066
|
postIdentityLogoutToNativeWebView();
|
|
2601
3067
|
}, [state.hostedIdentityLogoutVersion, state.isPresented, state.conversationUrl, state.configured]);
|
|
2602
3068
|
const handleWebFrameLoad = () => {
|
|
2603
3069
|
postIdentityLogoutToWebFrame();
|
|
2604
3070
|
postIdentityToWebFrame();
|
|
2605
3071
|
};
|
|
2606
|
-
if (
|
|
3072
|
+
if (import_react_native4.Platform.OS === "web") {
|
|
2607
3073
|
return (0, import_react.createElement)(
|
|
2608
|
-
|
|
3074
|
+
import_react_native4.View,
|
|
2609
3075
|
{ style: styles.root },
|
|
2610
3076
|
children,
|
|
2611
3077
|
state.configured && !state.isPresented && state.shouldPreload && state.preloadUrl ? (0, import_react.createElement)("iframe", {
|
|
@@ -2614,20 +3080,20 @@ function SagepilotChatProvider({
|
|
|
2614
3080
|
title: "Sagepilot chat preload"
|
|
2615
3081
|
}) : null,
|
|
2616
3082
|
state.configured && state.isPresented && state.conversationUrl ? (0, import_react.createElement)(
|
|
2617
|
-
|
|
3083
|
+
import_react_native4.View,
|
|
2618
3084
|
{ style: styles.webOverlay },
|
|
2619
3085
|
(0, import_react.createElement)(
|
|
2620
|
-
|
|
3086
|
+
import_react_native4.View,
|
|
2621
3087
|
{ style: styles.webPanel },
|
|
2622
3088
|
showCloseButton ? (0, import_react.createElement)(
|
|
2623
|
-
|
|
3089
|
+
import_react_native4.Pressable,
|
|
2624
3090
|
{
|
|
2625
3091
|
accessibilityRole: "button",
|
|
2626
3092
|
accessibilityLabel: closeLabel,
|
|
2627
3093
|
onPress: () => internalSagepilotChat.dismiss(),
|
|
2628
3094
|
style: styles.webCloseButton
|
|
2629
3095
|
},
|
|
2630
|
-
(0, import_react.createElement)(
|
|
3096
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.closeText }, closeLabel)
|
|
2631
3097
|
) : null,
|
|
2632
3098
|
(0, import_react.createElement)("iframe", {
|
|
2633
3099
|
ref: webFrameRef,
|
|
@@ -2641,7 +3107,7 @@ function SagepilotChatProvider({
|
|
|
2641
3107
|
);
|
|
2642
3108
|
}
|
|
2643
3109
|
return (0, import_react.createElement)(
|
|
2644
|
-
|
|
3110
|
+
import_react_native4.View,
|
|
2645
3111
|
{ style: styles.root },
|
|
2646
3112
|
children,
|
|
2647
3113
|
state.configured && !state.isPresented && state.shouldPreload && state.preloadUrl ? (0, import_react.createElement)(import_react_native_webview.WebView, {
|
|
@@ -2651,7 +3117,7 @@ function SagepilotChatProvider({
|
|
|
2651
3117
|
// disrupt an in-flight delivery). onRenderProcessGone must still be
|
|
2652
3118
|
// handled here or an unhandled renderer kill crashes the whole app.
|
|
2653
3119
|
key: `sagepilot-preload-webview-${preloadWebViewKey}`,
|
|
2654
|
-
source: { uri: state.preloadUrl },
|
|
3120
|
+
source: { uri: state.preloadUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
|
|
2655
3121
|
style: styles.preloadWebview,
|
|
2656
3122
|
injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
|
|
2657
3123
|
onMessage: handleWebViewMessage,
|
|
@@ -2660,13 +3126,13 @@ function SagepilotChatProvider({
|
|
|
2660
3126
|
onContentProcessDidTerminate: recoverPreloadWebView
|
|
2661
3127
|
}) : null,
|
|
2662
3128
|
(0, import_react.createElement)(
|
|
2663
|
-
|
|
3129
|
+
import_react_native4.Modal,
|
|
2664
3130
|
{
|
|
2665
3131
|
visible: state.configured && state.isPresented,
|
|
2666
3132
|
animationType,
|
|
2667
3133
|
presentationStyle: isFullScreenModal ? "fullScreen" : "pageSheet",
|
|
2668
|
-
statusBarTranslucent:
|
|
2669
|
-
navigationBarTranslucent:
|
|
3134
|
+
statusBarTranslucent: import_react_native4.Platform.OS === "android",
|
|
3135
|
+
navigationBarTranslucent: import_react_native4.Platform.OS === "android",
|
|
2670
3136
|
onRequestClose: () => internalSagepilotChat.dismiss()
|
|
2671
3137
|
},
|
|
2672
3138
|
(0, import_react.createElement)(
|
|
@@ -2676,28 +3142,28 @@ function SagepilotChatProvider({
|
|
|
2676
3142
|
ChatContentContainer,
|
|
2677
3143
|
chatContentContainerProps,
|
|
2678
3144
|
showCloseButton ? (0, import_react.createElement)(
|
|
2679
|
-
|
|
3145
|
+
import_react_native4.View,
|
|
2680
3146
|
{ style: styles.header },
|
|
2681
3147
|
(0, import_react.createElement)(
|
|
2682
|
-
|
|
3148
|
+
import_react_native4.Pressable,
|
|
2683
3149
|
{
|
|
2684
3150
|
accessibilityRole: "button",
|
|
2685
3151
|
accessibilityLabel: closeLabel,
|
|
2686
3152
|
onPress: () => internalSagepilotChat.dismiss(),
|
|
2687
3153
|
style: styles.closeButton
|
|
2688
3154
|
},
|
|
2689
|
-
(0, import_react.createElement)(
|
|
3155
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.closeText }, closeLabel)
|
|
2690
3156
|
)
|
|
2691
3157
|
) : null,
|
|
2692
3158
|
state.conversationUrl ? (0, import_react.createElement)(import_react_native_webview.WebView, {
|
|
2693
3159
|
...hostedChatWebViewProps,
|
|
2694
3160
|
key: `sagepilot-hosted-webview-${nativeWebViewKey}`,
|
|
2695
3161
|
ref: nativeWebViewRef,
|
|
2696
|
-
source: { uri: state.conversationUrl },
|
|
3162
|
+
source: { uri: state.conversationUrl, headers: { "X-Sagepilot-Sdk-Name": SDK_NAME, "X-Sagepilot-Sdk-Version": SDK_VERSION } },
|
|
2697
3163
|
// The imperceptible opacity toggle forces the Android WebView
|
|
2698
3164
|
// surface to re-composite on resume, clearing the blank-but-alive
|
|
2699
3165
|
// surface bug without a reload (see runLivenessProbe).
|
|
2700
|
-
style:
|
|
3166
|
+
style: import_react_native4.Platform.OS === "android" ? [styles.webview, { opacity: 1 - androidRepaintTick % 2 * 1e-3 }] : styles.webview,
|
|
2701
3167
|
startInLoadingState: true,
|
|
2702
3168
|
injectedJavaScriptBeforeContentLoaded: getInjectedWebViewScript(),
|
|
2703
3169
|
onMessage: handleWebViewMessage,
|
|
@@ -2709,10 +3175,10 @@ function SagepilotChatProvider({
|
|
|
2709
3175
|
// iOS equivalent: WKWebView content process terminated.
|
|
2710
3176
|
onContentProcessDidTerminate: recoverNativeWebView,
|
|
2711
3177
|
renderLoading: () => (0, import_react.createElement)(
|
|
2712
|
-
|
|
3178
|
+
import_react_native4.View,
|
|
2713
3179
|
{ style: styles.loading },
|
|
2714
|
-
(0, import_react.createElement)(
|
|
2715
|
-
(0, import_react.createElement)(
|
|
3180
|
+
(0, import_react.createElement)(import_react_native4.ActivityIndicator, null),
|
|
3181
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.loadingText }, loadingLabel)
|
|
2716
3182
|
)
|
|
2717
3183
|
}) : null
|
|
2718
3184
|
)
|
|
@@ -2721,7 +3187,7 @@ function SagepilotChatProvider({
|
|
|
2721
3187
|
// Native attachment-source chooser. Replaces the Android Alert (capped at
|
|
2722
3188
|
// 3 buttons) so camera/library/documents all show on every platform.
|
|
2723
3189
|
(0, import_react.createElement)(
|
|
2724
|
-
|
|
3190
|
+
import_react_native4.Modal,
|
|
2725
3191
|
{
|
|
2726
3192
|
visible: sourceChooser !== null,
|
|
2727
3193
|
transparent: true,
|
|
@@ -2730,39 +3196,39 @@ function SagepilotChatProvider({
|
|
|
2730
3196
|
onRequestClose: () => setSourceChooser(null)
|
|
2731
3197
|
},
|
|
2732
3198
|
(0, import_react.createElement)(
|
|
2733
|
-
|
|
3199
|
+
import_react_native4.Pressable,
|
|
2734
3200
|
{ style: styles.sheetBackdrop, onPress: () => setSourceChooser(null) },
|
|
2735
3201
|
(0, import_react.createElement)(
|
|
2736
|
-
|
|
3202
|
+
import_react_native4.View,
|
|
2737
3203
|
{ style: styles.sheetCard },
|
|
2738
|
-
(0, import_react.createElement)(
|
|
3204
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.sheetTitle }, "Add attachment"),
|
|
2739
3205
|
...(internalSagepilotChat.getConfig()?.filePicker?.sources ?? []).map(
|
|
2740
3206
|
(source) => (0, import_react.createElement)(
|
|
2741
|
-
|
|
3207
|
+
import_react_native4.Pressable,
|
|
2742
3208
|
{
|
|
2743
3209
|
key: source,
|
|
2744
3210
|
accessibilityRole: "button",
|
|
2745
3211
|
style: styles.sheetButton,
|
|
2746
3212
|
onPress: () => handleSourceChoice(source)
|
|
2747
3213
|
},
|
|
2748
|
-
(0, import_react.createElement)(
|
|
3214
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.sheetButtonText }, FILE_PICKER_SOURCE_LABELS[source])
|
|
2749
3215
|
)
|
|
2750
3216
|
),
|
|
2751
3217
|
(0, import_react.createElement)(
|
|
2752
|
-
|
|
3218
|
+
import_react_native4.Pressable,
|
|
2753
3219
|
{
|
|
2754
3220
|
accessibilityRole: "button",
|
|
2755
3221
|
style: [styles.sheetButton, styles.sheetCancelButton],
|
|
2756
3222
|
onPress: () => setSourceChooser(null)
|
|
2757
3223
|
},
|
|
2758
|
-
(0, import_react.createElement)(
|
|
3224
|
+
(0, import_react.createElement)(import_react_native4.Text, { style: styles.sheetCancelText }, "Cancel")
|
|
2759
3225
|
)
|
|
2760
3226
|
)
|
|
2761
3227
|
)
|
|
2762
3228
|
)
|
|
2763
3229
|
);
|
|
2764
3230
|
}
|
|
2765
|
-
var styles =
|
|
3231
|
+
var styles = import_react_native4.StyleSheet.create({
|
|
2766
3232
|
root: {
|
|
2767
3233
|
flex: 1
|
|
2768
3234
|
},
|
|
@@ -2848,7 +3314,7 @@ var styles = import_react_native3.StyleSheet.create({
|
|
|
2848
3314
|
borderStyle: "none"
|
|
2849
3315
|
},
|
|
2850
3316
|
loading: {
|
|
2851
|
-
...
|
|
3317
|
+
...import_react_native4.StyleSheet.absoluteFillObject,
|
|
2852
3318
|
alignItems: "center",
|
|
2853
3319
|
justifyContent: "center",
|
|
2854
3320
|
backgroundColor: "#ffffff"
|
|
@@ -2949,16 +3415,113 @@ function useSagepilotChat() {
|
|
|
2949
3415
|
onConversationCreated
|
|
2950
3416
|
};
|
|
2951
3417
|
}
|
|
3418
|
+
|
|
3419
|
+
// src/brandPush.ts
|
|
3420
|
+
var import_react_native5 = require("react-native");
|
|
3421
|
+
var SagepilotBrandPush = class {
|
|
3422
|
+
/** Keeps brand credentials separate from chat and other workspace/channel sessions. */
|
|
3423
|
+
constructor(config) {
|
|
3424
|
+
this.config = config;
|
|
3425
|
+
this.session = null;
|
|
3426
|
+
this.pending = Promise.resolve();
|
|
3427
|
+
this.started = false;
|
|
3428
|
+
this.appStateSubscription = null;
|
|
3429
|
+
this.scope = parseKey(config.key);
|
|
3430
|
+
if (import_react_native5.Platform.OS !== "android" && import_react_native5.Platform.OS !== "ios") throw new Error("Brand push requires Android or iOS.");
|
|
3431
|
+
this.tokens = new SagepilotTokenManager(`push_${this.scope.workspaceId}_${this.scope.channelId}`, config.tokenStorage);
|
|
3432
|
+
this.http = new SagepilotHttpClient({ fetch: resolveFetch(config.fetch) });
|
|
3433
|
+
this.host = resolveCustomerApiHost(config.host);
|
|
3434
|
+
this.push = new SagepilotPush(config.push, {
|
|
3435
|
+
...this.scope,
|
|
3436
|
+
platform: import_react_native5.Platform.OS,
|
|
3437
|
+
brand: true,
|
|
3438
|
+
customerId: () => this.session?.customer_id ?? null,
|
|
3439
|
+
onError: config.onError,
|
|
3440
|
+
request: (path, method, body) => this.request(path, method, body)
|
|
3441
|
+
});
|
|
3442
|
+
}
|
|
3443
|
+
/** Serializes identity transitions so an old installation is revoked with its original credentials. */
|
|
3444
|
+
transition(operation) {
|
|
3445
|
+
const next = this.pending.then(operation);
|
|
3446
|
+
this.pending = next.catch(() => void 0);
|
|
3447
|
+
return next;
|
|
3448
|
+
}
|
|
3449
|
+
/** Sends through the shared version-stamped transport using the current brand credential. */
|
|
3450
|
+
request(path, method, body) {
|
|
3451
|
+
if (!this.session) return Promise.reject(new Error("Identify a brand customer before using push."));
|
|
3452
|
+
return this.http.request(`${this.host}${CUSTOMER_API_PREFIX}${path}`, {
|
|
3453
|
+
method,
|
|
3454
|
+
headers: withJsonHeaders(this.tokens.createAuthorizationHeader(this.session.session_token)),
|
|
3455
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
3456
|
+
errorMessage: "Push request failed"
|
|
3457
|
+
});
|
|
3458
|
+
}
|
|
3459
|
+
/** Restores durable credentials before registering listeners; never prompts for permission. */
|
|
3460
|
+
start() {
|
|
3461
|
+
return this.transition(async () => {
|
|
3462
|
+
if (this.started) return;
|
|
3463
|
+
this.session = await this.tokens.getSession();
|
|
3464
|
+
await this.push.start();
|
|
3465
|
+
this.appStateSubscription = import_react_native5.AppState.addEventListener("change", (state) => {
|
|
3466
|
+
if (state === "active") {
|
|
3467
|
+
void this.push.sync().catch(this.config.onError);
|
|
3468
|
+
void this.push.flush().catch(this.config.onError);
|
|
3469
|
+
}
|
|
3470
|
+
});
|
|
3471
|
+
this.started = true;
|
|
3472
|
+
});
|
|
3473
|
+
}
|
|
3474
|
+
/** Exchanges a host-server proof, then revokes old ownership before adopting the new session. */
|
|
3475
|
+
identify(identityToken) {
|
|
3476
|
+
return this.transition(async () => {
|
|
3477
|
+
if (!this.started) throw new Error("Call start before identify.");
|
|
3478
|
+
const next = await this.http.request(
|
|
3479
|
+
`${this.host}${CUSTOMER_API_PREFIX}/push/sessions`,
|
|
3480
|
+
{
|
|
3481
|
+
method: "POST",
|
|
3482
|
+
headers: withJsonHeaders(void 0),
|
|
3483
|
+
body: JSON.stringify({ channel_id: this.scope.channelId, identity_token: identityToken }),
|
|
3484
|
+
errorMessage: "Brand identity verification failed"
|
|
3485
|
+
}
|
|
3486
|
+
);
|
|
3487
|
+
if (next.workspace_id !== this.scope.workspaceId || next.channel_id !== this.scope.channelId || !next.customer_id || !next.session_token || !next.session_id || !next.authenticated) {
|
|
3488
|
+
throw new Error("Brand session scope mismatch.");
|
|
3489
|
+
}
|
|
3490
|
+
if (this.session?.customer_id !== next.customer_id) await this.push.pauseAndRevoke();
|
|
3491
|
+
await this.tokens.setSession(next);
|
|
3492
|
+
this.session = next;
|
|
3493
|
+
this.push.resume();
|
|
3494
|
+
});
|
|
3495
|
+
}
|
|
3496
|
+
/** Retains credentials on failed revocation so logout can be retried safely. */
|
|
3497
|
+
logout() {
|
|
3498
|
+
return this.transition(async () => {
|
|
3499
|
+
if (!this.started) throw new Error("Call start before logout.");
|
|
3500
|
+
await this.push.pauseAndRevoke();
|
|
3501
|
+
await this.tokens.clearSession();
|
|
3502
|
+
this.session = null;
|
|
3503
|
+
});
|
|
3504
|
+
}
|
|
3505
|
+
/** Stops listeners; call logout first when the customer is signing out. */
|
|
3506
|
+
destroy() {
|
|
3507
|
+
return this.transition(async () => {
|
|
3508
|
+
this.appStateSubscription?.remove();
|
|
3509
|
+
this.push.stop();
|
|
3510
|
+
});
|
|
3511
|
+
}
|
|
3512
|
+
};
|
|
2952
3513
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2953
3514
|
0 && (module.exports = {
|
|
2954
3515
|
SAGEPILOT_DEFAULT_IMAGE_MAX_DIMENSION,
|
|
2955
3516
|
SAGEPILOT_DEFAULT_IMAGE_MAX_FILE_SIZE_BYTES,
|
|
2956
3517
|
SAGEPILOT_DEFAULT_IMAGE_QUALITY,
|
|
3518
|
+
SagepilotBrandPush,
|
|
2957
3519
|
SagepilotChat,
|
|
2958
3520
|
SagepilotChatError,
|
|
2959
3521
|
SagepilotChatProvider,
|
|
2960
3522
|
SagepilotFilePickerError,
|
|
2961
3523
|
createAsyncStorageCacheStorage,
|
|
3524
|
+
createFirebasePushAdapter,
|
|
2962
3525
|
createKeychainTokenStorage,
|
|
2963
3526
|
createSagepilotFilePicker,
|
|
2964
3527
|
createSagepilotFileStore,
|