@tolstoy-ai/react-native-sdk 0.3.0 → 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.
Files changed (52) hide show
  1. package/README.md +118 -6
  2. package/lib/TolstoyFeed.js +4 -0
  3. package/lib/TolstoyVideoCarousel.js +1 -1
  4. package/lib/analytics.d.ts +5 -3
  5. package/lib/analytics.js +4 -4
  6. package/lib/api.d.ts +10 -0
  7. package/lib/api.js +5 -0
  8. package/lib/bridge.d.ts +1 -0
  9. package/lib/bridge.js +4 -0
  10. package/lib/config.d.ts +5 -0
  11. package/lib/config.js +10 -0
  12. package/lib/index.d.ts +5 -4
  13. package/lib/index.js +3 -2
  14. package/lib/{TolstoyTryOn.js → tryOn/TolstoyTryOn.js} +5 -5
  15. package/lib/tryOn/methods/shopperSignIn.d.ts +12 -0
  16. package/lib/tryOn/methods/shopperSignIn.js +29 -0
  17. package/lib/tryOn/methods/tryOnJob.d.ts +17 -0
  18. package/lib/tryOn/methods/tryOnJob.js +56 -0
  19. package/lib/tryOn/methods/tryOnPhotos.d.ts +19 -0
  20. package/lib/tryOn/methods/tryOnPhotos.js +112 -0
  21. package/lib/tryOn/methods/tryOnProduct.d.ts +169 -0
  22. package/lib/tryOn/methods/tryOnProduct.js +49 -0
  23. package/lib/tryOn/methods/tryOnSession.d.ts +14 -0
  24. package/lib/tryOn/methods/tryOnSession.js +26 -0
  25. package/lib/tryOn/screen/Header.d.ts +9 -0
  26. package/lib/tryOn/screen/Header.js +22 -0
  27. package/lib/tryOn/screen/Icon.d.ts +6 -0
  28. package/lib/tryOn/screen/Icon.js +6 -0
  29. package/lib/tryOn/screen/PhotoStep.d.ts +12 -0
  30. package/lib/tryOn/screen/PhotoStep.js +70 -0
  31. package/lib/tryOn/screen/PillButton.d.ts +10 -0
  32. package/lib/tryOn/screen/PillButton.js +31 -0
  33. package/lib/tryOn/screen/ProgressStep.d.ts +16 -0
  34. package/lib/tryOn/screen/ProgressStep.js +82 -0
  35. package/lib/tryOn/screen/ResultStep.d.ts +12 -0
  36. package/lib/tryOn/screen/ResultStep.js +114 -0
  37. package/lib/tryOn/screen/TolstoyMark.d.ts +4 -0
  38. package/lib/tryOn/screen/TolstoyMark.js +18 -0
  39. package/lib/tryOn/screen/TolstoyTryOnScreen.d.ts +6 -0
  40. package/lib/tryOn/screen/TolstoyTryOnScreen.js +39 -0
  41. package/lib/tryOn/screen/TopImage.d.ts +8 -0
  42. package/lib/tryOn/screen/TopImage.js +22 -0
  43. package/lib/tryOn/screen/icons.d.ts +24 -0
  44. package/lib/tryOn/screen/icons.js +10 -0
  45. package/lib/tryOn/screen/pickPhoto.d.ts +9 -0
  46. package/lib/tryOn/screen/pickPhoto.js +21 -0
  47. package/lib/tryOn/screen/useEstimatedProgress.d.ts +2 -0
  48. package/lib/tryOn/screen/useEstimatedProgress.js +22 -0
  49. package/lib/tryOn/useTolstoyTryOn.d.ts +44 -0
  50. package/lib/tryOn/useTolstoyTryOn.js +194 -0
  51. package/package.json +10 -1
  52. /package/lib/{TolstoyTryOn.d.ts → tryOn/TolstoyTryOn.d.ts} +0 -0
package/README.md CHANGED
@@ -4,6 +4,7 @@ Tolstoy shoppable videos and virtual try-on for a bare React Native app. The pac
4
4
 
5
5
  - Video carousels for the home screen and the product screen. The videos play natively with your `react-native-video`.
6
6
  - A full-screen video feed with product cards. A tap on a product card calls your `onProductPress(productId, variantId, handle)`.
7
+ - A native try-on screen: the shopper picks a photo, sees the product on it, and adds a size to your cart. The hook and the functions under it let you build your own try-on screen.
7
8
  - A try-on screen in a WebView. The shopper signs in with your app account or with an email.
8
9
  - Video, play, product tap, and add to cart events for your analytics, and a cart attribute that lets Tolstoy attribute app orders to the videos.
9
10
 
@@ -11,6 +12,7 @@ Tolstoy shoppable videos and virtual try-on for a bare React Native app. The pac
11
12
 
12
13
  - React Native 0.81 or later, with the New Architecture and Hermes.
13
14
  - These peer packages in your app: `react-native-video` (6.16.1 or later) and `react-native-webview` (13.16 or later). Install them and their native parts as their own guides tell you. The package root needs both. `@tolstoy-ai/react-native-sdk/api` needs neither (see "Use your own player").
15
+ - `react-native-image-picker` (8.3.0 or later), only for `@tolstoy-ai/react-native-sdk/try-on-screen`. The package root does not need it. Set its permissions as "Native try-on screen" tells you.
14
16
 
15
17
  ## Install
16
18
 
@@ -29,6 +31,7 @@ import {
29
31
  TolstoyProductVideos,
30
32
  TolstoyTryOn,
31
33
  } from '@tolstoy-ai/react-native-sdk';
34
+ import { TolstoyTryOnScreen } from '@tolstoy-ai/react-native-sdk/try-on-screen';
32
35
 
33
36
  <TolstoyProvider
34
37
  appKey="<your Tolstoy app key>"
@@ -46,9 +49,11 @@ import {
46
49
  </TolstoyProvider>
47
50
  ```
48
51
 
49
- Show the try-on screen full screen, for example in a modal or as its own route:
52
+ Show a try-on screen full screen, for example in a modal or as its own route:
50
53
 
51
54
  ```tsx
55
+ <TolstoyTryOnScreen productId={product.id} variantId={selectedVariant.id} onClose={() => navigation.goBack()} />
56
+ // or, in a WebView:
52
57
  <TolstoyTryOn productId={product.id} onClose={() => navigation.goBack()} />
53
58
  ```
54
59
 
@@ -65,7 +70,8 @@ Show the try-on screen full screen, for example in a modal or as its own route:
65
70
  | `onEvent(event)` | `TolstoyProvider`, optional | Tells your app what the shopper does (see "Events"). |
66
71
  | `environment` | `TolstoyProvider`, optional | `production` (default) or `dev`. |
67
72
  | `publishId` | carousels | The publish id of a Tolstoy player. Tolstoy gives it to you. |
68
- | `productId` | `TolstoyProductVideos`, `TolstoyTryOn` | The numeric Shopify product id. |
73
+ | `productId` | `TolstoyProductVideos`, `TolstoyTryOnScreen`, `TolstoyTryOn` | The numeric Shopify product id. |
74
+ | `variantId` | `TolstoyTryOnScreen`, optional | The numeric Shopify id of the variant the shopper chose. Try-on shows its colour. Without it, try-on shows the colour of the product's main image. |
69
75
  | `widgetId` | `TolstoyTryOn`, optional | Your app's own Tolstoy try-on widget. Tolstoy gives it to you. Without it, try-on uses the store's website try-on widget. |
70
76
 
71
77
  `TolstoyProductVideos` shows nothing when the product has no videos. `useTolstoyVideos(publishId, productId?)` gives the same data for your own UI. `TolstoyFeed` needs the `publishId` of the player whose videos it shows.
@@ -97,7 +103,9 @@ const anonymousId = await getOrCreateStoredUuid(); // your code: read the saved
97
103
  | `product_press` | The shopper taps a product card. | `publishId`, `videoId`, `productId`, `variantId?`, `handle?` |
98
104
  | `add_to_cart` | Your `onAddToCart` added the lines from try-on. | `productId` (the product of the try-on screen), `lines` |
99
105
 
100
- The package also sends the views, plays, watch time, and product taps to Tolstoy, as the Tolstoy player on your website does. Your Tolstoy analytics then count them.
106
+ The package also sends the views, plays, watch time, and product taps to Tolstoy, as the Tolstoy player on your website does. The native try-on screen sends its views, its try-on starts, and its adds to cart, as the try-on widget on your website does. Your Tolstoy analytics then count them.
107
+
108
+ The events that the package sends, and the requests of the WebView try-on page, have `TolstoyReactNativeSDK/<version>` in their user agent. Tolstoy analytics show their events in the App channel. The WebView try-on page uses the `anonymousId` of the provider, so its events have the same id as the other events of the shopper.
101
109
 
102
110
  ## Order attribution
103
111
 
@@ -113,6 +121,110 @@ const { cartAttributes } = useTolstoy();
113
121
 
114
122
  The value is the `anonymousId` of the provider. Keep the same `anonymousId` across launches, so that the events and the order have the same id.
115
123
 
124
+ ## Native try-on screen
125
+
126
+ `TolstoyTryOnScreen` (from `@tolstoy-ai/react-native-sdk/try-on-screen`) shows the try-on in native views. It needs no WebView and no widget id: `appKey`, `appUrl`, and `anonymousId` on the provider are sufficient. Its look is fixed.
127
+
128
+ 1. Photo: the shopper's saved photos come first. A tap on a saved photo starts the try-on. "Upload a New Photo" opens the photo library, and "Take a photo in a mirror" opens the camera.
129
+ 2. Progress: the screen shows the photo and the product while Tolstoy makes the image. When the try-on fails, the shopper can try the same photo again or change it.
130
+ 3. Result: the try-on image. "Choose Size" opens the sizes of the tried colour. "Add to Cart" adds one item of the chosen size through your `onAddToCart`. "Change photo" goes back to the photos.
131
+
132
+ - Tolstoy checks each new photo. When it rejects the photo, the screen shows the reason and the shopper picks another photo.
133
+ - The store pays for each try-on, as for a try-on on its website.
134
+ - Saved photos belong to the `anonymousId`. When `getAppSession` gives the token of a signed-in shopper, the saved photos belong to the shopper's account, and show on each device where the shopper signs in.
135
+
136
+ Permissions for `react-native-image-picker`:
137
+
138
+ - iOS: add `NSPhotoLibraryUsageDescription` and `NSCameraUsageDescription` to your `Info.plist`, with text that tells the shopper why the app needs the photos and the camera.
139
+ - Android: the photo library needs no permission. When your app declares `android.permission.CAMERA` in its manifest, get the permission from the shopper (`PermissionsAndroid`) before the shopper opens the try-on screen. Otherwise the camera does not open.
140
+
141
+ ## Your own try-on screen
142
+
143
+ `useTolstoyTryOn({ productId, variantId })` has the full try-on flow without views. `TolstoyTryOnScreen` uses it. Use it in a component inside `TolstoyProvider`.
144
+
145
+ | Field | Description |
146
+ | --- | --- |
147
+ | `product` | The product with its variants. `null` until it loads, and when the store's catalog does not have it. |
148
+ | `triedVariant` | The variant whose colour try-on shows. |
149
+ | `sizes` | The sizes of the tried colour: `variantId`, `label`, `available`. |
150
+ | `photos` | The shopper's saved photos (`id`, `url`), newest first. `null` while they load. |
151
+ | `step` | `photo` (with `error`), `uploading` (with `photoUri`, `percent`), `generating` (with `photoUri`), `failed` (with `photoUri`, `error`), or `result` (with `imageUrl`). |
152
+ | `tryOnPhoto(photo)` | Starts a try-on with a saved photo. |
153
+ | `tryOnFile(file)` | Uploads a photo file (`uri`, `type?`, `fileName?`, as an image picker gives it), then starts a try-on. |
154
+ | `retry()` | Starts the failed try-on again with the same photo. |
155
+ | `backToPhotos()` | Stops the try-on and goes back to the `photo` step. |
156
+ | `deletePhoto(photo)` | Deletes a saved photo. |
157
+ | `addToCart(variantId)` | Adds one item through your `onAddToCart`. Rejects when the add fails. |
158
+
159
+ `error` texts are for the shopper. The hook needs no image picker: give `tryOnFile` a file from any picker.
160
+
161
+ Your screen shows one view for each `step.name`. In this example, `PhotoPicker`, `Progress`, `TryOnFailed`, and `TryOnResult` are your own components:
162
+
163
+ ```tsx
164
+ import { useTolstoyTryOn } from '@tolstoy-ai/react-native-sdk';
165
+
166
+ // Render it inside TolstoyProvider.
167
+ export function MyTryOnScreen({ productId, variantId, onClose }) {
168
+ const tryOn = useTolstoyTryOn({ productId, variantId });
169
+ const { step } = tryOn;
170
+
171
+ switch (step.name) {
172
+ case 'photo':
173
+ return (
174
+ <PhotoPicker
175
+ photos={tryOn.photos} // null while they load
176
+ error={step.error}
177
+ onSavedPhoto={(photo) => tryOn.tryOnPhoto(photo)}
178
+ onDeletePhoto={(photo) => tryOn.deletePhoto(photo)}
179
+ onPickedFile={(file) => tryOn.tryOnFile(file)} // { uri, type?, fileName? } from your image picker
180
+ onClose={onClose}
181
+ />
182
+ );
183
+ case 'uploading':
184
+ return <Progress photoUri={step.photoUri} percent={step.percent} onClose={onClose} />;
185
+ case 'generating':
186
+ return <Progress photoUri={step.photoUri} onClose={onClose} />;
187
+ case 'failed':
188
+ return (
189
+ <TryOnFailed
190
+ photoUri={step.photoUri}
191
+ error={step.error}
192
+ onRetry={tryOn.retry}
193
+ onChangePhoto={tryOn.backToPhotos}
194
+ onClose={onClose}
195
+ />
196
+ );
197
+ case 'result':
198
+ return (
199
+ <TryOnResult
200
+ imageUrl={step.imageUrl}
201
+ title={tryOn.product?.title}
202
+ sizes={tryOn.sizes}
203
+ onChooseSize={(size) => tryOn.addToCart(size.variantId)} // rejects when the add fails
204
+ onChangePhoto={tryOn.backToPhotos}
205
+ onClose={onClose}
206
+ />
207
+ );
208
+ }
209
+ }
210
+ ```
211
+
212
+ When your screen unmounts, the hook stops a running try-on. The hook sends the try-on events to Tolstoy analytics, as `TolstoyTryOnScreen` does. The functions below send no events.
213
+
214
+ The functions under the hook are in `@tolstoy-ai/react-native-sdk/api` and in the package root. Each takes a session: `appKey`, `appUrl`, `environment`, `anonymousId`, and `shopperToken` when a shopper is signed in.
215
+
216
+ | Function | Description |
217
+ | --- | --- |
218
+ | `getTryOnPhotos(session)` | The saved photos. |
219
+ | `uploadTryOnPhoto(session, file, onProgress?, signal?)` | Uploads and checks a photo, and saves it. Gives the saved photo. |
220
+ | `deleteTryOnPhoto(session, photoId)` | Deletes a saved photo. |
221
+ | `runTryOn(session, { productId, variantId, variantImageUrl, photoUrl }, signal?)` | Tries the variant on the photo and waits for the image. Gives `imageUrl`. |
222
+ | `getTryOnProduct(store, productId)` | The product with its variants. |
223
+ | `getTryOnVariant(product, variantId?)`, `getSizeChoices(product, variant)` | The variant to try on, and the sizes of its colour. |
224
+ | `signInShopper(session, { customerAccessToken, storefrontAccessToken? })` | Gives the `shopperToken` for the token of your signed-in shopper (see "Token contract"). |
225
+
226
+ A `TolstoyTryOnError` has a message for the shopper, for example the reason Tolstoy rejected a photo. Other errors are for your logs.
227
+
116
228
  ## Use your own player
117
229
 
118
230
  `getVideos` gives the videos of a player with their products, as the carousels show them. Import it from `@tolstoy-ai/react-native-sdk/api`, which needs neither `react-native-video` nor `react-native-webview`. Your app can keep the result with its own cache and play the videos with its own player.
@@ -144,9 +256,9 @@ const videos = await getVideos(
144
256
  - Do not give an Appbrew token or your own session token. Tolstoy cannot verify them, and the shopper must then sign in with an email.
145
257
  - When `getAppSession` is not set, or gives `null`, the shopper signs in with an email on the try-on screen.
146
258
 
147
- ## How the try-on screen talks to your app
259
+ ## How the WebView try-on screen talks to your app
148
260
 
149
- The try-on screen is a Tolstoy web page in a WebView. The page sends these messages to the package, and the package calls your props:
261
+ `TolstoyTryOn` is a Tolstoy web page in a WebView. The page sends these messages to the package, and the package calls your props:
150
262
 
151
263
  | Message | Prop |
152
264
  | --- | --- |
@@ -155,4 +267,4 @@ The try-on screen is a Tolstoy web page in a WebView. The page sends these messa
155
267
  | `cart/open` | `onOpenCart()` |
156
268
  | `go/back` (the shopper closes the chat) | the `onClose` of `TolstoyTryOn` |
157
269
 
158
- Try-on works only for a store that has the Tolstoy shopper chat switched on.
270
+ The WebView try-on works only for a store that has the Tolstoy shopper chat switched on.
@@ -25,6 +25,7 @@ export function TolstoyFeed({ publishId, productId, videos, startIndex, visible,
25
25
  useEffect(() => {
26
26
  sendTolstoyEvent(contextRef.current, 'sessionStart', {
27
27
  publishId,
28
+ playerType: 'carousel',
28
29
  currentPageProductId: productId,
29
30
  videoId: videos[startIndex]?.id,
30
31
  });
@@ -36,6 +37,7 @@ export function TolstoyFeed({ publishId, productId, videos, startIndex, visible,
36
37
  onEvent?.({ type: 'play', publishId, videoId: video.id });
37
38
  sendTolstoyEvent(context, 'videoLoaded', {
38
39
  publishId,
40
+ playerType: 'carousel',
39
41
  currentPageProductId: productId,
40
42
  videoId: video.id,
41
43
  productIds: productIds(video),
@@ -62,6 +64,7 @@ export function TolstoyFeed({ publishId, productId, videos, startIndex, visible,
62
64
  return;
63
65
  sendTolstoyEvent(contextRef.current, 'videoWatched', {
64
66
  publishId,
67
+ playerType: 'carousel',
65
68
  currentPageProductId: productId,
66
69
  videoId: current.video.id,
67
70
  productIds: productIds(current.video),
@@ -114,6 +117,7 @@ export function TolstoyFeed({ publishId, productId, videos, startIndex, visible,
114
117
  });
115
118
  sendTolstoyEvent(context, 'clickViewProduct', {
116
119
  publishId,
120
+ playerType: 'carousel',
117
121
  currentPageProductId: productId,
118
122
  videoId: item.id,
119
123
  productIds: [product.id],
@@ -13,7 +13,7 @@ function Carousel({ publishId, productId, videos, title, style }) {
13
13
  contextRef.current = context;
14
14
  useEffect(() => {
15
15
  contextRef.current.onEvent?.({ type: 'view', publishId, productId, videoIds: videos.map((video) => video.id) });
16
- sendTolstoyEvent(contextRef.current, 'embedView', { publishId, currentPageProductId: productId });
16
+ sendTolstoyEvent(contextRef.current, 'embedView', { publishId, playerType: 'carousel', currentPageProductId: productId });
17
17
  }, [publishId, productId, videos]);
18
18
  return (_jsxs(View, { style: style, children: [title ? _jsx(Text, { style: styles.title, children: title }) : null, _jsx(FlatList, { horizontal: true, data: videos, keyExtractor: (video) => video.id, showsHorizontalScrollIndicator: false, contentContainerStyle: styles.list, renderItem: ({ item, index }) => (_jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: item.title ?? 'Play video', onPress: () => setOpenIndex(index), style: styles.tile, children: [item.posterUrl ? _jsx(Image, { source: { uri: item.posterUrl }, style: styles.poster }) : null, _jsx(Text, { style: styles.play, children: "\u25B6" })] })) }), openIndex !== null ? (_jsx(TolstoyFeed, { publishId: publishId, productId: productId, videos: videos, startIndex: openIndex, visible: true, onClose: () => setOpenIndex(null) })) : null] }));
19
19
  }
@@ -5,17 +5,19 @@ export type TolstoyAnalyticsStore = {
5
5
  environment: TolstoyEnvironment;
6
6
  anonymousId: string;
7
7
  };
8
- type TolstoyEventName = 'embedView' | 'sessionStart' | 'videoLoaded' | 'videoWatched' | 'clickViewProduct';
8
+ type TolstoyEventName = 'pageView' | 'embedView' | 'sessionStart' | 'videoLoaded' | 'videoWatched' | 'clickViewProduct' | 'tryon.panel.open' | 'tryon.upload.success' | 'tryon.upload.error' | 'tryon.photo.reject' | 'tryon.generate.start' | 'tryon.generate.success' | 'tryon.generate.error' | 'tryon.result.view' | 'tryon.cart.add';
9
9
  type TolstoyEventFields = {
10
- publishId: string;
10
+ publishId?: string;
11
+ playerType?: 'carousel';
11
12
  currentPageProductId?: string;
12
13
  videoId?: string;
13
14
  productIds?: string[];
14
15
  videoWatchedTime?: number;
15
16
  videoDuration?: number;
16
17
  videoLoopCount?: number;
18
+ customParams?: Record<string, string | number>;
17
19
  };
18
20
  export declare function createTolstoyId(): string;
19
21
  /** Sends an event to the Tolstoy analytics endpoint of the website player, so the store's reports count it. */
20
- export declare function sendTolstoyEvent(store: TolstoyAnalyticsStore, eventName: TolstoyEventName, { productIds, ...fields }: TolstoyEventFields): void;
22
+ export declare function sendTolstoyEvent(store: TolstoyAnalyticsStore, eventName: TolstoyEventName, { productIds, customParams, ...fields }: TolstoyEventFields): void;
21
23
  export {};
package/lib/analytics.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ENVIRONMENTS } from './config';
1
+ import { ENVIRONMENTS, SDK_USER_AGENT } from './config';
2
2
  // The event API keeps only RFC 4122 ids (version 0-5, variant 8-b) in anonymousId.
3
3
  export function createTolstoyId() {
4
4
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
@@ -8,7 +8,7 @@ export function createTolstoyId() {
8
8
  }
9
9
  const sessionId = createTolstoyId();
10
10
  /** Sends an event to the Tolstoy analytics endpoint of the website player, so the store's reports count it. */
11
- export function sendTolstoyEvent(store, eventName, { productIds, ...fields }) {
11
+ export function sendTolstoyEvent(store, eventName, { productIds, customParams, ...fields }) {
12
12
  const event = {
13
13
  eventName,
14
14
  appKey: store.appKey,
@@ -17,15 +17,15 @@ export function sendTolstoyEvent(store, eventName, { productIds, ...fields }) {
17
17
  parentUrl: `https://${store.appUrl}`,
18
18
  anonymousId: store.anonymousId,
19
19
  sessionId,
20
- playerType: 'carousel',
21
20
  isMobile: 'true',
22
21
  timestamp: new Date().toISOString(),
23
22
  productIds: productIds && JSON.stringify(productIds),
23
+ customParams: customParams && JSON.stringify(customParams),
24
24
  ...fields,
25
25
  };
26
26
  fetch(ENVIRONMENTS[store.environment].eventsUrl, {
27
27
  method: 'POST',
28
- headers: { 'Content-Type': 'application/json' },
28
+ headers: { 'Content-Type': 'application/json', 'User-Agent': SDK_USER_AGENT },
29
29
  body: JSON.stringify(event),
30
30
  }).catch((error) => console.warn('Tolstoy analytics event was not sent', eventName, error));
31
31
  }
package/lib/api.d.ts CHANGED
@@ -23,3 +23,13 @@ export type TolstoyStore = {
23
23
  environment: TolstoyEnvironment;
24
24
  };
25
25
  export declare function getVideos(store: TolstoyStore, publishId: string, productId?: string): Promise<TolstoyVideo[]>;
26
+ export { getTryOnPhotos, deleteTryOnPhoto, uploadTryOnPhoto } from './tryOn/methods/tryOnPhotos';
27
+ export type { TolstoyPhotoFile, TolstoyTryOnPhoto } from './tryOn/methods/tryOnPhotos';
28
+ export { runTryOn } from './tryOn/methods/tryOnJob';
29
+ export type { TolstoyTryOnInput, TolstoyTryOnResult } from './tryOn/methods/tryOnJob';
30
+ export { getTryOnProduct, getTryOnVariant, getSizeChoices } from './tryOn/methods/tryOnProduct';
31
+ export type { TolstoySizeChoice, TolstoyTryOnProduct, TolstoyTryOnVariant } from './tryOn/methods/tryOnProduct';
32
+ export { signInShopper } from './tryOn/methods/shopperSignIn';
33
+ export type { TolstoyAppSession } from './tryOn/methods/shopperSignIn';
34
+ export { TolstoyTryOnError } from './tryOn/methods/tryOnSession';
35
+ export type { TolstoyTryOnSession } from './tryOn/methods/tryOnSession';
package/lib/api.js CHANGED
@@ -85,3 +85,8 @@ export async function getVideos(store, publishId, productId) {
85
85
  }),
86
86
  }));
87
87
  }
88
+ export { getTryOnPhotos, deleteTryOnPhoto, uploadTryOnPhoto } from './tryOn/methods/tryOnPhotos';
89
+ export { runTryOn } from './tryOn/methods/tryOnJob';
90
+ export { getTryOnProduct, getTryOnVariant, getSizeChoices } from './tryOn/methods/tryOnProduct';
91
+ export { signInShopper } from './tryOn/methods/shopperSignIn';
92
+ export { TolstoyTryOnError } from './tryOn/methods/tryOnSession';
package/lib/bridge.d.ts CHANGED
@@ -108,4 +108,5 @@ export type BridgeAction = z.infer<typeof BridgeActionSchema>;
108
108
  export type BridgeActionName = BridgeAction['name'];
109
109
  export declare function parseBridgeAction(message: string): BridgeAction | null;
110
110
  export declare function appSessionScript(customerAccessToken: string | null, storefrontAccessToken?: string): string;
111
+ export declare function anonymousIdScript(anonymousId: string): string;
111
112
  export declare function respondScript(id: string, result: 'success' | 'error'): string;
package/lib/bridge.js CHANGED
@@ -30,6 +30,10 @@ export function appSessionScript(customerAccessToken, storefrontAccessToken) {
30
30
  };
31
31
  return `window.Tapcart && window.Tapcart.mobile.load(${JSON.stringify(payload)}); true;`;
32
32
  }
33
+ // The page's AI widget reads the shopper's id from this key, so its events and photos name the provider's anonymousId.
34
+ export function anonymousIdScript(anonymousId) {
35
+ return `localStorage.setItem('tolstoy-anonymousId', ${JSON.stringify(anonymousId)}); true;`;
36
+ }
33
37
  export function respondScript(id, result) {
34
38
  return `window.Tapcart && window.Tapcart.mobile.respond(${JSON.stringify(id)}, ${JSON.stringify(result)}); true;`;
35
39
  }
package/lib/config.d.ts CHANGED
@@ -1,9 +1,14 @@
1
1
  export type TolstoyEnvironment = 'production' | 'dev';
2
2
  type EnvironmentHosts = {
3
3
  apiBase: string;
4
+ directApiBase: string;
5
+ serviceApiBase: string;
4
6
  tryOnPage: string;
5
7
  eventsUrl: string;
6
8
  };
7
9
  export declare const ENVIRONMENTS: Record<TolstoyEnvironment, EnvironmentHosts>;
10
+ export declare const SDK_VERSION = "0.4.0";
11
+ export declare const SDK_USER_AGENT_TOKEN = "TolstoyReactNativeSDK/0.4.0";
12
+ export declare const SDK_USER_AGENT: string;
8
13
  export declare function toQuery(params: Record<string, string | undefined>): string;
9
14
  export {};
package/lib/config.js CHANGED
@@ -1,15 +1,25 @@
1
+ import { Platform } from 'react-native';
1
2
  export const ENVIRONMENTS = {
2
3
  production: {
3
4
  apiBase: 'https://cf-apilb.gotolstoy.com',
5
+ directApiBase: 'https://apilb.gotolstoy.com',
6
+ serviceApiBase: 'https://api.gotolstoy.com',
4
7
  tryOnPage: 'https://play.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
5
8
  eventsUrl: 'https://analytics-v2.gotolstoy.com/event',
6
9
  },
7
10
  dev: {
8
11
  apiBase: 'https://dev-cf-apilb.gotolstoy.com',
12
+ directApiBase: 'https://dev-apilb.gotolstoy.com',
13
+ serviceApiBase: 'https://dev-api.gotolstoy.com',
9
14
  tryOnPage: 'https://play-dev.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
10
15
  eventsUrl: 'https://analytics-v2-dev.gotolstoy.com/event',
11
16
  },
12
17
  };
18
+ // Keep equal to the version in package.json.
19
+ export const SDK_VERSION = '0.4.0';
20
+ // Reports count a request whose user agent carries this name as app traffic.
21
+ export const SDK_USER_AGENT_TOKEN = `TolstoyReactNativeSDK/${SDK_VERSION}`;
22
+ export const SDK_USER_AGENT = `${SDK_USER_AGENT_TOKEN} (${Platform.OS} ${Platform.Version})`;
13
23
  export function toQuery(params) {
14
24
  return Object.entries(params)
15
25
  .flatMap(([key, value]) => (value === undefined ? [] : [`${encodeURIComponent(key)}=${encodeURIComponent(value)}`]))
package/lib/index.d.ts CHANGED
@@ -4,10 +4,11 @@ export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarous
4
4
  export type { TolstoyVideoCarouselProps, TolstoyProductVideosProps } from './TolstoyVideoCarousel';
5
5
  export { TolstoyFeed } from './TolstoyFeed';
6
6
  export type { TolstoyFeedProps } from './TolstoyFeed';
7
- export { TolstoyTryOn } from './TolstoyTryOn';
8
- export type { TolstoyTryOnProps } from './TolstoyTryOn';
7
+ export { TolstoyTryOn } from './tryOn/TolstoyTryOn';
8
+ export type { TolstoyTryOnProps } from './tryOn/TolstoyTryOn';
9
+ export { useTolstoyTryOn } from './tryOn/useTolstoyTryOn';
10
+ export type { TolstoyTryOnState, TolstoyTryOnStep, UseTolstoyTryOnOptions } from './tryOn/useTolstoyTryOn';
9
11
  export { useTolstoyVideos } from './useTolstoyVideos';
10
12
  export type { TolstoyVideosState } from './useTolstoyVideos';
11
- export { getVideos } from './api';
12
- export type { TolstoyProduct, TolstoyStore, TolstoyVideo } from './api';
13
+ export * from './api';
13
14
  export type { TolstoyEnvironment } from './config';
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { TolstoyProvider, useTolstoy } from './TolstoyProvider';
2
2
  export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarousel';
3
3
  export { TolstoyFeed } from './TolstoyFeed';
4
- export { TolstoyTryOn } from './TolstoyTryOn';
4
+ export { TolstoyTryOn } from './tryOn/TolstoyTryOn';
5
+ export { useTolstoyTryOn } from './tryOn/useTolstoyTryOn';
5
6
  export { useTolstoyVideos } from './useTolstoyVideos';
6
- export { getVideos } from './api';
7
+ export * from './api';
@@ -2,9 +2,9 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from 'react';
3
3
  import { ActivityIndicator, StyleSheet, View } from 'react-native';
4
4
  import { WebView } from 'react-native-webview';
5
- import { appSessionScript, parseBridgeAction, respondScript } from './bridge';
6
- import { ENVIRONMENTS, toQuery } from './config';
7
- import { useTolstoy } from './TolstoyProvider';
5
+ import { anonymousIdScript, appSessionScript, parseBridgeAction, respondScript } from '../bridge';
6
+ import { ENVIRONMENTS, SDK_USER_AGENT_TOKEN, toQuery } from '../config';
7
+ import { useTolstoy } from '../TolstoyProvider';
8
8
  const ACTION_HANDLERS = {
9
9
  'product/open': ({ data }, { onProductPress }) => onProductPress(data.productId, data.variantId),
10
10
  'cart/add': ({ data }, { onAddToCart, onEvent, productId }, respond) => {
@@ -24,7 +24,7 @@ function runAction(action, context, respond) {
24
24
  }
25
25
  export function TolstoyTryOn({ productId, widgetId, onClose }) {
26
26
  const context = useTolstoy();
27
- const { appKey, appUrl, environment, getAppSession, storefrontAccessToken } = context;
27
+ const { appKey, appUrl, environment, anonymousId, getAppSession, storefrontAccessToken } = context;
28
28
  const webView = useRef(null);
29
29
  const [session, setSession] = useState(getAppSession ? null : { token: null });
30
30
  useEffect(() => {
@@ -51,7 +51,7 @@ export function TolstoyTryOn({ productId, widgetId, onClose }) {
51
51
  };
52
52
  runAction(action, { ...context, productId, onClose }, respond);
53
53
  };
54
- return (_jsx(WebView, { ref: webView, style: styles.webView, source: { uri: `${ENVIRONMENTS[environment].tryOnPage}?${query}` }, injectedJavaScript: appSessionScript(session.token, storefrontAccessToken), onMessage: onMessage, allowsInlineMediaPlayback: true, mediaPlaybackRequiresUserAction: false, javaScriptEnabled: true, domStorageEnabled: true }));
54
+ return (_jsx(WebView, { ref: webView, style: styles.webView, source: { uri: `${ENVIRONMENTS[environment].tryOnPage}?${query}` }, injectedJavaScriptBeforeContentLoaded: anonymousIdScript(anonymousId), injectedJavaScript: appSessionScript(session.token, storefrontAccessToken), applicationNameForUserAgent: SDK_USER_AGENT_TOKEN, onMessage: onMessage, allowsInlineMediaPlayback: true, mediaPlaybackRequiresUserAction: false, javaScriptEnabled: true, domStorageEnabled: true }));
55
55
  }
56
56
  const styles = StyleSheet.create({
57
57
  loading: { flex: 1, alignItems: 'center', justifyContent: 'center' },
@@ -0,0 +1,12 @@
1
+ import type { TolstoyTryOnSession } from './tryOnSession';
2
+ export type TolstoyAppSession = {
3
+ /** The token `getAppSession` gives (see "Token contract" in the README). */
4
+ customerAccessToken: string;
5
+ /** Set when `customerAccessToken` is a Storefront API customer access token. */
6
+ storefrontAccessToken?: string;
7
+ };
8
+ /**
9
+ * Exchanges the app's Shopify customer token for a Tolstoy shopper token and links this device's anonymous id to
10
+ * the shopper, so their saved photos follow their account. Shopify checks the token; Tolstoy does not keep it.
11
+ */
12
+ export declare function signInShopper(session: TolstoyTryOnSession, appSession: TolstoyAppSession): Promise<string>;
@@ -0,0 +1,29 @@
1
+ import { z } from 'zod';
2
+ import { ENVIRONMENTS } from '../../config';
3
+ import { jsonHeaders, readJson, shopperQuery } from './tryOnSession';
4
+ const SignInSchema = z.object({ success: z.boolean(), token: z.string().optional() });
5
+ /**
6
+ * Exchanges the app's Shopify customer token for a Tolstoy shopper token and links this device's anonymous id to
7
+ * the shopper, so their saved photos follow their account. Shopify checks the token; Tolstoy does not keep it.
8
+ */
9
+ export async function signInShopper(session, appSession) {
10
+ const { serviceApiBase, directApiBase } = ENVIRONMENTS[session.environment];
11
+ const tokens = appSession.storefrontAccessToken
12
+ ? {
13
+ shopifyStorefrontCustomerAccessToken: appSession.customerAccessToken,
14
+ shopifyStorefrontAccessToken: appSession.storefrontAccessToken,
15
+ }
16
+ : { shopifyCustomerAccessToken: appSession.customerAccessToken };
17
+ const response = await fetch(`${serviceApiBase}/customers-service/tapcart/signin`, {
18
+ method: 'POST',
19
+ headers: { 'Content-Type': 'application/json' },
20
+ body: JSON.stringify({ appKey: session.appKey, appUrl: session.appUrl, anonId: session.anonymousId, ...tokens }),
21
+ });
22
+ const { success, token } = await readJson(response, SignInSchema, 'shopper sign-in');
23
+ if (!success || !token)
24
+ throw new Error('Tolstoy shopper sign-in failed: Shopify did not accept the customer token');
25
+ const signedIn = { ...session, shopperToken: token };
26
+ const linked = await fetch(`${directApiBase}/shop-assistant-service/api/customer/register-email?${shopperQuery(signedIn)}`, { method: 'POST', headers: jsonHeaders(signedIn), body: '{}' });
27
+ await readJson(linked, z.unknown(), 'shopper link');
28
+ return token;
29
+ }
@@ -0,0 +1,17 @@
1
+ import type { TolstoyTryOnSession } from './tryOnSession';
2
+ export type TolstoyTryOnInput = {
3
+ productId: string;
4
+ variantId: string | null;
5
+ variantImageUrl: string | null;
6
+ /** The url of a saved photo or of the photo `uploadTryOnPhoto` gave. */
7
+ photoUrl: string;
8
+ };
9
+ export type TolstoyTryOnResult = {
10
+ imageUrl: string;
11
+ shopperMediaId: string;
12
+ };
13
+ /**
14
+ * Tries the product variant on the photo and waits for the image. The store pays for it. A refusal or a failed
15
+ * try-on throws a TolstoyTryOnError with the server's message for the shopper. An aborted signal stops the wait.
16
+ */
17
+ export declare function runTryOn(session: TolstoyTryOnSession, input: TolstoyTryOnInput, signal?: AbortSignal): Promise<TolstoyTryOnResult>;
@@ -0,0 +1,56 @@
1
+ import { z } from 'zod';
2
+ import { ENVIRONMENTS } from '../../config';
3
+ import { jsonHeaders, readJson, shopperQuery, TolstoyTryOnError } from './tryOnSession';
4
+ const RefusedSchema = z.object({ success: z.literal(false), message: z.string() });
5
+ const StartSchema = z.union([z.object({ success: z.literal(true), jobId: z.string() }), RefusedSchema]);
6
+ const PollSchema = z.union([
7
+ z.object({
8
+ success: z.literal(true),
9
+ job: z.object({
10
+ status: z.enum(['running', 'completed', 'failed']),
11
+ result: z.object({ mediaUrl: z.string(), shopperMediaId: z.string() }).optional(),
12
+ error: z.object({ message: z.string() }).optional(),
13
+ }),
14
+ }),
15
+ RefusedSchema,
16
+ ]);
17
+ const POLL_INTERVAL_MS = 3000;
18
+ // The server fails a job that is not final after 20 minutes.
19
+ const MAX_WAIT_MS = 21 * 60 * 1000;
20
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
21
+ async function postJob(session, operation, body, schema, signal) {
22
+ const url = `${ENVIRONMENTS[session.environment].directApiBase}/shop-assistant-service/api/generation/${operation}?${shopperQuery(session)}`;
23
+ const response = await fetch(url, { method: 'POST', headers: jsonHeaders(session), body: JSON.stringify(body), signal });
24
+ return readJson(response, schema, operation);
25
+ }
26
+ /**
27
+ * Tries the product variant on the photo and waits for the image. The store pays for it. A refusal or a failed
28
+ * try-on throws a TolstoyTryOnError with the server's message for the shopper. An aborted signal stops the wait.
29
+ */
30
+ export async function runTryOn(session, input, signal) {
31
+ const started = await postJob(session, 'startGenerationJob', {
32
+ kind: 'tryon',
33
+ input: {
34
+ humanImageUrl: input.photoUrl,
35
+ products: [{ productId: input.productId, variantId: input.variantId, variantImageUrl: input.variantImageUrl }],
36
+ },
37
+ surface: 'ai-widget',
38
+ }, StartSchema, signal);
39
+ if (!started.success)
40
+ throw new TolstoyTryOnError(started.message);
41
+ const deadline = Date.now() + MAX_WAIT_MS;
42
+ while (Date.now() < deadline) {
43
+ await sleep(POLL_INTERVAL_MS);
44
+ if (signal?.aborted)
45
+ throw new Error('Tolstoy try-on was cancelled');
46
+ const polled = await postJob(session, 'getGenerationJob', { id: started.jobId }, PollSchema, signal);
47
+ if (!polled.success)
48
+ throw new TolstoyTryOnError(polled.message);
49
+ const { status, result, error } = polled.job;
50
+ if (status === 'completed' && result)
51
+ return { imageUrl: result.mediaUrl, shopperMediaId: result.shopperMediaId };
52
+ if (status === 'failed')
53
+ throw new TolstoyTryOnError(error?.message || 'The try-on failed. Please try again.');
54
+ }
55
+ throw new TolstoyTryOnError('The try-on is taking longer than expected. Please try again later.');
56
+ }
@@ -0,0 +1,19 @@
1
+ import type { TolstoyTryOnSession } from './tryOnSession';
2
+ export type TolstoyTryOnPhoto = {
3
+ id: string;
4
+ url: string;
5
+ };
6
+ /** A photo file on the device, as an image picker gives it. */
7
+ export type TolstoyPhotoFile = {
8
+ uri: string;
9
+ type?: string;
10
+ fileName?: string;
11
+ };
12
+ /** The shopper's saved photos, newest first. A signed-in shopper gets the photos of every device they used. */
13
+ export declare function getTryOnPhotos(session: TolstoyTryOnSession): Promise<TolstoyTryOnPhoto[]>;
14
+ export declare function deleteTryOnPhoto(session: TolstoyTryOnSession, photoId: string): Promise<void>;
15
+ /**
16
+ * Uploads a photo and runs the photo check. A photo the check rejects throws a TolstoyTryOnError
17
+ * with the server's reason, for the shopper to read. An aborted signal stops the upload.
18
+ */
19
+ export declare function uploadTryOnPhoto(session: TolstoyTryOnSession, file: TolstoyPhotoFile, onProgress?: (percent: number) => void, signal?: AbortSignal): Promise<TolstoyTryOnPhoto>;