@onairosofficial/onairos-capacitor 0.1.1 → 0.1.2

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.
@@ -0,0 +1,152 @@
1
+ # OnairosButton — props reference (web / npm package)
2
+
3
+ This document describes the public surface of **`OnairosButton`** in the **web** SDK (`onairos` npm). The **source of truth for runtime behavior** is `src/onairosButton.jsx` (props forwarded to `src/components/UniversalOnboarding.jsx`, `src/components/TrainingScreen.jsx`, and helpers such as `src/utils/pollTrainingStatus.js`).
4
+
5
+ For **cross-platform contracts** (training polling, `autoFetch` + `backgroundLoadData` matrix, `authorizedData`, completion shape), see [`CROSS_SDK_PARITY.md`](./CROSS_SDK_PARITY.md).
6
+
7
+ ---
8
+
9
+ ## Migration from v7.x → v8.0.0
10
+
11
+ Two breaking changes consolidate the training props.
12
+
13
+ | Old | New |
14
+ | --- | --- |
15
+ | `enableTraining={false}` | `backgroundLoadData={true}` (host owns lifecycle) **or** `trainingScreenMode="none"` (returning users only) |
16
+ | `trainingScreenMode="real"` (was the default — fast traits-only completion) | `trainingScreenMode="fast"` |
17
+ | `trainingScreenMode="full"` | `trainingScreenMode="real"` |
18
+
19
+ `enableTraining` is removed entirely. The `'real'` value now means the slow
20
+ full-model-train mode (was `'full'`). The new default is `'fast'` (was `'real'`'s
21
+ behaviour). When `backgroundLoadData={true}` and `trainingScreenMode` is unset,
22
+ the SDK auto-resolves to `'none'` so no loading screen renders after PIN.
23
+
24
+ ---
25
+
26
+ ## Entry points
27
+
28
+ | Entry | Role |
29
+ |--------|------|
30
+ | **`<OnairosButton />`** | Renders the touch target; opens onboarding modals (`UniversalOnboarding` / `TrainingScreen` / explainer steps). |
31
+ | **`ref.trigger()`** | Same path as a tap (`handlePress` → modal). |
32
+ | **`initializeApiKey`** | From `src/services/apiKeyService.js` — must succeed before the button is interactive (unless `skipApiKeyInitialization` or inline `apiKey` init applies). |
33
+
34
+ ---
35
+
36
+ ## Result type: `onComplete(result)`
37
+
38
+ The modern callback is **`onComplete?: (result) => void`**.
39
+
40
+ | Field | Meaning |
41
+ |--------|---------|
42
+ | `token` | Bearer token for `apiUrl` and `training.statusUrl` polling |
43
+ | `apiUrl` | Backend URL for follow-up API calls |
44
+ | `approved` | String list of approved data tiers / scopes |
45
+ | `userData` | `{ email?, username?, connectedAccounts, skipped? }` |
46
+ | `apiResponse?` | Fetched traits/insights when `autoFetch` populated them |
47
+ | `platformData?` | Raw per-platform payloads |
48
+ | `authorizedData?` | Flags aligned with backend (see parity doc §2) |
49
+ | `training?` | `{ ready, statusUrl?, pollIntervalMs? }` after URL resolution |
50
+
51
+ **Legacy:** `onResolved(apiUrl, token, userData)` may still fire after `onComplete` for backward compatibility.
52
+
53
+ **`onPress`:** Fires after a successful flow when completion runs (not on the initial tap).
54
+
55
+ ---
56
+
57
+ ## Parity props (data / training / OAuth)
58
+
59
+ | Prop | Default | Web behavior |
60
+ |------|---------|----------------|
61
+ | `autoFetch` | `false` | After resolution, POST to resolved `apiUrl` when training is ready (or traits-only path); merges into `apiResponse`. |
62
+ | `backgroundLoadData` | `false` | Drives the `trainingScreenMode` auto-default: when `true` and `trainingScreenMode` is not set, `'none'` is used so no SDK training loading screen renders after PIN/onboarding. Polling and the resolved `apiUrl` POST are still governed by `autoFetch`; hosts that own the result fetch should set `autoFetch={false}` and use `training.statusUrl`, `apiUrl`, and `token` from `onComplete`. |
63
+ | `trainingScreenMode` | `'fast'` (or `'none'` when `backgroundLoadData=true`) | One of `'mock' \| 'fast' \| 'real' \| 'none'`. `'mock'` — 5 s fake animation, no socket. `'fast'` — real socket, completes when personality traits land (~30 s – 1 min). `'real'` — real socket, waits for full MIND1 model train (~2 – 3 min). `'none'` — `TrainingScreen` does not render; intended for already-trained users or `backgroundLoadData=true` flows. |
64
+ | `preCheck` | — | If returns `false` or throws, flow stops and `onRejection` is called. |
65
+ | `onRejection` | — | Called when `preCheck` fails. |
66
+ | `returnLink` | — | On mobile/Capacitor OAuth, used as OAuth `returnUrl` when non-empty (normalized; onairos OAuth params stripped). |
67
+ | `recommendedPlatforms` | — | Platforms listed first in onboarding UI order (then remainder). |
68
+ | `preferredPlatform` | — | Same as RN `preferredPlatform`; merged with `priorityPlatform` as `effectivePriorityPlatform`. |
69
+ | `primaryAuthOnly` | `false` | Combined with `authOnly`: immediate exit after auth when either is true. |
70
+ | `useNewWelcomeFlow` | `false` | New users skip `dataExplainer` → go to `onboarding` (Valentine/Lunar/default new-user detection unchanged). |
71
+ | `preferencesMbti` | `false` | When `true` and the user approved **`preferences`**: set `Info.Options.preferencesMbti` on `/getAPIurlMobile` and send `preferencesMbti: true` on inference POSTs (server MBTI 16-type probe; optional/absent `Input` when the preset is in the token). Backend **3.9.35+**; see `sdk-integration/MBTI_INFERENCE_INPUT_PRESET.md`. |
72
+
73
+ ---
74
+
75
+ ## Pre-authenticated entry (skip the in-modal email/ID login)
76
+
77
+ For white-label / low-friction integrations, the host app can supply identity up front so
78
+ the user never sees the Onairos email/ID login step. This reduces the number of places a
79
+ user has to enter credentials and improves conversion.
80
+
81
+ | Prop | Type | Behavior |
82
+ |------|------|----------|
83
+ | `preAuthToken` | `string \| null` | A valid Onairos JWT minted by the host (or your backend on the user's behalf). When set, the SDK **skips login entirely** and routes straight to permissions/onboarding. The token is persisted to `localStorage` (`onairos_user_token`) and used to fetch the user's identity + connected platforms. Use this when your app already knows who the user is. |
84
+ | `preVerifiedEmail` | `string \| null` | A host-verified email address. The SDK pre-fills/short-circuits the email step so the user continues without re-entering or re-verifying their email. Use this when you have a verified email but not a full token. (`preverifiedEmail` / `preVerifiedEamil` are accepted aliases.) |
85
+
86
+ ```jsx
87
+ // Full pre-auth: user goes straight to connecting apps + consent.
88
+ <OnairosButton
89
+ webpageName="My App"
90
+ requestData={["personalization"]}
91
+ preAuthToken={hostMintedJwt}
92
+ onComplete={handleComplete}
93
+ />
94
+
95
+ // Email-only pre-auth: skip email entry/verification, keep the rest of the flow.
96
+ <OnairosButton
97
+ webpageName="My App"
98
+ requestData={["personalization"]}
99
+ preVerifiedEmail="user@example.com"
100
+ onComplete={handleComplete}
101
+ />
102
+ ```
103
+
104
+ **Notes**
105
+ - If `preAuthToken` is invalid/expired, the SDK falls through to the normal login flow.
106
+ - If the user explicitly dismisses the modal during a `preAuthToken` flow, it will not auto-reopen.
107
+ - Pair with `autoFetch` / `backgroundLoadData` to control whether the SDK fetches results or hands `apiUrl` + `token` back to you.
108
+
109
+ ---
110
+
111
+ ## Consent UI (DataRequest)
112
+
113
+ The consent sheet is intentionally minimal to reduce friction:
114
+
115
+ | Item | UI | Emitted `approved` scopes |
116
+ |------|----|---------------------------|
117
+ | **Basic Profile** | Always included (shown as a quiet line, not a checkbox) | `basic` |
118
+ | **Personalization** | The single checkbox (pre-selected). Combines the former *Preferences* + *Interests* toggles | `preferences`, `personality` |
119
+ | **Raw Memories** | Optional second checkbox — only shown when a raw-capable source is connected and the developer offers it | `rawMemories` |
120
+
121
+ So a typical app shows **one checkbox**, and **two at most** (when Raw Memories is available).
122
+ Collapsing the UI does **not** drop scopes: `requestData` is matched against each option's
123
+ underlying scopes, and an enabled combined toggle still emits every scope it represents.
124
+
125
+ | Prop | Default | Behavior |
126
+ |------|---------|----------|
127
+ | `privacyPolicyUrl` | `'https://privacy.onairos.io'` | URL opened by the info (ⓘ) control on the onboarding header and the consent sheet. Set to your own policy for white-label, or `null`/empty to hide the link. |
128
+ | `demoMode` | `false` | Shows a proof-of-concept note on the consent sheet and prevents the SDK from resolving or fetching user data after approval. `onComplete` still fires with the approved scopes and `demoMode: true`. |
129
+
130
+ ---
131
+
132
+ ## Other props (summary)
133
+
134
+ Styling, `AppName`, `requestData`, `allowedPlatforms`, `dataUsageDescription`, `fastTraits`, `inferenceData`, `debug`, `testMode`, `skipApiKeyInitialization`, `apiKey`, `authOnly`, `priorityPlatform`, `enableLogging`, etc. follow existing web wiring in `onairosButton.jsx` and `UniversalOnboarding.jsx`.
135
+
136
+ ---
137
+
138
+ ## Implementation map (web files)
139
+
140
+ | Concern | File |
141
+ |---------|------|
142
+ | Button, resolution, `authorizedData` / `training` on result | `src/onairosButton.jsx` |
143
+ | Platform list, OAuth return URL, explainer | `src/components/UniversalOnboarding.jsx` |
144
+ | Training UI + `trainingScreenMode === 'mock'` | `src/components/TrainingScreen.jsx` |
145
+ | Status URL polling (RN parity) | `src/utils/pollTrainingStatus.js` (also exportable from package `src/index.js`) |
146
+
147
+ ---
148
+
149
+ ## Change log
150
+
151
+ - **2026-06-17** — Documented pre-authenticated entry (`preAuthToken` / `preVerifiedEmail`); simplified consent UI to one checkbox (two with Raw Memories) by combining Preferences + Interests into **Personalization**; added `privacyPolicyUrl` and onboarding header copy that explains connector data usage.
152
+ - **2026-04-22** — Web parity props and docs; moved from `sdk-integration/` to `docs/`.
@@ -0,0 +1,559 @@
1
+ # Platform Connector APIs Reference
2
+
3
+ Quick reference for all platform data sources, APIs, authentication, and token management.
4
+
5
+ ---
6
+
7
+ ## Sephora
8
+
9
+ **Platform ID:** `mobile-sephora`
10
+ **Data Type:** E-commerce / Beauty
11
+
12
+ ### Authentication
13
+
14
+ | Key | Storage | Format |
15
+ |-----|---------|--------|
16
+ | `seph-access-token` | localStorage | JSON: `{ data: "JWT...", expiry: "timestamp" }` |
17
+ | `x-api-key` | Header | `nQc7BFt78yJBvfYDKtle9APd5RrX984i` |
18
+
19
+ **Token Expiry:** ~150 days (expiry is Unix timestamp in seconds)
20
+
21
+ ### APIs
22
+
23
+ | API | Endpoint | Method | Data Retrieved |
24
+ |-----|----------|--------|----------------|
25
+ | **Profile** | `/gapi/users/profiles/{profileId}/current/full` | GET | Name, email, VIB status, Beauty Insider points, skin/hair/makeup preferences, preferred store |
26
+ | **Basket** | `/api/shopping-cart/basket` | GET | Cart items, subtotal, BI points, shipping info |
27
+ | **Loves** | `/gway/v1/dotcom/users/profiles/{profileId}/lists/skus/all` | GET | Wishlist products with ratings, categories, prices, images |
28
+ | **Purchases** | `/api/bi/profiles/{profileId}/purchases` | GET | Purchase history with products, dates, order IDs |
29
+
30
+ ### Profile API Params
31
+ ```
32
+ ?skipApis=targetersResult
33
+ &includeApis=profile,basket,loves,shoppingList,segments
34
+ ```
35
+
36
+ ### Loves API Params
37
+ ```
38
+ ?itemsPerPage=100
39
+ &currentPage=1
40
+ &listShortNameLength=20
41
+ &skipProductDetails=false
42
+ &includeInactiveSkus=true
43
+ &fetchAllLovesList=true
44
+ &sortBy=recently
45
+ &includeCategories=true
46
+ ```
47
+
48
+ ### Purchases API Params
49
+ ```
50
+ ?sortBy=recently
51
+ &itemsPerPage=100
52
+ &groupBy=none
53
+ &excludeSamples=true
54
+ &excludeRewards=true
55
+ ```
56
+
57
+ ### Data Extracted
58
+
59
+ **Profile:**
60
+ - `profileId`, `firstName`, `lastName`, `email`
61
+ - `vibStatus` (BI, VIB, Rouge)
62
+ - Beauty Insider: points, segment, spending, birthday gift eligibility
63
+ - Preferences: skin concerns, hair concerns, makeup preferences
64
+ - Preferred store info
65
+
66
+ **Basket:**
67
+ - Items with SKU ID, product ID, name, brand, price, quantity, size, image
68
+
69
+ **Loves:**
70
+ - Products with ratings, reviews, categories, stock status, sale info
71
+
72
+ **Purchases:**
73
+ - Order history with product details, dates, quantities
74
+
75
+ ### Token Extraction
76
+
77
+ ```javascript
78
+ function getSephoraToken() {
79
+ var tokenKeys = ['seph-access-token', 'sephoraAccessToken', 'accessToken'];
80
+
81
+ // Try localStorage
82
+ for (var i = 0; i < tokenKeys.length; i++) {
83
+ var token = localStorage.getItem(tokenKeys[i]);
84
+ if (token) {
85
+ try {
86
+ var parsed = JSON.parse(token);
87
+ if (parsed && parsed.data) return parsed.data;
88
+ } catch (e) {
89
+ return token; // Not JSON, use as-is
90
+ }
91
+ }
92
+ }
93
+
94
+ // Try cookies
95
+ var cookieMatch = document.cookie.match(/seph-access-token=([^;]+)/);
96
+ if (cookieMatch) return cookieMatch[1];
97
+
98
+ // Try window state
99
+ if (window.__PRELOADED_STATE__ && window.__PRELOADED_STATE__.user) {
100
+ return window.__PRELOADED_STATE__.user.accessToken;
101
+ }
102
+
103
+ return null;
104
+ }
105
+ ```
106
+
107
+ ### Profile ID Extraction
108
+
109
+ The `profileId` is needed for most Sephora APIs. Extract from:
110
+
111
+ ```javascript
112
+ function getProfileId() {
113
+ // Method 1: From token (JWT payload)
114
+ var token = getSephoraToken();
115
+ if (token) {
116
+ try {
117
+ var payload = JSON.parse(atob(token.split('.')[1]));
118
+ if (payload.sub) return payload.sub;
119
+ } catch (e) {}
120
+ }
121
+
122
+ // Method 2: From localStorage
123
+ var profileId = localStorage.getItem('biAccountId') ||
124
+ localStorage.getItem('profileId');
125
+ if (profileId) return profileId;
126
+
127
+ // Method 3: From window state
128
+ if (window.__PRELOADED_STATE__ && window.__PRELOADED_STATE__.user) {
129
+ return window.__PRELOADED_STATE__.user.profileId;
130
+ }
131
+
132
+ // Method 4: From basket API (doesn't require profileId)
133
+ // Call /api/shopping-cart/basket first, extract profileId from response
134
+
135
+ return null;
136
+ }
137
+ ```
138
+
139
+ ### Token Expiry Check
140
+
141
+ ```javascript
142
+ function isTokenExpired() {
143
+ var tokenData = localStorage.getItem('seph-access-token');
144
+ if (!tokenData) return true;
145
+
146
+ try {
147
+ var parsed = JSON.parse(tokenData);
148
+ var expiry = parseInt(parsed.expiry, 10);
149
+ var now = Math.floor(Date.now() / 1000);
150
+ return now >= expiry;
151
+ } catch (e) {
152
+ return true;
153
+ }
154
+ }
155
+ ```
156
+
157
+ ---
158
+
159
+ ## Instagram
160
+
161
+ **Platform ID:** `mobile-instagram` (data connector) / `instagram` (OAuth)
162
+ **Data Type:** Social
163
+
164
+ ### Authentication
165
+
166
+ | Key | Storage | Notes |
167
+ |-----|---------|-------|
168
+ | `csrftoken` | Cookie | CSRF token for POST requests |
169
+ | `sessionid` | Cookie | Session authentication |
170
+ | `X-IG-App-ID` | Header | `936619743392459` |
171
+ | `__bkv` | URL param | Bloks version: `cc4d2103131ee3bbc02c20a86f633b7fb7a031cbf515d12d81e0c8ae7af305dd` |
172
+
173
+ **Token Expiry:** Session-based (tied to browser session cookie)
174
+
175
+ ### APIs
176
+
177
+ | API | Endpoint | Method | Data Retrieved |
178
+ |-----|----------|--------|----------------|
179
+ | **Liked Media (Bloks)** | `/async/wbloks/fetch/` | POST | Liked posts via Bloks framework |
180
+ | **Saved Posts** | `/api/v1/feed/saved/posts/` | GET | Saved posts with media, captions, owner info |
181
+ | **Timeline (GraphQL)** | `/graphql/query` | POST | Feed timeline with media, captions, engagement |
182
+
183
+ ### Bloks API (Liked Media)
184
+
185
+ **Endpoint:**
186
+ ```
187
+ POST https://www.instagram.com/async/wbloks/fetch/?appid=com.instagram.privacy.activity_center.liked_media_screen&type=app&__bkv={bloksVersionId}
188
+ ```
189
+
190
+ **Request Body:** `application/x-www-form-urlencoded`
191
+ ```
192
+ params=%7B%7D
193
+ ```
194
+
195
+ **Response Format:**
196
+ ```javascript
197
+ for (;;);{"__ar":1,"rid":"...","payload":{"layout":{"bloks_payload":{"data":[
198
+ {"id":"440463611_0","type":"gs","data":{...}},
199
+ ...
200
+ ]}}}}
201
+ ```
202
+
203
+ **Note:** Response has `for (;;);` prefix (anti-JSON hijacking) that must be stripped before JSON.parse()
204
+
205
+ **Parsing the Bloks payload:**
206
+ ```javascript
207
+ function parseLikedMedia(data) {
208
+ var likes = [];
209
+ if (data && data.payload && data.payload.layout && data.payload.layout.bloks_payload) {
210
+ var bloksData = data.payload.layout.bloks_payload.data || [];
211
+ bloksData.forEach(function(item, idx) {
212
+ // Bloks items have varying structures
213
+ if (item.type === 'media' || item.type === 'ig' || item.data) {
214
+ likes.push({
215
+ id: item.id || 'like_' + idx,
216
+ type: 'like',
217
+ rawData: item.data,
218
+ bloksType: item.type
219
+ });
220
+ }
221
+ });
222
+ }
223
+ return likes;
224
+ }
225
+ ```
226
+
227
+ **⚠️ Bloks Caveat:** The Bloks payload structure is complex and may vary. The `data` array contains UI component definitions, not clean media objects. You may need to recursively parse to extract actual media IDs.
228
+
229
+ ### Saved Posts API
230
+
231
+ **Endpoint:**
232
+ ```
233
+ GET https://www.instagram.com/api/v1/feed/saved/posts/
234
+ ```
235
+
236
+ **Response Format:**
237
+ ```javascript
238
+ {
239
+ "items": [
240
+ {
241
+ "media": {
242
+ "id": "...",
243
+ "pk": "...",
244
+ "code": "...",
245
+ "media_type": 1,
246
+ "caption": { "text": "..." },
247
+ "user": { "pk": "...", "username": "..." },
248
+ "like_count": 123,
249
+ "comment_count": 45,
250
+ "taken_at": 1706123456,
251
+ "image_versions2": { "candidates": [{ "url": "..." }] }
252
+ }
253
+ }
254
+ ],
255
+ "more_available": true,
256
+ "next_max_id": "..."
257
+ }
258
+ ```
259
+
260
+ ### GraphQL API (Timeline)
261
+
262
+ **Endpoint:**
263
+ ```
264
+ POST https://www.instagram.com/graphql/query
265
+ ```
266
+
267
+ **Request Body:** `application/x-www-form-urlencoded`
268
+ ```
269
+ doc_id=8845758582119845&variables={"first":12,"after":null}
270
+ ```
271
+
272
+ **Response Format:**
273
+ ```javascript
274
+ {
275
+ "data": {
276
+ "xdt_api__v1__feed__timeline__connection": {
277
+ "pagination_source": null,
278
+ "edges": [
279
+ {
280
+ "node": {
281
+ "media": {
282
+ "id": "3820598654428293407_10139962",
283
+ "pk": "3820598654428293407",
284
+ "code": "...",
285
+ "media_type": 1,
286
+ "caption": { "text": "..." },
287
+ "user": { "pk": "...", "username": "..." },
288
+ "like_count": 123,
289
+ "comment_count": 45,
290
+ "taken_at": 1706123456,
291
+ "image_versions2": { "candidates": [{ "url": "..." }] }
292
+ }
293
+ }
294
+ }
295
+ ]
296
+ }
297
+ }
298
+ }
299
+ ```
300
+
301
+ ### Required Headers
302
+
303
+ ```javascript
304
+ {
305
+ 'Accept': '*/*',
306
+ 'Accept-Language': 'en-US,en;q=0.9',
307
+ 'X-CSRFToken': csrfToken,
308
+ 'X-IG-App-ID': '936619743392459',
309
+ 'X-Requested-With': 'XMLHttpRequest',
310
+ 'X-ASBD-ID': '129477',
311
+ 'Content-Type': 'application/x-www-form-urlencoded'
312
+ }
313
+ ```
314
+
315
+ ### Data Extracted
316
+
317
+ **Liked Media:**
318
+ - Post IDs
319
+ - Bloks payload data (varies by content type)
320
+
321
+ **Saved Posts:**
322
+ - `id`, `pk`, `code` (shortcode for URL)
323
+ - `mediaType` (1=image, 2=video, 8=carousel)
324
+ - `caption` text
325
+ - `owner` (user info: id, username, full name)
326
+ - `likeCount`, `commentCount`
327
+ - `takenAt` (Unix timestamp)
328
+ - `imageUrl` (best quality candidate)
329
+
330
+ **Timeline:**
331
+ - `id`, `pk`, `code` (shortcode for URL)
332
+ - `mediaType` (1=image, 2=video, 8=carousel)
333
+ - `caption` text
334
+ - `owner` (user info: id, username, full name)
335
+ - `likeCount`, `commentCount`
336
+ - `takenAt` (Unix timestamp)
337
+ - `imageUrl` (best quality candidate)
338
+
339
+ ### User ID Extraction
340
+
341
+ Instagram requires the user's ID for some operations. Extract from page state:
342
+
343
+ ```javascript
344
+ function getUserId() {
345
+ // Method 1: window._sharedData (older pages)
346
+ if (window._sharedData && window._sharedData.config) {
347
+ return window._sharedData.config.viewerId;
348
+ }
349
+
350
+ // Method 2: window.__initialData (newer pages)
351
+ if (window.__initialData && window.__initialData.data && window.__initialData.data.user) {
352
+ return window.__initialData.data.user.id;
353
+ }
354
+
355
+ // Method 3: Script tag parsing (fallback)
356
+ var scripts = document.querySelectorAll('script');
357
+ for (var i = 0; i < scripts.length; i++) {
358
+ var text = scripts[i].textContent || '';
359
+ var match = text.match(/"userId":"(\d+)"/);
360
+ if (match) return match[1];
361
+ match = text.match(/"viewerId":"(\d+)"/);
362
+ if (match) return match[1];
363
+ }
364
+
365
+ return null;
366
+ }
367
+ ```
368
+
369
+ ### Bloks Version ID
370
+
371
+ The `__bkv` parameter is a hash that may change with Instagram updates.
372
+
373
+ **Current value:** `cc4d2103131ee3bbc02c20a86f633b7fb7a031cbf515d12d81e0c8ae7af305dd`
374
+
375
+ **To find current value:**
376
+ 1. Open Instagram DevTools → Network tab
377
+ 2. Navigate to Your Activity → Likes
378
+ 3. Look for requests to `/async/wbloks/fetch/`
379
+ 4. Copy `__bkv` value from URL
380
+
381
+ ### Pagination
382
+
383
+ **Saved Posts:**
384
+ ```javascript
385
+ // First request
386
+ GET /api/v1/feed/saved/posts/
387
+
388
+ // Subsequent requests (if more_available: true)
389
+ GET /api/v1/feed/saved/posts/?max_id={next_max_id}
390
+ ```
391
+
392
+ **GraphQL Timeline:**
393
+ ```javascript
394
+ // First request
395
+ doc_id=8845758582119845&variables={"first":12,"after":null}
396
+
397
+ // Subsequent requests
398
+ doc_id=8845758582119845&variables={"first":12,"after":"{end_cursor}"}
399
+ ```
400
+
401
+ The `end_cursor` comes from `pageInfo.end_cursor` in the response.
402
+
403
+ ### Cookie Extraction Helper
404
+
405
+ ```javascript
406
+ function getCookie(name) {
407
+ var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
408
+ return match ? match[2] : null;
409
+ }
410
+
411
+ // Usage
412
+ var csrfToken = getCookie('csrftoken');
413
+ var sessionId = getCookie('sessionid');
414
+ ```
415
+
416
+ ---
417
+
418
+ ## Hinge
419
+
420
+ **Platform ID:** `mobile-hinge`
421
+ **Data Type:** Dating
422
+
423
+ ### Authentication
424
+
425
+ | Key | Storage | Notes |
426
+ |-----|---------|-------|
427
+ | `auth_token` | Cookie/localStorage | TBD - need to confirm |
428
+ | `hinge_auth_token` | Cookie | Fallback |
429
+
430
+ ### APIs
431
+
432
+ | API | Endpoint | Data Retrieved |
433
+ |-----|----------|----------------|
434
+ | TBD | TBD | Matches, messages |
435
+
436
+ ### Data Extracted
437
+ - Matches (profiles)
438
+ - Messages/chat history
439
+
440
+ ---
441
+
442
+ ## Token Expiry Reference
443
+
444
+ | Platform | Token Lifetime | Refresh Mechanism |
445
+ |----------|---------------|-------------------|
446
+ | **Sephora** | ~150 days | Auto-refresh on site visit, `refreshToken` in localStorage |
447
+ | **Instagram** | Session-based | Tied to browser `sessionid` cookie, refreshes on site activity |
448
+ | **Hinge** | TBD | TBD |
449
+
450
+ ---
451
+
452
+ ## Common Request Headers
453
+
454
+ All platforms require:
455
+ ```javascript
456
+ {
457
+ 'Accept': 'application/json',
458
+ 'Content-Type': 'application/json',
459
+ 'credentials': 'include' // for cookies
460
+ }
461
+ ```
462
+
463
+ Platform-specific headers are added per connector.
464
+
465
+ ---
466
+
467
+ ## Onairos Backend Endpoint
468
+
469
+ All extracted data is sent to:
470
+ ```
471
+ POST https://api2.onairos.uk/platform-data/store
472
+ ```
473
+
474
+ With headers:
475
+ ```javascript
476
+ {
477
+ 'Content-Type': 'application/json',
478
+ 'Authorization': 'Bearer <onairos_user_token>'
479
+ }
480
+ ```
481
+
482
+ Payload structure:
483
+ ```javascript
484
+ {
485
+ platform: 'mobile-sephora', // platform ID
486
+ dataType: 'ecommerce', // data category
487
+ data: { ... }, // extracted data
488
+ summary: { ... }, // quick stats
489
+ mobileMetadata: {
490
+ platform: 'web',
491
+ source: 'bookmarklet-api',
492
+ extractedAt: 'ISO timestamp',
493
+ tokenExpiry: { ... } // token expiry info
494
+ }
495
+ }
496
+ ```
497
+
498
+ ---
499
+
500
+ ## Rate Limits & Best Practices
501
+
502
+ ### General Guidelines
503
+
504
+ | Platform | Rate Limit | Recommendation |
505
+ |----------|------------|----------------|
506
+ | **Sephora** | Unknown (generous) | Max 10 requests per extraction |
507
+ | **Instagram** | Strict (anti-bot) | Max 3-5 requests, add delays |
508
+ | **Hinge** | TBD | TBD |
509
+
510
+ ### Implementation Tips
511
+
512
+ 1. **Parallel requests** - Use `Promise.all()` for independent API calls
513
+ 2. **Error handling** - Gracefully handle 401/403 (re-auth needed), 429 (rate limited)
514
+ 3. **Credentials** - Always include `credentials: 'include'` for cookie-based auth
515
+ 4. **CORS** - These APIs work from same-origin (bookmarklet on the site), not cross-origin
516
+
517
+ ### Response Parsing
518
+
519
+ **Instagram Bloks (strip prefix):**
520
+ ```javascript
521
+ function parseBloksResponse(text) {
522
+ if (text.startsWith('for (;;);')) {
523
+ text = text.substring(9);
524
+ }
525
+ return JSON.parse(text);
526
+ }
527
+ ```
528
+
529
+ **Sephora (standard JSON):**
530
+ ```javascript
531
+ var data = await response.json();
532
+ ```
533
+
534
+ ### Error Codes
535
+
536
+ | Code | Meaning | Action |
537
+ |------|---------|--------|
538
+ | 200 | Success | Parse response |
539
+ | 401 | Unauthorized | Token expired, prompt re-login |
540
+ | 403 | Forbidden | Blocked/banned, try later |
541
+ | 429 | Rate Limited | Wait and retry |
542
+ | 500+ | Server Error | Retry with backoff |
543
+
544
+ ---
545
+
546
+ ## Quick Implementation Checklist
547
+
548
+ For each platform connector:
549
+
550
+ - [ ] Verify user is on correct domain
551
+ - [ ] Show consent popup
552
+ - [ ] Extract auth token(s)
553
+ - [ ] Check token validity/expiry
554
+ - [ ] Call APIs with proper headers
555
+ - [ ] Parse responses
556
+ - [ ] Build normalized payload
557
+ - [ ] Send to Onairos backend
558
+ - [ ] Show success/error message
559
+