@tolstoy-ai/react-native-sdk 0.0.0-stage → 0.1.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 CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # @tolstoy-ai/react-native-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tolstoy shoppable videos and virtual try-on for a bare React Native app. The package does not use Expo.
4
+
5
+ - Video carousels for the home screen and the product screen. The videos play natively with your `react-native-video`.
6
+ - A full-screen video feed with product cards. A tap on a product card calls your `onProductPress(productId, variantId)`.
7
+ - A try-on screen in a WebView. The shopper signs in with your app account or with an email.
8
+
9
+ ## Requirements
10
+
11
+ - React Native 0.81 or later, with the New Architecture and Hermes.
12
+ - 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.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ npm install @tolstoy-ai/react-native-sdk
18
+ ```
19
+
20
+ ## Use
21
+
22
+ Put `TolstoyProvider` around the screens that show Tolstoy parts.
23
+
24
+ ```tsx
25
+ import {
26
+ TolstoyProvider,
27
+ TolstoyVideoCarousel,
28
+ TolstoyProductVideos,
29
+ TolstoyTryOn,
30
+ } from '@tolstoy-ai/react-native-sdk';
31
+
32
+ <TolstoyProvider
33
+ appKey="<your Tolstoy app key>"
34
+ appUrl="<your-store>.myshopify.com"
35
+ onProductPress={(productId, variantId) => navigation.navigate('Product', { productId, variantId })}
36
+ getAppSession={async () => customerAccountAccessToken ?? null}
37
+ onAddToCart={async (lines) => addToAppCart(lines)}
38
+ onOpenCart={() => navigation.navigate('Cart')}
39
+ >
40
+ <TolstoyVideoCarousel publishId="<home player publish id>" />
41
+ <TolstoyProductVideos publishId="<product page player publish id>" productId={product.id} />
42
+ </TolstoyProvider>
43
+ ```
44
+
45
+ Show the try-on screen full screen, for example in a modal or as its own route:
46
+
47
+ ```tsx
48
+ <TolstoyTryOn productId={product.id} onClose={() => navigation.goBack()} />
49
+ ```
50
+
51
+ | Prop | Where | Description |
52
+ | --- | --- | --- |
53
+ | `appKey` | `TolstoyProvider` | Your Tolstoy app key. |
54
+ | `appUrl` | `TolstoyProvider` | Your store's `*.myshopify.com` domain. |
55
+ | `onProductPress(productId, variantId?)` | `TolstoyProvider` | Opens your product screen. The ids are numeric Shopify ids. |
56
+ | `getAppSession()` | `TolstoyProvider`, optional | Gives the signed-in shopper's token (see "Token contract"). Give `null` when no shopper is signed in. |
57
+ | `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. |
58
+ | `onOpenCart()` | `TolstoyProvider`, optional | Opens your cart screen. |
59
+ | `environment` | `TolstoyProvider`, optional | `production` (default) or `dev`. |
60
+ | `publishId` | carousels | The publish id of a Tolstoy player. Tolstoy gives it to you. |
61
+ | `productId` | `TolstoyProductVideos`, `TolstoyTryOn` | The numeric Shopify product id. |
62
+ | `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. |
63
+
64
+ `TolstoyProductVideos` shows nothing when the product has no videos. `useTolstoyVideos(publishId, productId?)` gives the same data for your own UI.
65
+
66
+ ## Token contract
67
+
68
+ `getAppSession()` must give the **Shopify Customer Account API access token** of the shopper who is signed in to your app. This is the access token that your app gets from the store's Customer Account API sign-in (OAuth), and it starts with `shcat_`.
69
+
70
+ - Tolstoy sends the token to the store's own Customer Account API (`https://<store>/.well-known/customer-account-api` gives its address). Shopify tells Tolstoy the shopper's email. Tolstoy then signs the shopper in to try-on.
71
+ - Tolstoy does not keep the token.
72
+ - Do not give a Storefront API customer access token, an Appbrew token, or your own session token. Tolstoy cannot verify them, and the shopper must then sign in with an email.
73
+ - When `getAppSession` is not set, or gives `null`, the shopper signs in with an email on the try-on screen.
74
+
75
+ ## How the try-on screen talks to your app
76
+
77
+ 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:
78
+
79
+ | Message | Prop |
80
+ | --- | --- |
81
+ | `product/open` ("View product") | `onProductPress(productId, variantId?)` |
82
+ | `cart/add` | `onAddToCart(lines)` |
83
+ | `cart/open` | `onOpenCart()` |
84
+ | `go/back` (the shopper closes the chat) | the `onClose` of `TolstoyTryOn` |
85
+
86
+ Try-on works only for a store that has the Tolstoy shopper chat switched on.
@@ -0,0 +1,8 @@
1
+ import type { TolstoyVideo } from './api';
2
+ export type TolstoyFeedProps = {
3
+ videos: TolstoyVideo[];
4
+ startIndex: number;
5
+ visible: boolean;
6
+ onClose: () => void;
7
+ };
8
+ export declare function TolstoyFeed({ videos, startIndex, visible, onClose }: TolstoyFeedProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,51 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useCallback, useRef, useState } from 'react';
3
+ import { FlatList, Image, Modal, Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
4
+ import Video from 'react-native-video';
5
+ import { useTolstoy } from './TolstoyProvider';
6
+ const PLAYERS_AROUND_ACTIVE = 1;
7
+ function ProductCard({ product, onOpen }) {
8
+ const { onProductPress } = useTolstoy();
9
+ return (_jsxs(Pressable, { accessibilityRole: "button", style: styles.productCard, onPress: () => {
10
+ onOpen();
11
+ onProductPress(product.id, product.variantId);
12
+ }, children: [product.imageUrl ? _jsx(Image, { source: { uri: product.imageUrl }, style: styles.productImage }) : null, _jsxs(View, { style: styles.productText, children: [_jsx(Text, { numberOfLines: 2, style: styles.productTitle, children: product.title }), product.price ? (_jsxs(Text, { style: styles.productPrice, children: [product.currencySymbol, product.price] })) : null] })] }));
13
+ }
14
+ export function TolstoyFeed({ videos, startIndex, visible, onClose }) {
15
+ const { height, width } = useWindowDimensions();
16
+ const [activeIndex, setActiveIndex] = useState(startIndex);
17
+ const [muted, setMuted] = useState(false);
18
+ const onViewableItemsChanged = useRef(({ viewableItems }) => {
19
+ const index = viewableItems[0]?.index;
20
+ if (typeof index === 'number')
21
+ setActiveIndex(index);
22
+ }).current;
23
+ const renderItem = useCallback(({ item, index }) => (_jsxs(View, { style: { height, width }, children: [Math.abs(index - activeIndex) <= PLAYERS_AROUND_ACTIVE ? (_jsx(Video, { source: { uri: item.videoUrl }, poster: item.posterUrl ? { source: { uri: item.posterUrl }, resizeMode: 'cover' } : undefined, style: StyleSheet.absoluteFill, resizeMode: "cover", paused: index !== activeIndex, muted: muted, repeat: true, playInBackground: false })) : item.posterUrl ? (_jsx(Image, { source: { uri: item.posterUrl }, style: StyleSheet.absoluteFill })) : null, _jsx(View, { style: styles.products, children: item.products.map((product) => (_jsx(ProductCard, { product: product, onOpen: onClose }, product.id))) })] })), [activeIndex, height, muted, onClose, width]);
24
+ return (_jsx(Modal, { visible: visible, animationType: "slide", onRequestClose: onClose, supportedOrientations: ['portrait'], children: _jsxs(View, { style: styles.feed, children: [_jsx(FlatList, { data: videos, keyExtractor: (video) => video.id, renderItem: renderItem, pagingEnabled: true, initialScrollIndex: startIndex, getItemLayout: (_, index) => ({ length: height, offset: height * index, index }), onViewableItemsChanged: onViewableItemsChanged, viewabilityConfig: { itemVisiblePercentThreshold: 80 }, showsVerticalScrollIndicator: false, windowSize: 3 }), _jsxs(View, { style: styles.controls, children: [_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Close", onPress: onClose, style: styles.control, children: _jsx(Text, { style: styles.controlText, children: "\u2715" }) }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: muted ? 'Unmute' : 'Mute', onPress: () => setMuted(!muted), style: styles.control, children: _jsx(Text, { style: styles.controlText, children: muted ? '🔇' : '🔊' }) })] })] }) }));
25
+ }
26
+ const styles = StyleSheet.create({
27
+ feed: { flex: 1, backgroundColor: '#000' },
28
+ controls: { position: 'absolute', top: 56, right: 16, gap: 12 },
29
+ control: {
30
+ width: 40,
31
+ height: 40,
32
+ borderRadius: 20,
33
+ backgroundColor: 'rgba(0,0,0,0.45)',
34
+ alignItems: 'center',
35
+ justifyContent: 'center',
36
+ },
37
+ controlText: { color: '#fff', fontSize: 18 },
38
+ products: { position: 'absolute', left: 16, right: 16, bottom: 48, gap: 8 },
39
+ productCard: {
40
+ flexDirection: 'row',
41
+ alignItems: 'center',
42
+ gap: 12,
43
+ padding: 8,
44
+ borderRadius: 12,
45
+ backgroundColor: 'rgba(255,255,255,0.95)',
46
+ },
47
+ productImage: { width: 48, height: 48, borderRadius: 8 },
48
+ productText: { flex: 1 },
49
+ productTitle: { fontSize: 14, fontWeight: '600', color: '#111' },
50
+ productPrice: { fontSize: 13, color: '#333', marginTop: 2 },
51
+ });
@@ -0,0 +1,21 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { TolstoyEnvironment } from './config';
3
+ export type TolstoyCartLine = {
4
+ variantId: string;
5
+ quantity: number;
6
+ };
7
+ export type TolstoyProviderProps = {
8
+ appKey: string;
9
+ appUrl: string;
10
+ environment?: TolstoyEnvironment;
11
+ onProductPress: (productId: string, variantId?: string) => void;
12
+ getAppSession?: () => Promise<string | null>;
13
+ onAddToCart?: (lines: TolstoyCartLine[]) => Promise<void>;
14
+ onOpenCart?: () => void;
15
+ children: ReactNode;
16
+ };
17
+ export type TolstoyContextValue = Omit<TolstoyProviderProps, 'children' | 'environment'> & {
18
+ environment: TolstoyEnvironment;
19
+ };
20
+ export declare function TolstoyProvider({ appKey, appUrl, environment, onProductPress, getAppSession, onAddToCart, onOpenCart, children, }: TolstoyProviderProps): import("react/jsx-runtime").JSX.Element;
21
+ export declare function useTolstoy(): TolstoyContextValue;
@@ -0,0 +1,13 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useMemo } from 'react';
3
+ const TolstoyContext = createContext(null);
4
+ export function TolstoyProvider({ appKey, appUrl, environment = 'production', onProductPress, getAppSession, onAddToCart, onOpenCart, children, }) {
5
+ const value = useMemo(() => ({ appKey, appUrl, environment, onProductPress, getAppSession, onAddToCart, onOpenCart }), [appKey, appUrl, environment, onProductPress, getAppSession, onAddToCart, onOpenCart]);
6
+ return _jsx(TolstoyContext.Provider, { value: value, children: children });
7
+ }
8
+ export function useTolstoy() {
9
+ const value = useContext(TolstoyContext);
10
+ if (!value)
11
+ throw new Error('Put Tolstoy components inside <TolstoyProvider>.');
12
+ return value;
13
+ }
@@ -0,0 +1,6 @@
1
+ export type TolstoyTryOnProps = {
2
+ productId: string;
3
+ widgetId?: string;
4
+ onClose: () => void;
5
+ };
6
+ export declare function TolstoyTryOn({ productId, widgetId, onClose }: TolstoyTryOnProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,55 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { ActivityIndicator, StyleSheet, View } from 'react-native';
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';
8
+ const ACTION_HANDLERS = {
9
+ 'product/open': ({ data }, { onProductPress }) => onProductPress(data.productId, data.variantId),
10
+ 'cart/add': ({ data }, { onAddToCart }, respond) => {
11
+ if (!onAddToCart)
12
+ return respond('error');
13
+ onAddToCart(data.lineItems).then(() => respond('success'), () => respond('error'));
14
+ },
15
+ 'cart/open': (_, { onOpenCart }) => onOpenCart?.(),
16
+ 'go/back': (_, { onClose }) => onClose(),
17
+ };
18
+ function runAction(action, context, respond) {
19
+ const handler = ACTION_HANDLERS[action.name];
20
+ handler(action, context, respond);
21
+ }
22
+ export function TolstoyTryOn({ productId, widgetId, onClose }) {
23
+ const context = useTolstoy();
24
+ const { appKey, appUrl, environment, getAppSession } = context;
25
+ const webView = useRef(null);
26
+ const [session, setSession] = useState(getAppSession ? null : { token: null });
27
+ useEffect(() => {
28
+ if (!getAppSession)
29
+ return;
30
+ let current = true;
31
+ getAppSession().then((token) => current && setSession({ token }), () => current && setSession({ token: null }));
32
+ return () => {
33
+ current = false;
34
+ };
35
+ }, [getAppSession]);
36
+ if (!session) {
37
+ return (_jsx(View, { style: styles.loading, children: _jsx(ActivityIndicator, {}) }));
38
+ }
39
+ const query = toQuery({ appKey, appUrl, productId, widgetId, appSession: 'shopify-customer-account' });
40
+ const onMessage = ({ nativeEvent }) => {
41
+ const action = parseBridgeAction(nativeEvent.data);
42
+ if (!action)
43
+ return;
44
+ const respond = (result) => {
45
+ if (action.id)
46
+ webView.current?.injectJavaScript(respondScript(action.id, result));
47
+ };
48
+ runAction(action, { ...context, onClose }, respond);
49
+ };
50
+ return (_jsx(WebView, { ref: webView, style: styles.webView, source: { uri: `${ENVIRONMENTS[environment].tryOnPage}?${query}` }, injectedJavaScript: appSessionScript(session.token), onMessage: onMessage, allowsInlineMediaPlayback: true, mediaPlaybackRequiresUserAction: false, javaScriptEnabled: true, domStorageEnabled: true }));
51
+ }
52
+ const styles = StyleSheet.create({
53
+ loading: { flex: 1, alignItems: 'center', justifyContent: 'center' },
54
+ webView: { flex: 1 },
55
+ });
@@ -0,0 +1,11 @@
1
+ import type { StyleProp, ViewStyle } from 'react-native';
2
+ export type TolstoyVideoCarouselProps = {
3
+ publishId: string;
4
+ title?: string;
5
+ style?: StyleProp<ViewStyle>;
6
+ };
7
+ export type TolstoyProductVideosProps = TolstoyVideoCarouselProps & {
8
+ productId: string;
9
+ };
10
+ export declare function TolstoyVideoCarousel({ publishId, title, style }: TolstoyVideoCarouselProps): import("react/jsx-runtime").JSX.Element | null;
11
+ export declare function TolstoyProductVideos({ publishId, productId, title, style }: TolstoyProductVideosProps): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from 'react';
3
+ import { FlatList, Image, Pressable, StyleSheet, Text, View } from 'react-native';
4
+ import { TolstoyFeed } from './TolstoyFeed';
5
+ import { useTolstoyVideos } from './useTolstoyVideos';
6
+ function Carousel({ videos, title, style }) {
7
+ const [openIndex, setOpenIndex] = useState(null);
8
+ 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, { videos: videos, startIndex: openIndex, visible: true, onClose: () => setOpenIndex(null) })) : null] }));
9
+ }
10
+ export function TolstoyVideoCarousel({ publishId, title, style }) {
11
+ const state = useTolstoyVideos(publishId);
12
+ if (state.status !== 'ready' || !state.videos.length)
13
+ return null;
14
+ return _jsx(Carousel, { videos: state.videos, title: title, style: style });
15
+ }
16
+ export function TolstoyProductVideos({ publishId, productId, title, style }) {
17
+ const state = useTolstoyVideos(publishId, productId);
18
+ if (state.status !== 'ready' || !state.videos.length)
19
+ return null;
20
+ return _jsx(Carousel, { videos: state.videos, title: title, style: style });
21
+ }
22
+ const styles = StyleSheet.create({
23
+ title: { fontSize: 16, fontWeight: '600', marginHorizontal: 16, marginBottom: 8 },
24
+ list: { paddingHorizontal: 16, gap: 8 },
25
+ tile: {
26
+ width: 120,
27
+ height: 213,
28
+ borderRadius: 12,
29
+ overflow: 'hidden',
30
+ backgroundColor: '#eee',
31
+ alignItems: 'center',
32
+ justifyContent: 'center',
33
+ },
34
+ poster: { ...StyleSheet.absoluteFillObject },
35
+ play: { color: '#fff', fontSize: 28, textShadowColor: 'rgba(0,0,0,0.5)', textShadowRadius: 6 },
36
+ });
package/lib/api.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { TolstoyEnvironment } from './config';
2
+ export type TolstoyProduct = {
3
+ id: string;
4
+ variantId?: string;
5
+ title?: string;
6
+ imageUrl?: string;
7
+ price?: string;
8
+ compareAtPrice?: string;
9
+ currencySymbol?: string;
10
+ };
11
+ export type TolstoyVideo = {
12
+ id: string;
13
+ title?: string;
14
+ videoUrl: string;
15
+ posterUrl?: string;
16
+ products: TolstoyProduct[];
17
+ };
18
+ export type TolstoyStore = {
19
+ appKey: string;
20
+ appUrl: string;
21
+ environment: TolstoyEnvironment;
22
+ };
23
+ export declare function getVideos(store: TolstoyStore, publishId: string, productId?: string): Promise<TolstoyVideo[]>;
package/lib/api.js ADDED
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ import { ENVIRONMENTS, toQuery } from './config';
3
+ const StepSchema = z.object({
4
+ videoId: z.string().optional(),
5
+ videoName: z.string().optional(),
6
+ products: z.array(z.object({ id: z.string().optional(), variantIds: z.array(z.string()).optional() })).optional(),
7
+ stockAsset: z.object({ videoUrl: z.string().optional(), posterUrl: z.string().optional() }).optional(),
8
+ });
9
+ const SettingsSchema = z.union([
10
+ z.object({ disabled: z.literal(true) }),
11
+ z.object({ steps: z.array(StepSchema).optional() }),
12
+ ]);
13
+ const VariantSchema = z.object({
14
+ id: z.string().optional(),
15
+ price: z.string().nullish(),
16
+ compareAtPrice: z.string().nullish(),
17
+ });
18
+ const ProductsSchema = z.record(z.string(), z.object({
19
+ id: z.string(),
20
+ title: z.string().optional(),
21
+ imageUrl: z.string().nullish(),
22
+ currencySymbol: z.string().nullish(),
23
+ handle: z.string().optional(),
24
+ variants: z.array(VariantSchema).optional(),
25
+ }));
26
+ async function getJson(url, schema) {
27
+ const response = await fetch(url);
28
+ if (!response.ok)
29
+ throw new Error(`Tolstoy request failed: ${response.status}`);
30
+ return schema.parse(await response.json());
31
+ }
32
+ export async function getVideos(store, publishId, productId) {
33
+ const { apiBase } = ENVIRONMENTS[store.environment];
34
+ const settingsQuery = toQuery({ publishId, appKey: store.appKey, productId });
35
+ const settings = await getJson(`${apiBase}/mobile-app/config/getMobileSettings?${settingsQuery}`, SettingsSchema);
36
+ if ('disabled' in settings)
37
+ return [];
38
+ const steps = (settings.steps ?? []).flatMap(({ videoId, videoName, products, stockAsset }) => videoId && stockAsset?.videoUrl
39
+ ? [{ videoId, videoName, products: products ?? [], videoUrl: stockAsset.videoUrl, posterUrl: stockAsset.posterUrl }]
40
+ : []);
41
+ if (!steps.length)
42
+ return [];
43
+ const productsQuery = toQuery({
44
+ appUrl: store.appUrl,
45
+ appKey: store.appKey,
46
+ vodAssetIds: steps.map((step) => step.videoId).join(','),
47
+ });
48
+ const products = await getJson(`${apiBase}/mobile-app/config/getMobileProducts?${productsQuery}`, ProductsSchema);
49
+ return steps.map((step) => ({
50
+ id: step.videoId,
51
+ title: step.videoName,
52
+ videoUrl: step.videoUrl,
53
+ posterUrl: step.posterUrl,
54
+ products: step.products.flatMap(({ id, variantIds }) => {
55
+ const product = id ? products[id] : undefined;
56
+ if (!product)
57
+ return [];
58
+ const variant = product.variants?.find((candidate) => candidate.id === variantIds?.[0]);
59
+ const shownPrice = variant ?? product.variants?.[0];
60
+ return [
61
+ {
62
+ id: product.id,
63
+ variantId: variant?.id,
64
+ title: product.title,
65
+ imageUrl: product.imageUrl ?? undefined,
66
+ price: shownPrice?.price ?? undefined,
67
+ compareAtPrice: shownPrice?.compareAtPrice ?? undefined,
68
+ currencySymbol: product.currencySymbol ?? undefined,
69
+ },
70
+ ];
71
+ }),
72
+ }));
73
+ }
@@ -0,0 +1,111 @@
1
+ import { z } from 'zod';
2
+ export declare const BridgeActionSchema: z.ZodDiscriminatedUnion<"name", [z.ZodObject<{
3
+ id: z.ZodOptional<z.ZodString>;
4
+ type: z.ZodLiteral<"action">;
5
+ } & {
6
+ name: z.ZodLiteral<"product/open">;
7
+ data: z.ZodObject<{
8
+ productId: z.ZodEffects<z.ZodUnion<[z.ZodString, z.ZodNumber]>, string, string | number>;
9
+ variantId: z.ZodOptional<z.ZodEffects<z.ZodUnion<[z.ZodString, z.ZodNumber]>, string, string | number>>;
10
+ }, "strip", z.ZodTypeAny, {
11
+ productId: string;
12
+ variantId?: string | undefined;
13
+ }, {
14
+ productId: string | number;
15
+ variantId?: string | number | undefined;
16
+ }>;
17
+ }, "strip", z.ZodTypeAny, {
18
+ type: "action";
19
+ data: {
20
+ productId: string;
21
+ variantId?: string | undefined;
22
+ };
23
+ name: "product/open";
24
+ id?: string | undefined;
25
+ }, {
26
+ type: "action";
27
+ data: {
28
+ productId: string | number;
29
+ variantId?: string | number | undefined;
30
+ };
31
+ name: "product/open";
32
+ id?: string | undefined;
33
+ }>, z.ZodObject<{
34
+ id: z.ZodOptional<z.ZodString>;
35
+ type: z.ZodLiteral<"action">;
36
+ } & {
37
+ name: z.ZodLiteral<"cart/add">;
38
+ data: z.ZodObject<{
39
+ lineItems: z.ZodArray<z.ZodObject<{
40
+ variantId: z.ZodEffects<z.ZodUnion<[z.ZodString, z.ZodNumber]>, string, string | number>;
41
+ quantity: z.ZodNumber;
42
+ }, "strip", z.ZodTypeAny, {
43
+ variantId: string;
44
+ quantity: number;
45
+ }, {
46
+ variantId: string | number;
47
+ quantity: number;
48
+ }>, "many">;
49
+ }, "strip", z.ZodTypeAny, {
50
+ lineItems: {
51
+ variantId: string;
52
+ quantity: number;
53
+ }[];
54
+ }, {
55
+ lineItems: {
56
+ variantId: string | number;
57
+ quantity: number;
58
+ }[];
59
+ }>;
60
+ }, "strip", z.ZodTypeAny, {
61
+ type: "action";
62
+ data: {
63
+ lineItems: {
64
+ variantId: string;
65
+ quantity: number;
66
+ }[];
67
+ };
68
+ name: "cart/add";
69
+ id?: string | undefined;
70
+ }, {
71
+ type: "action";
72
+ data: {
73
+ lineItems: {
74
+ variantId: string | number;
75
+ quantity: number;
76
+ }[];
77
+ };
78
+ name: "cart/add";
79
+ id?: string | undefined;
80
+ }>, z.ZodObject<{
81
+ id: z.ZodOptional<z.ZodString>;
82
+ type: z.ZodLiteral<"action">;
83
+ } & {
84
+ name: z.ZodLiteral<"cart/open">;
85
+ }, "strip", z.ZodTypeAny, {
86
+ type: "action";
87
+ name: "cart/open";
88
+ id?: string | undefined;
89
+ }, {
90
+ type: "action";
91
+ name: "cart/open";
92
+ id?: string | undefined;
93
+ }>, z.ZodObject<{
94
+ id: z.ZodOptional<z.ZodString>;
95
+ type: z.ZodLiteral<"action">;
96
+ } & {
97
+ name: z.ZodLiteral<"go/back">;
98
+ }, "strip", z.ZodTypeAny, {
99
+ type: "action";
100
+ name: "go/back";
101
+ id?: string | undefined;
102
+ }, {
103
+ type: "action";
104
+ name: "go/back";
105
+ id?: string | undefined;
106
+ }>]>;
107
+ export type BridgeAction = z.infer<typeof BridgeActionSchema>;
108
+ export type BridgeActionName = BridgeAction['name'];
109
+ export declare function parseBridgeAction(message: string): BridgeAction | null;
110
+ export declare function appSessionScript(customerAccessToken: string | null): string;
111
+ export declare function respondScript(id: string, result: 'success' | 'error'): string;
package/lib/bridge.js ADDED
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ const SHOPIFY_GID = /^gid:\/\/shopify\/\w+\/(\d+)$/;
3
+ const ShopifyId = z.union([z.string(), z.number()]).transform((id) => `${id}`.replace(SHOPIFY_GID, '$1'));
4
+ const ActionBase = z.object({ id: z.string().optional(), type: z.literal('action') });
5
+ export const BridgeActionSchema = z.discriminatedUnion('name', [
6
+ ActionBase.extend({
7
+ name: z.literal('product/open'),
8
+ data: z.object({ productId: ShopifyId, variantId: ShopifyId.optional() }),
9
+ }),
10
+ ActionBase.extend({
11
+ name: z.literal('cart/add'),
12
+ data: z.object({ lineItems: z.array(z.object({ variantId: ShopifyId, quantity: z.number().int().positive() })) }),
13
+ }),
14
+ ActionBase.extend({ name: z.literal('cart/open') }),
15
+ ActionBase.extend({ name: z.literal('go/back') }),
16
+ ]);
17
+ export function parseBridgeAction(message) {
18
+ try {
19
+ return BridgeActionSchema.safeParse(JSON.parse(message)).data ?? null;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ export function appSessionScript(customerAccessToken) {
26
+ const payload = {
27
+ messageHandlerName: 'ReactNativeWebView',
28
+ variables: {
29
+ customer: customerAccessToken ? { customerSession: { customerAccessToken: { access_token: customerAccessToken } } } : null,
30
+ },
31
+ };
32
+ return `window.Tapcart && window.Tapcart.mobile.load(${JSON.stringify(payload)}); true;`;
33
+ }
34
+ export function respondScript(id, result) {
35
+ return `window.Tapcart && window.Tapcart.mobile.respond(${JSON.stringify(id)}, ${JSON.stringify(result)}); true;`;
36
+ }
@@ -0,0 +1,8 @@
1
+ export type TolstoyEnvironment = 'production' | 'dev';
2
+ type EnvironmentHosts = {
3
+ apiBase: string;
4
+ tryOnPage: string;
5
+ };
6
+ export declare const ENVIRONMENTS: Record<TolstoyEnvironment, EnvironmentHosts>;
7
+ export declare function toQuery(params: Record<string, string | undefined>): string;
8
+ export {};
package/lib/config.js ADDED
@@ -0,0 +1,15 @@
1
+ export const ENVIRONMENTS = {
2
+ production: {
3
+ apiBase: 'https://cf-apilb.gotolstoy.com',
4
+ tryOnPage: 'https://play.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
5
+ },
6
+ dev: {
7
+ apiBase: 'https://dev-cf-apilb.gotolstoy.com',
8
+ tryOnPage: 'https://play-dev.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
9
+ },
10
+ };
11
+ export function toQuery(params) {
12
+ return Object.entries(params)
13
+ .flatMap(([key, value]) => (value === undefined ? [] : [`${encodeURIComponent(key)}=${encodeURIComponent(value)}`]))
14
+ .join('&');
15
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { TolstoyProvider, useTolstoy } from './TolstoyProvider';
2
+ export type { TolstoyCartLine, TolstoyProviderProps } from './TolstoyProvider';
3
+ export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarousel';
4
+ export type { TolstoyVideoCarouselProps, TolstoyProductVideosProps } from './TolstoyVideoCarousel';
5
+ export { TolstoyFeed } from './TolstoyFeed';
6
+ export type { TolstoyFeedProps } from './TolstoyFeed';
7
+ export { TolstoyTryOn } from './TolstoyTryOn';
8
+ export type { TolstoyTryOnProps } from './TolstoyTryOn';
9
+ export { useTolstoyVideos } from './useTolstoyVideos';
10
+ export type { TolstoyVideosState } from './useTolstoyVideos';
11
+ export type { TolstoyProduct, TolstoyVideo } from './api';
12
+ export type { TolstoyEnvironment } from './config';
package/lib/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { TolstoyProvider, useTolstoy } from './TolstoyProvider';
2
+ export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarousel';
3
+ export { TolstoyFeed } from './TolstoyFeed';
4
+ export { TolstoyTryOn } from './TolstoyTryOn';
5
+ export { useTolstoyVideos } from './useTolstoyVideos';
@@ -0,0 +1,11 @@
1
+ import type { TolstoyVideo } from './api';
2
+ export type TolstoyVideosState = {
3
+ status: 'loading';
4
+ } | {
5
+ status: 'ready';
6
+ videos: TolstoyVideo[];
7
+ } | {
8
+ status: 'error';
9
+ error: Error;
10
+ };
11
+ export declare function useTolstoyVideos(publishId: string, productId?: string): TolstoyVideosState;
@@ -0,0 +1,16 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { getVideos } from './api';
3
+ import { useTolstoy } from './TolstoyProvider';
4
+ export function useTolstoyVideos(publishId, productId) {
5
+ const { appKey, appUrl, environment } = useTolstoy();
6
+ const [state, setState] = useState({ status: 'loading' });
7
+ useEffect(() => {
8
+ let current = true;
9
+ setState({ status: 'loading' });
10
+ getVideos({ appKey, appUrl, environment }, publishId, productId).then((videos) => current && setState({ status: 'ready', videos }), (error) => current && setState({ status: 'error', error }));
11
+ return () => {
12
+ current = false;
13
+ };
14
+ }, [appKey, appUrl, environment, publishId, productId]);
15
+ return state;
16
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@tolstoy-ai/react-native-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Tolstoy shoppable videos and virtual try-on for bare React Native apps",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/GoTolstoy/tolstoy-backend-cdk.git",
8
+ "directory": "packages/front/packages/react-native-sdk"
9
+ },
10
+ "type": "module",
11
+ "main": "lib/index.js",
12
+ "types": "lib/index.d.ts",
13
+ "files": [
14
+ "lib"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "scripts": {
20
+ "build": "rm -rf lib && tsc -p tsconfig.build.json",
21
+ "lint": "biome check --max-diagnostics=none .",
22
+ "typecheck:fast": "tsc --noEmit -p tsconfig.json"
23
+ },
24
+ "dependencies": {
25
+ "zod": "^3.25.67"
26
+ },
27
+ "peerDependencies": {
28
+ "react": ">=19.1.0",
29
+ "react-native": ">=0.81.0",
30
+ "react-native-video": ">=6.16.1",
31
+ "react-native-webview": ">=13.16.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/react": "19.2.3",
35
+ "react": "19.1.4",
36
+ "react-native": "0.81.6",
37
+ "react-native-video": "6.16.1",
38
+ "react-native-webview": "13.16.1",
39
+ "typescript": "npm:@typescript/typescript6@6.0.2"
40
+ }
41
+ }