@onairosofficial/onairos-capacitor 0.1.4 → 0.1.5

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.
Files changed (88) hide show
  1. package/OnairosofficialOnairosCapacitor.podspec +1 -1
  2. package/README.md +1 -1
  3. package/dist/onairos.capacitor.esm.js +509 -1
  4. package/dist/onairos.capacitor.esm.turbopack.js +509 -1
  5. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +187 -945
  6. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosRNScrapers.swift +1800 -0
  7. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +180 -629
  8. package/onairos.d.ts +24 -0
  9. package/package.json +5 -2
  10. package/src/assets/connectors/Linkedinicon.png +0 -0
  11. package/src/assets/connectors/Redditicon.png +0 -0
  12. package/src/assets/connectors/YouTubeicon2.png +0 -0
  13. package/src/assets/connectors/chatgpt.png +0 -0
  14. package/src/assets/connectors/claude.png +0 -0
  15. package/src/assets/connectors/instagram.png +0 -0
  16. package/src/assets/connectors/netflix.png +0 -0
  17. package/src/assets/connectors/pinterest.png +0 -0
  18. package/src/assets/connectors/sephora.png +0 -0
  19. package/src/assets/connectors/spotify.png +0 -0
  20. package/src/assets/connectors/tiktok.png +0 -0
  21. package/src/assets/permissions/onairos.png +0 -0
  22. package/src/assets/permissions/personalization.png +0 -0
  23. package/src/assets/permissions/public-profile-person.png +0 -0
  24. package/src/assets/permissions/raw-memories.png +0 -0
  25. package/src/capacitorConnectorCatalog.js +2 -6
  26. package/src/components/DataRequest.jsx +96 -532
  27. package/src/components/PinSetup.jsx +39 -226
  28. package/src/components/SDKDesignPreview.jsx +33 -0
  29. package/src/components/SessionUserBar.jsx +2 -1
  30. package/src/components/UniversalOnboarding.jsx +190 -423
  31. package/src/components/WelcomeScreen.jsx +7 -0
  32. package/src/components/parity/NativeConnections.jsx +136 -0
  33. package/src/components/parity/NativeScreens.jsx +48 -0
  34. package/src/components/ui/PageLayout.jsx +7 -3
  35. package/src/nativeImport/ConnectorLoading.jsx +13 -0
  36. package/src/nativeImport/CustomImportSession.js +115 -0
  37. package/src/nativeImport/ImportIcon.jsx +29 -0
  38. package/src/nativeImport/ImportProgress.jsx +24 -0
  39. package/src/nativeImport/ImportStatus.jsx +9 -0
  40. package/src/nativeImport/NativeChatImport.jsx +28 -0
  41. package/src/nativeImport/NativeImportSession.js +123 -0
  42. package/src/nativeImport/NativeScraperImport.jsx +57 -0
  43. package/src/nativeImport/SmartFilter.jsx +28 -0
  44. package/src/nativeImport/customPayload.js +37 -0
  45. package/src/nativeImport/netflixExport.js +30 -0
  46. package/src/nativeImport/netflixHistory.js +28 -0
  47. package/src/nativeImport/netflixSession.js +59 -0
  48. package/src/nativeImport/rawHandoff.js +7 -0
  49. package/src/nativeImport/rn/config/api.js +5 -0
  50. package/src/nativeImport/rn/services/apiKeyService.js +2 -0
  51. package/src/nativeImport/rn/services/hingePayload.js +37 -0
  52. package/src/nativeImport/rn/services/nativeConversationImport.js +138 -0
  53. package/src/nativeImport/rn/services/nativeFileTransfer.js +127 -0
  54. package/src/nativeImport/rn/services/nativeRawRedaction.js +136 -0
  55. package/src/nativeImport/rn/services/netflixPayload.js +70 -0
  56. package/src/nativeImport/rn/services/rawMemoryPolicy.js +38 -0
  57. package/src/nativeImport/rn/services/sephoraPayload.js +166 -0
  58. package/src/nativeImport/rn/services/spotifyPayload.js +99 -0
  59. package/src/nativeImport/rn/source-manifest.json +45 -0
  60. package/src/nativeImport/rn/utils/importedFiles.js +74 -0
  61. package/src/nativeImport/rn/utils/nativeImportDates.js +45 -0
  62. package/src/nativeImport/rn/utils/nativeImportFileReceiver.js +51 -0
  63. package/src/nativeImport/rn/utils/nativeImportMetadata.js +74 -0
  64. package/src/nativeImport/rn/utils/nativeImportTopics.js +56 -0
  65. package/src/nativeImport/rn/utils/rawExportDelivery.js +12 -0
  66. package/src/nativeImport/rn/utils/webviewScripts/chatgptDiscovery.js +99 -0
  67. package/src/nativeImport/rn/utils/webviewScripts/claude.js +349 -0
  68. package/src/nativeImport/rn/utils/webviewScripts/gemini.js +356 -0
  69. package/src/nativeImport/rn/utils/webviewScripts/hinge.js +375 -0
  70. package/src/nativeImport/rn/utils/webviewScripts/instagram.js +152 -0
  71. package/src/nativeImport/rn/utils/webviewScripts/linkedin.js +825 -0
  72. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTImport.js +202 -0
  73. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTSession.js +63 -0
  74. package/src/nativeImport/rn/utils/webviewScripts/nativeImportFiles.js +132 -0
  75. package/src/nativeImport/rn/utils/webviewScripts/nativeImportProviders.js +80 -0
  76. package/src/nativeImport/rn/utils/webviewScripts/nativeLoginViewport.js +28 -0
  77. package/src/nativeImport/rn/utils/webviewScripts/netflix.js +257 -0
  78. package/src/nativeImport/rn/utils/webviewScripts/sephora.js +862 -0
  79. package/src/nativeImport/rn/utils/webviewScripts/sephoraSession.js +160 -0
  80. package/src/nativeImport/rn/utils/webviewScripts/spotify.js +1868 -0
  81. package/src/nativeImport/rn/utils/webviewScripts/telegram.js +630 -0
  82. package/src/nativeImport/rn/utils/webviewScripts/tiktok.js +2920 -0
  83. package/src/onairos.core.jsx +3 -0
  84. package/src/onairosButton.jsx +23 -17
  85. package/src/styles/onairos-rn-parity.css +175 -0
  86. package/src/styles/tailwind.capacitor.css +4 -0
  87. package/src/utils/nativeConnectorSession.js +18 -0
  88. package/src/utils/parityPolicy.js +41 -0
@@ -0,0 +1,862 @@
1
+ // Synced from RN utils/webviewScripts/sephora.ts by scripts/sync-rn-connectors.cjs.
2
+ import { SEPHORA_SESSION_SCRIPT } from "./sephoraSession.js";
3
+ const SEPHORA_CONSENT_POPUP_SCRIPT = `
4
+ (function() {
5
+ try {
6
+ const existing = document.getElementById('onairos-consent-overlay');
7
+ if (existing) existing.remove();
8
+
9
+ const overlay = document.createElement('div');
10
+ overlay.id = 'onairos-consent-overlay';
11
+ overlay.style.cssText = \`
12
+ position: fixed;
13
+ top: 0;
14
+ left: 0;
15
+ width: 100%;
16
+ height: 100%;
17
+ background: rgba(0, 0, 0, 0.7);
18
+ z-index: 999999;
19
+ display: flex;
20
+ align-items: center;
21
+ justify-content: center;
22
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
23
+ \`;
24
+
25
+ const popup = document.createElement('div');
26
+ popup.style.cssText = \`
27
+ background: white;
28
+ border-radius: 16px;
29
+ padding: 32px;
30
+ max-width: 400px;
31
+ width: 90%;
32
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
33
+ \`;
34
+
35
+ popup.innerHTML = \`
36
+ <div style="text-align: center;">
37
+ <div style="font-size: 48px; margin-bottom: 16px;">\u{1F484}</div>
38
+ <h2 style="margin: 0 0 12px 0; font-size: 24px; color: #1a1a1a;">
39
+ Export Sephora Data?
40
+ </h2>
41
+ <p style="margin: 0 0 24px 0; color: #666; font-size: 16px; line-height: 1.5;">
42
+ Allow Onairos to export your Sephora shopping activity (basket, favorites, purchases) for analysis?
43
+ </p>
44
+ <div style="display: flex; gap: 12px; justify-content: center;">
45
+ <button id="onairos-deny" style="
46
+ flex: 1;
47
+ padding: 14px 24px;
48
+ border: 2px solid #e0e0e0;
49
+ background: white;
50
+ color: #666;
51
+ border-radius: 8px;
52
+ font-size: 16px;
53
+ font-weight: 600;
54
+ cursor: pointer;
55
+ ">Deny</button>
56
+ <button id="onairos-allow" style="
57
+ flex: 1;
58
+ padding: 14px 24px;
59
+ border: none;
60
+ background: linear-gradient(135deg, #000000 0%, #333333 100%);
61
+ color: white;
62
+ border-radius: 8px;
63
+ font-size: 16px;
64
+ font-weight: 600;
65
+ cursor: pointer;
66
+ ">Allow</button>
67
+ </div>
68
+ </div>
69
+ \`;
70
+
71
+ overlay.appendChild(popup);
72
+ document.body.appendChild(overlay);
73
+
74
+ document.getElementById('onairos-deny').onclick = () => {
75
+ overlay.remove();
76
+ window.ReactNativeWebView.postMessage(JSON.stringify({
77
+ type: 'SEPHORA_CONSENT',
78
+ status: 'denied'
79
+ }));
80
+ };
81
+
82
+ document.getElementById('onairos-allow').onclick = () => {
83
+ document.getElementById('onairos-allow').innerHTML = '\u23F3 Starting...';
84
+ document.getElementById('onairos-allow').disabled = true;
85
+
86
+ window.ReactNativeWebView.postMessage(JSON.stringify({
87
+ type: 'SEPHORA_CONSENT',
88
+ status: 'allowed'
89
+ }));
90
+
91
+ setTimeout(() => overlay.remove(), 500);
92
+ };
93
+ } catch (error) {
94
+ window.ReactNativeWebView.postMessage(JSON.stringify({
95
+ type: 'SEPHORA_CONSENT',
96
+ status: 'error',
97
+ message: error.message
98
+ }));
99
+ }
100
+ })();
101
+ true;
102
+ `;
103
+ const SEPHORA_EXPORT_SCRIPT = SEPHORA_SESSION_SCRIPT + `
104
+ (function() {
105
+ try {
106
+ function postDebug(message, details) {
107
+ // Never bridge profile fields, tokens, request URLs or backend bodies as logs.
108
+ var safe = {};
109
+ Object.keys(details || {}).forEach(function(key) {
110
+ if (/^(has[A-Z]|isExpired$|ok$|status$|count$|itemCount$|orderCount$|basketItems$|loves$|purchases$)/.test(key) &&
111
+ (typeof details[key] === 'boolean' || typeof details[key] === 'number')) safe[key] = details[key];
112
+ });
113
+ try { window.ReactNativeWebView.postMessage(JSON.stringify({type: 'DEBUG_LOG', message: '[SEPHORA] ' + message, details: safe})); } catch (_) {}
114
+ }
115
+ var session = window.__onairosSephoraSession;
116
+ if (!session || !session.read().authenticated) {
117
+ window.ReactNativeWebView.postMessage(JSON.stringify({type: 'SEPHORA_EXPORT_ERROR', code: 'AUTH_REQUIRED'}));
118
+ return;
119
+ }
120
+ if (window.__onairosSephoraExportRunning) return;
121
+ postDebug('Script started', { version: 'SDK_V6_PURCHASE_DATE_SKU_FIX' });
122
+
123
+ if (!document.body) {
124
+ window.ReactNativeWebView.postMessage(JSON.stringify({
125
+ type: 'SEPHORA_EXPORT_ERROR',
126
+ message: 'Page not ready'
127
+ }));
128
+ return;
129
+ }
130
+
131
+ // ============================================================
132
+ // SEPHORA API CONFIGURATION
133
+ // ============================================================
134
+
135
+ // Try to pull the API key Sephora itself uses for its own requests
136
+ function extractApiKey() {
137
+ try {
138
+ var w = window;
139
+ if (w.sephoraConfig && w.sephoraConfig.xApiKey) return w.sephoraConfig.xApiKey;
140
+ if (w.SephoraBootstrap && w.SephoraBootstrap.apiKey) return w.SephoraBootstrap.apiKey;
141
+ if (w.__config__ && w.__config__.apiKey) return w.__config__.apiKey;
142
+ if (w.__PRELOADED_STATE__ && w.__PRELOADED_STATE__.config && w.__PRELOADED_STATE__.config.xApiKey) return w.__PRELOADED_STATE__.config.xApiKey;
143
+ // Scan meta tags
144
+ var meta = document.querySelector('meta[name="x-api-key"]') || document.querySelector('meta[name="apiKey"]');
145
+ if (meta) return meta.getAttribute('content');
146
+ } catch (e) {}
147
+ return 'nQc7BFt78yJBvfYDKtle9APd5RrX984i'; // fallback
148
+ }
149
+
150
+ const SEPHORA_CONFIG = {
151
+ baseUrl: 'https://www.sephora.com',
152
+ apiKey: extractApiKey(),
153
+
154
+ endpoints: {
155
+ basket: '/api/shopping-cart/basket',
156
+ profileTemplate: '/gapi/users/profiles/{profileId}/current/full',
157
+ lovesTemplate: '/gway/v1/dotcom/users/profiles/{profileId}/lists/skus/all',
158
+ purchasesTemplate: '/api/bi/profiles/{profileId}/purchases',
159
+ },
160
+
161
+ params: {
162
+ profile: '?skipApis=targetersResult&includeApis=profile,basket,loves,shoppingList,segments',
163
+ loves: '?itemsPerPage=100&currentPage=1&listShortNameLength=20&skipProductDetails=false&includeInactiveSkus=true&fetchAllLovesList=true&sortBy=recently&includeCategories=true',
164
+ purchases: '?sortBy=recently&itemsPerPage=100&groupBy=none&excludeSamples=true&excludeRewards=true',
165
+ }
166
+ };
167
+
168
+ postDebug('API key source', { hasKey: !!SEPHORA_CONFIG.apiKey });
169
+
170
+ // ============================================================
171
+ // TOKEN EXTRACTION - From PLATFORM_APIS.md spec
172
+ // ============================================================
173
+ function getSephoraToken() {
174
+ var tokenKeys = ['seph-access-token', 'sephoraAccessToken', 'accessToken'];
175
+
176
+ // Try localStorage
177
+ for (var i = 0; i < tokenKeys.length; i++) {
178
+ var token = localStorage.getItem(tokenKeys[i]);
179
+ if (token) {
180
+ try {
181
+ var parsed = JSON.parse(token);
182
+ if (parsed && parsed.data) return { token: parsed.data, expiry: parsed.expiry };
183
+ } catch (e) {
184
+ return { token: token, expiry: null }; // Not JSON, use as-is
185
+ }
186
+ }
187
+ }
188
+
189
+ // Try cookies
190
+ var cookieMatch = (document.cookie || '').match(/seph-access-token=([^;]+)/);
191
+ if (cookieMatch) return { token: cookieMatch[1], expiry: null };
192
+
193
+ // Try window state
194
+ if (window.__PRELOADED_STATE__ && window.__PRELOADED_STATE__.user) {
195
+ return { token: window.__PRELOADED_STATE__.user.accessToken, expiry: null };
196
+ }
197
+
198
+ return { token: null, expiry: null };
199
+ }
200
+
201
+ // ============================================================
202
+ // PROFILE ID EXTRACTION - From PLATFORM_APIS.md spec
203
+ // ============================================================
204
+ function getProfileId(tokenData) {
205
+ var confirmed = session.profile();
206
+ if (confirmed && confirmed.profileId) return confirmed.profileId;
207
+ // Method 1: From token (JWT payload)
208
+ if (tokenData.token) {
209
+ try {
210
+ var payload = JSON.parse(atob(tokenData.token.split('.')[1]));
211
+ if (payload.sub) return payload.sub;
212
+ } catch (e) {}
213
+ }
214
+
215
+ // Method 2: From localStorage
216
+ var profileId = localStorage.getItem('biAccountId') ||
217
+ localStorage.getItem('profileId');
218
+ if (profileId) return profileId;
219
+
220
+ // Method 3: From window state
221
+ if (window.__PRELOADED_STATE__ && window.__PRELOADED_STATE__.user) {
222
+ return window.__PRELOADED_STATE__.user.profileId;
223
+ }
224
+
225
+ return null;
226
+ }
227
+
228
+ // ============================================================
229
+ // TOKEN EXPIRY CHECK - From PLATFORM_APIS.md spec
230
+ // ============================================================
231
+ function isTokenExpired(tokenData) {
232
+ if (!tokenData || !tokenData.expiry) return false; // Can't check, assume valid
233
+
234
+ try {
235
+ var expiry = parseInt(tokenData.expiry, 10);
236
+ var now = Math.floor(Date.now() / 1000);
237
+ return now >= expiry;
238
+ } catch (e) {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ console.log('\u{1F680} [SEPHORA] Starting extraction with real APIs...');
244
+
245
+ (async () => {
246
+ try {
247
+ // STEP 1: Get authentication data
248
+ window.ReactNativeWebView.postMessage(JSON.stringify({
249
+ type: 'SEPHORA_EXPORT_PROGRESS',
250
+ stage: 'fetching_auth',
251
+ progress: 2,
252
+ message: 'Getting authentication...'
253
+ }));
254
+
255
+ console.log('[SEPHORA] Getting auth data...');
256
+ const tokenData = getSephoraToken();
257
+ const profileId = getProfileId(tokenData);
258
+
259
+ postDebug('Auth state', {
260
+ hasToken: !!tokenData.token,
261
+ tokenLength: tokenData.token ? tokenData.token.length : 0,
262
+ hasExpiry: !!tokenData.expiry,
263
+ isExpired: isTokenExpired(tokenData),
264
+ profileId: profileId
265
+ });
266
+
267
+
268
+
269
+ if (isTokenExpired(tokenData)) {
270
+ console.warn('[SEPHORA] Token may be expired');
271
+ }
272
+
273
+ // Use headers captured from Sephora's own page requests.
274
+ // Sephora APIs are cookie-authed \u2014 DON'T add a Bearer token unless Sephora
275
+ // itself sent one, as it can cause 401s on endpoints that don't expect it.
276
+ var capturedCapture = window.__onairosCapture || {};
277
+ var capturedHeaders = capturedCapture.headers || null;
278
+ var capturedData = capturedCapture.data || {};
279
+ var resolvedApiKey = (capturedHeaders && capturedHeaders['x-api-key']) || SEPHORA_CONFIG.apiKey;
280
+ var headers = {
281
+ 'Accept': 'application/json',
282
+ 'Content-Type': 'application/json',
283
+ 'x-api-key': resolvedApiKey,
284
+ };
285
+ // Replay only headers observed on Sephora's own requests. Cookie sessions
286
+ // do not need an invented Bearer header (guest tokens can cause 401s).
287
+ ['authorization', 'seph-access-token', 'x-seph-access-token'].forEach(function(name) {
288
+ if (capturedHeaders && capturedHeaders[name]) headers[name] = capturedHeaders[name];
289
+ });
290
+ window.__onairosSephoraExportRunning = true;
291
+ var originalFetch = window.fetch;
292
+ var requestStatuses = [];
293
+ var requestFailures = 0;
294
+ async function fetchWithTimeout(url, options) {
295
+ var controller = new AbortController();
296
+ var timeout = setTimeout(function() { controller.abort(); }, 15000);
297
+ try {
298
+ var response = await originalFetch(url, Object.assign({}, options, {signal: controller.signal}));
299
+ requestStatuses.push(response.status);
300
+ // Consume inside the deadline too; a response can stall while reading.
301
+ var body = await response.text();
302
+ return {ok: response.ok, status: response.status, text: async function() {return body;}, json: async function() {return JSON.parse(body);}};
303
+ } catch (error) { requestFailures++; throw error; } finally { clearTimeout(timeout); }
304
+ }
305
+ postDebug('Headers', {
306
+ apiKeySrc: (capturedHeaders && capturedHeaders['x-api-key']) ? 'captured' : 'fallback',
307
+ hasApiKey: !!resolvedApiKey,
308
+ hasAuth: !!(capturedHeaders && capturedHeaders['Authorization']),
309
+ capturedDataKeys: Object.keys(capturedData).join(',') || 'none',
310
+ });
311
+
312
+ // STEP 2: Fetch basket (doesn't require profileId)
313
+ window.ReactNativeWebView.postMessage(JSON.stringify({
314
+ type: 'SEPHORA_EXPORT_PROGRESS',
315
+ stage: 'fetching_basket',
316
+ progress: 10,
317
+ message: 'Fetching shopping basket...'
318
+ }));
319
+
320
+ let basket = { items: [], subtotal: 0 };
321
+ let extractedProfileId = profileId;
322
+ console.log('[SEPHORA] Fetching basket from:', SEPHORA_CONFIG.endpoints.basket);
323
+ postDebug('Fetching basket', {
324
+ url: SEPHORA_CONFIG.baseUrl + SEPHORA_CONFIG.endpoints.basket
325
+ });
326
+
327
+ function parseBasketData(basketData) {
328
+ var rawBasket = basketData.basket || basketData.BasketListModel || basketData;
329
+ var rawItems = rawBasket.items || rawBasket.products || basketData.items || basketData.products || [];
330
+ if (!Array.isArray(rawItems)) rawItems = [];
331
+ postDebug('Basket keys', { keys: Object.keys(basketData).join(','), count: rawItems.length });
332
+ basket = {
333
+ items: rawItems.map(function(item) {
334
+ return {
335
+ skuId: item.skuId || item.sku_id || (item.sku && item.sku.skuId) || item.id,
336
+ productId: item.productId || item.product_id || (item.sku && item.sku.productId),
337
+ name: item.displayName || item.name || item.productName || (item.sku && (item.sku.displayName || item.sku.productName)),
338
+ brand: item.brand || item.brandName || (item.sku && item.sku.brandName),
339
+ price: item.price || item.currentPrice || item.listPrice,
340
+ quantity: item.quantity || item.qty || 1,
341
+ size: item.size || item.variationValue,
342
+ imageUrl: item.image || item.heroImage || item.thumbnail,
343
+ };
344
+ }),
345
+ subtotal: rawBasket.subtotal || rawBasket.total || rawBasket.orderTotal || basketData.subtotal || 0,
346
+ biPoints: rawBasket.biPoints || rawBasket.beautyInsiderPoints || 0,
347
+ };
348
+ if (!extractedProfileId && (rawBasket.profileId || basketData.profileId)) {
349
+ extractedProfileId = rawBasket.profileId || basketData.profileId;
350
+ }
351
+ postDebug('Basket parsed', { itemCount: basket.items.length, subtotal: basket.subtotal });
352
+ }
353
+
354
+ function hasMeaningfulBasketCapture(data) {
355
+ if (!data || typeof data !== 'object') return false;
356
+ var rawBasket = data.basket || data.BasketListModel || data;
357
+ var rawItems = rawBasket.items || rawBasket.products || data.items || data.products || [];
358
+ return Array.isArray(rawItems) && rawItems.length > 0;
359
+ }
360
+
361
+ if (hasMeaningfulBasketCapture(capturedData.basket)) {
362
+ postDebug('Basket from meaningful capture', {});
363
+ parseBasketData(capturedData.basket);
364
+ } else {
365
+ if (capturedData.basket) {
366
+ postDebug('Basket capture unusable; fetching live basket', {});
367
+ }
368
+ try {
369
+ const basketResponse = await fetchWithTimeout(SEPHORA_CONFIG.baseUrl + SEPHORA_CONFIG.endpoints.basket, {
370
+ method: 'GET', credentials: 'include', headers: headers
371
+ });
372
+ postDebug('Basket HTTP status', { status: basketResponse.status, ok: basketResponse.ok });
373
+ const basketText = await basketResponse.text();
374
+ postDebug('Basket body received', { hasBody: basketText.length > 0 });
375
+ if (basketResponse.ok) {
376
+ var basketData = {};
377
+ try { basketData = JSON.parse(basketText); } catch (e) { postDebug('Basket parse error', { err: e.message }); }
378
+ parseBasketData(basketData);
379
+ }
380
+ } catch (basketErr) {
381
+ postDebug('Basket fetch error', { message: basketErr.message });
382
+ }
383
+ }
384
+
385
+ // STEP 3: Fetch Loves/Favorites (requires profileId)
386
+ window.ReactNativeWebView.postMessage(JSON.stringify({
387
+ type: 'SEPHORA_EXPORT_PROGRESS',
388
+ stage: 'fetching_loves',
389
+ progress: 30,
390
+ message: 'Fetching loved products...'
391
+ }));
392
+
393
+ let loves = [];
394
+ if (extractedProfileId) {
395
+ const lovesUrl = SEPHORA_CONFIG.baseUrl +
396
+ SEPHORA_CONFIG.endpoints.lovesTemplate.replace('{profileId}', extractedProfileId) +
397
+ SEPHORA_CONFIG.params.loves;
398
+
399
+ console.log('[SEPHORA] Fetching favorites');
400
+ postDebug('Fetching loves', { url: lovesUrl });
401
+
402
+ function parseLovesData(lovesData) {
403
+ var rawLoves = lovesData.skus || lovesData.items || lovesData.products ||
404
+ lovesData.listItems || (lovesData.skuList && lovesData.skuList.items) ||
405
+ (Array.isArray(lovesData) ? lovesData : []);
406
+ if (!Array.isArray(rawLoves) && rawLoves) {
407
+ rawLoves = rawLoves.items || rawLoves.products || rawLoves.skus || [];
408
+ }
409
+ if (!Array.isArray(rawLoves)) {
410
+ rawLoves = [];
411
+ }
412
+ postDebug('Loves keys', { keys: Object.keys(lovesData).join(','), count: rawLoves.length });
413
+ loves = rawLoves.map(function(item) {
414
+ var nestedSku = item && item.sku && typeof item.sku === 'object' ? item.sku : {};
415
+ var nestedProduct = item && item.product && typeof item.product === 'object' ? item.product : {};
416
+ return {
417
+ skuId: item.skuId || item.sku_id || nestedSku.skuId || nestedSku.id || item.id,
418
+ productId: item.productId || item.product_id || nestedSku.productId || nestedProduct.productId,
419
+ name: item.displayName || item.name || item.productName || nestedSku.displayName || nestedSku.productName || nestedProduct.displayName || nestedProduct.name,
420
+ brand: item.brand || item.brandName || nestedSku.brandName || nestedProduct.brandName,
421
+ category: item.category || item.primaryCategory || item.breadcrumb,
422
+ price: item.price || item.listPrice || item.currentPrice || nestedSku.listPrice || nestedSku.currentPrice,
423
+ salePrice: item.salePrice || item.discountedPrice,
424
+ rating: item.rating || item.averageRating || item.starRating,
425
+ reviewCount: item.reviewCount || item.numberOfReviews,
426
+ isInStock: item.isInStock !== false && item.inStock !== false,
427
+ isOnSale: item.isOnSale || item.onSale || !!item.salePrice,
428
+ imageUrl: item.image || item.heroImage || item.thumbnail || nestedSku.image,
429
+ addedAt: item.addedAt || item.dateAdded || item.createdAt,
430
+ };
431
+ });
432
+ postDebug('Loves parsed', { itemCount: loves.length });
433
+ }
434
+
435
+ function hasMeaningfulLovesCapture(data) {
436
+ if (!data || typeof data !== 'object') return false;
437
+ var rawLoves = data.skus || data.items || data.products ||
438
+ data.listItems || (data.skuList && data.skuList.items) ||
439
+ (Array.isArray(data) ? data : []);
440
+ if (!Array.isArray(rawLoves) && rawLoves) {
441
+ rawLoves = rawLoves.items || rawLoves.products || rawLoves.skus || [];
442
+ }
443
+ return Array.isArray(rawLoves) && rawLoves.length > 0;
444
+ }
445
+
446
+ if (hasMeaningfulLovesCapture(capturedData.loves)) {
447
+ postDebug('Loves from meaningful capture', {});
448
+ parseLovesData(capturedData.loves);
449
+ } else {
450
+ if (capturedData.loves) {
451
+ postDebug('Loves capture unusable; fetching live loves', {});
452
+ }
453
+ try {
454
+ const lovesResponse = await fetchWithTimeout(lovesUrl, {
455
+ method: 'GET', credentials: 'include', headers: headers
456
+ });
457
+ postDebug('Loves HTTP status', { status: lovesResponse.status, ok: lovesResponse.ok });
458
+ const lovesText = await lovesResponse.text();
459
+ postDebug('Loves body received', { hasBody: lovesText.length > 0 });
460
+ if (lovesResponse.ok) {
461
+ var lovesData = {};
462
+ try { lovesData = JSON.parse(lovesText); } catch (e) { postDebug('Loves parse error', { err: e.message }); }
463
+ parseLovesData(lovesData);
464
+ }
465
+ } catch (lovesErr) {
466
+ postDebug('Loves fetch error', { message: lovesErr.message });
467
+ }
468
+ }
469
+ } else {
470
+ console.warn('[SEPHORA] Skipping loves - no profileId');
471
+ postDebug('Skipping loves', { reason: 'no profileId' });
472
+ }
473
+
474
+ // STEP 4: Fetch Purchase History (requires profileId)
475
+ window.ReactNativeWebView.postMessage(JSON.stringify({
476
+ type: 'SEPHORA_EXPORT_PROGRESS',
477
+ stage: 'fetching_purchases',
478
+ progress: 55,
479
+ message: 'Fetching purchase history...'
480
+ }));
481
+
482
+ let purchases = [];
483
+
484
+ function parsePurchasesData(purchasesData) {
485
+ var rawPurchases = purchasesData.purchases || purchasesData.orders ||
486
+ purchasesData.purchaseHistoryList || purchasesData.items ||
487
+ purchasesData.purchasedItems ||
488
+ (purchasesData.purchaseHistory && purchasesData.purchaseHistory.orders) ||
489
+ (purchasesData.purchaseHistory && purchasesData.purchaseHistory.purchasedItems) ||
490
+ (Array.isArray(purchasesData) ? purchasesData : []);
491
+ if (!Array.isArray(rawPurchases) && rawPurchases) {
492
+ rawPurchases = rawPurchases.orders || rawPurchases.items || rawPurchases.purchasedItems || [];
493
+ }
494
+ if (!Array.isArray(rawPurchases)) {
495
+ rawPurchases = [];
496
+ }
497
+ postDebug('Purchases keys', { keys: Object.keys(purchasesData).join(','), count: rawPurchases.length });
498
+ if (rawPurchases.length > 0 && rawPurchases[0] && typeof rawPurchases[0] === 'object') {
499
+ postDebug('Purchases first entry keys', { keys: Object.keys(rawPurchases[0]).join(',') });
500
+ }
501
+
502
+ function normalizePurchaseItem(rawItem, index) {
503
+ var source = rawItem || {};
504
+ var nestedProduct = source.product || source.sku || source.skuItem || source.item || source.productData || {};
505
+ var sourceSku = source.sku;
506
+ var sourceSkuId = (sourceSku && typeof sourceSku === 'object') ? sourceSku.skuId : sourceSku;
507
+
508
+ var skuId = source.skuId || source.sku_id || sourceSkuId || nestedProduct.skuId || nestedProduct.sku_id || nestedProduct.id || source.id || null;
509
+ var productId = source.productId || source.product_id || nestedProduct.productId || nestedProduct.product_id || nestedProduct.id || null;
510
+ var name = source.displayName || source.name || source.productName || nestedProduct.displayName || nestedProduct.name || nestedProduct.productName || null;
511
+ var brand = source.brand || source.brandName || nestedProduct.brand || nestedProduct.brandName || null;
512
+ var price = source.price || source.purchasePrice || source.salePrice ||
513
+ source.listPrice || nestedProduct.price || nestedProduct.purchasePrice || nestedProduct.listPrice || null;
514
+ var quantity = source.quantity || nestedProduct.quantity || 1;
515
+
516
+ if (!skuId && productId) {
517
+ skuId = 'PRODUCT_' + productId;
518
+ }
519
+ if (!skuId && name) {
520
+ skuId = 'ITEM_' + index;
521
+ }
522
+ if (!name) {
523
+ name = source.title || nestedProduct.title || 'Unknown product';
524
+ }
525
+
526
+ return {
527
+ skuId: skuId,
528
+ productId: productId || undefined,
529
+ name: name,
530
+ brand: brand || undefined,
531
+ price: price || undefined,
532
+ quantity: quantity,
533
+ };
534
+ }
535
+
536
+ purchases = rawPurchases.map(function(orderLike, index) {
537
+ var nestedItems = orderLike.items || orderLike.products || orderLike.skus || [];
538
+ var hasNestedItems = Array.isArray(nestedItems) && nestedItems.length > 0;
539
+
540
+ var orderItems = hasNestedItems
541
+ ? nestedItems.map(function(item, nestedIndex) {
542
+ return normalizePurchaseItem(item, nestedIndex);
543
+ })
544
+ : [normalizePurchaseItem(orderLike, index)];
545
+
546
+ var fallbackOrderId = orderLike.orderId || orderLike.id || orderLike.orderNumber || ('ORDER_' + index);
547
+ var transactionDate = orderLike.transactionDate ||
548
+ orderLike.lastPurchasedDate ||
549
+ (orderLike.sku && orderLike.sku.transactionDate) ||
550
+ null;
551
+ var normalizedOrderDate = null;
552
+ if (typeof transactionDate === 'number') {
553
+ normalizedOrderDate = new Date(transactionDate).toISOString();
554
+ } else if (typeof transactionDate === 'string' && transactionDate) {
555
+ // If it's an epoch-in-string, normalize; otherwise pass through.
556
+ var asNumber = Number(transactionDate);
557
+ normalizedOrderDate = Number.isNaN(asNumber)
558
+ ? transactionDate
559
+ : new Date(asNumber).toISOString();
560
+ }
561
+
562
+ var fallbackOrderDate = orderLike.orderDate || orderLike.date || orderLike.purchaseDate ||
563
+ normalizedOrderDate || orderLike.createdAt || null;
564
+
565
+ return {
566
+ orderId: fallbackOrderId,
567
+ orderDate: fallbackOrderDate,
568
+ total: orderLike.total || orderLike.orderTotal || null,
569
+ channel: orderLike.channel || orderLike.purchaseChannel || 'online',
570
+ items: orderItems.filter(function(item) { return item && item.skuId && item.name; }),
571
+ };
572
+ }).filter(function(order) {
573
+ return !!order.orderId && order.items.length > 0;
574
+ });
575
+ postDebug('Purchases parsed', { orderCount: purchases.length });
576
+
577
+ var declaredCount = purchasesData.purchasedItemsCount || purchasesData.totalPurchasedItems || 0;
578
+ if (declaredCount > 0 && purchases.length === 0) {
579
+ postDebug('Purchases parse mismatch', {
580
+ declaredCount: declaredCount,
581
+ parsedCount: purchases.length
582
+ });
583
+ }
584
+ }
585
+
586
+ function hasMeaningfulPurchasesCapture(data) {
587
+ if (!data || typeof data !== 'object') return false;
588
+ var rawPurchases = data.purchases || data.orders ||
589
+ data.purchaseHistoryList || data.items ||
590
+ data.purchasedItems ||
591
+ (data.purchaseHistory && data.purchaseHistory.orders) ||
592
+ (data.purchaseHistory && data.purchaseHistory.purchasedItems) ||
593
+ (Array.isArray(data) ? data : []);
594
+ if (!Array.isArray(rawPurchases) && rawPurchases) {
595
+ rawPurchases = rawPurchases.orders || rawPurchases.items || rawPurchases.purchasedItems || [];
596
+ }
597
+ return Array.isArray(rawPurchases) && rawPurchases.length > 0;
598
+ }
599
+
600
+ if (hasMeaningfulPurchasesCapture(capturedData.purchases)) {
601
+ postDebug('Purchases from meaningful capture', {});
602
+ parsePurchasesData(capturedData.purchases);
603
+ } else if (extractedProfileId) {
604
+ if (capturedData.purchases) {
605
+ postDebug('Purchases capture unusable; fetching live purchases', {});
606
+ }
607
+ const purchasesUrl = SEPHORA_CONFIG.baseUrl +
608
+ SEPHORA_CONFIG.endpoints.purchasesTemplate.replace('{profileId}', extractedProfileId) +
609
+ SEPHORA_CONFIG.params.purchases;
610
+
611
+ postDebug('Fetching purchases', { url: purchasesUrl });
612
+
613
+ try {
614
+ const purchasesResponse = await fetchWithTimeout(purchasesUrl, {
615
+ method: 'GET',
616
+ credentials: 'include',
617
+ headers: headers
618
+ });
619
+
620
+ postDebug('Purchases HTTP status', { status: purchasesResponse.status, ok: purchasesResponse.ok });
621
+
622
+ const purchasesText = await purchasesResponse.text();
623
+ postDebug('Purchases body received', { hasBody: purchasesText.length > 0 });
624
+
625
+ if (purchasesResponse.ok) {
626
+ var purchasesData = {};
627
+ try { purchasesData = JSON.parse(purchasesText); } catch (e) { postDebug('Purchases parse error', { err: e.message }); }
628
+ parsePurchasesData(purchasesData);
629
+ } else if (purchasesResponse.status === 401 || purchasesResponse.status === 403) {
630
+ postDebug('Purchases auth failed, trying alt endpoint', { status: purchasesResponse.status });
631
+ try {
632
+ var altUrl = SEPHORA_CONFIG.baseUrl + '/api/users/profiles/' + extractedProfileId + '/orders?pageSize=50&currentPage=1';
633
+ const altResp = await fetchWithTimeout(altUrl, { method: 'GET', credentials: 'include', headers: headers });
634
+ postDebug('Purchases alt status', { status: altResp.status });
635
+ if (altResp.ok) {
636
+ var altData = {};
637
+ try { altData = JSON.parse(await altResp.text()); } catch(e) {}
638
+ parsePurchasesData(altData);
639
+ }
640
+ } catch(altErr) { postDebug('Purchases alt error', { message: altErr.message }); }
641
+ }
642
+ } catch (purchasesErr) {
643
+ postDebug('Purchases fetch error', { message: purchasesErr.message });
644
+ }
645
+ } else {
646
+ postDebug('Skipping purchases', { reason: 'no profileId' });
647
+ }
648
+
649
+ // STEP 5: Fetch User Profile (requires profileId)
650
+ window.ReactNativeWebView.postMessage(JSON.stringify({
651
+ type: 'SEPHORA_EXPORT_PROGRESS',
652
+ stage: 'fetching_profile',
653
+ progress: 75,
654
+ message: 'Fetching beauty profile...'
655
+ }));
656
+
657
+ let profile = null;
658
+
659
+ function parseProfileData(profileData) {
660
+ var pd = profileData.userProfile || profileData.profile || profileData.user || profileData;
661
+ if (!pd || profileData.error || profileData.errors || profileData.success === false ||
662
+ !pd.profileId || !(pd.email || pd.firstName || pd.lastName || pd.isSignedIn === true || pd.isLoggedIn === true)) return;
663
+ postDebug('Profile top-level keys', { keys: Object.keys(profileData).join(',') });
664
+ profile = {
665
+ profileId: pd.profileId || profileData.profileId || extractedProfileId,
666
+ firstName: pd.firstName,
667
+ lastName: pd.lastName,
668
+ email: pd.email,
669
+ vibStatus: pd.vibStatus || pd.biTier || pd.tier,
670
+ beautyInsider: {
671
+ points: pd.biPoints || pd.points || pd.beautyInsiderPoints,
672
+ segment: pd.segment || pd.biSegment,
673
+ spending: pd.spending || pd.yearlySpend,
674
+ },
675
+ preferences: {
676
+ skinConcerns: pd.skinConcerns || pd.skinType || [],
677
+ hairConcerns: pd.hairConcerns || pd.hairType || [],
678
+ makeupPreferences: pd.makeupPreferences || [],
679
+ },
680
+ preferredStore: pd.preferredStore || pd.homeStore,
681
+ };
682
+ postDebug('Profile parsed', {
683
+ profileId: profile.profileId,
684
+ firstName: profile.firstName,
685
+ vibStatus: profile.vibStatus,
686
+ });
687
+ }
688
+
689
+ function hasMeaningfulProfileCapture(data) {
690
+ if (!data || typeof data !== 'object') return false;
691
+ var pd = data.userProfile || data.profile || data.user || data;
692
+ return !!(pd && (pd.profileId || pd.firstName || pd.lastName || pd.email || pd.vibStatus || pd.biTier));
693
+ }
694
+
695
+ if (session.profile()) {
696
+ parseProfileData(session.profile());
697
+ } else if (hasMeaningfulProfileCapture(capturedData.profile)) {
698
+ postDebug('Profile from capture', {});
699
+ parseProfileData(capturedData.profile);
700
+ } else if (extractedProfileId) {
701
+ if (capturedData.profile) {
702
+ postDebug('Profile capture unusable; fetching live profile', {});
703
+ }
704
+ const profileUrl = SEPHORA_CONFIG.baseUrl +
705
+ SEPHORA_CONFIG.endpoints.profileTemplate.replace('{profileId}', extractedProfileId) +
706
+ SEPHORA_CONFIG.params.profile;
707
+
708
+ postDebug('Fetching profile', { url: profileUrl });
709
+
710
+ try {
711
+ const profileResponse = await fetchWithTimeout(profileUrl, {
712
+ method: 'GET',
713
+ credentials: 'include',
714
+ headers: headers
715
+ });
716
+
717
+ postDebug('Profile HTTP status', { status: profileResponse.status, ok: profileResponse.ok });
718
+
719
+ const profileText = await profileResponse.text();
720
+ postDebug('Profile body received', { hasBody: profileText.length > 0 });
721
+
722
+ if (profileResponse.ok) {
723
+ var profileData = {};
724
+ try { profileData = JSON.parse(profileText); } catch (e) { postDebug('Profile parse error', { e: e.message }); }
725
+ parseProfileData(profileData);
726
+ }
727
+ } catch (profileError) {
728
+ postDebug('Profile fetch error', { message: profileError.message });
729
+ }
730
+ }
731
+
732
+ // STEP 6: Send results
733
+ window.ReactNativeWebView.postMessage(JSON.stringify({
734
+ type: 'SEPHORA_EXPORT_PROGRESS',
735
+ stage: 'complete',
736
+ progress: 95,
737
+ message: 'Finalizing...'
738
+ }));
739
+
740
+ console.log('\u2705 [SEPHORA] Extraction complete:', {
741
+ basket: basket.items.length,
742
+ loves: loves.length,
743
+ purchases: purchases.length,
744
+ hasProfile: !!profile
745
+ });
746
+ postDebug('Extraction complete', {
747
+ basketItems: basket.items.length,
748
+ loves: loves.length,
749
+ purchases: purchases.length,
750
+ hasProfile: !!profile
751
+ });
752
+
753
+ var totalPurchasedItems = purchases.reduce(function(sum, order) {
754
+ return sum + ((order.items && order.items.length) || 0);
755
+ }, 0);
756
+ var vibStatus = (profile && profile.vibStatus) || 'unknown';
757
+ var biPoints = (profile && profile.beautyInsider && profile.beautyInsider.points) || basket.biPoints || 0;
758
+
759
+ if (basket.items.length === 0 && loves.length === 0 && purchases.length === 0 &&
760
+ (requestFailures > 0 || requestStatuses.some(function(status) { return status < 200 || status >= 300; }))) {
761
+ window.ReactNativeWebView.postMessage(JSON.stringify({type: 'SEPHORA_EXPORT_ERROR', code: 'FETCH_FAILED'}));
762
+ return;
763
+ }
764
+
765
+ if (basket.items.length === 0 && loves.length === 0 && purchases.length === 0 && !profile) {
766
+ postDebug('Extraction empty after live fetch attempts', {
767
+ profileId: extractedProfileId,
768
+ hasToken: !!(tokenData && tokenData.token),
769
+ });
770
+ window.ReactNativeWebView.postMessage(JSON.stringify({
771
+ type: 'SEPHORA_EXPORT_ERROR',
772
+ status: 'error',
773
+ code: requestStatuses.some(function(status) {return status === 401 || status === 403;}) ? 'AUTH_REQUIRED' : 'NO_DATA',
774
+ message: 'Sephora did not return shopping activity. You can retry without leaving this connection.',
775
+ success: false
776
+ }));
777
+ return;
778
+ }
779
+
780
+ if (!session.read().authenticated || session.profile()?.profileId !== profileId) {
781
+ window.ReactNativeWebView.postMessage(JSON.stringify({type: 'SEPHORA_EXPORT_ERROR', code: 'AUTH_REQUIRED'}));
782
+ return;
783
+ }
784
+ window.ReactNativeWebView.postMessage(JSON.stringify({
785
+ type: 'SEPHORA_EXPORT_COMPLETE',
786
+ status: 'success',
787
+ data: {
788
+ basket: basket,
789
+ loves: loves,
790
+ purchases: purchases,
791
+ profile: profile,
792
+ summary: {
793
+ totalBasketItems: basket.items.length,
794
+ basketSubtotal: basket.subtotal,
795
+ totalLovedProducts: loves.length,
796
+ totalOrders: purchases.length,
797
+ totalPurchasedItems: totalPurchasedItems,
798
+ vibStatus: vibStatus,
799
+ biPoints: biPoints,
800
+ },
801
+ tokenExpiry: {
802
+ expiry: tokenData.expiry,
803
+ isExpired: isTokenExpired(tokenData),
804
+ },
805
+ profileId: extractedProfileId,
806
+ },
807
+ success: true
808
+ }));
809
+
810
+ } catch (error) {
811
+ console.error('[SEPHORA] Export failed');
812
+ postDebug('Export failed', { message: error.message });
813
+ window.ReactNativeWebView.postMessage(JSON.stringify({
814
+ type: 'SEPHORA_EXPORT_ERROR',
815
+ status: 'error',
816
+ code: 'FETCH_FAILED',
817
+ message: 'Could not read Sephora activity. Please try again.',
818
+ success: false
819
+ }));
820
+ } finally {
821
+ window.__onairosSephoraExportRunning = false;
822
+ }
823
+ })();
824
+
825
+ } catch (error) {
826
+ console.error('[SEPHORA] Export initialization failed');
827
+ try {
828
+ window.ReactNativeWebView.postMessage(JSON.stringify({
829
+ type: 'DEBUG_LOG',
830
+ message: '[SEPHORA] Init error',
831
+ details: { failed: true }
832
+ }));
833
+ } catch (e) {}
834
+ window.ReactNativeWebView.postMessage(JSON.stringify({
835
+ type: 'SEPHORA_EXPORT_ERROR',
836
+ status: 'error',
837
+ code: 'FETCH_FAILED',
838
+ message: 'Could not prepare Sephora activity. Please try again.',
839
+ success: false
840
+ }));
841
+ }
842
+ })();
843
+ true;
844
+ `;
845
+ const SEPHORA_SUCCESS_SCRIPT = `
846
+ (function() {
847
+ console.log('\u2705 Sephora export successful!');
848
+ })();
849
+ true;
850
+ `;
851
+ const SEPHORA_ERROR_SCRIPT = `
852
+ (function() {
853
+ console.log('\u274C Sephora export failed!');
854
+ })();
855
+ true;
856
+ `;
857
+ export {
858
+ SEPHORA_CONSENT_POPUP_SCRIPT,
859
+ SEPHORA_ERROR_SCRIPT,
860
+ SEPHORA_EXPORT_SCRIPT,
861
+ SEPHORA_SUCCESS_SCRIPT
862
+ };