@tolstoy-ai/react-native-sdk 0.2.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.
- package/README.md +129 -8
- package/lib/TolstoyFeed.js +4 -0
- package/lib/TolstoyProvider.d.ts +1 -1
- package/lib/TolstoyProvider.js +1 -4
- package/lib/TolstoyVideoCarousel.js +1 -1
- package/lib/analytics.d.ts +5 -3
- package/lib/analytics.js +4 -4
- package/lib/api.d.ts +10 -0
- package/lib/api.js +5 -0
- package/lib/bridge.d.ts +1 -0
- package/lib/bridge.js +4 -0
- package/lib/config.d.ts +5 -0
- package/lib/config.js +10 -0
- package/lib/index.d.ts +5 -4
- package/lib/index.js +3 -2
- package/lib/{TolstoyTryOn.js → tryOn/TolstoyTryOn.js} +5 -5
- package/lib/tryOn/methods/shopperSignIn.d.ts +12 -0
- package/lib/tryOn/methods/shopperSignIn.js +29 -0
- package/lib/tryOn/methods/tryOnJob.d.ts +17 -0
- package/lib/tryOn/methods/tryOnJob.js +56 -0
- package/lib/tryOn/methods/tryOnPhotos.d.ts +19 -0
- package/lib/tryOn/methods/tryOnPhotos.js +112 -0
- package/lib/tryOn/methods/tryOnProduct.d.ts +169 -0
- package/lib/tryOn/methods/tryOnProduct.js +49 -0
- package/lib/tryOn/methods/tryOnSession.d.ts +14 -0
- package/lib/tryOn/methods/tryOnSession.js +26 -0
- package/lib/tryOn/screen/Header.d.ts +9 -0
- package/lib/tryOn/screen/Header.js +22 -0
- package/lib/tryOn/screen/Icon.d.ts +6 -0
- package/lib/tryOn/screen/Icon.js +6 -0
- package/lib/tryOn/screen/PhotoStep.d.ts +12 -0
- package/lib/tryOn/screen/PhotoStep.js +70 -0
- package/lib/tryOn/screen/PillButton.d.ts +10 -0
- package/lib/tryOn/screen/PillButton.js +31 -0
- package/lib/tryOn/screen/ProgressStep.d.ts +16 -0
- package/lib/tryOn/screen/ProgressStep.js +82 -0
- package/lib/tryOn/screen/ResultStep.d.ts +12 -0
- package/lib/tryOn/screen/ResultStep.js +114 -0
- package/lib/tryOn/screen/TolstoyMark.d.ts +4 -0
- package/lib/tryOn/screen/TolstoyMark.js +18 -0
- package/lib/tryOn/screen/TolstoyTryOnScreen.d.ts +6 -0
- package/lib/tryOn/screen/TolstoyTryOnScreen.js +39 -0
- package/lib/tryOn/screen/TopImage.d.ts +8 -0
- package/lib/tryOn/screen/TopImage.js +22 -0
- package/lib/tryOn/screen/icons.d.ts +24 -0
- package/lib/tryOn/screen/icons.js +10 -0
- package/lib/tryOn/screen/pickPhoto.d.ts +9 -0
- package/lib/tryOn/screen/pickPhoto.js +21 -0
- package/lib/tryOn/screen/useEstimatedProgress.d.ts +2 -0
- package/lib/tryOn/screen/useEstimatedProgress.js +22 -0
- package/lib/tryOn/useTolstoyTryOn.d.ts +44 -0
- package/lib/tryOn/useTolstoyTryOn.js +194 -0
- package/package.json +10 -1
- /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,10 +31,12 @@ 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>"
|
|
35
38
|
appUrl="<your-store>.myshopify.com"
|
|
39
|
+
anonymousId={anonymousId}
|
|
36
40
|
onProductPress={(productId, variantId, handle) => navigation.navigate('Product', { productId, variantId, handle })}
|
|
37
41
|
getAppSession={async () => customerAccessToken ?? null}
|
|
38
42
|
storefrontAccessToken="<your Storefront API public access token>"
|
|
@@ -45,9 +49,11 @@ import {
|
|
|
45
49
|
</TolstoyProvider>
|
|
46
50
|
```
|
|
47
51
|
|
|
48
|
-
Show
|
|
52
|
+
Show a try-on screen full screen, for example in a modal or as its own route:
|
|
49
53
|
|
|
50
54
|
```tsx
|
|
55
|
+
<TolstoyTryOnScreen productId={product.id} variantId={selectedVariant.id} onClose={() => navigation.goBack()} />
|
|
56
|
+
// or, in a WebView:
|
|
51
57
|
<TolstoyTryOn productId={product.id} onClose={() => navigation.goBack()} />
|
|
52
58
|
```
|
|
53
59
|
|
|
@@ -55,20 +61,29 @@ Show the try-on screen full screen, for example in a modal or as its own route:
|
|
|
55
61
|
| --- | --- | --- |
|
|
56
62
|
| `appKey` | `TolstoyProvider` | Your Tolstoy app key. |
|
|
57
63
|
| `appUrl` | `TolstoyProvider` | Your store's `*.myshopify.com` domain. |
|
|
64
|
+
| `anonymousId` | `TolstoyProvider` | A UUID that names the shopper's device in Tolstoy analytics (see "Anonymous id"). |
|
|
58
65
|
| `onProductPress(productId, variantId?, handle?)` | `TolstoyProvider` | Opens your product screen. The ids are numeric Shopify ids. `handle` is the product handle. A product card always gives it; "View product" in try-on does not. |
|
|
59
66
|
| `getAppSession()` | `TolstoyProvider`, optional | Gives the signed-in shopper's token (see "Token contract"). Give `null` when no shopper is signed in. |
|
|
60
67
|
| `storefrontAccessToken` | `TolstoyProvider`, optional | Your store's Storefront API public access token. Set it when `getAppSession` gives a Storefront API customer access token (see "Token contract"). |
|
|
61
68
|
| `onAddToCart(lines)` | `TolstoyProvider`, optional | Adds lines (`variantId`, `quantity`) to your app's cart. Reject the promise when the add fails. Without this prop, add to cart from try-on shows an error. |
|
|
62
69
|
| `onOpenCart()` | `TolstoyProvider`, optional | Opens your cart screen. |
|
|
63
70
|
| `onEvent(event)` | `TolstoyProvider`, optional | Tells your app what the shopper does (see "Events"). |
|
|
64
|
-
| `anonymousId` | `TolstoyProvider`, optional | A UUID that names the shopper's device in Tolstoy analytics. Without it, the package makes one for each app session. |
|
|
65
71
|
| `environment` | `TolstoyProvider`, optional | `production` (default) or `dev`. |
|
|
66
72
|
| `publishId` | carousels | The publish id of a Tolstoy player. Tolstoy gives it to you. |
|
|
67
|
-
| `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. |
|
|
68
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. |
|
|
69
76
|
|
|
70
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.
|
|
71
78
|
|
|
79
|
+
## Anonymous id
|
|
80
|
+
|
|
81
|
+
Tolstoy counts viewers by `anonymousId`. The package makes no id of its own. Create a UUID once, keep it on the device in your app's own storage, and pass the same value on every launch. An id that changes on each launch makes each launch a new viewer, and an order no longer matches the events of an earlier launch.
|
|
82
|
+
|
|
83
|
+
```tsx
|
|
84
|
+
const anonymousId = await getOrCreateStoredUuid(); // your code: read the saved UUID, or make one and save it
|
|
85
|
+
```
|
|
86
|
+
|
|
72
87
|
## Videos and product cards
|
|
73
88
|
|
|
74
89
|
- A video plays from its HLS stream when Tolstoy has one, and from its MP4 file when it does not.
|
|
@@ -88,7 +103,9 @@ Show the try-on screen full screen, for example in a modal or as its own route:
|
|
|
88
103
|
| `product_press` | The shopper taps a product card. | `publishId`, `videoId`, `productId`, `variantId?`, `handle?` |
|
|
89
104
|
| `add_to_cart` | Your `onAddToCart` added the lines from try-on. | `productId` (the product of the try-on screen), `lines` |
|
|
90
105
|
|
|
91
|
-
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.
|
|
92
109
|
|
|
93
110
|
## Order attribution
|
|
94
111
|
|
|
@@ -102,7 +119,111 @@ const { cartAttributes } = useTolstoy();
|
|
|
102
119
|
// Give them as `attributes` to the Storefront API cartCreate, or to cartAttributesUpdate.
|
|
103
120
|
```
|
|
104
121
|
|
|
105
|
-
The value is the `anonymousId` of the provider.
|
|
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.
|
|
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.
|
|
106
227
|
|
|
107
228
|
## Use your own player
|
|
108
229
|
|
|
@@ -135,9 +256,9 @@ const videos = await getVideos(
|
|
|
135
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.
|
|
136
257
|
- When `getAppSession` is not set, or gives `null`, the shopper signs in with an email on the try-on screen.
|
|
137
258
|
|
|
138
|
-
## How the try-on screen talks to your app
|
|
259
|
+
## How the WebView try-on screen talks to your app
|
|
139
260
|
|
|
140
|
-
|
|
261
|
+
`TolstoyTryOn` is a Tolstoy web page in a WebView. The page sends these messages to the package, and the package calls your props:
|
|
141
262
|
|
|
142
263
|
| Message | Prop |
|
|
143
264
|
| --- | --- |
|
|
@@ -146,4 +267,4 @@ The try-on screen is a Tolstoy web page in a WebView. The page sends these messa
|
|
|
146
267
|
| `cart/open` | `onOpenCart()` |
|
|
147
268
|
| `go/back` (the shopper closes the chat) | the `onClose` of `TolstoyTryOn` |
|
|
148
269
|
|
|
149
|
-
|
|
270
|
+
The WebView try-on works only for a store that has the Tolstoy shopper chat switched on.
|
package/lib/TolstoyFeed.js
CHANGED
|
@@ -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],
|
package/lib/TolstoyProvider.d.ts
CHANGED
|
@@ -33,7 +33,7 @@ export type TolstoyProviderProps = {
|
|
|
33
33
|
appKey: string;
|
|
34
34
|
appUrl: string;
|
|
35
35
|
environment?: TolstoyEnvironment;
|
|
36
|
-
anonymousId
|
|
36
|
+
anonymousId: string;
|
|
37
37
|
onProductPress: (productId: string, variantId?: string, handle?: string) => void;
|
|
38
38
|
getAppSession?: () => Promise<string | null>;
|
|
39
39
|
storefrontAccessToken?: string;
|
package/lib/TolstoyProvider.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
2
|
import { createContext, useContext, useMemo } from 'react';
|
|
3
|
-
import { createTolstoyId } from './analytics';
|
|
4
|
-
// Without an anonymousId from the app, the shopper is one Tolstoy visitor for the app session.
|
|
5
|
-
const sessionAnonymousId = createTolstoyId();
|
|
6
3
|
const TolstoyContext = createContext(null);
|
|
7
|
-
export function TolstoyProvider({ appKey, appUrl, environment = 'production', anonymousId
|
|
4
|
+
export function TolstoyProvider({ appKey, appUrl, environment = 'production', anonymousId, onProductPress, getAppSession, storefrontAccessToken, onAddToCart, onOpenCart, onEvent, children, }) {
|
|
8
5
|
const value = useMemo(() => ({
|
|
9
6
|
appKey,
|
|
10
7
|
appUrl,
|
|
@@ -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
|
}
|
package/lib/analytics.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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 '
|
|
6
|
-
import { ENVIRONMENTS, toQuery } from '
|
|
7
|
-
import { useTolstoy } from '
|
|
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>;
|