@tiun/react-native-sdk 0.3.0 → 0.5.0-staging.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
@@ -48,6 +48,29 @@ snippet without reloading:
48
48
  >
49
49
  ```
50
50
 
51
+ ### Products
52
+
53
+ `useTiun()` exposes the same product methods as the web SDK. Each returns a
54
+ Promise that rejects with `{ code, message }` when the request fails (e.g.
55
+ `http_404` for an unknown product, or `timeout`). Calls made before the snippet
56
+ is ready wait for it; calls still waiting when the provider unmounts reject with
57
+ `destroyed`.
58
+
59
+ ```tsx
60
+ const { listProducts, getProduct, listProductAccess, checkProductAccess } = useTiun();
61
+
62
+ const products = await listProducts(); // Product[]
63
+ const detail = await getProduct('prod_monthly'); // name, pricingLine, …
64
+ const access = await listProductAccess(); // [] when logged out
65
+ const { hasAccess } = await checkProductAccess('prod_monthly');
66
+
67
+ // Repeatable product: check a specific purchase
68
+ await checkProductAccess('prod_ticket', { referenceId: 'order-1042' });
69
+ ```
70
+
71
+ `checkProductAccess` resolves to `{ hasAccess: false, access: null }` when the
72
+ user has no access or isn't logged in.
73
+
51
74
  ## Peer dependencies
52
75
 
53
76
  `react`, `react-native`, `react-native-webview`, `react-native-secure-sign`,
package/dist/index.d.ts CHANGED
@@ -9,6 +9,12 @@ export declare interface CheckoutOptions {
9
9
  * Specific product ID to checkout (optional, for future use)
10
10
  */
11
11
  productId?: string;
12
+ /**
13
+ * Your own identifier for this purchase (e.g. an order or booking ID).
14
+ * Required for repeatable products, which can be bought more than once —
15
+ * each purchase is tied to its reference ID.
16
+ */
17
+ referenceId?: string;
12
18
  }
13
19
 
14
20
  declare interface PaywallHideEvent {
@@ -29,6 +35,49 @@ declare interface PaywallShowEvent {
29
35
  isConnected: boolean;
30
36
  }
31
37
 
38
+ export declare interface Product {
39
+ productId: string;
40
+ name: string;
41
+ type: ProductType;
42
+ }
43
+
44
+ export declare interface ProductAccess {
45
+ productId: string;
46
+ /** Purchase reference for repeatable products; null for ordinary access. */
47
+ referenceId?: string | null;
48
+ type: ProductType;
49
+ /** ISO 8601 date-time. */
50
+ activatedAt: string;
51
+ /**
52
+ * When the access ends (ISO 8601 date-time). null while a subscription is
53
+ * active and renewing; set to the end of the paid period once it's cancelled.
54
+ */
55
+ expiresAt?: string | null;
56
+ }
57
+
58
+ export declare interface ProductAccessCheck {
59
+ hasAccess: boolean;
60
+ /** Access details when `hasAccess` is true; null otherwise. */
61
+ access?: ProductAccess | null;
62
+ }
63
+
64
+ export declare interface ProductAccessOptions {
65
+ /**
66
+ * Purchase reference for repeatable products (the `referenceId` passed to
67
+ * `checkout()`). Omit for ordinary product access.
68
+ */
69
+ referenceId?: string;
70
+ }
71
+
72
+ export declare interface ProductDetail extends Product {
73
+ /** Localized price summary, e.g. "€9.90 / month". */
74
+ pricingLine: string;
75
+ /** Optional localized explanation shown under the price. */
76
+ explanationLine?: string | null;
77
+ }
78
+
79
+ export declare type ProductType = 'Subscription' | 'OneTime';
80
+
32
81
  export declare type TiunConfig = {
33
82
  /** tiun snippet id (goes in the asset route). */
34
83
  snippetId: string;
@@ -66,8 +115,22 @@ export declare type TiunContextValue = {
66
115
  logout: () => void;
67
116
  checkout: (options?: CheckoutOptions) => void;
68
117
  getUserVerificationToken: () => Promise<string | null>;
118
+ /** List the products available on this snippet. */
119
+ listProducts: () => Promise<Product[]>;
120
+ /** Get a product's details and localized pricing; rejects if it doesn't exist. */
121
+ getProduct: (productId: string) => Promise<ProductDetail>;
122
+ /** List the user's active product access ([] when logged out). */
123
+ listProductAccess: () => Promise<ProductAccess[]>;
124
+ /** Check access to a product ({ hasAccess: false, access: null } when logged out). */
125
+ checkProductAccess: (productId: string, options?: ProductAccessOptions) => Promise<ProductAccessCheck>;
69
126
  };
70
127
 
128
+ export declare interface TiunError {
129
+ code: string;
130
+ message: string;
131
+ details?: unknown;
132
+ }
133
+
71
134
  /** Events surfaced via `useTiunEvent` (names mirror the web SDK). */
72
135
  export declare type TiunEventName = 'ready' | 'userChange' | 'login' | 'logout' | 'paywallShow' | 'paywallHide' | 'error';
73
136
 
@@ -101,6 +164,8 @@ export declare type TiunUser = UserInfo;
101
164
  declare interface UserInfo {
102
165
  userId: string;
103
166
  email: string;
167
+ /** Whether the user has opted in to the newsletter. */
168
+ hasNewsletterOptIn: boolean;
104
169
  productAccess: string[];
105
170
  }
106
171
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var we=Object.defineProperty;var ve=(t,r,a)=>r in t?we(t,r,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[r]=a;var fe=(t,r,a)=>(ve(t,typeof r!="symbol"?r+"":r,a),a);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react"),b=require("react-native"),Se=require("react-native-webview"),M=require("react-native-inappbrowser-nitro"),te=require("react-native-secure-sign"),_e=require("react-native-keychain");function me(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const u=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(r,a,u.get?u:{enumerable:!0,get:()=>t[a]})}}return r.default=t,Object.freeze(r)}const ne=me(_e);var se={exports:{}},X={};/**
1
+ "use strict";var Se=Object.defineProperty;var we=(r,n,i)=>n in r?Se(r,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[n]=i;var fe=(r,n,i)=>(we(r,typeof n!="symbol"?n+"":n,i),i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react"),v=require("react-native"),ve=require("react-native-webview"),Q=require("react-native-inappbrowser-nitro"),ne=require("react-native-secure-sign"),Re=require("react-native-keychain");function me(r){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const i in r)if(i!=="default"){const l=Object.getOwnPropertyDescriptor(r,i);Object.defineProperty(n,i,l.get?l:{enumerable:!0,get:()=>r[i]})}}return n.default=r,Object.freeze(n)}const ae=me(Re);var se={exports:{}},Z={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var pe;function Re(){if(pe)return X;pe=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function a(u,o,d){var f=null;if(d!==void 0&&(f=""+d),o.key!==void 0&&(f=""+o.key),"key"in o){d={};for(var T in o)T!=="key"&&(d[T]=o[T])}else d=o;return o=d.ref,{$$typeof:t,type:u,key:f,ref:o!==void 0?o:null,props:d}}return X.Fragment=r,X.jsx=a,X.jsxs=a,X}var Q={};/**
9
+ */var pe;function ke(){if(pe)return Z;pe=1;var r=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function i(l,o,E){var S=null;if(E!==void 0&&(S=""+E),o.key!==void 0&&(S=""+o.key),"key"in o){E={};for(var T in o)T!=="key"&&(E[T]=o[T])}else E=o;return o=E.ref,{$$typeof:r,type:l,key:S,ref:o!==void 0?o:null,props:E}}return Z.Fragment=n,Z.jsx=i,Z.jsxs=i,Z}var ee={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,9 +14,9 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var he;function ge(){return he||(he=1,process.env.NODE_ENV!=="production"&&function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===m?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case y:return"Fragment";case q:return"Profiler";case N:return"StrictMode";case G:return"Suspense";case s:return"SuspenseList";case P:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case z:return"Portal";case B:return(e.displayName||"Context")+".Provider";case U:return(e._context.displayName||"Context")+".Consumer";case D:var c=e.render;return e=e.displayName,e||(e=c.displayName||c.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case _:return c=e.displayName||null,c!==null?c:t(e.type)||"Memo";case w:c=e._payload,e=e._init;try{return t(e(c))}catch{}}return null}function r(e){return""+e}function a(e){try{r(e);var c=!1}catch{c=!0}if(c){c=console;var p=c.error,v=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return p.call(c,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",v),r(e)}}function u(e){if(e===y)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===w)return"<...>";try{var c=t(e);return c?"<"+c+">":"<...>"}catch{return"<...>"}}function o(){var e=i.A;return e===null?null:e.getOwner()}function d(){return Error("react-stack-top-frame")}function f(e){if(n.call(e,"key")){var c=Object.getOwnPropertyDescriptor(e,"key").get;if(c&&c.isReactWarning)return!1}return e.key!==void 0}function T(e,c){function p(){h||(h=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",c))}p.isReactWarning=!0,Object.defineProperty(e,"key",{get:p,configurable:!0})}function V(){var e=t(this.type);return C[e]||(C[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function A(e,c,p,v,W,x,oe,ie){return p=x.ref,e={$$typeof:j,type:e,key:c,props:x,_owner:W},(p!==void 0?p:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:V}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:oe}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:ie}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function L(e,c,p,v,W,x,oe,ie){var S=c.children;if(S!==void 0)if(v)if(E(S)){for(v=0;v<S.length;v++)I(S[v]);Object.freeze&&Object.freeze(S)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else I(S);if(n.call(c,"key")){S=t(e);var H=Object.keys(c).filter(function(ye){return ye!=="key"});v=0<H.length?"{key: someKey, "+H.join(": ..., ")+": ...}":"{key: someKey}",$[S+v]||(H=0<H.length?"{"+H.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
17
+ */var Te;function ge(){return Te||(Te=1,process.env.NODE_ENV!=="production"&&function(){function r(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===B?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case L:return"Fragment";case D:return"Profiler";case y:return"StrictMode";case q:return"Suspense";case g:return"SuspenseList";case H:return"Activity"}if(typeof t=="object")switch(typeof t.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case W:return"Portal";case V:return(t.displayName||"Context")+".Provider";case x:return(t._context.displayName||"Context")+".Consumer";case Y:var c=t.render;return t=t.displayName,t||(t=c.displayName||c.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case G:return c=t.displayName||null,c!==null?c:r(t.type)||"Memo";case F:c=t._payload,t=t._init;try{return r(t(c))}catch{}}return null}function n(t){return""+t}function i(t){try{n(t);var c=!1}catch{c=!0}if(c){c=console;var h=c.error,w=typeof Symbol=="function"&&Symbol.toStringTag&&t[Symbol.toStringTag]||t.constructor.name||"Object";return h.call(c,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",w),n(t)}}function l(t){if(t===L)return"<>";if(typeof t=="object"&&t!==null&&t.$$typeof===F)return"<...>";try{var c=r(t);return c?"<"+c+">":"<...>"}catch{return"<...>"}}function o(){var t=a.A;return t===null?null:t.getOwner()}function E(){return Error("react-stack-top-frame")}function S(t){if(e.call(t,"key")){var c=Object.getOwnPropertyDescriptor(t,"key").get;if(c&&c.isReactWarning)return!1}return t.key!==void 0}function T(t,c){function h(){d||(d=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",c))}h.isReactWarning=!0,Object.defineProperty(t,"key",{get:h,configurable:!0})}function U(){var t=r(this.type);return b[t]||(b[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),t=this.props.ref,t!==void 0?t:null}function j(t,c,h,w,P,C,K,M){return h=C.ref,t={$$typeof:$,type:t,key:c,props:C,_owner:P},(h!==void 0?h:null)!==null?Object.defineProperty(t,"ref",{enumerable:!1,get:U}):Object.defineProperty(t,"ref",{enumerable:!1,value:null}),t._store={},Object.defineProperty(t._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(t,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(t,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:K}),Object.defineProperty(t,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.freeze&&(Object.freeze(t.props),Object.freeze(t)),t}function I(t,c,h,w,P,C,K,M){var p=c.children;if(p!==void 0)if(w)if(u(p)){for(w=0;w<p.length;w++)N(p[w]);Object.freeze&&Object.freeze(p)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else N(p);if(e.call(c,"key")){p=r(t);var _=Object.keys(c).filter(function(_e){return _e!=="key"});w=0<_.length?"{key: someKey, "+_.join(": ..., ")+": ...}":"{key: someKey}",X[p+w]||(_=0<_.length?"{"+_.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
18
  let props = %s;
19
19
  <%s {...props} />
20
20
  React keys must be passed directly to JSX without using spread:
21
21
  let props = %s;
22
- <%s key={someKey} {...props} />`,v,S,H,S),$[S+v]=!0)}if(S=null,p!==void 0&&(a(p),S=""+p),f(c)&&(a(c.key),S=""+c.key),"key"in c){p={};for(var ae in c)ae!=="key"&&(p[ae]=c[ae])}else p=c;return S&&T(p,typeof e=="function"?e.displayName||e.name||"Unknown":e),A(e,S,x,W,o(),p,oe,ie)}function I(e){typeof e=="object"&&e!==null&&e.$$typeof===j&&e._store&&(e._store.validated=1)}var k=l,j=Symbol.for("react.transitional.element"),z=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),q=Symbol.for("react.profiler"),U=Symbol.for("react.consumer"),B=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),G=Symbol.for("react.suspense"),s=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),w=Symbol.for("react.lazy"),P=Symbol.for("react.activity"),m=Symbol.for("react.client.reference"),i=k.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,n=Object.prototype.hasOwnProperty,E=Array.isArray,R=console.createTask?console.createTask:function(){return null};k={"react-stack-bottom-frame":function(e){return e()}};var h,C={},O=k["react-stack-bottom-frame"].bind(k,d)(),Y=R(u(d)),$={};Q.Fragment=y,Q.jsx=function(e,c,p,v,W){var x=1e4>i.recentlyCreatedOwnerStacks++;return L(e,c,p,!1,v,W,x?Error("react-stack-top-frame"):O,x?R(u(e)):Y)},Q.jsxs=function(e,c,p,v,W){var x=1e4>i.recentlyCreatedOwnerStacks++;return L(e,c,p,!0,v,W,x?Error("react-stack-top-frame"):O,x?R(u(e)):Y)}}()),Q}process.env.NODE_ENV==="production"?se.exports=Re():se.exports=ge();var g=se.exports;const ke={errorPillText:"Technical Error",errorNotificationTitle:"Technical error",errorNotificationSubtitle:"Please reload the page or contact our support.",errorTitle:"Technical error",errorTextBeforeEmail:"Try reloading the page. If the error persists, please contact ",errorTextAfterEmail:" and we’ll help you right away.",connectionErrorTitle:"No connection",connectionErrorText:"We couldn’t reach tiun. Check your internet connection and try again.",connectionErrorCta:"Try again"},Ne={errorPillText:"Erreur Technique",errorNotificationTitle:"Erreur technique",errorNotificationSubtitle:"Veuillez recharger la page ou contacter notre support.",errorTitle:"Erreur technique",errorTextBeforeEmail:"Veuillez recharger la page. Si l’erreur persiste, contactez ",errorTextAfterEmail:" et nous vous aiderons immédiatement.",connectionErrorTitle:"Pas de connexion",connectionErrorText:"Impossible de joindre tiun. Vérifiez votre connexion Internet et réessayez.",connectionErrorCta:"Réessayer"},Ce={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte lade die Seite neu, oder kontaktiere unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte lade die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktiere ",errorTextAfterEmail:" und wir helfen Dir sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfe deine Internetverbindung und versuche es erneut.",connectionErrorCta:"Erneut versuchen"},Oe={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte laden Sie die Seite neu, oder kontaktieren Sie unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte laden Sie die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktieren Sie ",errorTextAfterEmail:" und wir helfen Ihnen sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",connectionErrorCta:"Erneut versuchen"};function Ie(t,r="informal"){switch((t??"en").trim().toLowerCase()){case"de":return r==="formal"?Oe:Ce;case"fr":return Ne;default:return ke}}const K={start:"TIUN_START",checkout:"TIUN_CHECKOUT",updateContent:"TIUN_UPDATE_CONTENT",login:"TIUN_LOGIN",logout:"TIUN_LOGOUT",getVerificationToken:"TIUN_GET_VERIFICATION_TOKEN",setAppearance:"TIUN_SET_APPEARANCE",overlayChange:"TIUN_OVERLAY_CHANGE",popPubKeyRequest:"TIUN_POP_PUBKEY_REQUEST",popSignRequest:"TIUN_POP_SIGN_REQUEST",tokenGet:"TIUN_TOKEN_GET",tokenPersist:"TIUN_TOKEN_PERSIST",nativeReset:"TIUN_NATIVE_RESET",popPubKey:"TIUN_POP_PUBKEY",restoreToken:"TIUN_RESTORE_TOKEN",popSignResult:"TIUN_POP_SIGN_RESULT",resolveCheckout:"TIUN_RESOLVE_CHECKOUT"},Pe="__TIUN_NATIVE_CRYPTO__",xe="https://api.tiun.live";function ue(t){return(t.host??xe).replace(/\/$/,"")}function re(t){return`app.tiun.pop.${t.snippetId||"default"}`}function Z(t){return`app.tiun.token.${t.snippetId||"default"}`}function Ae(t){return`${`${ue(t)}/live_api/v2/snippets/${encodeURIComponent(t.snippetId)}/webview_return`}?to=${encodeURIComponent(t.returnUrl)}`}function je(t){const r={language:t.language??"en"},a=Object.entries(r).map(([o,d])=>`${encodeURIComponent(o)}=${encodeURIComponent(d)}`).join("&"),u=`${ue(t)}/live_api/v2/snippets/${encodeURIComponent(t.snippetId)}/webview_host`;return a?`${u}?${a}`:u}function Te(t){const r=t.indexOf("?");if(!(r<0))for(const a of t.slice(r+1).split("&")){const u=a.indexOf("=");if((u<0?a:a.slice(0,u))==="status"){const d=u<0?"":a.slice(u+1);return d?decodeURIComponent(d):void 0}}}function Ue(t,r){const a=t.returnUrl.split("?")[0];return r.startsWith(a)}const le="1005";function de(t){return t==null?void 0:t.code}async function $e(t){try{return await te.getPublicKey(t)}catch(r){if(de(r)===le)return te.generate(t,{requireUserAuthentication:!1});throw r}}async function Fe(t){try{return await te.getPublicKey(t)}catch(r){if(de(r)===le)return null;throw r}}function Le(t,r){return te.sign(t,r)}async function We(t){try{await te.removeKey(t)}catch(r){if(de(r)!==le)throw r}}const Ve="tiun_auth_token";async function qe(t){const r=await ne.getGenericPassword({service:t});return r?r.password:null}async function Ye(t,r){await ne.setGenericPassword(Ve,r,{service:t,accessible:ne.ACCESSIBLE.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY})}async function ce(t){await ne.resetGenericPassword({service:t})}function Be(t){const r=Ie(t);return{title:r.connectionErrorTitle,text:r.connectionErrorText,cta:r.connectionErrorCta}}function De({language:t,dark:r,onRetry:a}){const u=Be(t),o=r?Ge:null;return g.jsxs(b.View,{style:[F.container,o==null?void 0:o.container],children:[g.jsxs(b.View,{style:F.content,children:[g.jsx(b.Text,{style:[F.title,o==null?void 0:o.title],children:u.title}),g.jsx(b.View,{style:[F.iconBadge,o==null?void 0:o.iconBadge],children:g.jsx(b.Text,{style:[F.iconGlyph,o==null?void 0:o.iconGlyph],children:"!"})}),g.jsx(b.Text,{style:[F.text,o==null?void 0:o.text],children:u.text})]}),g.jsx(b.Pressable,{accessibilityRole:"button",onPress:a,style:({pressed:d})=>[F.button,o==null?void 0:o.button,d&&F.buttonPressed],children:g.jsx(b.Text,{style:[F.buttonText,o==null?void 0:o.buttonText],children:u.cta})})]})}const F=b.StyleSheet.create({container:{...b.StyleSheet.absoluteFillObject,backgroundColor:"#fff",padding:24,justifyContent:"space-between"},content:{flex:1,alignItems:"center",justifyContent:"center",gap:24},title:{fontSize:20,fontWeight:"600",color:"#000",textAlign:"center"},iconBadge:{width:40,height:40,borderRadius:20,backgroundColor:"#FCE7F3",alignItems:"center",justifyContent:"center"},iconGlyph:{color:"#DB2777",fontSize:22,fontWeight:"700",lineHeight:26},text:{fontSize:16,fontWeight:"500",color:"#4B5563",textAlign:"center"},button:{backgroundColor:"#000",borderRadius:999,minHeight:56,alignItems:"center",justifyContent:"center",alignSelf:"stretch"},buttonPressed:{opacity:.9},buttonText:{color:"#fff",fontSize:16,fontWeight:"500"}}),Ge=b.StyleSheet.create({container:{backgroundColor:"#0a0a0a"},title:{color:"#fafafa"},iconBadge:{backgroundColor:"#500724"},iconGlyph:{color:"#F472B6"},text:{color:"#A1A1AA"},button:{backgroundColor:"#fafafa"},buttonText:{color:"#000"}}),He=Se.WebView;function J(t){return`try{window.tiunHost&&${t};}catch(e){}; true;`}const Ke=l.forwardRef(function({config:r,onEvent:a},u){const o=!!r.debug,d=b.useColorScheme(),f=r.appearance==="dark"||r.appearance==="auto"&&d==="dark"?"dark":"light",T=l.useRef(null),[V,A]=l.useState(!1),[L,I]=l.useState(!1),k=l.useRef(!1),j=l.useRef(!1),z=()=>{var i;I(!1),(i=T.current)==null||i.reload()};l.useEffect(()=>{if(!L)return;const i=b.AppState.addEventListener("change",n=>{var E;n==="active"&&(I(!1),(E=T.current)==null||E.reload())});return()=>i.remove()},[L]);const y=`window.${Pe} = true;window.__TIUN_CONFIG__ = Object.assign({}, window.__TIUN_CONFIG__, { returnUrl: ${JSON.stringify(Ae(r))}, appearance: ${JSON.stringify(f)} });true;`,N=(i,...n)=>{var E;return(E=T.current)==null?void 0:E.injectJavaScript(J(`window.tiunHost.${i}(${n.map(R=>JSON.stringify(R)??"null").join(",")})`))},q=l.useRef(f);l.useEffect(()=>{f!==q.current&&(q.current=f,N("setAppearance",f))},[f]);const U=i=>{var n;j.current||(j.current=!0,M.close().catch(()=>{}),M.closeAuth().catch(()=>{}),A(!0),(n=T.current)==null||n.injectJavaScript(J(`window.tiunHost.resolveCheckout(${i?JSON.stringify(i):""})`)))},B=i=>{var n,E,R;switch(i.type){case K.popPubKeyRequest:return $e(re(r)).then(h=>N("popPubKey",h)).catch(h=>{o&&console.warn("[tiun] ensurePopKey failed:",h),N("popPubKey",null)}),!0;case K.tokenGet:return(async()=>{try{const h=await qe(Z(r));if(h&&!await Fe(re(r))){await ce(Z(r)),N("restoreToken",null);return}N("restoreToken",h)}catch{N("restoreToken",null)}})(),!0;case K.popSignRequest:{const h=(n=i.payload)==null?void 0:n.requestId,C=(E=i.payload)==null?void 0:E.information;return Le(re(r),C).then(O=>N("popSignResult",h,O,null)).catch(O=>{const Y=(O==null?void 0:O.code)??"sign_failed";o&&console.warn("[tiun] popSign failed:",O),N("popSignResult",h,null,String(Y))}),!0}case K.tokenPersist:{const h=((R=i.payload)==null?void 0:R.token)??null;return(h?Ye(Z(r),h):ce(Z(r))).catch(C=>o&&console.warn("[tiun] token persist failed:",C)),!0}case K.nativeReset:return Promise.allSettled([We(re(r)),ce(Z(r))]),!0;default:return!1}};l.useImperativeHandle(u,()=>({login:()=>{var i;A(!0),(i=T.current)==null||i.injectJavaScript(J("window.tiunHost.login()"))},checkout:i=>{var n;A(!0),k.current=!0,j.current=!1,(n=T.current)==null||n.injectJavaScript(J(`window.tiunHost.checkout(${i?JSON.stringify(i):""})`))},logout:()=>{var i;return(i=T.current)==null?void 0:i.injectJavaScript(J("window.tiunHost.logout()"))},getVerificationToken:i=>{var n;return(n=T.current)==null?void 0:n.injectJavaScript(J(`window.tiunHost.getVerificationToken(${i?JSON.stringify(i):""})`))},resolveCheckout:U,reload:()=>{var i;return(i=T.current)==null?void 0:i.reload()}}),[]);const D=i=>{var E,R,h;let n=null;try{n=JSON.parse(i.nativeEvent.data)}catch{o&&console.warn("[tiun] non-JSON bridge message:",i.nativeEvent.data);return}if(!(!n||typeof n.type!="string")){if(n.type==="console"){o&&console.log("[tiun webview]",(E=n.payload)==null?void 0:E.level,(R=n.payload)==null?void 0:R.message);return}if((n.type==="cryptoCheck"||n.type==="hostBridgeReady")&&I(!1),o&&console.log("[tiun] <-",n.type,n.payload),!B(n)){if(n.type===K.overlayChange){const C=!!((h=n.payload)!=null&&h.overlay);A(C),C||(k.current=!1)}a(n)}}},G=i=>{if(k.current=!1,b.Platform.OS==="ios"){M.openAuth(i,r.returnUrl).then(n=>{n.type==="success"&&n.url?U(Te(n.url)):n.type==="cancel"&&U("cancelled")}).catch(n=>o&&console.warn("[tiun] openAuth error:",n));return}M.open(i,{showTitle:!1,enableUrlBarHiding:!1,enableDefaultShare:!1,forceCloseOnRedirection:!1}).then(n=>{n.type==="cancel"&&U("cancelled")}).catch(n=>o&&console.warn("[tiun] in-app browser open error:",n))},s=i=>{M.open(i,{modalPresentationStyle:"fullScreen",modalEnabled:!0,animated:!0,enableBarCollapsing:!0}).catch(n=>o&&console.warn("[tiun] in-app browser open failed:",n))},_=i=>{var E;const n=(E=i.nativeEvent)==null?void 0:E.targetUrl;n&&(k.current?G(n):s(n))},w=i=>{const n=i.url;return n.startsWith(ue(r))||n.startsWith("about:")||n.startsWith("data:")||n==="about:blank"?!0:n.startsWith("http://")||n.startsWith("https://")?(k.current&&i.isTopFrame!==!1?G(n):s(n),!1):!0},{width:P,height:m}=b.useWindowDimensions();return g.jsxs(b.View,{pointerEvents:V?"auto":"none",style:[ee.container,{width:P,height:m},V?ee.visible:ee.hidden],children:[g.jsx(He,{ref:T,source:{uri:je(r)},originWhitelist:["*"],onMessage:D,onShouldStartLoadWithRequest:w,onOpenWindow:_,injectedJavaScriptBeforeContentLoaded:y,javaScriptEnabled:!0,domStorageEnabled:!0,style:ee.webview,containerStyle:ee.webview,onError:i=>{o&&console.warn("[tiun] webview load error:",i.nativeEvent),I(!0)},onHttpError:i=>{o&&console.warn("[tiun] webview http error:",i.nativeEvent),I(!0)}}),L&&V?g.jsx(De,{language:r.language,dark:f==="dark",onRetry:z}):null]})}),ee=b.StyleSheet.create({container:{position:"absolute",top:0,left:0,zIndex:9999,elevation:9999},webview:{flex:1,backgroundColor:"transparent"},visible:{opacity:1},hidden:{opacity:0}});class Je{constructor(){fe(this,"listeners",new Map)}on(r,a){let u=this.listeners.get(r);return u||(u=new Set,this.listeners.set(r,u)),u.add(a),()=>{var o;(o=this.listeners.get(r))==null||o.delete(a)}}emit(r,a){const u=this.listeners.get(r);if(u)for(const o of u)try{o(a)}catch{}}}const Ee=l.createContext(null),be=l.createContext(null);function ze({config:t,children:r}){const a=l.useRef(null),u=l.useRef(!1),o=l.useRef([]),d=l.useRef(new Map),f=l.useRef(new Je).current,[T,V]=l.useState(!1),[A,L]=l.useState(null),[I,k]=l.useState(!1),[j,z]=l.useState(null),y=l.useCallback(s=>{u.current?s():o.current.push(s)},[]),N=l.useCallback(s=>{var _,w,P,m,i,n,E,R,h,C,O,Y;switch(s.type){case"cryptoCheck":z(!!((_=s.payload)!=null&&_.subtle&&((w=s.payload)!=null&&w.secureContext)));break;case"TIUN_SNIPPET_INITIALIZED":{u.current=!0,k(!0),f.emit("ready",void 0);const $=o.current;o.current=[],$.forEach(e=>e());break}case"TIUN_USER_CHANGE":{const $=!!((P=s.payload)!=null&&P.isAuthenticated),e=((m=s.payload)==null?void 0:m.user)??null;V($),L(e),f.emit("userChange",{isAuthenticated:$,user:e}),((i=s.payload)==null?void 0:i.userEvent)==="login"&&f.emit("login",{user:e}),((n=s.payload)==null?void 0:n.userEvent)==="logout"&&f.emit("logout",void 0);break}case"TIUN_VERIFICATION_TOKEN":{const $=((E=s.payload)==null?void 0:E.token)??null,e=(R=s.payload)==null?void 0:R.requestId;e&&d.current.has(e)&&(d.current.get(e)($),d.current.delete(e));break}case"TIUN_SHOW_PAYWALL":f.emit("paywallShow",{isConnected:!!((h=s.payload)!=null&&h.isConnected)});break;case"TIUN_HIDE_PAYWALL":f.emit("paywallHide",{sessionId:((C=s.payload)==null?void 0:C.sessionId)??"",isConnected:((O=s.payload)==null?void 0:O.isConnected)??!0});break;case"TIUN_ERROR":f.emit("error",((Y=s.payload)==null?void 0:Y.error)??s.payload??{});break}},[f]);l.useEffect(()=>{const s=w=>{if(!w||!Ue(t,w))return;const P=Te(w);y(()=>{var m;return(m=a.current)==null?void 0:m.resolveCheckout(P)})},_=b.Linking.addEventListener("url",({url:w})=>s(w));return b.Linking.getInitialURL().then(s).catch(()=>{}),()=>_.remove()},[t,y]);const q=l.useCallback(()=>y(()=>{var s;return(s=a.current)==null?void 0:s.login()}),[y]),U=l.useCallback(()=>y(()=>{var s;return(s=a.current)==null?void 0:s.logout()}),[y]),B=l.useCallback(s=>y(()=>{var _;return(_=a.current)==null?void 0:_.checkout(s==null?void 0:s.productId)}),[y]),D=l.useCallback(()=>new Promise(s=>{const _=`vt_${Math.random().toString(36).slice(2)}_${Date.now()}`;let w=!1;const P=m=>{w||(w=!0,d.current.delete(_),s(m))};d.current.set(_,P),y(()=>{var m;return(m=a.current)==null?void 0:m.getVerificationToken(_)}),setTimeout(()=>P(null),5e3)}),[y]),G=l.useMemo(()=>({isAuthenticated:T,user:A,ready:I,cryptoOk:j,login:q,logout:U,checkout:B,getUserVerificationToken:D}),[T,A,I,j,q,U,B,D]);return g.jsx(Ee.Provider,{value:G,children:g.jsxs(be.Provider,{value:f,children:[r,g.jsx(Ke,{ref:a,config:t,onEvent:N})]})})}function Me(){const t=l.useContext(Ee);if(!t)throw new Error("useTiun must be used within a <TiunProvider>");return t}function Xe(t,r){const a=l.useContext(be),u=l.useRef(r);u.current=r,l.useEffect(()=>{if(!a)throw new Error("useTiunEvent must be used within a <TiunProvider>");return a.on(t,o=>u.current(o))},[a,t])}exports.TiunProvider=ze;exports.useTiun=Me;exports.useTiunEvent=Xe;
22
+ <%s key={someKey} {...props} />`,w,p,_,p),X[p+w]=!0)}if(p=null,h!==void 0&&(i(h),p=""+h),S(c)&&(i(c.key),p=""+c.key),"key"in c){h={};for(var ie in c)ie!=="key"&&(h[ie]=c[ie])}else h=c;return p&&T(h,typeof t=="function"?t.displayName||t.name||"Unknown":t),j(t,p,C,P,o(),h,K,M)}function N(t){typeof t=="object"&&t!==null&&t.$$typeof===$&&t._store&&(t._store.validated=1)}var k=s,$=Symbol.for("react.transitional.element"),W=Symbol.for("react.portal"),L=Symbol.for("react.fragment"),y=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),x=Symbol.for("react.consumer"),V=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),q=Symbol.for("react.suspense"),g=Symbol.for("react.suspense_list"),G=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),B=Symbol.for("react.client.reference"),a=k.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,e=Object.prototype.hasOwnProperty,u=Array.isArray,f=console.createTask?console.createTask:function(){return null};k={"react-stack-bottom-frame":function(t){return t()}};var d,b={},R=k["react-stack-bottom-frame"].bind(k,E)(),O=f(l(E)),X={};ee.Fragment=L,ee.jsx=function(t,c,h,w,P){var C=1e4>a.recentlyCreatedOwnerStacks++;return I(t,c,h,!1,w,P,C?Error("react-stack-top-frame"):R,C?f(l(t)):O)},ee.jsxs=function(t,c,h,w,P){var C=1e4>a.recentlyCreatedOwnerStacks++;return I(t,c,h,!0,w,P,C?Error("react-stack-top-frame"):R,C?f(l(t)):O)}}()),ee}process.env.NODE_ENV==="production"?se.exports=ke():se.exports=ge();var m=se.exports;const Ce={errorPillText:"Technical Error",errorNotificationTitle:"Technical error",errorNotificationSubtitle:"Please reload the page or contact our support.",errorTitle:"Technical error",errorTextBeforeEmail:"Try reloading the page. If the error persists, please contact ",errorTextAfterEmail:" and we’ll help you right away.",connectionErrorTitle:"No connection",connectionErrorText:"We couldn’t reach tiun. Check your internet connection and try again.",connectionErrorCta:"Try again"},Pe={errorPillText:"Erreur Technique",errorNotificationTitle:"Erreur technique",errorNotificationSubtitle:"Veuillez recharger la page ou contacter notre support.",errorTitle:"Erreur technique",errorTextBeforeEmail:"Veuillez recharger la page. Si l’erreur persiste, contactez ",errorTextAfterEmail:" et nous vous aiderons immédiatement.",connectionErrorTitle:"Pas de connexion",connectionErrorText:"Impossible de joindre tiun. Vérifiez votre connexion Internet et réessayez.",connectionErrorCta:"Réessayer"},Ne={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte lade die Seite neu, oder kontaktiere unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte lade die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktiere ",errorTextAfterEmail:" und wir helfen Dir sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfe deine Internetverbindung und versuche es erneut.",connectionErrorCta:"Erneut versuchen"},Oe={errorPillText:"Technischer Fehler",errorNotificationTitle:"Technischer Fehler",errorNotificationSubtitle:"Bitte laden Sie die Seite neu, oder kontaktieren Sie unseren Support.",errorTitle:"Technischer Fehler",errorTextBeforeEmail:"Bitte laden Sie die Seite neu. Sollte der Fehler weiterhin auftreten, kontaktieren Sie ",errorTextAfterEmail:" und wir helfen Ihnen sofort weiter.",connectionErrorTitle:"Keine Verbindung",connectionErrorText:"tiun konnte nicht erreicht werden. Überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",connectionErrorCta:"Erneut versuchen"};function Ie(r,n="informal"){switch((r??"en").trim().toLowerCase()){case"de":return n==="formal"?Oe:Ne;case"fr":return Pe;default:return Ce}}const J={start:"TIUN_START",checkout:"TIUN_CHECKOUT",updateContent:"TIUN_UPDATE_CONTENT",login:"TIUN_LOGIN",logout:"TIUN_LOGOUT",getVerificationToken:"TIUN_GET_VERIFICATION_TOKEN",setAppearance:"TIUN_SET_APPEARANCE",listProducts:"TIUN_LIST_PRODUCTS",getProduct:"TIUN_GET_PRODUCT",listProductAccess:"TIUN_LIST_PRODUCT_ACCESS",checkProductAccess:"TIUN_CHECK_PRODUCT_ACCESS",productResult:"TIUN_PRODUCT_RESULT",overlayChange:"TIUN_OVERLAY_CHANGE",popPubKeyRequest:"TIUN_POP_PUBKEY_REQUEST",popSignRequest:"TIUN_POP_SIGN_REQUEST",tokenGet:"TIUN_TOKEN_GET",tokenPersist:"TIUN_TOKEN_PERSIST",nativeReset:"TIUN_NATIVE_RESET",popPubKey:"TIUN_POP_PUBKEY",restoreToken:"TIUN_RESTORE_TOKEN",popSignResult:"TIUN_POP_SIGN_RESULT",resolveCheckout:"TIUN_RESOLVE_CHECKOUT"},xe="__TIUN_NATIVE_CRYPTO__",Ae="https://api.tiun.live";function ue(r){return(r.host??Ae).replace(/\/$/,"")}function oe(r){return`app.tiun.pop.${r.snippetId||"default"}`}function te(r){return`app.tiun.token.${r.snippetId||"default"}`}function Ue(r){return`${`${ue(r)}/live_api/v2/snippets/${encodeURIComponent(r.snippetId)}/webview_return`}?to=${encodeURIComponent(r.returnUrl)}`}function je(r){const n={language:r.language??"en"},i=Object.entries(n).map(([o,E])=>`${encodeURIComponent(o)}=${encodeURIComponent(E)}`).join("&"),l=`${ue(r)}/live_api/v2/snippets/${encodeURIComponent(r.snippetId)}/webview_host`;return i?`${l}?${i}`:l}function Ee(r){const n=r.indexOf("?");if(!(n<0))for(const i of r.slice(n+1).split("&")){const l=i.indexOf("=");if((l<0?i:i.slice(0,l))==="status"){const E=l<0?"":i.slice(l+1);return E?decodeURIComponent(E):void 0}}}function $e(r,n){const i=r.returnUrl.split("?")[0];return n.startsWith(i)}const le="1005";function de(r){return r==null?void 0:r.code}async function Le(r){try{return await ne.getPublicKey(r)}catch(n){if(de(n)===le)return ne.generate(r,{requireUserAuthentication:!1});throw n}}async function qe(r){try{return await ne.getPublicKey(r)}catch(n){if(de(n)===le)return null;throw n}}function Fe(r,n){return ne.sign(r,n)}async function We(r){try{await ne.removeKey(r)}catch(n){if(de(n)!==le)throw n}}const De="tiun_auth_token";async function Ve(r){const n=await ae.getGenericPassword({service:r});return n?n.password:null}async function Ye(r,n){await ae.setGenericPassword(De,n,{service:r,accessible:ae.ACCESSIBLE.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY})}async function ce(r){await ae.resetGenericPassword({service:r})}function Ge(r){const n=Ie(r);return{title:n.connectionErrorTitle,text:n.connectionErrorText,cta:n.connectionErrorCta}}function He({language:r,dark:n,onRetry:i}){const l=Ge(r),o=n?Be:null;return m.jsxs(v.View,{style:[A.container,o==null?void 0:o.container],children:[m.jsxs(v.View,{style:A.content,children:[m.jsx(v.Text,{style:[A.title,o==null?void 0:o.title],children:l.title}),m.jsx(v.View,{style:[A.iconBadge,o==null?void 0:o.iconBadge],children:m.jsx(v.Text,{style:[A.iconGlyph,o==null?void 0:o.iconGlyph],children:"!"})}),m.jsx(v.Text,{style:[A.text,o==null?void 0:o.text],children:l.text})]}),m.jsx(v.Pressable,{accessibilityRole:"button",onPress:i,style:({pressed:E})=>[A.button,o==null?void 0:o.button,E&&A.buttonPressed],children:m.jsx(v.Text,{style:[A.buttonText,o==null?void 0:o.buttonText],children:l.cta})})]})}const A=v.StyleSheet.create({container:{...v.StyleSheet.absoluteFillObject,backgroundColor:"#fff",padding:24,justifyContent:"space-between"},content:{flex:1,alignItems:"center",justifyContent:"center",gap:24},title:{fontSize:20,fontWeight:"600",color:"#000",textAlign:"center"},iconBadge:{width:40,height:40,borderRadius:20,backgroundColor:"#FCE7F3",alignItems:"center",justifyContent:"center"},iconGlyph:{color:"#DB2777",fontSize:22,fontWeight:"700",lineHeight:26},text:{fontSize:16,fontWeight:"500",color:"#4B5563",textAlign:"center"},button:{backgroundColor:"#000",borderRadius:999,minHeight:56,alignItems:"center",justifyContent:"center",alignSelf:"stretch"},buttonPressed:{opacity:.9},buttonText:{color:"#fff",fontSize:16,fontWeight:"500"}}),Be=v.StyleSheet.create({container:{backgroundColor:"#0a0a0a"},title:{color:"#fafafa"},iconBadge:{backgroundColor:"#500724"},iconGlyph:{color:"#F472B6"},text:{color:"#A1A1AA"},button:{backgroundColor:"#fafafa"},buttonText:{color:"#000"}}),Ke=ve.WebView;function z(r){return`try{window.tiunHost&&${r};}catch(e){}; true;`}const Me=s.forwardRef(function({config:n,onEvent:i},l){const o=!!n.debug,E=v.useColorScheme(),S=n.appearance==="dark"||n.appearance==="auto"&&E==="dark"?"dark":"light",T=s.useRef(null),[U,j]=s.useState(!1),[I,N]=s.useState(!1),k=s.useRef(!1),$=s.useRef(!1),W=()=>{var a;N(!1),(a=T.current)==null||a.reload()};s.useEffect(()=>{if(!I)return;const a=v.AppState.addEventListener("change",e=>{var u;e==="active"&&(N(!1),(u=T.current)==null||u.reload())});return()=>a.remove()},[I]);const L=`window.${xe} = true;window.__TIUN_CONFIG__ = Object.assign({}, window.__TIUN_CONFIG__, { returnUrl: ${JSON.stringify(Ue(n))}, appearance: ${JSON.stringify(S)} });true;`,y=(a,...e)=>{var u;return(u=T.current)==null?void 0:u.injectJavaScript(z(`window.tiunHost.${a}(${e.map(f=>JSON.stringify(f)??"null").join(",")})`))},D=s.useRef(S);s.useEffect(()=>{S!==D.current&&(D.current=S,y("setAppearance",S))},[S]);const x=a=>{var e;$.current||($.current=!0,Q.close().catch(()=>{}),Q.closeAuth().catch(()=>{}),j(!0),(e=T.current)==null||e.injectJavaScript(z(`window.tiunHost.resolveCheckout(${a?JSON.stringify(a):""})`)))},V=a=>{var e,u,f;switch(a.type){case J.popPubKeyRequest:return Le(oe(n)).then(d=>y("popPubKey",d)).catch(d=>{o&&console.warn("[tiun] ensurePopKey failed:",d),y("popPubKey",null)}),!0;case J.tokenGet:return(async()=>{try{const d=await Ve(te(n));if(d&&!await qe(oe(n))){await ce(te(n)),y("restoreToken",null);return}y("restoreToken",d)}catch{y("restoreToken",null)}})(),!0;case J.popSignRequest:{const d=(e=a.payload)==null?void 0:e.requestId,b=(u=a.payload)==null?void 0:u.information;return Fe(oe(n),b).then(R=>y("popSignResult",d,R,null)).catch(R=>{const O=(R==null?void 0:R.code)??"sign_failed";o&&console.warn("[tiun] popSign failed:",R),y("popSignResult",d,null,String(O))}),!0}case J.tokenPersist:{const d=((f=a.payload)==null?void 0:f.token)??null;return(d?Ye(te(n),d):ce(te(n))).catch(b=>o&&console.warn("[tiun] token persist failed:",b)),!0}case J.nativeReset:return Promise.allSettled([We(oe(n)),ce(te(n))]),!0;default:return!1}};s.useImperativeHandle(l,()=>({login:()=>{var a;j(!0),(a=T.current)==null||a.injectJavaScript(z("window.tiunHost.login()"))},checkout:(a,e)=>{var f;j(!0),k.current=!0,$.current=!1;const u=e?[a||null,e]:a?[a]:[];(f=T.current)==null||f.injectJavaScript(z(`window.tiunHost.checkout(${u.map(d=>JSON.stringify(d)).join(",")})`))},logout:()=>{var a;return(a=T.current)==null?void 0:a.injectJavaScript(z("window.tiunHost.logout()"))},getVerificationToken:a=>{var e;return(e=T.current)==null?void 0:e.injectJavaScript(z(`window.tiunHost.getVerificationToken(${a?JSON.stringify(a):""})`))},productRequest:(a,e,...u)=>y(a,e,...u),resolveCheckout:x,reload:()=>{var a;return(a=T.current)==null?void 0:a.reload()}}),[]);const Y=a=>{var u,f,d;let e=null;try{e=JSON.parse(a.nativeEvent.data)}catch{o&&console.warn("[tiun] non-JSON bridge message:",a.nativeEvent.data);return}if(!(!e||typeof e.type!="string")){if(e.type==="console"){o&&console.log("[tiun webview]",(u=e.payload)==null?void 0:u.level,(f=e.payload)==null?void 0:f.message);return}if((e.type==="cryptoCheck"||e.type==="hostBridgeReady")&&N(!1),o&&console.log("[tiun] <-",e.type,e.payload),!V(e)){if(e.type===J.overlayChange){const b=!!((d=e.payload)!=null&&d.overlay);j(b),b||(k.current=!1)}i(e)}}},q=a=>{if(k.current=!1,v.Platform.OS==="ios"){Q.openAuth(a,n.returnUrl).then(e=>{e.type==="success"&&e.url?x(Ee(e.url)):e.type==="cancel"&&x("cancelled")}).catch(e=>o&&console.warn("[tiun] openAuth error:",e));return}Q.open(a,{showTitle:!1,enableUrlBarHiding:!1,enableDefaultShare:!1,forceCloseOnRedirection:!1}).then(e=>{e.type==="cancel"&&x("cancelled")}).catch(e=>o&&console.warn("[tiun] in-app browser open error:",e))},g=a=>{Q.open(a,{modalPresentationStyle:"fullScreen",modalEnabled:!0,animated:!0,enableBarCollapsing:!0}).catch(e=>o&&console.warn("[tiun] in-app browser open failed:",e))},G=a=>{var u;const e=(u=a.nativeEvent)==null?void 0:u.targetUrl;e&&(k.current?q(e):g(e))},F=a=>{const e=a.url;return e.startsWith(ue(n))||e.startsWith("about:")||e.startsWith("data:")||e==="about:blank"?!0:e.startsWith("http://")||e.startsWith("https://")?(k.current&&a.isTopFrame!==!1?q(e):g(e),!1):!0},{width:H,height:B}=v.useWindowDimensions();return m.jsxs(v.View,{pointerEvents:U?"auto":"none",style:[re.container,{width:H,height:B},U?re.visible:re.hidden],children:[m.jsx(Ke,{ref:T,source:{uri:je(n)},originWhitelist:["*"],onMessage:Y,onShouldStartLoadWithRequest:F,onOpenWindow:G,injectedJavaScriptBeforeContentLoaded:L,javaScriptEnabled:!0,domStorageEnabled:!0,style:re.webview,containerStyle:re.webview,onError:a=>{o&&console.warn("[tiun] webview load error:",a.nativeEvent),N(!0)},onHttpError:a=>{o&&console.warn("[tiun] webview http error:",a.nativeEvent),N(!0)}}),I&&U?m.jsx(He,{language:n.language,dark:S==="dark",onRetry:W}):null]})}),re=v.StyleSheet.create({container:{position:"absolute",top:0,left:0,zIndex:9999,elevation:9999},webview:{flex:1,backgroundColor:"transparent"},visible:{opacity:1},hidden:{opacity:0}});class Je{constructor(){fe(this,"listeners",new Map)}on(n,i){let l=this.listeners.get(n);return l||(l=new Set,this.listeners.set(n,l)),l.add(i),()=>{var o;(o=this.listeners.get(n))==null||o.delete(i)}}emit(n,i){const l=this.listeners.get(n);if(l)for(const o of l)try{o(i)}catch{}}}const ze=1e4,he=()=>Promise.reject({code:"invalid_argument",message:"productId is required"}),be=s.createContext(null),ye=s.createContext(null);function Xe({config:r,children:n}){const i=s.useRef(null),l=s.useRef(!1),o=s.useRef([]),E=s.useRef(new Map),S=s.useRef(new Map),T=s.useRef(new Je).current,[U,j]=s.useState(!1),[I,N]=s.useState(null),[k,$]=s.useState(!1),[W,L]=s.useState(null),y=s.useCallback(e=>{l.current?e():o.current.push(e)},[]),D=s.useCallback(e=>{var u,f,d,b,R,O,X,t,c,h,w,P,C,K,M;switch(e.type){case"cryptoCheck":L(!!((u=e.payload)!=null&&u.subtle&&((f=e.payload)!=null&&f.secureContext)));break;case"TIUN_SNIPPET_INITIALIZED":{l.current=!0,$(!0),T.emit("ready",void 0);const p=o.current;o.current=[],p.forEach(_=>_());break}case"TIUN_USER_CHANGE":{const p=!!((d=e.payload)!=null&&d.isAuthenticated),_=((b=e.payload)==null?void 0:b.user)??null;j(p),N(_),T.emit("userChange",{isAuthenticated:p,user:_}),((R=e.payload)==null?void 0:R.userEvent)==="login"&&T.emit("login",{user:_}),((O=e.payload)==null?void 0:O.userEvent)==="logout"&&T.emit("logout",void 0);break}case"TIUN_VERIFICATION_TOKEN":{const p=((X=e.payload)==null?void 0:X.token)??null,_=(t=e.payload)==null?void 0:t.requestId;_&&E.current.has(_)&&(E.current.get(_)(p),E.current.delete(_));break}case"TIUN_PRODUCT_RESULT":{const p=(c=e.payload)==null?void 0:c.requestId,_=p?S.current.get(p):void 0;if(!_)break;clearTimeout(_.timer),S.current.delete(p),(h=e.payload)!=null&&h.error?_.reject(e.payload.error):_.resolve((w=e.payload)==null?void 0:w.result);break}case"TIUN_SHOW_PAYWALL":T.emit("paywallShow",{isConnected:!!((P=e.payload)!=null&&P.isConnected)});break;case"TIUN_HIDE_PAYWALL":T.emit("paywallHide",{sessionId:((C=e.payload)==null?void 0:C.sessionId)??"",isConnected:((K=e.payload)==null?void 0:K.isConnected)??!0});break;case"TIUN_ERROR":T.emit("error",((M=e.payload)==null?void 0:M.error)??e.payload??{});break}},[T]);s.useEffect(()=>{const e=f=>{if(!f||!$e(r,f))return;const d=Ee(f);y(()=>{var b;return(b=i.current)==null?void 0:b.resolveCheckout(d)})},u=v.Linking.addEventListener("url",({url:f})=>e(f));return v.Linking.getInitialURL().then(e).catch(()=>{}),()=>u.remove()},[r,y]);const x=s.useCallback(()=>y(()=>{var e;return(e=i.current)==null?void 0:e.login()}),[y]),V=s.useCallback(()=>y(()=>{var e;return(e=i.current)==null?void 0:e.logout()}),[y]),Y=s.useCallback(e=>y(()=>{var u;return(u=i.current)==null?void 0:u.checkout(e==null?void 0:e.productId,e==null?void 0:e.referenceId)}),[y]),q=s.useCallback(()=>new Promise(e=>{const u=`vt_${Math.random().toString(36).slice(2)}_${Date.now()}`;let f=!1;const d=b=>{f||(f=!0,E.current.delete(u),e(b))};E.current.set(u,d),y(()=>{var b;return(b=i.current)==null?void 0:b.getVerificationToken(u)}),setTimeout(()=>d(null),5e3)}),[y]),g=s.useCallback((e,...u)=>new Promise((f,d)=>{const b=`pr_${Math.random().toString(36).slice(2)}_${Date.now()}`,R={resolve:f,reject:d};S.current.set(b,R),y(()=>{var O;S.current.get(b)===R&&(R.timer=setTimeout(()=>{S.current.delete(b),d({code:"timeout",message:`${e} timed out`})},ze),(O=i.current)==null||O.productRequest(e,b,...u))})}),[y]);s.useEffect(()=>{const e=S.current;return()=>{e.forEach(({reject:u,timer:f})=>{clearTimeout(f),u({code:"destroyed",message:"TiunProvider was unmounted"})}),e.clear()}},[]);const G=s.useCallback(()=>g("listProducts"),[g]),F=s.useCallback(e=>e?g("getProduct",e):he(),[g]),H=s.useCallback(()=>g("listProductAccess"),[g]),B=s.useCallback((e,u)=>e?g("checkProductAccess",e,(u==null?void 0:u.referenceId)||void 0):he(),[g]),a=s.useMemo(()=>({isAuthenticated:U,user:I,ready:k,cryptoOk:W,login:x,logout:V,checkout:Y,getUserVerificationToken:q,listProducts:G,getProduct:F,listProductAccess:H,checkProductAccess:B}),[U,I,k,W,x,V,Y,q,G,F,H,B]);return m.jsx(be.Provider,{value:a,children:m.jsxs(ye.Provider,{value:T,children:[n,m.jsx(Me,{ref:i,config:r,onEvent:D})]})})}function Qe(){const r=s.useContext(be);if(!r)throw new Error("useTiun must be used within a <TiunProvider>");return r}function Ze(r,n){const i=s.useContext(ye),l=s.useRef(n);l.current=n,s.useEffect(()=>{if(!i)throw new Error("useTiunEvent must be used within a <TiunProvider>");return i.on(r,o=>l.current(o))},[i,r])}exports.TiunProvider=Xe;exports.useTiun=Qe;exports.useTiunEvent=Ze;