@aifeatures/react 0.3.1 → 0.5.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/dist/index.cjs +1 -1
- package/dist/index.d.cts +632 -3
- package/dist/index.d.ts +632 -3
- package/dist/index.js +1 -1
- package/package.json +11 -10
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{useState as Ze,useEffect as Tt}from"react";import{Turnstile as Lt}from"@marsidev/react-turnstile";import{jsx as Xe}from"react/jsx-runtime";function Et({formId:e,apiUrl:t="https://aifeatures.dev",onVerify:r,onError:n,className:i}){let[o,p]=Ze(null),[l,h]=Ze(!0);return Tt(()=>{h(!0),fetch(`${t}/f/${e}/config`).then(s=>s.json()).then(s=>{p(s.turnstile_sitekey),h(!1)}).catch(()=>{h(!1)})},[e,t]),l||!o?null:Xe("div",{className:i,children:Xe(Lt,{siteKey:o,onSuccess:r,onError:n,onExpire:n,options:{theme:"light"}})})}import{useCallback as At,useEffect as Ut,useRef as Vt,useState as fe}from"react";var pe=[1e3,3e3];function Q(e,t={}){let r=t.apiUrl??"https://aifeatures.dev",n=t.country??null,[i,o]=fe(null),[p,l]=fe(!0),[h,s]=fe(null),[d,a]=fe(0),b=Vt(e);Ut(()=>{let u=!1,P;l(!0),s(null),b.current!==e&&(b.current=e,o(null));let R=I=>{fetch(`${r}/v1/p/${encodeURIComponent(e)}${n?`?country=${encodeURIComponent(n)}`:""}`).then(async x=>{let O=await x.json().catch(()=>null);if(!u)if(!x.ok||!O){if(x.status>=500&&I<pe.length){P=setTimeout(()=>R(I+1),pe[I]);return}s(O?.error??`Request failed (${x.status})`),o(null),l(!1)}else o(O),l(!1)}).catch(x=>{if(!u){if(I<pe.length){P=setTimeout(()=>R(I+1),pe[I]);return}s(x instanceof Error?x.message:"Failed to load product"),l(!1)}})};return R(0),()=>{u=!0,P&&clearTimeout(P)}},[e,r,n,d]);let m=At(()=>a(u=>u+1),[]);return{product:i,loading:p,error:h,refresh:m}}var et=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function D(e,t,r){let n=et.has(t.toLowerCase())?e:e/100;try{return new Intl.NumberFormat(r,{style:"currency",currency:t.toUpperCase()}).format(n)}catch{return`${n} ${t.toUpperCase()}`}}function H(e){return e.variants??[]}function ee(e){return e.options??[]}function oe(e){return ee(e).length>0}function me(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function Z(e,t){let r=Object.keys(t);return e.find(n=>{let i=n.option_values;return i.length!==r.length?!1:i.every(o=>t[o.option_id]===o.value_id)})??null}function we(e,t,r,n){return e.some(i=>{let o=me(i);if(o[r]!==n)return!1;for(let[p,l]of Object.entries(t))if(p!==r&&o[p]!==l)return!1;return!0})}function _e(e,t,r){return e.some(n=>me(n)[t]===r)}function Pe(e,t,r,n){let i={[r]:n};for(let[p,l]of Object.entries(t)){if(p===r)continue;e.some(s=>{let d=me(s);return d[r]===n&&d[p]===l})&&(i[p]=l)}return e.some(p=>{let l=me(p);return Object.entries(i).every(([h,s])=>l[h]===s)})?i:{[r]:n}}function xe(e){let t=e.map(r=>r.unit_amount).filter(r=>r!==null);return t.length===0?null:{min:Math.min(...t),max:Math.max(...t)}}function tt(e,t){let r={};for(let n of ee(e)){let i=t[n.id];if(!i)continue;let o=n.values.find(p=>p.id===i);o&&(r[n.title]=o.value)}return r}function z(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Re(e,t){let r=t instanceof URLSearchParams?t:new URLSearchParams(t),n=new Map;r.forEach((o,p)=>{n.has(z(p))||n.set(z(p),o)});let i={};for(let o of ee(e)){let p=z(o.title);if(p.length===0)continue;let l=n.get(p);if(l===void 0)continue;let h=z(l);if(h.length===0)continue;let s=o.values.find(d=>z(d.value)===h);s&&(i[o.id]=s.id)}return i}function ge(e,t){let r={};for(let[n,i]of Object.entries(tt(e,t))){let o=z(n),p=z(i);o.length===0||p.length===0||(r[o]=p)}return r}function ae(e,t){let r=[];for(let n of ee(e)){let i=t[n.id];if(!i)continue;let o=n.values.find(p=>p.id===i);o?.images?.length&&r.push(...o.images)}return r.length>0?r:e.images??[]}function Ie(e,t){if(typeof window>"u")return;let r=new URL(window.location.href);for(let n of ee(e)){let i=z(n.title);i.length!==0&&r.searchParams.delete(i)}for(let[n,i]of Object.entries(ge(e,t)))r.searchParams.set(n,i);window.history.replaceState(window.history.state,"",r.toString())}import{useCallback as qt,useEffect as ut,useRef as ct,useState as Ue}from"react";var Te="aifeatures_cart",Le="aifeatures_market",nt="aifeatures_cart_cleared";var Oe="aifeatures:cart-storage",se=new Map;function Ee(e){if(se.has(e))return se.get(e)??null;if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Ae(e,t){if(typeof window>"u"){se.set(e,t);return}try{t===null?window.localStorage.removeItem(e):window.localStorage.setItem(e,t),se.delete(e)}catch{se.set(e,t)}Mt(e)}function Mt(e){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(Oe,{detail:{key:e}}))}catch{}}function rt(e,t){if(typeof window>"u")return()=>{};let r=i=>{(i.key===e||i.key===null)&&t()},n=i=>{i.detail?.key===e&&t()};return window.addEventListener("storage",r),window.addEventListener(Oe,n),()=>{window.removeEventListener("storage",r),window.removeEventListener(Oe,n)}}function Nt(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.productId!="string"||t.productId.length===0||typeof t.variantId!="string"||t.variantId.length===0)return null;let r=typeof t.quantity=="number"&&Number.isFinite(t.quantity)?Math.max(1,Math.floor(t.quantity)):1,n={};if(typeof t.selection=="object"&&t.selection!==null)for(let[p,l]of Object.entries(t.selection))typeof l=="string"&&(n[p]=l);let i=typeof t.display=="object"&&t.display!==null?t.display:{},o={name:typeof i.name=="string"?i.name:"",variantTitle:typeof i.variantTitle=="string"?i.variantTitle:null,image:typeof i.image=="string"?i.image:null};return{productId:t.productId,variantId:t.variantId,quantity:r,selection:n,display:o}}function Y(){let e=Ee(Te);if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let r=[],n=new Set;for(let i of t){let o=Nt(i);o&&!n.has(o.variantId)&&(n.add(o.variantId),r.push(o))}return r}function j(e){Ae(Te,JSON.stringify(e))}function it(e){return rt(Te,e)}function ot(e){let t=new Map;for(let n of e)!n.variantId||!(n.quantity>0)||t.set(n.variantId,(t.get(n.variantId)??0)+n.quantity);if(t.size===0)return;let r=[];for(let n of Y()){let i=t.get(n.variantId);if(i===void 0){r.push(n);continue}let o=n.quantity-i;o>0&&r.push({...n,quantity:o})}j(r)}function N(){let e=Ee(Le);return typeof e!="string"||!/^[A-Za-z]{2}$/.test(e)?null:e.toUpperCase()}function at(e){Ae(Le,e!==null&&/^[A-Za-z]{2}$/.test(e)?e.toUpperCase():null)}function te(e){return rt(Le,e)}function st(e){let t=[],r=Ee(nt);if(r)try{let i=JSON.parse(r);Array.isArray(i)&&(t=i.filter(o=>typeof o=="object"&&o!==null&&typeof o.id=="string"&&typeof o.ts=="number"))}catch{}let n=Date.now()-6048e5;return t=t.filter(i=>i.ts>n),t.some(i=>i.id===e)?!1:(t.push({id:e,ts:Date.now()}),t.length>200&&(t=t.slice(-200)),Ae(nt,JSON.stringify(t)),!0)}var Bt=1500;function Ve(){try{if(typeof crypto<"u"&&"randomUUID"in crypto)return crypto.randomUUID()}catch{}return`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function ye(e,t){return!("requestId"in e)||e.requestId===t}function Me(e,t){return typeof window>"u"||window.self===window.top?Promise.resolve(!1):new Promise(r=>{let n=!1,i=l=>{n||(n=!0,window.removeEventListener("message",o),clearTimeout(p),r(l))},o=l=>{if(l.source!==window.parent)return;let h=l.data;h?.type==="aifeatures:test-checkout-ack"&&ye(h,t)&&i(h.status==="accepted")},p=setTimeout(()=>i(!1),Bt);window.addEventListener("message",o);try{window.parent.postMessage({type:"aifeatures:test-checkout",requestId:t,...e},"*")}catch{i(!1)}})}function Ne(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Ue(!1),[i,o]=Ue(null),[p,l]=Ue(null),h=ct(!1),s=ct(null);return ut(()=>{let a=b=>{b.persisted&&(h.current=!1,n(!1))};return window.addEventListener("pageshow",a),()=>window.removeEventListener("pageshow",a)},[]),ut(()=>{if(typeof window>"u"||window.self===window.top)return;let a=b=>{if(b.source!==window.parent)return;let m=b.data;if(m?.type!=="aifeatures:test-checkout-ack"||m.status!=="failed")return;let u=s.current;u===null||!ye(m,u)||(s.current=null,o(typeof m.error=="string"&&m.error?m.error:"The test purchase could not be created."),h.current=!1,n(!1))};return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[]),{startCheckout:qt(async({productId:a,variantId:b,quantity:m,amount:u,metadata:P,successUrl:R,cancelUrl:I,customerEmail:x,expectedUnitAmount:O,expectedCurrency:v})=>{if(!h.current){h.current=!0,n(!0),o(null),l(null);try{let f=N(),c=await fetch(`${t}/v1/p/${a}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...b!==void 0?{variant_id:b}:{},...m!==void 0?{quantity:m}:{},...u!==void 0?{amount:u}:{},...P!==void 0?{metadata:P}:{},...x!==void 0?{customer_email:x}:{},...O!==void 0&&v!==void 0?{expected_unit_amount:O,expected_currency:v}:{},...f!==null?{country:f}:{},success_url:R??`${window.location.origin}/order/confirmation`,cancel_url:I??window.location.href})}),g=await c.json().catch(()=>null);if(!c.ok){if(g?.error==="price_changed"&&typeof g.current_unit_amount=="number"&&typeof g.currency=="string"){l({currentUnitAmount:g.current_unit_amount,currency:g.currency}),o(`The price has changed to ${D(g.current_unit_amount,g.currency)} \u2014 please review and try again.`),h.current=!1,n(!1);return}if(g?.code==="preview_domain"){let k=Ve();if(s.current=k,await Me({productId:a,...b!==void 0?{variantId:b}:{},...m!==void 0?{quantity:m}:{},...u!==void 0?{amount:u}:{},...x!==void 0?{customerEmail:x}:{}},k))return;s.current=null}o(g?.error??`Checkout failed (${c.status})`),h.current=!1,n(!1);return}if(!g?.url){o("Checkout failed: no redirect URL returned"),h.current=!1,n(!1);return}if(window.self!==window.top)try{window.top.location.href=g.url;return}catch{if(window.open(g.url,"_blank")){h.current=!1,n(!1);return}}window.location.href=g.url}catch(f){o(f instanceof Error?f.message:"Checkout failed"),h.current=!1,n(!1)}}},[t]),loading:r,error:i,priceChange:p}}import{useCallback as he,useEffect as Dt,useState as lt}from"react";var ft=20;function dt(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.floor(e))}function W(){let[e,t]=lt([]),[r,n]=lt(!1);Dt(()=>{let s=()=>t(Y());return s(),n(!0),it(s)},[]);let i=he(s=>{let d=Y(),a=dt(s.quantity);return d.find(m=>m.variantId===s.variantId)?(j(d.map(m=>m.variantId===s.variantId?{...m,quantity:m.quantity+a,selection:s.selection??m.selection,display:s.display}:m)),{ok:!0}):d.length>=ft?{ok:!1,reason:"cart_full"}:(j([...d,{productId:s.productId,variantId:s.variantId,quantity:a,selection:s.selection??{},display:s.display}]),{ok:!0})},[]),o=he(s=>{j(Y().filter(d=>d.variantId!==s))},[]),p=he((s,d)=>{let a=Y();if(d<=0){j(a.filter(m=>m.variantId!==s));return}let b=dt(d);j(a.map(m=>m.variantId===s?{...m,quantity:b}:m))},[]),l=he(()=>{j([])},[]),h=e.reduce((s,d)=>s+d.quantity,0);return{items:e,count:h,hydrated:r,add:i,remove:o,setQuantity:p,clear:l}}import{useCallback as $t,useEffect as pt,useMemo as qe,useRef as Ft,useState as ue}from"react";var be={image:null,unitAmount:null,currency:null,baseCurrency:null,inStock:!1,available:null,maxQuantity:null,pdpSearch:{},status:"unavailable"},jt={...be,inStock:!0,status:"error"};function zt(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function Be(e={}){let t=e.apiUrl??"https://aifeatures.dev",{items:r,hydrated:n}=W(),[i,o]=ue({}),[p,l]=ue({shippingRates:null,freeShippingOver:null,shippingCountries:null}),[h,s]=ue(!0),[d,a]=ue(null),[b,m]=ue(0),u=Ft(new Set),P=qe(()=>JSON.stringify(r.map(v=>[v.productId,v.variantId,v.selection])),[r]),R=$t(()=>m(v=>v+1),[]);pt(()=>te(R),[R]),pt(()=>{if(!n)return;if(r.length===0){o({}),l({shippingRates:null,freeShippingOver:null,shippingCountries:null}),a(null),s(!1);return}let v=!1;s(!0);let f=r,c=[...new Set(f.map(k=>k.productId))],g=async k=>{let y=new Map;return await Promise.all(c.map(async C=>{try{let _=await fetch(`${t}/v1/p/${encodeURIComponent(C)}${k?`?country=${encodeURIComponent(k)}`:""}`);if(_.status===404){y.set(C,{kind:"not_found"});return}if(!_.ok){y.set(C,{kind:"error",message:`Request failed (${_.status})`});return}let w=await _.json();y.set(C,{kind:"ok",product:w})}catch(_){y.set(C,{kind:"error",message:_ instanceof Error?_.message:"Failed to load product"})}})),y};return(async()=>{let k=N(),y=await g(k);if(k){let S=[...y.values()].filter(U=>U.kind==="ok"),L=S.filter(U=>U.product.base_currency);L.length>0&&L.length<S.length&&(y=await g(null))}if(v)return;let C=null,_=null,w=null;for(let S of c){let L=y.get(S);!L||L.kind!=="ok"||(C===null&&L.product.shipping_rates&&(C=L.product.shipping_rates),_===null&&L.product.free_shipping_over!=null&&(_=L.product.free_shipping_over),w===null&&L.product.shipping_countries&&(w=L.product.shipping_countries))}let T={},V=new Map,$=null;for(let S of f){let L=y.get(S.productId);if(!L||L.kind==="error"){T[S.variantId]=jt,L&&$===null&&($=L.message);continue}if(L.kind==="not_found"){T[S.variantId]=be;continue}let{product:U}=L;if(!U.active||U.purchasable===!1){T[S.variantId]=be;continue}let q=U.variants??[],F=q.find(K=>K.id===S.variantId)??null,B=S.variantId;if(!F){let K=Z(q,S.selection);if(!K){T[S.variantId]=be;continue}let Qe=V.get(S.variantId)??{};Qe.reanchorTo={variantId:K.id,selection:zt(K)},V.set(S.variantId,Qe),u.current.add(K.id),F=K,B=K.id}let M=ae(U,S.selection)[0]??null,ie={image:M,unitAmount:F.unit_amount,currency:F.currency,baseCurrency:U.base_currency??null,inStock:F.in_stock,available:F.available,maxQuantity:U.max_quantity,pdpSearch:ge(U,S.selection),status:u.current.has(B)?"reanchored":"ok"};T[S.variantId]=ie,T[B]=ie;let Ge=V.get(S.variantId)??{};Ge.display={name:U.name,variantTitle:F.title,image:M},V.set(S.variantId,Ge)}let E=new Set(f.map(S=>S.variantId));for(let S of[...u.current])!E.has(S)&&!(S in T)&&u.current.delete(S);if(V.size>0){let S=Y(),L=[],U=new Map,q=!1;for(let F of S){let B=V.get(F.variantId),M={...F};B?.reanchorTo&&(M.variantId=B.reanchorTo.variantId,M.selection=B.reanchorTo.selection,q=!0),B?.display&&(M.display.name!==B.display.name||M.display.variantTitle!==B.display.variantTitle||M.display.image!==B.display.image)&&(M.display=B.display,q=!0);let ie=U.get(M.variantId);if(ie){ie.quantity+=M.quantity,q=!0;continue}L.push(M),U.set(M.variantId,M)}q&&j(L)}v||(o(T),l({shippingRates:C,freeShippingOver:_,shippingCountries:w}),a($),s(!1))})(),()=>{v=!0}},[n,P,t,b]);let I=qe(()=>r.map(v=>{let f=i[v.variantId];return f?{...v,...f,image:f.image??v.display.image}:{...v,image:v.display.image,unitAmount:null,currency:null,baseCurrency:null,inStock:!0,available:null,maxQuantity:null,pdpSearch:{},status:"ok"}}),[r,i]),{subtotal:x,currency:O}=qe(()=>{let v=0,f=null;for(let c of I)c.unitAmount===null||c.currency===null||(v+=c.unitAmount*c.quantity,f=f??c.currency);return{subtotal:v,currency:f}},[I]);return{lines:I,subtotal:x,currency:O,shippingRates:p.shippingRates,freeShippingOver:p.freeShippingOver,shippingCountries:p.shippingCountries,loading:h,error:d,refresh:R}}import{useCallback as Wt,useEffect as mt,useMemo as Kt,useRef as De,useState as ce}from"react";var Ht=2e3;function Yt(e={}){let t=e.apiUrl??"https://aifeatures.dev",r=e.debounceMs??250,n=e.shippingOption??null,{items:i,hydrated:o}=W(),[p,l]=ce(null),[h,s]=ce(!1),[d,a]=ce(null),[b,m]=ce(null),[u,P]=ce(0);mt(()=>(m(N()),te(()=>m(N()))),[]);let R=Kt(()=>i.map(f=>`${f.variantId}:${f.quantity}`).sort().join(","),[i]),I=Wt(()=>P(f=>f+1),[]),x=De(0),O=De(!1),v=De("idle");return mt(()=>{if(!o)return;if(i.length===0){l(null),a(null),s(!1);return}let f=++x.current,c=new AbortController,g=!1,k,y=O.current?r:0;O.current=!0,v.current=v.current==="pending"?"spent":"idle";let C=setTimeout(async()=>{s(!0);try{let _=await fetch(`${t}/v1/p/checkout/summary`,{method:"POST",headers:{"Content-Type":"application/json"},signal:c.signal,body:JSON.stringify({items:i.map(T=>({variant_id:T.variantId,quantity:T.quantity})),...b?{country:b}:{},...n?{shipping_option:n}:{}})});if(g||f!==x.current)return;if(!_.ok){if(_.status===429){let T=v.current==="idle";T&&(k=setTimeout(()=>{g||f!==x.current||(v.current="pending",P(V=>V+1))},Ht)),a(T?"Too many updates \u2014 retrying shortly":"Too many updates \u2014 the total will refresh on the next cart change")}else a(`Could not price this cart (${_.status})`);return}let w=await _.json();if(g||f!==x.current)return;l({currency:w.currency,subtotal:w.subtotal,shipping:w.shipping?{options:w.shipping.options.map(T=>({label:T.label,amount:T.amount,undiscountedAmount:T.undiscounted_amount})),selectedAmount:w.shipping.selected_amount,selectedLabel:w.shipping.selected_label,freeShippingOver:w.shipping.free_shipping_over,freeShippingCurrency:w.shipping.free_shipping_currency,thresholdMet:w.shipping.threshold_met,collectsAddress:w.shipping.collects_address}:null,total:w.total,totalIsFinal:w.total_is_final,tax:w.tax??null,unavailableVariantIds:w.unavailable_variant_ids}),a(null)}catch(_){if(g||c.signal.aborted||f!==x.current)return;a(_ instanceof Error?_.message:"Could not price this cart")}finally{!g&&f===x.current&&s(!1)}},y);return()=>{g=!0,clearTimeout(C),k!==void 0&&clearTimeout(k),c.abort()}},[o,R,b,t,r,n,u]),{summary:p,loading:h,error:d,refresh:I}}import{useCallback as Jt,useEffect as gt,useRef as yt,useState as Ce}from"react";function $e(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Ce(!1),[i,o]=Ce(null),[p,l]=Ce(null),[h,s]=Ce(null),d=yt(!1),a=yt(null);return gt(()=>{let m=u=>{u.persisted&&(d.current=!1,n(!1))};return window.addEventListener("pageshow",m),()=>window.removeEventListener("pageshow",m)},[]),gt(()=>{if(typeof window>"u"||window.self===window.top)return;let m=u=>{if(u.source!==window.parent)return;let P=u.data;if(P?.type!=="aifeatures:test-checkout-ack"||P.status!=="failed")return;let R=a.current;R===null||!ye(P,R)||(a.current=null,o(typeof P.error=="string"&&P.error?P.error:"The test purchase could not be created."),d.current=!1,n(!1))};return window.addEventListener("message",m),()=>window.removeEventListener("message",m)},[]),{startCheckout:Jt(async(m,{successUrl:u,cancelUrl:P,customerEmail:R,metadata:I,shippingOption:x}={})=>{if(!d.current){d.current=!0,n(!0),o(null),l(null),s(null);try{let O=N(),v=await fetch(`${t}/v1/p/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:m.map(c=>({variant_id:c.variantId,quantity:c.quantity,...typeof c.unitAmount=="number"&&typeof c.currency=="string"?{expected_unit_amount:c.unitAmount,expected_currency:c.currency}:{}})),...O!==null?{country:O}:{},...x?{shipping_option:x}:{},...I!==void 0?{metadata:I}:{},...R!==void 0?{customer_email:R}:{},success_url:u??`${window.location.origin}/order/confirmation`,cancel_url:P??window.location.href})}),f=await v.json().catch(()=>null);if(!v.ok){if(f?.code==="shipping_option_unavailable"&&typeof f.requested=="string"&&Array.isArray(f.available)){s({requested:f.requested,available:f.available,currency:typeof f.currency=="string"?f.currency:""}),d.current=!1,n(!1);return}if(f?.error==="cart_conflict"&&Array.isArray(f.items)){let c={};for(let g of f.items)g&&typeof g.variant_id=="string"&&(c[g.variant_id]=g);l(c),d.current=!1,n(!1);return}if(f?.code==="preview_domain"){let c=Ve();if(a.current=c,await Me({items:m.map(k=>({productId:k.productId,variantId:k.variantId,quantity:k.quantity})),...R!==void 0?{customerEmail:R}:{}},c))return;a.current=null}o(f?.error??`Checkout failed (${v.status})`),d.current=!1,n(!1);return}if(!f?.url){o("Checkout failed: no redirect URL returned"),d.current=!1,n(!1);return}if(window.self!==window.top)try{window.top.location.href=f.url;return}catch{if(window.open(f.url,"_blank")){d.current=!1,n(!1);return}}window.location.href=f.url}catch(O){o(O instanceof Error?O.message:"Checkout failed"),d.current=!1,n(!1)}}},[t]),loading:r,error:i,conflicts:p,shippingConflict:h}}import{useCallback as Gt,useEffect as ht,useState as Fe}from"react";var je=[{country:"US",currency:"usd"},{country:"GB",currency:"gbp"},{country:"CA",currency:"cad"},{country:"AU",currency:"aud"},{country:"NZ",currency:"nzd"},{country:"JP",currency:"jpy"},{country:"CH",currency:"chf"},{country:"SE",currency:"sek"},{country:"NO",currency:"nok"},{country:"DK",currency:"dkk"},{country:"PL",currency:"pln"},{country:"CZ",currency:"czk"},{country:"SG",currency:"sgd"},{country:"HK",currency:"hkd"},{country:"MX",currency:"mxn"},{country:"BR",currency:"brl"},{country:"IN",currency:"inr"},{country:"ZA",currency:"zar"},{country:"AE",currency:"aed"},{country:"IL",currency:"ils"},{country:"AT",currency:"eur"},{country:"BE",currency:"eur"},{country:"HR",currency:"eur"},{country:"CY",currency:"eur"},{country:"EE",currency:"eur"},{country:"FI",currency:"eur"},{country:"FR",currency:"eur"},{country:"DE",currency:"eur"},{country:"GR",currency:"eur"},{country:"IE",currency:"eur"},{country:"IT",currency:"eur"},{country:"LV",currency:"eur"},{country:"LT",currency:"eur"},{country:"LU",currency:"eur"},{country:"MT",currency:"eur"},{country:"NL",currency:"eur"},{country:"PT",currency:"eur"},{country:"SK",currency:"eur"},{country:"SI",currency:"eur"},{country:"ES",currency:"eur"}];function bt(e){return e?je.find(t=>t.country===e.toUpperCase())?.currency??null:null}var Ct=new Map;function Qt(e){let t=Ct.get(e);return t||(t=fetch(`${e}/v1/geo`).then(async r=>{if(!r.ok)return null;let n=await r.json().catch(()=>null);return typeof n?.country=="string"&&/^[A-Za-z]{2}$/.test(n.country)?n.country.toUpperCase():null}).catch(()=>null),Ct.set(e,t)),t}function Zt(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Fe(null),[i,o]=Fe(!1),[p,l]=Fe(null);ht(()=>{let a=()=>n(N());return a(),o(!0),te(a)},[]),ht(()=>{let a=!1;return Qt(t).then(b=>{a||l(b)}),()=>{a=!0}},[t]);let h=Gt(a=>{at(a)},[]),s=bt(p),d=i&&s!==null&&s!==bt(r);return{market:r,suggestedCountry:p,setMarket:h,markets:je,shouldPrompt:d}}import{jsx as ze,jsxs as tn}from"react/jsx-runtime";var Xt={textDecoration:"line-through",opacity:.6,marginRight:"0.4em"};function en({productId:e,variantId:t,apiUrl:r,locale:n,className:i,style:o,compareAtClassName:p}){let{product:l,loading:h}=Q(e,{apiUrl:r});if(h||!l)return null;let s=H(l),d=t!==void 0?s.find(b=>b.id===t)??null:l.options.length===0?s[0]??null:null;if(d){if(d.unit_amount===null)return null;let b=d.compare_at_amount!==null&&d.compare_at_amount>d.unit_amount;return tn("span",{className:i,style:o,children:[b&&ze("span",{className:p,style:p?void 0:Xt,children:D(d.compare_at_amount,d.currency,n)}),D(d.unit_amount,d.currency,n)]})}let a=xe(s);return a?ze("span",{className:i,style:o,children:a.min===a.max?D(a.min,l.currency,n):`${D(a.min,l.currency,n)} \u2013 ${D(a.max,l.currency,n)}`}):l.unit_amount===null?null:ze("span",{className:i,style:o,children:D(l.unit_amount,l.currency,n)})}import{useEffect as We,useMemo as nn,useRef as St,useState as vt}from"react";import{Fragment as yn,jsx as ne,jsxs as kt}from"react/jsx-runtime";var rn={marginBottom:"0.75rem"},on={display:"block",fontSize:"0.875rem",fontWeight:600,marginBottom:"0.375rem"},an={display:"flex",flexWrap:"wrap",gap:"0.5rem"},sn={padding:"0.375rem 0.75rem",border:"1px solid #d1d5db",borderRadius:6,background:"white",cursor:"pointer",fontSize:"0.875rem"},un={borderColor:"#111827",boxShadow:"inset 0 0 0 1px #111827",fontWeight:600},wt={opacity:.4,textDecoration:"line-through",cursor:"not-allowed"},cn={...wt,cursor:"pointer"},ln=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,dn=e=>ln.test(e),fn={padding:"0.375rem",width:"2.25rem",height:"2.25rem",lineHeight:0},pn={display:"block",width:"1.5rem",height:"1.5rem",maxWidth:"100%",maxHeight:"100%",boxSizing:"border-box",borderRadius:3,backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f3f4f6",border:"1px solid rgba(0, 0, 0, 0.2)"},mn="linear-gradient(to top right, transparent calc(50% - 2px), rgba(0,0,0,0.55) calc(50% - 2px), rgba(255,255,255,0.95) calc(50% - 1px), rgba(255,255,255,0.95) calc(50% + 1px), rgba(0,0,0,0.55) calc(50% + 1px), transparent calc(50% + 2px))";function gn({options:e,variants:t,value:r,syncUrl:n=!0,onChange:i,onVariantChange:o,className:p,style:l,optionClassName:h,optionLabelClassName:s,valueClassName:d,selectedValueClassName:a,unavailableValueClassName:b,swatchClassName:m}){let u=r!==void 0,[P,R]=vt(r??{}),I=u?r:P,[x,O]=vt(()=>new Set),v=y=>O(C=>C.has(y)?C:new Set(C).add(y));We(()=>{O(y=>y.size===0?y:new Set)},[e]);let f=St(!1);We(()=>{if(!n||u||f.current||e.length===0||typeof window>"u"||(f.current=!0,Object.keys(P).length>0))return;let y=Re({options:e},window.location.search);Object.keys(y).length!==0&&(R(y),i?.(y))},[n,u,e]);let c=nn(()=>e.length>0?t.filter(y=>y.option_values.length===e.length):t,[t,e]),g=St(void 0);if(We(()=>{let y=Z(c,I),C=y?.id??null;g.current!==C&&(g.current=C,o?.(y))},[c,I]),e.length===0)return null;let k=(y,C)=>{let _=Pe(c,I,y,C);u||(R(_),n&&Ie({options:e},_)),i?.(_)};return ne("div",{className:p,style:l,children:e.map(y=>kt("div",{className:h,style:h?void 0:rn,children:[ne("span",{className:s,style:s?void 0:on,children:y.title}),ne("div",{style:an,children:y.values.map(C=>{let _=I[y.id]===C.id,w=we(c,I,y.id,C.id),T=w||_e(c,y.id,C.id),V=[d,_?a:void 0,w?void 0:b].filter(Boolean).join(" ")||void 0,$=C.swatch??null,E=$&&!x.has($)?$:null,S=E?dn(E):!1,L=d?void 0:{...sn,..._?un:{},...w?{}:T?cn:wt,...E?{...fn,textDecoration:"none"}:{}},U=w?C.value:`${C.value} \u2014 unavailable with your current selection`;return ne("button",{type:"button",className:V,style:L,disabled:!T,"aria-pressed":_,"aria-label":E?U:void 0,title:E?U:void 0,"data-selected":_?"true":void 0,"data-available":w?"true":"false","data-swatch":E?S?"hex":"image":void 0,onClick:()=>k(y.id,C.id),children:E?kt(yn,{children:[ne("span",{"aria-hidden":"true",className:m,style:m?void 0:{...pn,...S?{background:E}:{},...S&&w?{}:{backgroundImage:[...w?[]:[mn],...S?[]:[`url(${JSON.stringify(E)})`]].join(", ")}}}),S?null:ne("img",{src:E,alt:"","aria-hidden":"true",referrerPolicy:"no-referrer",style:{display:"none"},onError:()=>v(E)})]}):C.value},C.id)})})]},y.id))})}import{useEffect as hn}from"react";import{Fragment as Ke,jsx as X,jsxs as le}from"react/jsx-runtime";var bn={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"},Cn={background:"none",border:"none",padding:0,marginLeft:"0.35em",font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"};function _t(){return le("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",style:{display:"inline-block",marginRight:"0.5em",verticalAlign:"-0.125em",flexShrink:0},children:[X("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),X("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:X("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function Sn({productId:e,variantId:t,quantity:r,amount:n,metadata:i,successUrl:o,cancelUrl:p,customerEmail:l,apiUrl:h,disabled:s,className:d,style:a,errorClassName:b,spinner:m=!0,children:u}){let{product:P,loading:R,error:I,refresh:x}=Q(e,{apiUrl:h}),{startCheckout:O,loading:v,error:f,priceChange:c}=Ne({apiUrl:h});hn(()=>{c&&x()},[c,x]);let g=P!==null&&!P.payments_ready,k=P!==null&&!P.active,y=P!==null&&P.purchasable===!1,C=P!==null&&oe(P),_=P!==null?H(P):[],w=t!==void 0?_.find(U=>U.id===t)??null:!C&&_.length===1?_[0]:null,T=C&&!w,V=w!==null&&!w.in_stock,$=!!s||R||!P||g||k||y||T||V||v,E;v?E=le(Ke,{children:[m&&X(_t,{}),"Processing\u2026"]}):R?E=le(Ke,{children:[m&&X(_t,{}),u??"Buy now"]}):g?E="Payments not set up":k||y?E="Unavailable":T?E="Select options":V?E="Out of stock":u!==void 0?E=u:E="Buy now";let S=f??I;return le(Ke,{children:[X("button",{type:"button",className:d,style:a,disabled:$,onClick:()=>{let U=n===void 0&&N()===null&&w!==null&&!w.allow_custom_amount&&typeof w.unit_amount=="number"?{expectedUnitAmount:w.unit_amount,expectedCurrency:w.currency}:{};O({productId:e,variantId:t,quantity:r,amount:n,metadata:i,successUrl:o,cancelUrl:p,customerEmail:l,...U})},children:E}),S&&le("div",{role:"alert",className:b,style:b?void 0:bn,children:[S,P===null&&!R&&I!==null&&X("button",{type:"button",onClick:x,style:Cn,children:"Tap to retry"})]})]})}import{useEffect as vn,useRef as kn,useState as Pt}from"react";import{Fragment as xt,jsx as re,jsxs as Se}from"react/jsx-runtime";var wn={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"},_n={background:"none",border:"none",padding:0,marginLeft:"0.35em",font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"},Pn=1500;function xn(){return Se("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",style:{display:"inline-block",marginRight:"0.5em",verticalAlign:"-0.125em",flexShrink:0},children:[re("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),re("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:re("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function Rn(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function In({productId:e,variantId:t,selection:r,quantity:n,apiUrl:i,disabled:o,className:p,style:l,errorClassName:h,spinner:s=!0,children:d}){let{product:a,loading:b,error:m,refresh:u}=Q(e,{apiUrl:i}),{add:P}=W(),[R,I]=Pt(!1),[x,O]=Pt(!1),v=kn(void 0);vn(()=>()=>{v.current&&clearTimeout(v.current)},[]);let f=a!==null&&!a.payments_ready,c=a!==null&&!a.active,g=a!==null&&a.purchasable===!1,k=a!==null&&!b&&H(a).length===0,y=a!==null&&a.allow_custom_amount,C=a!==null&&oe(a),_=a!==null?H(a):[],w=t!==void 0?_.find(q=>q.id===t)??null:r!==void 0&&C?Z(_,r):!C&&_.length===1?_[0]:null,T=a!==null&&!k&&!w,V=w!==null&&!w.in_stock,$=!!o||b||!a||f||c||g||k||y||T||V,E=()=>{if(!a||!w)return;let q=r??Rn(w);if(!P({productId:e,variantId:w.id,quantity:n,selection:q,display:{name:a.name,variantTitle:w.title,image:ae(a,q)[0]??null}}).ok){I(!0);return}I(!1),O(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>O(!1),Pn)},S;b?S=Se(xt,{children:[s&&re(xn,{}),d??"Add to cart"]}):f?S="Payments not set up":c||g||k||y?S="Unavailable":T?S="Select options":V?S="Out of stock":x?S="Added to cart":d!==void 0?S=d:S="Add to cart";let L=R?"Your cart is full \u2014 remove an item before adding another.":m;return Se(xt,{children:[re("button",{type:"button",className:p,style:l,disabled:$,"data-added":x?"true":void 0,onClick:E,children:S}),L&&Se("div",{role:"alert",className:h,style:h?void 0:wn,children:[L,a===null&&!b&&m!==null&&!R&&re("button",{type:"button",onClick:u,style:_n,children:"Tap to retry"})]})]})}import{Fragment as He,jsx as J,jsxs as ve}from"react/jsx-runtime";var Rt={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"};function It(){return ve("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",style:{display:"inline-block",marginRight:"0.5em",verticalAlign:"-0.125em",flexShrink:0},children:[J("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),J("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:J("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function On({apiUrl:e,successUrl:t,cancelUrl:r,customerEmail:n,metadata:i,shippingOption:o,disabled:p,className:l,style:h,errorClassName:s,spinner:d=!0,children:a}){let{items:b,hydrated:m}=W(),{lines:u}=Be({apiUrl:e}),{startCheckout:P,loading:R,error:I,conflicts:x}=$e({apiUrl:e}),O=m&&b.length===0,v=u.some(k=>k.status==="unavailable"),f=!!p||!m||O||v||R,c;R?c=ve(He,{children:[d&&J(It,{}),"Processing\u2026"]}):m?O?c="Cart is empty":v?c="Remove unavailable items":a!==void 0?c=a:c="Checkout":c=ve(He,{children:[d&&J(It,{}),a??"Checkout"]});let g=x?Object.keys(x).length:0;return ve(He,{children:[J("button",{type:"button",className:l,style:h,disabled:f,onClick:()=>P(u,{successUrl:t,cancelUrl:r,customerEmail:n,metadata:i,shippingOption:o}),children:c}),g>0&&J("div",{role:"alert",className:s,style:s?void 0:Rt,children:g===1?"An item in your cart changed \u2014 please review your cart and try again.":`${g} items in your cart changed \u2014 please review your cart and try again.`}),I&&J("div",{role:"alert",className:s,style:s?void 0:Rt,children:I})]})}import{useEffect as ke,useRef as Ot,useState as Ye}from"react";import{Fragment as de,jsx as A,jsxs as G}from"react/jsx-runtime";var Je="af_order_confirmation_session",Tn=1800*1e3;function Ln({apiUrl:e="https://aifeatures.dev",className:t,style:r,sessionId:n,pollIntervalMs:i=2e3,pollTimeoutMs:o=6e4,followRedirect:p=!0,redirectDelayMs:l=1500,renderNoSession:h,renderPending:s,renderPaid:d,renderFailed:a}){let[b,m]=Ye(n),[u,P]=Ye(null),[R,I]=Ye(!1),x=Ot(void 0);ke(()=>{if(n!==void 0){m(n);return}if(x.current!==void 0){m(x.current);return}let c=new URL(window.location.href),g=c.searchParams.get("session_id");if(g){c.searchParams.delete("session_id"),window.history.replaceState(window.history.state,"",c.toString());try{sessionStorage.setItem(Je,JSON.stringify({id:g,ts:Date.now()}))}catch{}}else try{let k=sessionStorage.getItem(Je);if(k){let y=JSON.parse(k);typeof y.id=="string"&&typeof y.ts=="number"&&Date.now()-y.ts<=Tn?g=y.id:sessionStorage.removeItem(Je)}}catch{}x.current=g,m(g)},[n]),ke(()=>{if(!b)return;let c=!1,g,k=Date.now(),y=async()=>{try{let C=await fetch(`${e}/v1/o/session/${encodeURIComponent(b)}`);if(C.ok){let _=await C.json();if(c||(P(_),_.status!=="pending"))return}}catch{}if(!c){if(Date.now()-k>=o){I(!0);return}g=setTimeout(y,i)}};return y(),()=>{c=!0,g&&clearTimeout(g)}},[b,e,i,o]);let O=u!==null&&(u.status==="paid"||u.status==="partially_refunded"),v=Ot(!1);ke(()=>{if(!b||u===null||v.current||!(u.status==="paid"||u.status==="partially_refunded"||u.is_test===!0)||(v.current=!0,!st(b)))return;let g=(u.line_items??[]).filter(k=>typeof k.variant_id=="string"&&k.variant_id.length>0).map(k=>({variantId:k.variant_id,quantity:k.quantity}));g.length>0&&ot(g)},[b,u]);let f=O&&u.fulfillment.type==="redirect"?u.fulfillment.redirect_url:void 0;if(ke(()=>{if(!f||!p)return;let c=setTimeout(()=>{window.location.href=f},l);return()=>clearTimeout(c)},[f,p,l]),b===void 0)return null;if(b===null)return h?A(de,{children:h()}):G("div",{className:t,style:r,children:[A("h2",{children:"Thank you for your order!"}),A("p",{children:"If you completed a payment, a confirmation email with your receipt and any download links is on its way to you. This page can only show live order details right after checkout."})]});if(!u||u.status==="pending")return s?A(de,{children:s({timedOut:R})}):A("div",{className:t,style:r,role:"status",children:A("p",{children:R?"This is taking longer than expected. You will receive an email confirmation once your payment is processed.":"Confirming your payment\u2026"})});if(O){if(d)return A(de,{children:d(u)});let{fulfillment:c}=u,g=u.amount_total!==void 0&&u.currency?D(u.amount_total,u.currency):null,k=c.files??[],y=k.length===0?c.download_url:void 0;return G("div",{className:t,style:r,children:[A("h2",{children:"Thank you for your purchase!"}),u.is_test&&G("p",{children:[A("strong",{children:"Test purchase"})," \u2014 no payment was collected."]}),u.line_items&&u.line_items.length>0&&A("ul",{children:u.line_items.map((C,_)=>G("li",{children:[C.quantity>1?`${C.quantity} \xD7 `:"",C.name,C.refunded&&A("em",{children:C.refund_reason==="oversold"?" \u2014 sold out and refunded; check your email for details":" \u2014 refunded"})]},_))}),g&&G("p",{children:["Total paid: ",g]}),k.length>0&&G(de,{children:[A("p",{children:"Your downloads:"}),A("ul",{children:k.map((C,_)=>A("li",{children:A("a",{href:C.download_url,children:C.name})},_))})]}),y&&A("p",{children:A("a",{href:y,children:"Download your file"})}),f?G("p",{children:["Taking you to your content\u2026"," ",A("a",{href:f,children:"Continue if you are not redirected"})]}):c.redirect_url?A("p",{children:A("a",{href:c.redirect_url,children:"Continue to your content"})}):null,k.length===0&&!y&&!c.redirect_url&&A("p",{children:"A confirmation email is on its way to you."}),u.order_id&&G("p",{children:["Order reference: ",A("code",{children:u.order_id})," \u2014 keep this if you ever need help with your order."]})]})}return a?A(de,{children:a(u)}):A("div",{className:t,style:r,children:A("p",{children:"We couldn't confirm your payment. If you were charged, you'll receive an email confirmation \u2014 otherwise you can safely try again."})})}export{In as AddToCartButton,Et as AifeaturesCaptcha,Sn as BuyButton,On as CartCheckoutButton,je as MARKET_COUNTRIES,ft as MAX_CART_LINES,Ln as OrderConfirmation,en as ProductPrice,gn as VariantPicker,et as ZERO_DECIMAL_CURRENCIES,Ie as applySelectionToUrl,D as formatPrice,ee as getOptions,H as getVariants,oe as isMultiVariant,we as isValueAvailable,_e as isValueInCatalog,Pe as reanchorSelection,Z as resolveVariant,ge as searchFromSelection,ae as selectedImages,tt as selectedValues,Re as selectionFromSearch,W as useCart,$e as useCartCheckout,Be as useCartItems,Yt as useCartSummary,Ne as useCheckout,Zt as useMarket,Q as useProduct,z as valueSlug,xe as variantPriceRange};
|
|
2
|
+
import{useState as Vt,useEffect as Ln}from"react";import{Turnstile as In}from"@marsidev/react-turnstile";import{jsx as qt}from"react/jsx-runtime";function En({formId:e,apiUrl:t="https://aifeatures.dev",onVerify:r,onError:n,className:o}){let[i,l]=Vt(null),[f,y]=Vt(!0);return Ln(()=>{y(!0),fetch(`${t}/f/${e}/config`).then(u=>u.json()).then(u=>{l(u.turnstile_sitekey),y(!1)}).catch(()=>{y(!1)})},[e,t]),f||!i?null:qt("div",{className:o,children:qt(In,{siteKey:i,onSuccess:r,onError:n,onExpire:n,options:{theme:"light",appearance:"interaction-only"}})})}import{useCallback as Un,useEffect as Nn,useRef as Mn,useState as $e}from"react";var De=[1e3,3e3];function ue(e,t={}){let r=t.apiUrl??"https://aifeatures.dev",n=t.country??null,[o,i]=$e(null),[l,f]=$e(!0),[y,u]=$e(null),[v,d]=$e(0),x=Mn(e);Nn(()=>{let p=!1,O;f(!0),u(null),x.current!==e&&(x.current=e,i(null));let w=b=>{fetch(`${r}/v1/p/${encodeURIComponent(e)}${n?`?country=${encodeURIComponent(n)}`:""}`).then(async a=>{let P=await a.json().catch(()=>null);if(!p)if(!a.ok||!P){if(a.status>=500&&b<De.length){O=setTimeout(()=>w(b+1),De[b]);return}u(P?.error??`Request failed (${a.status})`),i(null),f(!1)}else i(P),f(!1)}).catch(a=>{if(!p){if(b<De.length){O=setTimeout(()=>w(b+1),De[b]);return}u(a instanceof Error?a.message:"Failed to load product"),f(!1)}})};return w(0),()=>{p=!0,O&&clearTimeout(O)}},[e,r,n,v]);let k=Un(()=>d(p=>p+1),[]);return{product:o,loading:l,error:y,refresh:k}}var $t=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function F(e,t,r){let n=$t.has(t.toLowerCase())?e:e/100;try{return new Intl.NumberFormat(r,{style:"currency",currency:t.toUpperCase()}).format(n)}catch{return`${n} ${t.toUpperCase()}`}}function oe(e){return e.variants??[]}function fe(e){return e.options??[]}function _e(e){return fe(e).length>0}function Be(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function le(e,t){let r=Object.keys(t);return e.find(n=>{let o=n.option_values;return o.length!==r.length?!1:o.every(i=>t[i.option_id]===i.value_id)})??null}function ot(e,t,r,n){return e.some(o=>{let i=Be(o);if(i[r]!==n)return!1;for(let[l,f]of Object.entries(t))if(l!==r&&i[l]!==f)return!1;return!0})}function st(e,t,r){return e.some(n=>Be(n)[t]===r)}function at(e,t,r,n){let o={[r]:n};for(let[l,f]of Object.entries(t)){if(l===r)continue;e.some(u=>{let v=Be(u);return v[r]===n&&v[l]===f})&&(o[l]=f)}return e.some(l=>{let f=Be(l);return Object.entries(o).every(([y,u])=>f[y]===u)})?o:{[r]:n}}function ut(e){let t=e.map(r=>r.unit_amount).filter(r=>r!==null);return t.length===0?null:{min:Math.min(...t),max:Math.max(...t)}}function Dt(e,t){let r={};for(let n of fe(e)){let o=t[n.id];if(!o)continue;let i=n.values.find(l=>l.id===o);i&&(r[n.title]=i.value)}return r}function ne(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function lt(e,t){let r=t instanceof URLSearchParams?t:new URLSearchParams(t),n=new Map;r.forEach((i,l)=>{n.has(ne(l))||n.set(ne(l),i)});let o={};for(let i of fe(e)){let l=ne(i.title);if(l.length===0)continue;let f=n.get(l);if(f===void 0)continue;let y=ne(f);if(y.length===0)continue;let u=i.values.find(v=>ne(v.value)===y);u&&(o[i.id]=u.id)}return o}function Fe(e,t){let r={};for(let[n,o]of Object.entries(Dt(e,t))){let i=ne(n),l=ne(o);i.length===0||l.length===0||(r[i]=l)}return r}function xe(e,t){let r=[];for(let n of fe(e)){let o=t[n.id];if(!o)continue;let i=n.values.find(l=>l.id===o);i?.images?.length&&r.push(...i.images)}return r.length>0?r:e.images??[]}function ct(e,t){if(typeof window>"u")return;let r=new URL(window.location.href);for(let n of fe(e)){let o=ne(n.title);o.length!==0&&r.searchParams.delete(o)}for(let[n,o]of Object.entries(Fe(e,t)))r.searchParams.set(n,o);window.history.replaceState(window.history.state,"",r.toString())}import{useCallback as Dn,useEffect as Jt,useRef as Gt,useState as gt}from"react";var pt="aifeatures_cart",ft="aifeatures_market",Bt="aifeatures_cart_cleared";var dt="aifeatures:cart-storage",Re=new Map;function Ae(e){if(Re.has(e))return Re.get(e)??null;if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function me(e,t){if(typeof window>"u"){Re.set(e,t);return}try{t===null?window.localStorage.removeItem(e):window.localStorage.setItem(e,t),Re.delete(e)}catch{Re.set(e,t)}Vn(e)}function Vn(e){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(dt,{detail:{key:e}}))}catch{}}function ze(e,t){if(typeof window>"u")return()=>{};let r=o=>{(o.key===e||o.key===null)&&t()},n=o=>{o.detail?.key===e&&t()};return window.addEventListener("storage",r),window.addEventListener(dt,n),()=>{window.removeEventListener("storage",r),window.removeEventListener(dt,n)}}function qn(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.productId!="string"||t.productId.length===0||typeof t.variantId!="string"||t.variantId.length===0)return null;let r=typeof t.quantity=="number"&&Number.isFinite(t.quantity)?Math.max(1,Math.floor(t.quantity)):1,n={};if(typeof t.selection=="object"&&t.selection!==null)for(let[l,f]of Object.entries(t.selection))typeof f=="string"&&(n[l]=f);let o=typeof t.display=="object"&&t.display!==null?t.display:{},i={name:typeof o.name=="string"?o.name:"",variantTitle:typeof o.variantTitle=="string"?o.variantTitle:null,image:typeof o.image=="string"?o.image:null};return{productId:t.productId,variantId:t.variantId,quantity:r,selection:n,display:i}}function se(){let e=Ae(pt);if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let r=[],n=new Set;for(let o of t){let i=qn(o);i&&!n.has(i.variantId)&&(n.add(i.variantId),r.push(i))}return r}function X(e){me(pt,JSON.stringify(e))}function Ft(e){return ze(pt,e)}function zt(e){let t=new Map;for(let n of e)!n.variantId||!(n.quantity>0)||t.set(n.variantId,(t.get(n.variantId)??0)+n.quantity);if(t.size===0)return;let r=[];for(let n of se()){let o=t.get(n.variantId);if(o===void 0){r.push(n);continue}let i=n.quantity-o;i>0&&r.push({...n,quantity:i})}X(r)}function W(){let e=Ae(ft);return typeof e!="string"||!/^[A-Za-z]{2}$/.test(e)?null:e.toUpperCase()}function jt(e){me(ft,e!==null&&/^[A-Za-z]{2}$/.test(e)?e.toUpperCase():null)}function ge(e){return ze(ft,e)}function Kt(e){let t=[],r=Ae(Bt);if(r)try{let o=JSON.parse(r);Array.isArray(o)&&(t=o.filter(i=>typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.ts=="number"))}catch{}let n=Date.now()-6048e5;return t=t.filter(o=>o.ts>n),t.some(o=>o.id===e)?!1:(t.push({id:e,ts:Date.now()}),t.length>200&&(t=t.slice(-200)),me(Bt,JSON.stringify(t)),!0)}var je="aifeatures_session",mt=null;function Yt(){return mt}function $n(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.token!="string"||t.token.length===0)return null;let r=null;if(typeof t.customer=="object"&&t.customer!==null){let n=t.customer;typeof n.email=="string"&&n.email.length>0&&(r={email:n.email,name:typeof n.name=="string"?n.name:null})}return{token:t.token,customer:r}}function ce(){let e=Ae(je);if(!e)return null;try{return $n(JSON.parse(e))}catch{return null}}function Wt(){return ce()?.token??null}function Ke(e){mt=null,me(je,JSON.stringify(e))}function ee(e){mt=e??null,me(je,null)}function Ht(e){return ze(je,e)}var Bn=1500;function Oe(){try{if(typeof crypto<"u"&&"randomUUID"in crypto)return crypto.randomUUID()}catch{}return`req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function Ye(e,t){return!("requestId"in e)||e.requestId===t}function yt(e,t){return typeof window>"u"||window.self===window.top?Promise.resolve(!1):new Promise(r=>{let n=!1,o=f=>{n||(n=!0,window.removeEventListener("message",i),clearTimeout(l),r(f))},i=f=>{if(f.source!==window.parent)return;let y=f.data;y?.type==="aifeatures:test-checkout-ack"&&Ye(y,t)&&o(y.status==="accepted")},l=setTimeout(()=>o(!1),Bn);window.addEventListener("message",i);try{window.parent.postMessage({type:"aifeatures:test-checkout",requestId:t,...e},"*")}catch{o(!1)}})}function Zt(e){if(window.self!==window.top)try{return window.top.location.href=e,"navigating"}catch{if(window.open(e,"_blank"))return"stayed"}return window.location.href=e,"navigating"}function bt(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=gt(!1),[o,i]=gt(null),[l,f]=gt(null),y=Gt(!1),u=Gt(null);return Jt(()=>{let d=x=>{x.persisted&&(y.current=!1,n(!1))};return window.addEventListener("pageshow",d),()=>window.removeEventListener("pageshow",d)},[]),Jt(()=>{if(typeof window>"u"||window.self===window.top)return;let d=x=>{if(x.source!==window.parent)return;let k=x.data;if(k?.type!=="aifeatures:test-checkout-ack"||k.status!=="failed")return;let p=u.current;p===null||!Ye(k,p)||(u.current=null,i(typeof k.error=="string"&&k.error?k.error:"The test purchase could not be created."),y.current=!1,n(!1))};return window.addEventListener("message",d),()=>window.removeEventListener("message",d)},[]),{startCheckout:Dn(async({productId:d,variantId:x,quantity:k,amount:p,metadata:O,successUrl:w,cancelUrl:b,customerEmail:a,planId:P,expectedUnitAmount:_,expectedCurrency:s})=>{if(!y.current){if(y.current=!0,n(!0),i(null),f(null),P!==void 0){let c=Wt();if(c)try{let m=await fetch(`${t}/v1/account/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify({product_id:d,plan_id:P,...x!==void 0?{variant_id:x}:{},success_url:w??`${window.location.origin}/order/confirmation`,cancel_url:b??window.location.href})}),g=await m.text().catch(()=>""),h=null;try{h=g?JSON.parse(g):null}catch{h=null}if(m.ok){if(!h?.url){i("Checkout failed: no redirect URL returned"),y.current=!1,n(!1);return}Zt(h.url)==="stayed"&&(y.current=!1,n(!1));return}let C=m.status===404&&g.trim()==="";if(m.status===401||C)ee();else{i(h?.error??`Checkout failed (${m.status})`),y.current=!1,n(!1);return}}catch(m){i(m instanceof Error?m.message:"Checkout failed"),y.current=!1,n(!1);return}}try{let c=P===void 0?W():null,m=await fetch(`${t}/v1/p/${d}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...x!==void 0?{variant_id:x}:{},...k!==void 0&&P===void 0?{quantity:k}:{},...p!==void 0?{amount:p}:{},...P!==void 0?{plan_id:P}:{},...O!==void 0?{metadata:O}:{},...a!==void 0?{customer_email:a}:{},..._!==void 0&&s!==void 0&&P===void 0?{expected_unit_amount:_,expected_currency:s}:{},...c!==null?{country:c}:{},success_url:w??`${window.location.origin}/order/confirmation`,cancel_url:b??window.location.href})}),g=await m.json().catch(()=>null);if(!m.ok){if(g?.error==="price_changed"&&typeof g.current_unit_amount=="number"&&typeof g.currency=="string"){f({currentUnitAmount:g.current_unit_amount,currency:g.currency}),i(`The price has changed to ${F(g.current_unit_amount,g.currency)} \u2014 please review and try again.`),y.current=!1,n(!1);return}if(g?.code==="preview_domain"){let h=Oe();if(u.current=h,await yt({productId:d,...x!==void 0?{variantId:x}:{},...k!==void 0&&P===void 0?{quantity:k}:{},...p!==void 0?{amount:p}:{},...P!==void 0?{planId:P}:{},...a!==void 0?{customerEmail:a}:{},...O!==void 0?{metadata:O}:{}},h))return;u.current=null}i(g?.error??`Checkout failed (${m.status})`),y.current=!1,n(!1);return}if(!g?.url){i("Checkout failed: no redirect URL returned"),y.current=!1,n(!1);return}Zt(g.url)==="stayed"&&(y.current=!1,n(!1))}catch(c){i(c instanceof Error?c.message:"Checkout failed"),y.current=!1,n(!1)}}},[t]),loading:r,error:o,priceChange:l}}import{useCallback as We,useEffect as Fn,useState as Qt}from"react";var en=20;function Xt(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.floor(e))}function re(){let[e,t]=Qt([]),[r,n]=Qt(!1);Fn(()=>{let u=()=>t(se());return u(),n(!0),Ft(u)},[]);let o=We(u=>{let v=se(),d=Xt(u.quantity);return v.find(k=>k.variantId===u.variantId)?(X(v.map(k=>k.variantId===u.variantId?{...k,quantity:k.quantity+d,selection:u.selection??k.selection,display:u.display}:k)),{ok:!0}):v.length>=en?{ok:!1,reason:"cart_full"}:(X([...v,{productId:u.productId,variantId:u.variantId,quantity:d,selection:u.selection??{},display:u.display}]),{ok:!0})},[]),i=We(u=>{X(se().filter(v=>v.variantId!==u))},[]),l=We((u,v)=>{let d=se();if(v<=0){X(d.filter(k=>k.variantId!==u));return}let x=Xt(v);X(d.map(k=>k.variantId===u?{...k,quantity:x}:k))},[]),f=We(()=>{X([])},[]),y=e.reduce((u,v)=>u+v.quantity,0);return{items:e,count:y,hydrated:r,add:o,remove:i,setQuantity:l,clear:f}}import{useCallback as zn,useEffect as tn,useMemo as ht,useRef as jn,useState as Te}from"react";var He={image:null,unitAmount:null,currency:null,baseCurrency:null,inStock:!1,available:null,maxQuantity:null,pdpSearch:{},status:"unavailable"},Kn={...He,inStock:!0,status:"error"};function Yn(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function St(e={}){let t=e.apiUrl??"https://aifeatures.dev",{items:r,hydrated:n}=re(),[o,i]=Te({}),[l,f]=Te({shippingRates:null,freeShippingOver:null,shippingCountries:null}),[y,u]=Te(!0),[v,d]=Te(null),[x,k]=Te(0),p=jn(new Set),O=ht(()=>JSON.stringify(r.map(_=>[_.productId,_.variantId,_.selection])),[r]),w=zn(()=>k(_=>_+1),[]);tn(()=>ge(w),[w]),tn(()=>{if(!n)return;if(r.length===0){i({}),f({shippingRates:null,freeShippingOver:null,shippingCountries:null}),d(null),u(!1);return}let _=!1;u(!0);let s=r,c=[...new Set(s.map(g=>g.productId))],m=async g=>{let h=new Map;return await Promise.all(c.map(async C=>{try{let S=await fetch(`${t}/v1/p/${encodeURIComponent(C)}${g?`?country=${encodeURIComponent(g)}`:""}`);if(S.status===404){h.set(C,{kind:"not_found"});return}if(!S.ok){h.set(C,{kind:"error",message:`Request failed (${S.status})`});return}let R=await S.json();h.set(C,{kind:"ok",product:R})}catch(S){h.set(C,{kind:"error",message:S instanceof Error?S.message:"Failed to load product"})}})),h};return(async()=>{let g=W(),h=await m(g);if(g){let A=[...h.values()].filter(U=>U.kind==="ok"),E=A.filter(U=>U.product.base_currency);E.length>0&&E.length<A.length&&(h=await m(null))}if(_)return;let C=null,S=null,R=null;for(let A of c){let E=h.get(A);!E||E.kind!=="ok"||(C===null&&E.product.shipping_rates&&(C=E.product.shipping_rates),S===null&&E.product.free_shipping_over!=null&&(S=E.product.free_shipping_over),R===null&&E.product.shipping_countries&&(R=E.product.shipping_countries))}let T={},q=new Map,K=null;for(let A of s){let E=h.get(A.productId);if(!E||E.kind==="error"){T[A.variantId]=Kn,E&&K===null&&(K=E.message);continue}if(E.kind==="not_found"){T[A.variantId]=He;continue}let{product:U}=E;if(!U.active||U.purchasable===!1){T[A.variantId]=He;continue}let z=U.variants??[],M=z.find(H=>H.id===A.variantId)??null,j=A.variantId;if(!M){let H=le(z,A.selection);if(!H){T[A.variantId]=He;continue}let Mt=q.get(A.variantId)??{};Mt.reanchorTo={variantId:H.id,selection:Yn(H)},q.set(A.variantId,Mt),p.current.add(H.id),M=H,j=H.id}let I=xe(U,A.selection)[0]??null,L={image:I,unitAmount:M.unit_amount,currency:M.currency,baseCurrency:U.base_currency??null,inStock:M.in_stock,available:M.available,maxQuantity:U.max_quantity,pdpSearch:Fe(U,A.selection),status:p.current.has(j)?"reanchored":"ok"};T[A.variantId]=L,T[j]=L;let B=q.get(A.variantId)??{};B.display={name:U.name,variantTitle:M.title,image:I},q.set(A.variantId,B)}let D=new Set(s.map(A=>A.variantId));for(let A of[...p.current])!D.has(A)&&!(A in T)&&p.current.delete(A);if(q.size>0){let A=se(),E=[],U=new Map,z=!1;for(let M of A){let j=q.get(M.variantId),I={...M};j?.reanchorTo&&(I.variantId=j.reanchorTo.variantId,I.selection=j.reanchorTo.selection,z=!0),j?.display&&(I.display.name!==j.display.name||I.display.variantTitle!==j.display.variantTitle||I.display.image!==j.display.image)&&(I.display=j.display,z=!0);let L=U.get(I.variantId);if(L){L.quantity+=I.quantity,z=!0;continue}E.push(I),U.set(I.variantId,I)}z&&X(E)}_||(i(T),f({shippingRates:C,freeShippingOver:S,shippingCountries:R}),d(K),u(!1))})(),()=>{_=!0}},[n,O,t,x]);let b=ht(()=>r.map(_=>{let s=o[_.variantId];return s?{..._,...s,image:s.image??_.display.image}:{..._,image:_.display.image,unitAmount:null,currency:null,baseCurrency:null,inStock:!0,available:null,maxQuantity:null,pdpSearch:{},status:"ok"}}),[r,o]),{subtotal:a,currency:P}=ht(()=>{let _=0,s=null;for(let c of b)c.unitAmount===null||c.currency===null||(_+=c.unitAmount*c.quantity,s=s??c.currency);return{subtotal:_,currency:s}},[b]);return{lines:b,subtotal:a,currency:P,shippingRates:l.shippingRates,freeShippingOver:l.freeShippingOver,shippingCountries:l.shippingCountries,loading:y,error:v,refresh:w}}import{useCallback as Wn,useEffect as nn,useMemo as Hn,useRef as vt,useState as Le}from"react";var Jn=2e3;function Gn(e={}){let t=e.apiUrl??"https://aifeatures.dev",r=e.debounceMs??250,n=e.shippingOption??null,{items:o,hydrated:i}=re(),[l,f]=Le(null),[y,u]=Le(!1),[v,d]=Le(null),[x,k]=Le(null),[p,O]=Le(0);nn(()=>(k(W()),ge(()=>k(W()))),[]);let w=Hn(()=>o.map(s=>`${s.variantId}:${s.quantity}`).sort().join(","),[o]),b=Wn(()=>O(s=>s+1),[]),a=vt(0),P=vt(!1),_=vt("idle");return nn(()=>{if(!i)return;if(o.length===0){f(null),d(null),u(!1);return}let s=++a.current,c=new AbortController,m=!1,g,h=P.current?r:0;P.current=!0,_.current=_.current==="pending"?"spent":"idle";let C=setTimeout(async()=>{u(!0);try{let S=await fetch(`${t}/v1/p/checkout/summary`,{method:"POST",headers:{"Content-Type":"application/json"},signal:c.signal,body:JSON.stringify({items:o.map(T=>({variant_id:T.variantId,quantity:T.quantity})),...x?{country:x}:{},...n?{shipping_option:n}:{}})});if(m||s!==a.current)return;if(!S.ok){if(S.status===429){let T=_.current==="idle";T&&(g=setTimeout(()=>{m||s!==a.current||(_.current="pending",O(q=>q+1))},Jn)),d(T?"Too many updates \u2014 retrying shortly":"Too many updates \u2014 the total will refresh on the next cart change")}else d(`Could not price this cart (${S.status})`);return}let R=await S.json();if(m||s!==a.current)return;f({currency:R.currency,subtotal:R.subtotal,shipping:R.shipping?{options:R.shipping.options.map(T=>({label:T.label,amount:T.amount,undiscountedAmount:T.undiscounted_amount})),selectedAmount:R.shipping.selected_amount,selectedLabel:R.shipping.selected_label,freeShippingOver:R.shipping.free_shipping_over,freeShippingCurrency:R.shipping.free_shipping_currency,thresholdMet:R.shipping.threshold_met,collectsAddress:R.shipping.collects_address}:null,total:R.total,totalIsFinal:R.total_is_final,tax:R.tax??null,unavailableVariantIds:R.unavailable_variant_ids}),d(null)}catch(S){if(m||c.signal.aborted||s!==a.current)return;d(S instanceof Error?S.message:"Could not price this cart")}finally{!m&&s===a.current&&u(!1)}},h);return()=>{m=!0,clearTimeout(C),g!==void 0&&clearTimeout(g),c.abort()}},[i,w,x,t,r,n,p]),{summary:l,loading:y,error:v,refresh:b}}import{useCallback as Zn,useEffect as rn,useRef as on,useState as Je}from"react";function kt(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Je(!1),[o,i]=Je(null),[l,f]=Je(null),[y,u]=Je(null),v=on(!1),d=on(null);return rn(()=>{let k=p=>{p.persisted&&(v.current=!1,n(!1))};return window.addEventListener("pageshow",k),()=>window.removeEventListener("pageshow",k)},[]),rn(()=>{if(typeof window>"u"||window.self===window.top)return;let k=p=>{if(p.source!==window.parent)return;let O=p.data;if(O?.type!=="aifeatures:test-checkout-ack"||O.status!=="failed")return;let w=d.current;w===null||!Ye(O,w)||(d.current=null,i(typeof O.error=="string"&&O.error?O.error:"The test purchase could not be created."),v.current=!1,n(!1))};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),{startCheckout:Zn(async(k,{successUrl:p,cancelUrl:O,customerEmail:w,metadata:b,shippingOption:a}={})=>{if(!v.current){v.current=!0,n(!0),i(null),f(null),u(null);try{let P=W(),_=await fetch(`${t}/v1/p/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:k.map(c=>({variant_id:c.variantId,quantity:c.quantity,...typeof c.unitAmount=="number"&&typeof c.currency=="string"?{expected_unit_amount:c.unitAmount,expected_currency:c.currency}:{}})),...P!==null?{country:P}:{},...a?{shipping_option:a}:{},...b!==void 0?{metadata:b}:{},...w!==void 0?{customer_email:w}:{},success_url:p??`${window.location.origin}/order/confirmation`,cancel_url:O??window.location.href})}),s=await _.json().catch(()=>null);if(!_.ok){if(s?.code==="shipping_option_unavailable"&&typeof s.requested=="string"&&Array.isArray(s.available)){u({requested:s.requested,available:s.available,currency:typeof s.currency=="string"?s.currency:""}),v.current=!1,n(!1);return}if(s?.error==="cart_conflict"&&Array.isArray(s.items)){let c={};for(let m of s.items)m&&typeof m.variant_id=="string"&&(c[m.variant_id]=m);f(c),v.current=!1,n(!1);return}if(s?.code==="preview_domain"){let c=Oe();if(d.current=c,await yt({items:k.map(g=>({productId:g.productId,variantId:g.variantId,quantity:g.quantity})),...w!==void 0?{customerEmail:w}:{},...b!==void 0?{metadata:b}:{}},c))return;d.current=null}i(s?.error??`Checkout failed (${_.status})`),v.current=!1,n(!1);return}if(!s?.url){i("Checkout failed: no redirect URL returned"),v.current=!1,n(!1);return}if(window.self!==window.top)try{window.top.location.href=s.url;return}catch{if(window.open(s.url,"_blank")){v.current=!1,n(!1);return}}window.location.href=s.url}catch(P){i(P instanceof Error?P.message:"Checkout failed"),v.current=!1,n(!1)}}},[t]),loading:r,error:o,conflicts:l,shippingConflict:y}}import{useCallback as Qn,useEffect as sn,useState as Ct}from"react";var wt=[{country:"US",currency:"usd"},{country:"GB",currency:"gbp"},{country:"CA",currency:"cad"},{country:"AU",currency:"aud"},{country:"NZ",currency:"nzd"},{country:"JP",currency:"jpy"},{country:"CH",currency:"chf"},{country:"SE",currency:"sek"},{country:"NO",currency:"nok"},{country:"DK",currency:"dkk"},{country:"PL",currency:"pln"},{country:"CZ",currency:"czk"},{country:"SG",currency:"sgd"},{country:"HK",currency:"hkd"},{country:"MX",currency:"mxn"},{country:"BR",currency:"brl"},{country:"IN",currency:"inr"},{country:"ZA",currency:"zar"},{country:"AE",currency:"aed"},{country:"IL",currency:"ils"},{country:"AT",currency:"eur"},{country:"BE",currency:"eur"},{country:"HR",currency:"eur"},{country:"CY",currency:"eur"},{country:"EE",currency:"eur"},{country:"FI",currency:"eur"},{country:"FR",currency:"eur"},{country:"DE",currency:"eur"},{country:"GR",currency:"eur"},{country:"IE",currency:"eur"},{country:"IT",currency:"eur"},{country:"LV",currency:"eur"},{country:"LT",currency:"eur"},{country:"LU",currency:"eur"},{country:"MT",currency:"eur"},{country:"NL",currency:"eur"},{country:"PT",currency:"eur"},{country:"SK",currency:"eur"},{country:"SI",currency:"eur"},{country:"ES",currency:"eur"}];function an(e){return e?wt.find(t=>t.country===e.toUpperCase())?.currency??null:null}var un=new Map;function Xn(e){let t=un.get(e);return t||(t=fetch(`${e}/v1/geo`).then(async r=>{if(!r.ok)return null;let n=await r.json().catch(()=>null);return typeof n?.country=="string"&&/^[A-Za-z]{2}$/.test(n.country)?n.country.toUpperCase():null}).catch(()=>null),un.set(e,t)),t}function er(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Ct(null),[o,i]=Ct(!1),[l,f]=Ct(null);sn(()=>{let d=()=>n(W());return d(),i(!0),ge(d)},[]),sn(()=>{let d=!1;return Xn(t).then(x=>{d||f(x)}),()=>{d=!0}},[t]);let y=Qn(d=>{jt(d)},[]),u=an(l),v=o&&u!==null&&u!==an(r);return{market:r,suggestedCountry:l,setMarket:y,markets:wt,shouldPrompt:v}}import{jsx as Pt,jsxs as rr}from"react/jsx-runtime";var tr={textDecoration:"line-through",opacity:.6,marginRight:"0.4em"};function nr({productId:e,variantId:t,apiUrl:r,locale:n,className:o,style:i,compareAtClassName:l}){let{product:f,loading:y}=ue(e,{apiUrl:r});if(y||!f)return null;let u=oe(f),v=t!==void 0?u.find(x=>x.id===t)??null:f.options.length===0?u[0]??null:null;if(v){if(v.unit_amount===null)return null;let x=v.compare_at_amount!==null&&v.compare_at_amount>v.unit_amount;return rr("span",{className:o,style:i,children:[x&&Pt("span",{className:l,style:l?void 0:tr,children:F(v.compare_at_amount,v.currency,n)}),F(v.unit_amount,v.currency,n)]})}let d=ut(u);return d?Pt("span",{className:o,style:i,children:d.min===d.max?F(d.min,f.currency,n):`${F(d.min,f.currency,n)} \u2013 ${F(d.max,f.currency,n)}`}):f.unit_amount===null?null:Pt("span",{className:o,style:i,children:F(f.unit_amount,f.currency,n)})}import{useEffect as _t,useMemo as ir,useRef as ln,useState as cn}from"react";import{Fragment as br,jsx as ye,jsxs as dn}from"react/jsx-runtime";var or={marginBottom:"0.75rem"},sr={display:"block",fontSize:"0.875rem",fontWeight:600,marginBottom:"0.375rem"},ar={display:"flex",flexWrap:"wrap",gap:"0.5rem"},ur={padding:"0.375rem 0.75rem",border:"1px solid #d1d5db",borderRadius:6,background:"white",cursor:"pointer",fontSize:"0.875rem"},lr={borderColor:"#111827",boxShadow:"inset 0 0 0 1px #111827",fontWeight:600},pn={opacity:.4,textDecoration:"line-through",cursor:"not-allowed"},cr={...pn,cursor:"pointer"},dr=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,pr=e=>dr.test(e),fr={padding:"0.375rem",width:"2.25rem",height:"2.25rem",lineHeight:0},mr={display:"block",width:"1.5rem",height:"1.5rem",maxWidth:"100%",maxHeight:"100%",boxSizing:"border-box",borderRadius:3,backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f3f4f6",border:"1px solid rgba(0, 0, 0, 0.2)"},gr="linear-gradient(to top right, transparent calc(50% - 2px), rgba(0,0,0,0.55) calc(50% - 2px), rgba(255,255,255,0.95) calc(50% - 1px), rgba(255,255,255,0.95) calc(50% + 1px), rgba(0,0,0,0.55) calc(50% + 1px), transparent calc(50% + 2px))";function yr({options:e,variants:t,value:r,syncUrl:n=!0,onChange:o,onVariantChange:i,className:l,style:f,optionClassName:y,optionLabelClassName:u,valueClassName:v,selectedValueClassName:d,unavailableValueClassName:x,swatchClassName:k}){let p=r!==void 0,[O,w]=cn(r??{}),b=p?r:O,[a,P]=cn(()=>new Set),_=h=>P(C=>C.has(h)?C:new Set(C).add(h));_t(()=>{P(h=>h.size===0?h:new Set)},[e]);let s=ln(!1);_t(()=>{if(!n||p||s.current||e.length===0||typeof window>"u"||(s.current=!0,Object.keys(O).length>0))return;let h=lt({options:e},window.location.search);Object.keys(h).length!==0&&(w(h),o?.(h))},[n,p,e]);let c=ir(()=>e.length>0?t.filter(h=>h.option_values.length===e.length):t,[t,e]),m=ln(void 0);if(_t(()=>{let h=le(c,b),C=h?.id??null;m.current!==C&&(m.current=C,i?.(h))},[c,b]),e.length===0)return null;let g=(h,C)=>{let S=at(c,b,h,C);p||(w(S),n&&ct({options:e},S)),o?.(S)};return ye("div",{className:l,style:f,children:e.map(h=>dn("div",{className:y,style:y?void 0:or,children:[ye("span",{className:u,style:u?void 0:sr,children:h.title}),ye("div",{style:ar,children:h.values.map(C=>{let S=b[h.id]===C.id,R=ot(c,b,h.id,C.id),T=R||st(c,h.id,C.id),q=[v,S?d:void 0,R?void 0:x].filter(Boolean).join(" ")||void 0,K=C.swatch??null,D=K&&!a.has(K)?K:null,A=D?pr(D):!1,E=v?void 0:{...ur,...S?lr:{},...R?{}:T?cr:pn,...D?{...fr,textDecoration:"none"}:{}},U=R?C.value:`${C.value} \u2014 unavailable with your current selection`;return ye("button",{type:"button",className:q,style:E,disabled:!T,"aria-pressed":S,"aria-label":D?U:void 0,title:D?U:void 0,"data-selected":S?"true":void 0,"data-available":R?"true":"false","data-swatch":D?A?"hex":"image":void 0,onClick:()=>g(h.id,C.id),children:D?dn(br,{children:[ye("span",{"aria-hidden":"true",className:k,style:k?void 0:{...mr,...A?{background:D}:{},...A&&R?{}:{backgroundImage:[...R?[]:[gr],...A?[]:[`url(${JSON.stringify(D)})`]].join(", ")}}}),A?null:ye("img",{src:D,alt:"","aria-hidden":"true",referrerPolicy:"no-referrer",style:{display:"none"},onError:()=>_(D)})]}):C.value},C.id)})})]},h.id))})}import{useEffect as hr}from"react";import{Fragment as xt,jsx as de,jsxs as Ie}from"react/jsx-runtime";var Sr={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"},vr={background:"none",border:"none",padding:0,marginLeft:"0.35em",font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"};function fn(){return Ie("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",style:{display:"inline-block",marginRight:"0.5em",verticalAlign:"-0.125em",flexShrink:0},children:[de("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),de("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:de("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function kr({productId:e,variantId:t,quantity:r,planId:n,amount:o,metadata:i,successUrl:l,cancelUrl:f,customerEmail:y,apiUrl:u,disabled:v,className:d,style:x,errorClassName:k,spinner:p=!0,children:O}){let{product:w,loading:b,error:a,refresh:P}=ue(e,{apiUrl:u}),{startCheckout:_,loading:s,error:c,priceChange:m}=bt({apiUrl:u});hr(()=>{m&&P()},[m,P]);let g=w!==null&&!w.payments_ready,h=w!==null&&!w.active,C=w!==null&&w.purchasable===!1,S=w!==null&&_e(w),R=w!==null?oe(w):[],T=t!==void 0?R.find(L=>L.id===t)??null:!S&&R.length===1?R[0]:null,q=S&&!T,K=T!==null&&!T.in_stock,D=n??void 0,A=w?.subscription??null,E=A!==null&&A.required&&!A.ready,U=A!==null&&A.required&&A.ready&&D===void 0,z=!!v||b||!w||g||h||C||E||U||q||K||s,M;s?M=Ie(xt,{children:[p&&de(fn,{}),"Processing\u2026"]}):b?M=Ie(xt,{children:[p&&de(fn,{}),O??"Buy now"]}):g?M="Payments not set up":h||C?M="Unavailable":E?M="Currently unavailable":U?M="Select a plan":q?M="Select options":K?M="Out of stock":O!==void 0?M=O:D!==void 0?M="Subscribe":M="Buy now";let j=c??a;return Ie(xt,{children:[de("button",{type:"button",className:d,style:x,disabled:z,onClick:()=>{let L=o===void 0&&D===void 0&&W()===null&&T!==null&&!T.allow_custom_amount&&typeof T.unit_amount=="number"?{expectedUnitAmount:T.unit_amount,expectedCurrency:T.currency}:{};_({productId:e,variantId:t,quantity:D!==void 0?void 0:r,amount:o,planId:D,metadata:i,successUrl:l,cancelUrl:f,customerEmail:y,...L})},children:M}),j&&Ie("div",{role:"alert",className:k,style:k?void 0:Sr,children:[j,w===null&&!b&&a!==null&&de("button",{type:"button",onClick:P,style:vr,children:"Tap to retry"})]})]})}import{useEffect as Cr,useRef as wr,useState as mn}from"react";import{Fragment as gn,jsx as be,jsxs as Ge}from"react/jsx-runtime";var Pr={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"},_r={background:"none",border:"none",padding:0,marginLeft:"0.35em",font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"},xr=1500;function Rr(){return Ge("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",style:{display:"inline-block",marginRight:"0.5em",verticalAlign:"-0.125em",flexShrink:0},children:[be("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),be("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:be("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function Ar(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function Or({productId:e,variantId:t,selection:r,quantity:n,apiUrl:o,disabled:i,className:l,style:f,errorClassName:y,spinner:u=!0,children:v}){let{product:d,loading:x,error:k,refresh:p}=ue(e,{apiUrl:o}),{add:O}=re(),[w,b]=mn(!1),[a,P]=mn(!1),_=wr(void 0);Cr(()=>()=>{_.current&&clearTimeout(_.current)},[]);let s=d!==null&&!d.payments_ready,c=d!==null&&!d.active,m=d!==null&&d.purchasable===!1,g=d!==null&&!x&&oe(d).length===0,h=d!==null&&d.allow_custom_amount,C=d!==null&&_e(d),S=d!==null?oe(d):[],R=t!==void 0?S.find(z=>z.id===t)??null:r!==void 0&&C?le(S,r):!C&&S.length===1?S[0]:null,T=d!==null&&!g&&!R,q=R!==null&&!R.in_stock,K=!!i||x||!d||s||c||m||g||h||T||q,D=()=>{if(!d||!R)return;let z=r??Ar(R);if(!O({productId:e,variantId:R.id,quantity:n,selection:z,display:{name:d.name,variantTitle:R.title,image:xe(d,z)[0]??null}}).ok){b(!0);return}b(!1),P(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>P(!1),xr)},A;x?A=Ge(gn,{children:[u&&be(Rr,{}),v??"Add to cart"]}):s?A="Payments not set up":c||m||g||h?A="Unavailable":T?A="Select options":q?A="Out of stock":a?A="Added to cart":v!==void 0?A=v:A="Add to cart";let E=w?"Your cart is full \u2014 remove an item before adding another.":k;return Ge(gn,{children:[be("button",{type:"button",className:l,style:f,disabled:K,"data-added":a?"true":void 0,onClick:D,children:A}),E&&Ge("div",{role:"alert",className:y,style:y?void 0:Pr,children:[E,d===null&&!x&&k!==null&&!w&&be("button",{type:"button",onClick:p,style:_r,children:"Tap to retry"})]})]})}import{Fragment as Rt,jsx as ae,jsxs as Ze}from"react/jsx-runtime";var yn={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"};function bn(){return Ze("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",focusable:"false",style:{display:"inline-block",marginRight:"0.5em",verticalAlign:"-0.125em",flexShrink:0},children:[ae("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),ae("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:ae("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function Tr({apiUrl:e,successUrl:t,cancelUrl:r,customerEmail:n,metadata:o,shippingOption:i,disabled:l,className:f,style:y,errorClassName:u,spinner:v=!0,children:d}){let{items:x,hydrated:k}=re(),{lines:p}=St({apiUrl:e}),{startCheckout:O,loading:w,error:b,conflicts:a}=kt({apiUrl:e}),P=k&&x.length===0,_=p.some(g=>g.status==="unavailable"),s=!!l||!k||P||_||w,c;w?c=Ze(Rt,{children:[v&&ae(bn,{}),"Processing\u2026"]}):k?P?c="Cart is empty":_?c="Remove unavailable items":d!==void 0?c=d:c="Checkout":c=Ze(Rt,{children:[v&&ae(bn,{}),d??"Checkout"]});let m=a?Object.keys(a).length:0;return Ze(Rt,{children:[ae("button",{type:"button",className:f,style:y,disabled:s,onClick:()=>O(p,{successUrl:t,cancelUrl:r,customerEmail:n,metadata:o,shippingOption:i}),children:c}),m>0&&ae("div",{role:"alert",className:u,style:u?void 0:yn,children:m===1?"An item in your cart changed \u2014 please review your cart and try again.":`${m} items in your cart changed \u2014 please review your cart and try again.`}),b&&ae("div",{role:"alert",className:u,style:u?void 0:yn,children:b})]})}import{useEffect as Qe,useRef as hn,useState as At}from"react";import{Fragment as he,jsx as $,jsxs as G}from"react/jsx-runtime";var Ot="af_order_confirmation_session",Lr=1800*1e3;function Ir({apiUrl:e="https://aifeatures.dev",className:t,style:r,sessionId:n,pollIntervalMs:o=2e3,pollTimeoutMs:i=6e4,followRedirect:l=!0,redirectDelayMs:f=1500,renderNoSession:y,renderPending:u,renderPaid:v,renderFailed:d}){let[x,k]=At(n),[p,O]=At(null),[w,b]=At(!1),a=hn(void 0);Qe(()=>{if(n!==void 0){k(n);return}if(a.current!==void 0){k(a.current);return}let c=new URL(window.location.href),m=c.searchParams.get("session_id");if(m){c.searchParams.delete("session_id"),window.history.replaceState(window.history.state,"",c.toString());try{sessionStorage.setItem(Ot,JSON.stringify({id:m,ts:Date.now()}))}catch{}}else try{let g=sessionStorage.getItem(Ot);if(g){let h=JSON.parse(g);typeof h.id=="string"&&typeof h.ts=="number"&&Date.now()-h.ts<=Lr?m=h.id:sessionStorage.removeItem(Ot)}}catch{}a.current=m,k(m)},[n]),Qe(()=>{if(!x)return;let c=!1,m,g=Date.now(),h=async()=>{try{let C=await fetch(`${e}/v1/o/session/${encodeURIComponent(x)}`);if(C.ok){let S=await C.json();if(c||(O(S),S.status!=="pending"))return}}catch{}if(!c){if(Date.now()-g>=i){b(!0);return}m=setTimeout(h,o)}};return h(),()=>{c=!0,m&&clearTimeout(m)}},[x,e,o,i]);let P=p!==null&&(p.status==="paid"||p.status==="partially_refunded"),_=hn(!1);Qe(()=>{if(!x||p===null||_.current||!(p.status==="paid"||p.status==="partially_refunded"||p.is_test===!0)||(_.current=!0,!Kt(x)))return;let m=(p.line_items??[]).filter(g=>typeof g.variant_id=="string"&&g.variant_id.length>0).map(g=>({variantId:g.variant_id,quantity:g.quantity}));m.length>0&&zt(m)},[x,p]);let s=P&&p.fulfillment.type==="redirect"?p.fulfillment.redirect_url:void 0;if(Qe(()=>{if(!s||!l)return;let c=setTimeout(()=>{window.location.href=s},f);return()=>clearTimeout(c)},[s,l,f]),x===void 0)return null;if(x===null)return y?$(he,{children:y()}):G("div",{className:t,style:r,children:[$("h2",{children:"Thank you for your order!"}),$("p",{children:"If you completed a payment, a confirmation email with your receipt and any download links is on its way to you. This page can only show live order details right after checkout."})]});if(!p||p.status==="pending")return u?$(he,{children:u({timedOut:w})}):$("div",{className:t,style:r,role:"status",children:$("p",{children:w?"This is taking longer than expected. You will receive an email confirmation once your payment is processed.":"Confirming your payment\u2026"})});if(P){if(v)return $(he,{children:v(p)});let{fulfillment:c}=p,m=p.amount_total!==void 0&&p.currency?F(p.amount_total,p.currency):null,g=c.files??[],h=g.length===0?c.download_url:void 0;return G("div",{className:t,style:r,children:[$("h2",{children:"Thank you for your purchase!"}),p.is_test&&G("p",{children:[$("strong",{children:"Test purchase"})," \u2014 no payment was collected."]}),p.line_items&&p.line_items.length>0&&$("ul",{children:p.line_items.map((C,S)=>G("li",{children:[C.quantity>1?`${C.quantity} \xD7 `:"",C.name,C.refunded&&$("em",{children:C.refund_reason==="oversold"?" \u2014 sold out and refunded; check your email for details":" \u2014 refunded"})]},S))}),m&&G("p",{children:["Total paid: ",m]}),p.source==="subscription"&&p.subscription&&G(he,{children:[G("p",{children:["Your subscription renews"," ",p.subscription.interval_count>1?`every ${p.subscription.interval_count} ${p.subscription.interval}s`:`every ${p.subscription.interval}`," ","at"," ",F(p.subscription.amount,p.subscription.currency),"."]}),G("p",{children:["You can view, update, or cancel it any time on"," ",$("a",{href:"/account",children:"your account page"})," \u2014 sign in with the email you used at checkout."]})]}),g.length>0&&G(he,{children:[$("p",{children:"Your downloads:"}),$("ul",{children:g.map((C,S)=>$("li",{children:$("a",{href:C.download_url,children:C.name})},S))})]}),h&&$("p",{children:$("a",{href:h,children:"Download your file"})}),s?G("p",{children:["Taking you to your content\u2026"," ",$("a",{href:s,children:"Continue if you are not redirected"})]}):c.redirect_url?$("p",{children:$("a",{href:c.redirect_url,children:"Continue to your content"})}):null,g.length===0&&!h&&!c.redirect_url&&$("p",{children:"A confirmation email is on its way to you."}),p.order_id&&G("p",{children:["Order reference: ",$("code",{children:p.order_id})," \u2014 keep this if you ever need help with your order."]})]})}return d?$(he,{children:d(p)}):$("div",{className:t,style:r,children:$("p",{children:"We couldn't confirm your payment. If you were charged, you'll receive an email confirmation \u2014 otherwise you can safely try again."})})}import{useEffect as Er,useState as Ur}from"react";import{Fragment as $r,jsx as Se}from"react/jsx-runtime";function Sn(e,t){if(t.unit_amount!==null&&t.unit_amount!==void 0)return t.unit_amount;let r=t.percent_off_bps??0;return e-Math.floor(e*r/1e4)}function Tt(e){return e.interval_count>1?`every ${e.interval_count} ${e.interval}s`:`every ${e.interval}`}var Nr={display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"0.75rem"},Mr={display:"block",width:"100%",textAlign:"left",padding:"0.5rem 0.75rem",border:"1px solid #d1d5db",borderRadius:6,background:"white",cursor:"pointer",fontSize:"0.875rem"},Vr={borderColor:"#111827",boxShadow:"inset 0 0 0 1px #111827",fontWeight:600};function qr({product:e,subscription:t,baseUnitAmount:r,currency:n,value:o,onChange:i,className:l,style:f,optionClassName:y,selectedOptionClassName:u,oneTimeLabel:v,renderOption:d,renderUnavailable:x}){let k=t??e?.subscription??null,p=k?.required===!0,O=k?.ready===!0,w=[...k?.plans??[]].sort((S,R)=>S.position-R.position),[b,a]=Ur(null),P=o!==void 0,_=P?o:b,s=w.map(S=>S.id).join("|"),c=w.length>0?w[0].id:null;if(Er(()=>{if(!(!p||!O)&&!(_!==null&&w.some(S=>S.id===_))){if(c===null){if(_===null)return;P||a(null),i?.(null);return}P||a(c),i?.(c)}},[p,O,c,s,_,P]),!k)return null;if(!O)return p?x?Se($r,{children:x()}):Se("div",{className:l,style:f,"data-state":"unavailable",children:Se("p",{children:"This product is currently unavailable."})}):null;if(w.length===0)return null;let m=e?.base_currency!==void 0&&e?.base_currency!==null,g=r!==void 0?r:m?null:e?.unit_amount??null,h=n??e?.base_currency??e?.currency??"usd",C=[];if(!p){let S=g;C.push({plan:null,selected:_===null,price:S,priceLabel:S!==null?F(S,h):null,label:"One-time purchase",select:()=>{P||a(null),i?.(null)}})}for(let S of w){let R=S.unit_amount!==null?S.unit_amount:g!==null?Sn(g,S):null,T=R!==null?F(R,h):null,q=S.title&&S.title.trim().length>0?S.title.trim():`Subscribe ${Tt(S)}`,K=T?`${q} \u2014 ${T} ${Tt(S)}`:`${q} \u2014 billed ${Tt(S)}`;C.push({plan:S,selected:_===S.id,price:R,priceLabel:T,label:K,select:()=>{P||a(S.id),i?.(S.id)}})}return Se("div",{role:"radiogroup","aria-label":"Purchase options",className:l,style:l?f:{...Nr,...f},children:C.map(S=>{if(d)return Se("span",{style:{display:"contents"},children:d(S)},S.plan?.id??"one-time");let R=S.selected;return Se("button",{type:"button",role:"radio","aria-checked":R,"data-selected":R?"true":void 0,"data-plan-id":S.plan?.id,className:[y,R?u:void 0].filter(Boolean).join(" ")||void 0,style:y?void 0:{...Mr,...R?Vr:{}},onClick:S.select,children:S.plan===null&&v!==void 0?v:S.plan===null?S.priceLabel?`One-time purchase \u2014 ${S.priceLabel}`:"One-time purchase":S.label},S.plan?.id??"one-time")})})}import{useCallback as Xe,useEffect as kn,useRef as Dr,useState as et}from"react";async function Z(e,t,r={}){let n;try{n=await fetch(`${e}${t}`,{method:r.method??"GET",headers:{...r.body!==void 0?{"Content-Type":"application/json"}:{},...r.token?{Authorization:`Bearer ${r.token}`}:{}},...r.body!==void 0?{body:JSON.stringify(r.body)}:{}})}catch(u){return{ok:!1,failure:{kind:"network",error:u instanceof Error?u.message:"Network error"}}}let o=await n.text().catch(()=>""),i=null;try{i=o?JSON.parse(o):null}catch{i=null}let l=typeof i=="object"&&i!==null?i:null;if(n.ok)return l===null?{ok:!1,failure:{kind:"parse_error",error:"The server sent an unreadable response \u2014 please try again"}}:{ok:!0,data:l};if(n.status===404&&o.trim()==="")return{ok:!1,failure:{kind:"unavailable"}};let f=typeof l?.code=="string"?l.code:null,y=typeof l?.error=="string"&&l.error?l.error:`Request failed (${n.status})`;return n.status===401?{ok:!1,failure:{kind:"unauthorized",code:f,error:y}}:{ok:!1,failure:{kind:"http",status:n.status,code:f,error:y}}}function vn(e,t){return t>1?`every ${t} ${e}s`:`every ${e}`}function Ee(e){if(!e)return null;let t=e.includes("T")?e:e.replace(" ","T")+"Z",r=Date.parse(t);if(Number.isNaN(r))return null;try{return new Date(r).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"})}catch{return null}}var Br=1500;function Cn(e){if(!e)return!1;try{return e.self!==e.top}catch{return!0}}function Fr(e,t){return e.requestId===t}function zr(e,t){return typeof window>"u"||!Cn(window)?Promise.resolve({claimed:!1}):new Promise(r=>{let n=!1,o=f=>{n||(n=!0,window.removeEventListener("message",i),clearTimeout(l),r(f))},i=f=>{if(f.source!==window.parent)return;let y=f.data;if(y?.type==="aifeatures:preview-session-ack"&&Fr(y??{},t)){if(typeof y.token=="string"&&y.token.length>0){let u=null;if(typeof y.customer=="object"&&y.customer!==null){let v=y.customer;typeof v.email=="string"&&(u={email:v.email,name:typeof v.name=="string"?v.name:null})}o({claimed:!0,token:y.token,customer:u});return}o({claimed:!0,token:null,customer:null,error:typeof y.error=="string"&&y.error?y.error:"The preview sign-in could not be created."})}},l=setTimeout(()=>o({claimed:!1}),Br);window.addEventListener("message",i);try{window.parent.postMessage({type:"aifeatures:preview-session",requestId:t,email:e},"*")}catch{o({claimed:!1})}})}function Ue(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=et(()=>ce()),[o,i]=et(null),[l,f]=et(!1),[y,u]=et(!1),v=Dr(void 0);kn(()=>Ht(()=>{let b=ce();n(b),i(b===null?a=>Yt()??a:null)}),[]);let d=Xe(async b=>{u(!0);try{let a=await Z(t,"/v1/account/verify",{method:"POST",body:{code:b}});if(a.ok&&typeof a.data.token=="string"){let _=a.data.customer&&typeof a.data.customer.email=="string"?{email:a.data.customer.email,name:typeof a.data.customer.name=="string"?a.data.customer.name:null}:null;return Ke({token:a.data.token,customer:_}),n({token:a.data.token,customer:_}),i(null),f(!1),{ok:!0}}return!a.ok&&a.failure.kind==="unavailable"?(f(!0),{ok:!1,code:"unavailable",error:"Sign-in is temporarily unavailable \u2014 please try again later."}):!a.ok&&a.failure.kind==="http"&&a.failure.status===429?{ok:!1,code:"rate_limited",error:a.failure.error}:!a.ok&&(a.failure.kind==="http"||a.failure.kind==="unauthorized")&&a.failure.code==="invalid_code"?(i("invalid_code"),{ok:!1,code:"invalid_code",error:a.failure.error}):{ok:!1,code:"error",error:a.ok||a.failure.kind==="unavailable"?"Sign-in failed \u2014 please request a new link.":a.failure.error}}finally{u(!1)}},[t]),x=e.consumeUrlCode??!0;kn(()=>{if(!(typeof window>"u")&&v.current===void 0){if(!x){v.current=null;return}let b=new URL(window.location.href),a=b.searchParams.get("code");a&&(b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString())),v.current=a,a&&d(a)}},[d,x]);let k=Xe(async b=>{if(typeof window<"u"&&Cn(window)){let P=await zr(b,Oe());if(P.claimed){if(P.token!==null){let _=P.customer??{email:b,name:null};return Ke({token:P.token,customer:_}),n({token:P.token,customer:_}),i(null),{ok:!0,via:"preview"}}return{ok:!1,code:"error",error:P.error}}}let a=await Z(t,"/v1/account/login",{method:"POST",body:{email:b}});return a.ok?{ok:!0,via:"email"}:a.failure.kind==="unavailable"?(f(!0),{ok:!1,code:"unavailable",error:"Sign-in is temporarily unavailable \u2014 please try again later."}):a.failure.kind==="http"&&a.failure.status===429?{ok:!1,code:"rate_limited",error:a.failure.error}:{ok:!1,code:"error",error:(a.failure.kind==="network",a.failure.error)}},[t]),p=Xe(async()=>{let b=ce()?.token;b&&await Z(t,"/v1/account/logout",{method:"POST",token:b,body:{}}),ee(),n(null),i(null)},[t]),O=Xe(async()=>{let b=ce();if(!b)return;let a=await Z(t,"/v1/account/me",{token:b.token}),P=()=>ce()?.token===b.token;if(a.ok){if(!P())return;let _=a.data.customer??b.customer;Ke({token:b.token,customer:_}),n({token:b.token,customer:_}),f(!1);return}if(a.failure.kind==="unauthorized"){if(!P())return;ee("session_expired"),n(null),i("session_expired");return}if(a.failure.kind==="unavailable"){f(!0);return}},[t]);return{status:y?"pending":r?"signed_in":l?"unavailable":"signed_out",customer:r?.customer??null,token:r?.token??null,reason:r?null:o,login:k,verifyCode:d,logout:p,refresh:O}}import{useCallback as Ve,useEffect as Nt,useRef as rt,useState as qe}from"react";import{useEffect as jr,useRef as wn,useState as ve}from"react";import{Fragment as It,jsx as Y,jsxs as Ne}from"react/jsx-runtime";var Lt={display:"flex",flexDirection:"column",gap:"0.75rem",maxWidth:"24rem"},Kr={padding:"0.5rem 0.75rem",border:"1px solid #d1d5db",borderRadius:6,fontSize:"1rem"},Yr={padding:"0.5rem 0.75rem",border:"1px solid #111827",borderRadius:6,background:"#111827",color:"white",cursor:"pointer",fontSize:"1rem"},Pn={background:"none",border:"none",padding:0,font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"},ke={margin:0},Wr={color:"#b91c1c",margin:0};function tt({apiUrl:e,session:t,resendDelayMs:r=3e4,className:n,style:o,renderForm:i,renderSent:l,renderUnavailable:f}){let y=Ue({apiUrl:e,consumeUrlCode:t===void 0}),u=t??y,[v,d]=ve(""),[x,k]=ve("form"),[p,O]=ve(!1),[w,b]=ve(null),[a,P]=ve(null),[_,s]=ve(!1),c=wn(void 0),m=wn(!1);jr(()=>()=>{c.current&&clearTimeout(c.current)},[]);let g=()=>{s(!1),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>s(!0),r)},h=async()=>{let R=v.trim();if(!R||p||m.current)return;m.current=!0,O(!0),b(null),P(null);let T=await u.login(R);if(m.current=!1,O(!1),T.ok){if(T.via==="preview")return;k("sent"),g();return}T.code!=="unavailable"&&(b(T.code==="rate_limited"?"rate_limited":"error"),P(T.error))};if(u.status==="unavailable")return f?Y(It,{children:f()}):Y("div",{className:n,style:n?o:{...Lt,...o},"data-state":"unavailable",children:Y("p",{style:ke,children:"Sign-in is temporarily unavailable \u2014 please try again in a few minutes."})});if(x==="sent"){let R={email:v.trim(),canResend:_,resend:()=>{h(),g()},submitting:p,reset:()=>k("form")};return l?Y(It,{children:l(R)}):Ne("div",{className:n,style:n?o:{...Lt,...o},"data-state":"sent",children:[Ne("p",{style:ke,children:["Check your email \u2014 if ",Y("strong",{children:R.email})," has orders with this store, a sign-in link is on its way. It expires after a few minutes."]}),_?Ne("p",{style:ke,children:["Didn't get it?"," ",Y("button",{type:"button",style:Pn,onClick:R.resend,disabled:p,children:"Send it again"})," ","or"," ",Y("button",{type:"button",style:Pn,onClick:R.reset,children:"use a different email"}),"."]}):Y("p",{style:ke,children:"It can take a minute to arrive."})]})}let C={email:v,setEmail:d,submit:()=>void h(),submitting:p,errorKind:w,errorMessage:a,reason:u.reason};if(i)return Y(It,{children:i(C)});let S=R=>{R.preventDefault(),C.submit()};return Ne("form",{className:n,style:n?o:{...Lt,...o},onSubmit:S,"data-state":"form",children:[u.reason==="session_expired"&&Y("p",{style:ke,role:"status",children:"Your session has expired \u2014 sign in again to continue."}),u.reason==="invalid_code"&&Y("p",{style:ke,role:"status",children:"That sign-in link is invalid or has expired. Enter your email and we'll send you a new one."}),Ne("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:[Y("span",{children:"Email address"}),Y("input",{type:"email",value:v,onChange:R=>d(R.target.value),autoComplete:"email",required:!0,style:Kr})]}),Y("button",{type:"submit",style:Yr,disabled:p,children:p?"Sending\u2026":u.reason==="invalid_code"?"Email me a new link":"Email me a sign-in link"}),a&&Y("p",{style:Wr,role:"alert",children:w==="rate_limited"?"Too many attempts \u2014 please wait a moment and try again.":a})]})}import{Fragment as Zr,jsx as te,jsxs as Ce}from"react/jsx-runtime";var Hr={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:"0.75rem"},Jr={border:"1px solid #e5e7eb",borderRadius:8,padding:"0.75rem"},Me={color:"#6b7280",fontSize:"0.875rem"};function Gr(e){switch(e.status){case"paid":return null;case"refunded":return"Refunded";case"partially_refunded":return"Partially refunded";case"disputed":return"Disputed";default:return e.status}}function Et({orders:e,className:t,style:r,heading:n="Your orders",renderEmpty:o,renderOrder:i}){return e.length===0?o?te(Zr,{children:o()}):Ce("div",{className:t,style:r,"data-state":"empty",children:[n!==null&&te("h3",{children:n}),te("p",{style:Me,children:"No orders yet."})]}):Ce("div",{className:t,style:r,children:[n!==null&&te("h3",{children:n}),te("ul",{style:t?void 0:Hr,children:e.map(l=>{if(i)return te("li",{style:{display:"contents"},children:i(l)},l.id);let f=Ee(l.created_at),y=Gr(l);return Ce("li",{style:t?void 0:Jr,children:[Ce("div",{children:[l.order_number!==null&&Ce("strong",{children:["Order #",l.order_number]})," ",f&&te("span",{style:Me,children:f})," ",l.source==="subscription"&&te("span",{style:Me,children:"\xB7 subscription"}),y&&Ce("span",{style:Me,children:[" \xB7 ",y]})]}),l.line_items.length>0&&te("div",{style:Me,children:l.line_items.map(u=>u.name?`${u.quantity&&u.quantity>1?`${u.quantity} \xD7 `:""}${u.name}`:null).filter(Boolean).join(", ")}),te("div",{children:F(l.amount_total,l.currency)})]},l.id)})})]})}import{useEffect as _n,useRef as Qr,useState as ie}from"react";import{Fragment as An,jsx as V,jsxs as Q}from"react/jsx-runtime";var Xr={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:"0.75rem"},ei={border:"1px solid #e5e7eb",borderRadius:8,padding:"0.75rem",display:"flex",flexDirection:"column",gap:"0.5rem"},we={color:"#6b7280",fontSize:"0.875rem"},ti={color:"#b91c1c",fontSize:"0.875rem",margin:0},ni={color:"#065f46",fontSize:"0.875rem",margin:0},Ut={display:"flex",flexWrap:"wrap",gap:"0.5rem"},pe={padding:"0.375rem 0.75rem",border:"1px solid #d1d5db",borderRadius:6,background:"white",cursor:"pointer",fontSize:"0.875rem"},Rn={...pe,border:"1px solid #111827",background:"#111827",color:"white"},ri={...pe,border:"1px solid #b91c1c",color:"#b91c1c"},ii={padding:"0.375rem 0.5rem",border:"1px solid #d1d5db",borderRadius:6,fontSize:"0.875rem",width:"100%",boxSizing:"border-box"},xn={panel:"none",mutation:null,portalRefused:!1};function oi(e){let t=Ee(e.current_period_end);return e.ended?{text:"This subscription has ended.",tone:"ended"}:e.cancel_at_period_end?{text:t?`Scheduled to cancel \u2014 stays active until ${t}.`:"Scheduled to cancel at the end of the current period.",tone:"warn"}:e.status==="past_due"||e.status==="unpaid"?{text:"There's a problem with your last payment \u2014 please update your card.",tone:"warn"}:e.status==="active"||e.status==="trialing"?{text:t?`Renews on ${t}.`:"Active.",tone:"ok"}:{text:`Status: ${e.status}.`,tone:"warn"}}function si({initial:e,pending:t,onSave:r,onCancel:n}){let o=e?.address??null,[i,l]=ie(e?.name??""),[f,y]=ie(o?.line1??""),[u,v]=ie(o?.line2??""),[d,x]=ie(o?.city??""),[k,p]=ie(o?.state??""),[O,w]=ie(o?.postal_code??""),[b,a]=ie(o?.country??""),P=(_,s,c,m)=>Q("label",{style:{display:"flex",flexDirection:"column",gap:"0.25rem",fontSize:"0.875rem"},children:[V("span",{children:_}),V("input",{style:ii,value:s,onChange:g=>c(g.target.value),required:m?.required,maxLength:m?.maxLength})]});return Q("form",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},onSubmit:_=>{_.preventDefault(),r({name:i.trim()||null,address:{line1:f.trim(),line2:u.trim()||null,city:d.trim()||null,state:k.trim()||null,postal_code:O.trim()||null,country:b.trim().toUpperCase()}})},children:[P("Name",i,l),P("Address line 1",f,y,{required:!0}),P("Address line 2",u,v),P("City",d,x),P("State / region",k,p),P("Postal code",O,w),P("Country (2-letter code)",b,a,{required:!0,maxLength:2}),Q("div",{style:Ut,children:[V("button",{type:"submit",style:Rn,disabled:t,children:t?"Saving\u2026":"Save address"}),V("button",{type:"button",style:pe,onClick:n,disabled:t,children:"Cancel"})]})]})}function nt({apiUrl:e="https://aifeatures.dev",subscriptions:t,auth:r,onAuthError:n,onUnavailable:o,onSubscriptionChange:i,className:l,style:f,heading:y="Your subscriptions",renderEmpty:u,renderRow:v}){let[d,x]=ie(t),[k,p]=ie({}),O=Qr(new Set);_n(()=>{x(t)},[t]),_n(()=>{let s=c=>{c.persisted&&(O.current.clear(),p(m=>{let g=!1,h={};for(let[C,S]of Object.entries(m))S.mutation?.phase==="pending"?(h[C]={...S,mutation:null},g=!0):h[C]=S;return g?h:m}))};return window.addEventListener("pageshow",s),()=>window.removeEventListener("pageshow",s)},[]);let w=(s,c)=>p(m=>({...m,[s]:{...m[s]??xn,...c}})),b=s=>{x(c=>c.map(m=>m.id===s.id?s:m)),i?.(s)},a=async(s,c,m,g)=>{if(O.current.has(s.id))return{ok:!1};O.current.add(s.id);try{w(s.id,{mutation:{kind:c,phase:"pending"}});let h=await Z(e,m,{method:"POST",token:r.token,body:g??{}});if(h.ok)return{ok:!0,data:h.data};let{failure:C}=h;return C.kind==="unauthorized"?(n?.({code:C.code,error:C.error}),w(s.id,{mutation:null,panel:"none"}),{ok:!1}):C.kind==="unavailable"?(o?.(),w(s.id,{mutation:null,panel:"none"}),{ok:!1}):C.kind==="http"&&C.code==="ended"?(b({...s,ended:!0,status:"canceled"}),w(s.id,{mutation:null,panel:"none"}),{ok:!1}):C.kind==="http"&&C.code==="portal_unavailable"?(w(s.id,{portalRefused:!0,mutation:{kind:c,phase:"error",error:"Card update is temporarily unavailable."}}),{ok:!1}):(w(s.id,{mutation:{kind:c,phase:"error",error:C.kind==="network"?"That didn't go through \u2014 please check your connection and try again.":C.error}}),{ok:!1})}finally{O.current.delete(s.id)}},P=s=>r.kind==="session"?{cancel:`/v1/account/subscriptions/${encodeURIComponent(s.id)}/cancel`,reactivate:`/v1/account/subscriptions/${encodeURIComponent(s.id)}/reactivate`,address:`/v1/account/subscriptions/${encodeURIComponent(s.id)}/address`,portal:`/v1/account/subscriptions/${encodeURIComponent(s.id)}/portal-session`}:{cancel:"/v1/account/manage/cancel",reactivate:null,address:null,portal:"/v1/account/manage/portal-session"},_=s=>{let c=k[s.id]??xn,m=P(s);return{subscription:s,panel:c.panel,mutation:c.mutation,portalHidden:s.is_test||c.portalRefused,openCancelConfirm:()=>w(s.id,{panel:"confirm_cancel",mutation:null}),closePanel:()=>w(s.id,{panel:"none",mutation:null}),confirmCancel:()=>{(async()=>{let g=await a(s,"cancel",m.cancel);if(g.ok){let h=g.data.subscription;h&&b(h),w(s.id,{panel:"none",mutation:{kind:"cancel",phase:"success"}})}})()},reactivateAvailable:m.reactivate!==null,reactivate:()=>{m.reactivate&&(async()=>{let g=await a(s,"reactivate",m.reactivate);if(g.ok){let h=g.data.subscription;h&&b(h),w(s.id,{panel:"none",mutation:{kind:"reactivate",phase:"success"}})}})()},openAddressForm:()=>{m.address&&w(s.id,{panel:"address",mutation:null})},saveAddress:g=>{m.address&&(async()=>{let h=await a(s,"address",m.address,{shipping_address:g});if(h.ok){let C=h.data.subscription;C&&b(C),w(s.id,{panel:"none",mutation:{kind:"address",phase:"success"}})}})()},openPortal:()=>{(async()=>{let g=await a(s,"portal",m.portal);g.ok&&typeof g.data.url=="string"?window.location.href=g.data.url:g.ok&&w(s.id,{mutation:{kind:"portal",phase:"error",error:"Card update is temporarily unavailable."}})})()}}};return d.length===0?u?V(An,{children:u()}):Q("div",{className:l,style:f,"data-state":"empty",children:[y!==null&&V("h3",{children:y}),V("p",{style:we,children:"No subscriptions."})]}):Q("div",{className:l,style:f,children:[y!==null&&V("h3",{children:y}),V("ul",{style:l?void 0:Xr,children:d.map(s=>{let c=_(s);return v?V("li",{style:{display:"contents"},children:v(c)},s.id):V("li",{style:l?void 0:ei,"data-status":s.status,"data-ended":s.ended||void 0,children:V(ai,{ctx:c})},s.id)})})]})}function ai({ctx:e}){let t=e.subscription,r=oi(t),n=Ee(t.current_period_end),o=`${F(t.current_amount,t.currency)} ${vn(t.plan_interval,t.plan_interval_count)}`,i=e.mutation?.phase==="pending",l=i?e.mutation?.kind:null;return Q(An,{children:[Q("div",{children:[V("strong",{children:t.plan_title??"Subscription"})," ",Q("span",{style:we,children:["\xB7 ",o]}),t.is_test&&V("span",{style:we,children:" \xB7 test"})]}),V("div",{style:r.tone==="warn"?void 0:we,children:r.text}),t.ended?V("p",{style:we,children:"This subscription has ended \u2014 to start again, subscribe from the product page."}):e.panel==="confirm_cancel"?Q("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[V("p",{style:{margin:0},children:n?`Your subscription stays active until ${n} \u2014 after that it won't renew and you won't be charged again.`:"Your subscription stays active until the end of the current billing period \u2014 after that it won't renew and you won't be charged again."}),Q("div",{style:Ut,children:[V("button",{type:"button",style:ri,onClick:e.confirmCancel,disabled:i,children:l==="cancel"?"Canceling\u2026":"Confirm cancellation"}),V("button",{type:"button",style:pe,onClick:e.closePanel,disabled:i,children:"Keep subscription"})]})]}):e.panel==="address"?V(si,{initial:t.shipping_address??null,pending:l==="address",onSave:e.saveAddress,onCancel:e.closePanel}):Q("div",{style:Ut,children:[t.cancel_at_period_end?e.reactivateAvailable?V("button",{type:"button",style:Rn,onClick:e.reactivate,disabled:i,children:l==="reactivate"?"Resuming\u2026":"Keep my subscription"}):V("span",{style:we,children:"To keep this subscription, sign in with your email address on this page."}):V("button",{type:"button",style:pe,onClick:e.openCancelConfirm,disabled:i,children:"Cancel subscription"}),t.shipping_address!==void 0&&!t.cancel_at_period_end&&V("button",{type:"button",style:pe,onClick:e.openAddressForm,disabled:i,children:"Update shipping address"}),!e.portalHidden&&V("button",{type:"button",style:pe,onClick:e.openPortal,disabled:i,children:l==="portal"?"Opening\u2026":"Update card"})]}),e.mutation?.phase==="error"&&V("p",{style:ti,role:"alert",children:e.mutation.error}),e.mutation?.phase==="success"&&V("p",{style:ni,role:"status",children:e.mutation.kind==="cancel"?n?`Cancellation scheduled \u2014 you keep access until ${n}.`:"Cancellation scheduled.":e.mutation.kind==="reactivate"?"Your subscription will continue.":e.mutation.kind==="address"?"Shipping address updated.":"Done."})]})}import{Fragment as Pe,jsx as N,jsxs as J}from"react/jsx-runtime";var ui={display:"flex",flexDirection:"column",gap:"1.25rem"},On={color:"#6b7280",fontSize:"0.875rem"},li={border:"1px solid #d1d5db",borderRadius:8,padding:"0.75rem"},Tn={color:"#b91c1c"},it={background:"none",border:"none",padding:0,font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"};function ci({apiUrl:e="https://aifeatures.dev",className:t,style:r,resendDelayMs:n,loginProps:o,renderLoading:i,renderError:l,renderEmpty:f,renderHeader:y,renderPmBanner:u,renderManageExpired:v}){let d=Ue({apiUrl:e}),x=rt(void 0),[k,p]=qe(null),[O,w]=qe(!1);Nt(()=>{if(!(typeof window>"u")){if(x.current===void 0){let I=new URL(window.location.href),L=I.searchParams.get("manage_code"),B=I.searchParams.get("pm");(L!==null||B!==null)&&(I.searchParams.delete("manage_code"),I.searchParams.delete("pm"),window.history.replaceState(window.history.state,"",I.toString())),x.current={manageCode:L,pmUpdated:B==="updated"}}p(x.current.manageCode),w(x.current.pmUpdated)}},[]);let[b,a]=qe(null),P=rt(!1),_=rt(0),s=Ve(I=>{a({phase:"verifying"}),(async()=>{let L=await Z(e,"/v1/account/manage/verify",{method:"POST",body:{manage_code:I}});if(L.ok&&typeof L.data.manage_token=="string"&&L.data.subscription){a({phase:"active",token:L.data.manage_token,sub:L.data.subscription,siteName:null});return}if(!L.ok&&L.failure.kind==="unavailable"){a({phase:"unavailable"});return}if(!L.ok&&L.failure.kind==="network"){a({phase:"error",error:L.failure.error});return}a({phase:"expired"})})()},[e]);Nt(()=>{!k||P.current||(P.current=!0,s(k))},[k,s]);let c=Ve(async()=>{let I=b;if(!I||I.phase!=="active")return;let L=++_.current,B=await Z(e,"/v1/account/manage/subscription",{token:I.token});L===_.current&&(B.ok&&B.data.subscription?a({phase:"active",token:I.token,sub:B.data.subscription,siteName:typeof B.data.site?.name=="string"?B.data.site.name:I.siteName}):!B.ok&&B.failure.kind==="unauthorized"?a({phase:"expired"}):!B.ok&&B.failure.kind==="unavailable"&&a({phase:"unavailable"}))},[e,b]),[m,g]=qe({phase:"loading"}),[h,C]=qe(0),S=h>0,R=rt(0),T=d.token,q=Ve(async()=>{if(!T)return;let I=++R.current,L=await Z(e,"/v1/account/me",{token:T});if(I===R.current){if(L.ok){g({phase:"ready",data:L.data});return}if(L.failure.kind==="unauthorized"){ee("session_expired");return}if(L.failure.kind==="unavailable"){ee();return}g({phase:"error",error:L.failure.error})}},[e,T]);Nt(()=>{!T||k||(g({phase:"loading"}),q())},[T,k,q]);let K=Ve(async()=>{C(I=>I+1);try{b&&b.phase==="active"?await c():await q()}finally{C(I=>I-1)}},[b,c,q]),D=Ve(I=>{R.current++,_.current++,a(L=>L&&L.phase==="active"&&L.sub.id===I.id?{...L,sub:I}:L),g(L=>L.phase==="ready"?{phase:"ready",data:{...L.data,subscriptions:L.data.subscriptions.map(B=>B.id===I.id?I:B)}}:L)},[]),A=t?r:{...ui,...r},E=I=>{if(!O)return null;let B={state:I.some(H=>!H.ended&&(H.status==="past_due"||H.status==="unpaid"))?"retrying":"recovered",checkAgain:()=>void K(),checking:S};return u?u(B):N("div",{style:li,role:"status","data-pm-state":B.state,children:B.state==="retrying"?J(Pe,{children:[N("p",{style:{margin:0},children:"Card updated \u2014 we're retrying your payment. This can take a few minutes."}),N("p",{style:{margin:"0.375rem 0 0"},children:N("button",{type:"button",style:it,onClick:B.checkAgain,disabled:S,children:S?"Checking\u2026":"Check again"})})]}):N("p",{style:{margin:0},children:"Card updated \u2014 your subscription is back in good standing."})})};if(k)return!b||b.phase==="verifying"?i?N(Pe,{children:i()}):N("div",{className:t,style:A,role:"status",children:N("p",{children:"Opening your subscription\u2026"})}):b.phase==="active"?J("div",{className:t,style:A,children:[E([b.sub]),N(nt,{apiUrl:e,subscriptions:[b.sub],auth:{kind:"manage",token:b.token},heading:"Your subscription",onSubscriptionChange:D,onAuthError:()=>a({phase:"expired"}),onUnavailable:()=>a({phase:"unavailable"})})]}):b.phase==="unavailable"?N("div",{className:t,style:A,"data-state":"unavailable",children:N("p",{children:"Subscription management is temporarily unavailable \u2014 please try again in a few minutes."})}):b.phase==="error"?J("div",{className:t,style:A,children:[N("p",{style:Tn,role:"alert",children:b.error}),N("p",{children:N("button",{type:"button",style:it,onClick:()=>s(k),children:"Try again"})})]}):J("div",{className:t,style:A,"data-state":"manage-expired",children:[v?v():N("p",{children:"This manage link is no longer valid. Sign in below with the email you used at checkout to manage your subscription."}),N(tt,{apiUrl:e,session:d,resendDelayMs:n,...o})]});if(d.status==="pending")return i?N(Pe,{children:i()}):N("div",{className:t,style:A,role:"status",children:N("p",{children:"Signing you in\u2026"})});if(d.status!=="signed_in")return N("div",{className:t,style:A,children:N(tt,{apiUrl:e,session:d,resendDelayMs:n,...o})});if(m.phase==="loading")return i?N(Pe,{children:i()}):N("div",{className:t,style:A,role:"status",children:N("p",{children:"Loading your account\u2026"})});if(m.phase==="error")return l?N(Pe,{children:l({error:m.error,retry:()=>void q()})}):J("div",{className:t,style:A,children:[J("p",{style:Tn,role:"alert",children:["We couldn't load your account \u2014 ",m.error]}),N("p",{children:N("button",{type:"button",style:it,onClick:()=>void q(),children:"Try again"})})]});let{data:U}=m,z=U.customer??d.customer??{email:"",name:null},M=()=>void d.logout(),j=U.orders.length===0&&U.subscriptions.length===0;return J("div",{className:t,style:A,children:[y?y({customer:z,site:U.site??null,signOut:M}):J("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:"1rem",flexWrap:"wrap"},children:[J("div",{children:[N("h2",{style:{margin:0},children:"Your account"}),J("p",{style:{...On,margin:0},children:["Signed in as ",z.email]})]}),N("button",{type:"button",style:it,onClick:M,children:"Sign out"})]}),E(U.subscriptions),j?f?f():J("p",{style:On,children:["Nothing here yet \u2014 orders and subscriptions for ",z.email," ","will show up on this page."]}):J(Pe,{children:[U.subscriptions.length>0&&N(nt,{apiUrl:e,subscriptions:U.subscriptions,auth:{kind:"session",token:T},onSubscriptionChange:D,onAuthError:()=>ee("session_expired"),onUnavailable:()=>ee()}),N(Et,{orders:U.orders})]})]})}export{tt as AccountLogin,Et as AccountOrders,ci as AccountPage,Or as AddToCartButton,En as AifeaturesCaptcha,kr as BuyButton,Tr as CartCheckoutButton,wt as MARKET_COUNTRIES,en as MAX_CART_LINES,Ir as OrderConfirmation,qr as PlanPicker,nr as ProductPrice,nt as SubscriptionList,yr as VariantPicker,$t as ZERO_DECIMAL_CURRENCIES,ct as applySelectionToUrl,F as formatPrice,fe as getOptions,oe as getVariants,_e as isMultiVariant,ot as isValueAvailable,st as isValueInCatalog,Sn as planRecurringAmount,at as reanchorSelection,le as resolveVariant,Fe as searchFromSelection,xe as selectedImages,Dt as selectedValues,lt as selectionFromSearch,re as useCart,kt as useCartCheckout,St as useCartItems,Gn as useCartSummary,bt as useCheckout,er as useMarket,ue as useProduct,Ue as useSession,ne as valueSlug,ut as variantPriceRange};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aifeatures/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "React components for aifeatures sites: form CAPTCHA (Cloudflare Turnstile) and headless payments (product price, buy button, order confirmation)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -21,6 +21,15 @@
|
|
|
21
21
|
"files": [
|
|
22
22
|
"dist"
|
|
23
23
|
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup",
|
|
26
|
+
"prepack": "pnpm build",
|
|
27
|
+
"dev": "tsup --watch",
|
|
28
|
+
"lint": "eslint src/",
|
|
29
|
+
"typecheck": "tsc --noEmit",
|
|
30
|
+
"storybook": "storybook dev -p 6007",
|
|
31
|
+
"build-storybook": "storybook build"
|
|
32
|
+
},
|
|
24
33
|
"peerDependencies": {
|
|
25
34
|
"react": ">=18",
|
|
26
35
|
"react-dom": ">=18"
|
|
@@ -50,13 +59,5 @@
|
|
|
50
59
|
"workerDirectory": [
|
|
51
60
|
".storybook/public"
|
|
52
61
|
]
|
|
53
|
-
},
|
|
54
|
-
"scripts": {
|
|
55
|
-
"build": "tsup",
|
|
56
|
-
"dev": "tsup --watch",
|
|
57
|
-
"lint": "eslint src/",
|
|
58
|
-
"typecheck": "tsc --noEmit",
|
|
59
|
-
"storybook": "storybook dev -p 6007",
|
|
60
|
-
"build-storybook": "storybook build"
|
|
61
62
|
}
|
|
62
|
-
}
|
|
63
|
+
}
|