@aifeatures/react 0.1.8 → 0.3.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 -67
- package/dist/index.d.cts +1225 -1
- package/dist/index.d.ts +1225 -1
- package/dist/index.js +1 -41
- package/package.json +2 -2
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,42 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
3
|
-
// src/AifeaturesCaptcha.tsx
|
|
4
|
-
import { useState, useEffect } from "react";
|
|
5
|
-
import { Turnstile } from "@marsidev/react-turnstile";
|
|
6
|
-
import { jsx } from "react/jsx-runtime";
|
|
7
|
-
function AifeaturesCaptcha({
|
|
8
|
-
formId,
|
|
9
|
-
apiUrl = "https://aifeatures.dev",
|
|
10
|
-
onVerify,
|
|
11
|
-
onError,
|
|
12
|
-
className
|
|
13
|
-
}) {
|
|
14
|
-
const [sitekey, setSitekey] = useState(null);
|
|
15
|
-
const [isLoading, setIsLoading] = useState(true);
|
|
16
|
-
useEffect(() => {
|
|
17
|
-
setIsLoading(true);
|
|
18
|
-
fetch(`${apiUrl}/f/${formId}/config`).then((r) => r.json()).then((config) => {
|
|
19
|
-
setSitekey(config.turnstile_sitekey);
|
|
20
|
-
setIsLoading(false);
|
|
21
|
-
}).catch(() => {
|
|
22
|
-
setIsLoading(false);
|
|
23
|
-
});
|
|
24
|
-
}, [formId, apiUrl]);
|
|
25
|
-
if (isLoading || !sitekey) {
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
return /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsx(
|
|
29
|
-
Turnstile,
|
|
30
|
-
{
|
|
31
|
-
siteKey: sitekey,
|
|
32
|
-
onSuccess: onVerify,
|
|
33
|
-
onError,
|
|
34
|
-
onExpire: onError,
|
|
35
|
-
options: { theme: "light" }
|
|
36
|
-
}
|
|
37
|
-
) });
|
|
38
|
-
}
|
|
39
|
-
export {
|
|
40
|
-
AifeaturesCaptcha
|
|
41
|
-
};
|
|
42
|
-
//# sourceMappingURL=index.js.map
|
|
2
|
+
import{useState as Ze,useEffect as It}from"react";import{Turnstile as Ot}from"@marsidev/react-turnstile";import{jsx as He}from"react/jsx-runtime";function Tt({formId:e,apiUrl:t="https://aifeatures.dev",onVerify:r,onError:n,className:i}){let[o,g]=Ze(null),[p,y]=Ze(!0);return It(()=>{y(!0),fetch(`${t}/f/${e}/config`).then(l=>l.json()).then(l=>{g(l.turnstile_sitekey),y(!1)}).catch(()=>{y(!1)})},[e,t]),p||!o?null:He("div",{className:i,children:He(Ot,{siteKey:o,onSuccess:r,onError:n,onExpire:n,options:{theme:"light"}})})}import{useCallback as Lt,useEffect as Et,useRef as At,useState as de}from"react";var pe=[1e3,3e3];function Z(e,t={}){let r=t.apiUrl??"https://aifeatures.dev",n=t.country??null,[i,o]=de(null),[g,p]=de(!0),[y,l]=de(null),[f,a]=de(0),h=At(e);Et(()=>{let c=!1,v;p(!0),l(null),h.current!==e&&(h.current=e,o(null));let _=R=>{fetch(`${r}/v1/p/${encodeURIComponent(e)}${n?`?country=${encodeURIComponent(n)}`:""}`).then(async S=>{let I=await S.json().catch(()=>null);if(!c)if(!S.ok||!I){if(S.status>=500&&R<pe.length){v=setTimeout(()=>_(R+1),pe[R]);return}l(I?.error??`Request failed (${S.status})`),o(null),p(!1)}else o(I),p(!1)}).catch(S=>{if(!c){if(R<pe.length){v=setTimeout(()=>_(R+1),pe[R]);return}l(S instanceof Error?S.message:"Failed to load product"),p(!1)}})};return _(0),()=>{c=!0,v&&clearTimeout(v)}},[e,r,n,f]);let m=Lt(()=>a(c=>c+1),[]);return{product:i,loading:g,error:y,refresh:m}}var Xe=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","vnd","vuv","xaf","xof","xpf"]);function D(e,t,r){let n=Xe.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 W(e){return e.variants??[]}function ee(e){return e.options??[]}function ie(e){return ee(e).length>0}function fe(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function H(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 _e(e,t,r,n){return e.some(i=>{let o=fe(i);if(o[r]!==n)return!1;for(let[g,p]of Object.entries(t))if(g!==r&&o[g]!==p)return!1;return!0})}function we(e,t,r){return e.some(n=>fe(n)[t]===r)}function Pe(e,t,r,n){let i={[r]:n};for(let[g,p]of Object.entries(t)){if(g===r)continue;e.some(l=>{let f=fe(l);return f[r]===n&&f[g]===p})&&(i[g]=p)}return e.some(g=>{let p=fe(g);return Object.entries(i).every(([y,l])=>p[y]===l)})?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 et(e,t){let r={};for(let n of ee(e)){let i=t[n.id];if(!i)continue;let o=n.values.find(g=>g.id===i);o&&(r[n.title]=o.value)}return r}function j(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,g)=>{n.has(j(g))||n.set(j(g),o)});let i={};for(let o of ee(e)){let g=j(o.title);if(g.length===0)continue;let p=n.get(g);if(p===void 0)continue;let y=j(p);if(y.length===0)continue;let l=o.values.find(f=>j(f.value)===y);l&&(i[o.id]=l.id)}return i}function me(e,t){let r={};for(let[n,i]of Object.entries(et(e,t))){let o=j(n),g=j(i);o.length===0||g.length===0||(r[o]=g)}return r}function oe(e,t){let r=[];for(let n of ee(e)){let i=t[n.id];if(!i)continue;let o=n.values.find(g=>g.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=j(n.title);i.length!==0&&r.searchParams.delete(i)}for(let[n,i]of Object.entries(me(e,t)))r.searchParams.set(n,i);window.history.replaceState(window.history.state,"",r.toString())}import{useCallback as Mt,useEffect as st,useRef as ut,useState as Ue}from"react";var Te="aifeatures_cart",Le="aifeatures_market",tt="aifeatures_cart_cleared";var Oe="aifeatures:cart-storage",ae=new Map;function Ee(e){if(ae.has(e))return ae.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"){ae.set(e,t);return}try{t===null?window.localStorage.removeItem(e):window.localStorage.setItem(e,t),ae.delete(e)}catch{ae.set(e,t)}Ut(e)}function Ut(e){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(Oe,{detail:{key:e}}))}catch{}}function nt(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 Vt(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[g,p]of Object.entries(t.selection))typeof p=="string"&&(n[g]=p);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=Vt(i);o&&!n.has(o.variantId)&&(n.add(o.variantId),r.push(o))}return r}function F(e){Ae(Te,JSON.stringify(e))}function rt(e){return nt(Te,e)}function it(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})}F(r)}function N(){let e=Ee(Le);return typeof e!="string"||!/^[A-Za-z]{2}$/.test(e)?null:e.toUpperCase()}function ot(e){Ae(Le,e!==null&&/^[A-Za-z]{2}$/.test(e)?e.toUpperCase():null)}function te(e){return nt(Le,e)}function at(e){let t=[],r=Ee(tt);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(tt,JSON.stringify(t)),!0)}var Nt=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 ge(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=p=>{n||(n=!0,window.removeEventListener("message",o),clearTimeout(g),r(p))},o=p=>{if(p.source!==window.parent)return;let y=p.data;y?.type==="aifeatures:test-checkout-ack"&&ge(y,t)&&i(y.status==="accepted")},g=setTimeout(()=>i(!1),Nt);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),[g,p]=Ue(null),y=ut(!1),l=ut(null);return st(()=>{let a=h=>{h.persisted&&(y.current=!1,n(!1))};return window.addEventListener("pageshow",a),()=>window.removeEventListener("pageshow",a)},[]),st(()=>{if(typeof window>"u"||window.self===window.top)return;let a=h=>{if(h.source!==window.parent)return;let m=h.data;if(m?.type!=="aifeatures:test-checkout-ack"||m.status!=="failed")return;let c=l.current;c===null||!ge(m,c)||(l.current=null,o(typeof m.error=="string"&&m.error?m.error:"The test purchase could not be created."),y.current=!1,n(!1))};return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},[]),{startCheckout:Mt(async({productId:a,variantId:h,quantity:m,amount:c,metadata:v,successUrl:_,cancelUrl:R,customerEmail:S,expectedUnitAmount:I,expectedCurrency:b})=>{if(!y.current){y.current=!0,n(!0),o(null),p(null);try{let s=N(),u=await fetch(`${t}/v1/p/${a}/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...h!==void 0?{variant_id:h}:{},...m!==void 0?{quantity:m}:{},...c!==void 0?{amount:c}:{},...v!==void 0?{metadata:v}:{},...S!==void 0?{customer_email:S}:{},...I!==void 0&&b!==void 0?{expected_unit_amount:I,expected_currency:b}:{},...s!==null?{country:s}:{},success_url:_??`${window.location.origin}/order/confirmation`,cancel_url:R??window.location.href})}),d=await u.json().catch(()=>null);if(!u.ok){if(d?.error==="price_changed"&&typeof d.current_unit_amount=="number"&&typeof d.currency=="string"){p({currentUnitAmount:d.current_unit_amount,currency:d.currency}),o(`The price has changed to ${D(d.current_unit_amount,d.currency)} \u2014 please review and try again.`),y.current=!1,n(!1);return}if(d?.code==="preview_domain"){let C=Ve();if(l.current=C,await Me({productId:a,...h!==void 0?{variantId:h}:{},...m!==void 0?{quantity:m}:{},...c!==void 0?{amount:c}:{},...S!==void 0?{customerEmail:S}:{}},C))return;l.current=null}o(d?.error??`Checkout failed (${u.status})`),y.current=!1,n(!1);return}if(!d?.url){o("Checkout failed: no redirect URL returned"),y.current=!1,n(!1);return}if(window.self!==window.top)try{window.top.location.href=d.url;return}catch{if(window.open(d.url,"_blank")){y.current=!1,n(!1);return}}window.location.href=d.url}catch(s){o(s instanceof Error?s.message:"Checkout failed"),y.current=!1,n(!1)}}},[t]),loading:r,error:i,priceChange:g}}import{useCallback as ye,useEffect as qt,useState as lt}from"react";var dt=20;function ct(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.max(1,Math.floor(e))}function z(){let[e,t]=lt([]),[r,n]=lt(!1);qt(()=>{let l=()=>t(Y());return l(),n(!0),rt(l)},[]);let i=ye(l=>{let f=Y(),a=ct(l.quantity);return f.find(m=>m.variantId===l.variantId)?(F(f.map(m=>m.variantId===l.variantId?{...m,quantity:m.quantity+a,selection:l.selection??m.selection,display:l.display}:m)),{ok:!0}):f.length>=dt?{ok:!1,reason:"cart_full"}:(F([...f,{productId:l.productId,variantId:l.variantId,quantity:a,selection:l.selection??{},display:l.display}]),{ok:!0})},[]),o=ye(l=>{F(Y().filter(f=>f.variantId!==l))},[]),g=ye((l,f)=>{let a=Y();if(f<=0){F(a.filter(m=>m.variantId!==l));return}let h=ct(f);F(a.map(m=>m.variantId===l?{...m,quantity:h}:m))},[]),p=ye(()=>{F([])},[]),y=e.reduce((l,f)=>l+f.quantity,0);return{items:e,count:y,hydrated:r,add:i,remove:o,setQuantity:g,clear:p}}import{useCallback as Bt,useEffect as pt,useMemo as qe,useRef as Dt,useState as se}from"react";var he={image:null,unitAmount:null,currency:null,baseCurrency:null,inStock:!1,available:null,maxQuantity:null,pdpSearch:{},status:"unavailable"},$t={...he,inStock:!0,status:"error"};function Ft(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}=z(),[i,o]=se({}),[g,p]=se({shippingRates:null,freeShippingOver:null,shippingCountries:null}),[y,l]=se(!0),[f,a]=se(null),[h,m]=se(0),c=Dt(new Set),v=qe(()=>JSON.stringify(r.map(b=>[b.productId,b.variantId,b.selection])),[r]),_=Bt(()=>m(b=>b+1),[]);pt(()=>te(_),[_]),pt(()=>{if(!n)return;if(r.length===0){o({}),p({shippingRates:null,freeShippingOver:null,shippingCountries:null}),a(null),l(!1);return}let b=!1;l(!0);let s=r,u=[...new Set(s.map(C=>C.productId))],d=async C=>{let x=new Map;return await Promise.all(u.map(async O=>{try{let w=await fetch(`${t}/v1/p/${encodeURIComponent(O)}${C?`?country=${encodeURIComponent(C)}`:""}`);if(w.status===404){x.set(O,{kind:"not_found"});return}if(!w.ok){x.set(O,{kind:"error",message:`Request failed (${w.status})`});return}let P=await w.json();x.set(O,{kind:"ok",product:P})}catch(w){x.set(O,{kind:"error",message:w instanceof Error?w.message:"Failed to load product"})}})),x};return(async()=>{let C=N(),x=await d(C);if(C){let k=[...x.values()].filter(A=>A.kind==="ok"),T=k.filter(A=>A.product.base_currency);T.length>0&&T.length<k.length&&(x=await d(null))}if(b)return;let O=null,w=null,P=null;for(let k of u){let T=x.get(k);!T||T.kind!=="ok"||(O===null&&T.product.shipping_rates&&(O=T.product.shipping_rates),w===null&&T.product.free_shipping_over!=null&&(w=T.product.free_shipping_over),P===null&&T.product.shipping_countries&&(P=T.product.shipping_countries))}let E={},U=new Map,Q=null;for(let k of s){let T=x.get(k.productId);if(!T||T.kind==="error"){E[k.variantId]=$t,T&&Q===null&&(Q=T.message);continue}if(T.kind==="not_found"){E[k.variantId]=he;continue}let{product:A}=T;if(!A.active||A.purchasable===!1){E[k.variantId]=he;continue}let q=A.variants??[],$=q.find(K=>K.id===k.variantId)??null,B=k.variantId;if(!$){let K=H(q,k.selection);if(!K){E[k.variantId]=he;continue}let Qe=U.get(k.variantId)??{};Qe.reanchorTo={variantId:K.id,selection:Ft(K)},U.set(k.variantId,Qe),c.current.add(K.id),$=K,B=K.id}let V=oe(A,k.selection)[0]??null,re={image:V,unitAmount:$.unit_amount,currency:$.currency,baseCurrency:A.base_currency??null,inStock:$.in_stock,available:$.available,maxQuantity:A.max_quantity,pdpSearch:me(A,k.selection),status:c.current.has(B)?"reanchored":"ok"};E[k.variantId]=re,E[B]=re;let Ge=U.get(k.variantId)??{};Ge.display={name:A.name,variantTitle:$.title,image:V},U.set(k.variantId,Ge)}let M=new Set(s.map(k=>k.variantId));for(let k of[...c.current])!M.has(k)&&!(k in E)&&c.current.delete(k);if(U.size>0){let k=Y(),T=[],A=new Map,q=!1;for(let $ of k){let B=U.get($.variantId),V={...$};B?.reanchorTo&&(V.variantId=B.reanchorTo.variantId,V.selection=B.reanchorTo.selection,q=!0),B?.display&&(V.display.name!==B.display.name||V.display.variantTitle!==B.display.variantTitle||V.display.image!==B.display.image)&&(V.display=B.display,q=!0);let re=A.get(V.variantId);if(re){re.quantity+=V.quantity,q=!0;continue}T.push(V),A.set(V.variantId,V)}q&&F(T)}b||(o(E),p({shippingRates:O,freeShippingOver:w,shippingCountries:P}),a(Q),l(!1))})(),()=>{b=!0}},[n,v,t,h]);let R=qe(()=>r.map(b=>{let s=i[b.variantId];return s?{...b,...s,image:s.image??b.display.image}:{...b,image:b.display.image,unitAmount:null,currency:null,baseCurrency:null,inStock:!0,available:null,maxQuantity:null,pdpSearch:{},status:"ok"}}),[r,i]),{subtotal:S,currency:I}=qe(()=>{let b=0,s=null;for(let u of R)u.unitAmount===null||u.currency===null||(b+=u.unitAmount*u.quantity,s=s??u.currency);return{subtotal:b,currency:s}},[R]);return{lines:R,subtotal:S,currency:I,shippingRates:g.shippingRates,freeShippingOver:g.freeShippingOver,shippingCountries:g.shippingCountries,loading:y,error:f,refresh:_}}import{useCallback as jt,useEffect as ft,useMemo as zt,useRef as De,useState as ue}from"react";var Kt=2e3;function Wt(e={}){let t=e.apiUrl??"https://aifeatures.dev",r=e.debounceMs??250,n=e.shippingOption??null,{items:i,hydrated:o}=z(),[g,p]=ue(null),[y,l]=ue(!1),[f,a]=ue(null),[h,m]=ue(null),[c,v]=ue(0);ft(()=>(m(N()),te(()=>m(N()))),[]);let _=zt(()=>i.map(s=>`${s.variantId}:${s.quantity}`).sort().join(","),[i]),R=jt(()=>v(s=>s+1),[]),S=De(0),I=De(!1),b=De("idle");return ft(()=>{if(!o)return;if(i.length===0){p(null),a(null),l(!1);return}let s=++S.current,u=new AbortController,d=!1,C,x=I.current?r:0;I.current=!0,b.current=b.current==="pending"?"spent":"idle";let O=setTimeout(async()=>{l(!0);try{let w=await fetch(`${t}/v1/p/checkout/summary`,{method:"POST",headers:{"Content-Type":"application/json"},signal:u.signal,body:JSON.stringify({items:i.map(E=>({variant_id:E.variantId,quantity:E.quantity})),...h?{country:h}:{},...n?{shipping_option:n}:{}})});if(d||s!==S.current)return;if(!w.ok){if(w.status===429){let E=b.current==="idle";E&&(C=setTimeout(()=>{d||s!==S.current||(b.current="pending",v(U=>U+1))},Kt)),a(E?"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 (${w.status})`);return}let P=await w.json();if(d||s!==S.current)return;p({currency:P.currency,subtotal:P.subtotal,shipping:P.shipping?{options:P.shipping.options.map(E=>({label:E.label,amount:E.amount,undiscountedAmount:E.undiscounted_amount})),selectedAmount:P.shipping.selected_amount,selectedLabel:P.shipping.selected_label,freeShippingOver:P.shipping.free_shipping_over,freeShippingCurrency:P.shipping.free_shipping_currency,thresholdMet:P.shipping.threshold_met,collectsAddress:P.shipping.collects_address}:null,total:P.total,totalIsFinal:P.total_is_final,tax:P.tax??null,unavailableVariantIds:P.unavailable_variant_ids}),a(null)}catch(w){if(d||u.signal.aborted||s!==S.current)return;a(w instanceof Error?w.message:"Could not price this cart")}finally{!d&&s===S.current&&l(!1)}},x);return()=>{d=!0,clearTimeout(O),C!==void 0&&clearTimeout(C),u.abort()}},[o,_,h,t,r,n,c]),{summary:g,loading:y,error:f,refresh:R}}import{useCallback as Yt,useEffect as mt,useRef as gt,useState as Ce}from"react";function $e(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Ce(!1),[i,o]=Ce(null),[g,p]=Ce(null),[y,l]=Ce(null),f=gt(!1),a=gt(null);return mt(()=>{let m=c=>{c.persisted&&(f.current=!1,n(!1))};return window.addEventListener("pageshow",m),()=>window.removeEventListener("pageshow",m)},[]),mt(()=>{if(typeof window>"u"||window.self===window.top)return;let m=c=>{if(c.source!==window.parent)return;let v=c.data;if(v?.type!=="aifeatures:test-checkout-ack"||v.status!=="failed")return;let _=a.current;_===null||!ge(v,_)||(a.current=null,o(typeof v.error=="string"&&v.error?v.error:"The test purchase could not be created."),f.current=!1,n(!1))};return window.addEventListener("message",m),()=>window.removeEventListener("message",m)},[]),{startCheckout:Yt(async(m,{successUrl:c,cancelUrl:v,customerEmail:_,metadata:R,shippingOption:S}={})=>{if(!f.current){f.current=!0,n(!0),o(null),p(null),l(null);try{let I=N(),b=await fetch(`${t}/v1/p/checkout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:m.map(u=>({variant_id:u.variantId,quantity:u.quantity,...typeof u.unitAmount=="number"&&typeof u.currency=="string"?{expected_unit_amount:u.unitAmount,expected_currency:u.currency}:{}})),...I!==null?{country:I}:{},...S?{shipping_option:S}:{},...R!==void 0?{metadata:R}:{},..._!==void 0?{customer_email:_}:{},success_url:c??`${window.location.origin}/order/confirmation`,cancel_url:v??window.location.href})}),s=await b.json().catch(()=>null);if(!b.ok){if(s?.code==="shipping_option_unavailable"&&typeof s.requested=="string"&&Array.isArray(s.available)){l({requested:s.requested,available:s.available,currency:typeof s.currency=="string"?s.currency:""}),f.current=!1,n(!1);return}if(s?.error==="cart_conflict"&&Array.isArray(s.items)){let u={};for(let d of s.items)d&&typeof d.variant_id=="string"&&(u[d.variant_id]=d);p(u),f.current=!1,n(!1);return}if(s?.code==="preview_domain"){let u=Ve();if(a.current=u,await Me({items:m.map(C=>({productId:C.productId,variantId:C.variantId,quantity:C.quantity})),..._!==void 0?{customerEmail:_}:{}},u))return;a.current=null}o(s?.error??`Checkout failed (${b.status})`),f.current=!1,n(!1);return}if(!s?.url){o("Checkout failed: no redirect URL returned"),f.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")){f.current=!1,n(!1);return}}window.location.href=s.url}catch(I){o(I instanceof Error?I.message:"Checkout failed"),f.current=!1,n(!1)}}},[t]),loading:r,error:i,conflicts:g,shippingConflict:y}}import{useCallback as Jt,useEffect as yt,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 ht(e){return e?je.find(t=>t.country===e.toUpperCase())?.currency??null:null}var Ct=new Map;function Gt(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 Qt(e={}){let t=e.apiUrl??"https://aifeatures.dev",[r,n]=Fe(null),[i,o]=Fe(!1),[g,p]=Fe(null);yt(()=>{let a=()=>n(N());return a(),o(!0),te(a)},[]),yt(()=>{let a=!1;return Gt(t).then(h=>{a||p(h)}),()=>{a=!0}},[t]);let y=Jt(a=>{ot(a)},[]),l=ht(g),f=i&&l!==null&&l!==ht(r);return{market:r,suggestedCountry:g,setMarket:y,markets:je,shouldPrompt:f}}import{jsx as ze,jsxs as Xt}from"react/jsx-runtime";var Zt={textDecoration:"line-through",opacity:.6,marginRight:"0.4em"};function Ht({productId:e,variantId:t,apiUrl:r,locale:n,className:i,style:o,compareAtClassName:g}){let{product:p,loading:y}=Z(e,{apiUrl:r});if(y||!p)return null;let l=W(p),f=t!==void 0?l.find(h=>h.id===t)??null:p.options.length===0?l[0]??null:null;if(f){if(f.unit_amount===null)return null;let h=f.compare_at_amount!==null&&f.compare_at_amount>f.unit_amount;return Xt("span",{className:i,style:o,children:[h&&ze("span",{className:g,style:g?void 0:Zt,children:D(f.compare_at_amount,f.currency,n)}),D(f.unit_amount,f.currency,n)]})}let a=xe(l);return a?ze("span",{className:i,style:o,children:a.min===a.max?D(a.min,p.currency,n):`${D(a.min,p.currency,n)} \u2013 ${D(a.max,p.currency,n)}`}):p.unit_amount===null?null:ze("span",{className:i,style:o,children:D(p.unit_amount,p.currency,n)})}import{useEffect as bt,useMemo as en,useRef as St,useState as tn}from"react";import{jsx as be,jsxs as cn}from"react/jsx-runtime";var nn={marginBottom:"0.75rem"},rn={display:"block",fontSize:"0.875rem",fontWeight:600,marginBottom:"0.375rem"},on={display:"flex",flexWrap:"wrap",gap:"0.5rem"},an={padding:"0.375rem 0.75rem",border:"1px solid #d1d5db",borderRadius:6,background:"white",cursor:"pointer",fontSize:"0.875rem"},sn={borderColor:"#111827",boxShadow:"inset 0 0 0 1px #111827",fontWeight:600},vt={opacity:.4,textDecoration:"line-through",cursor:"not-allowed"},un={...vt,cursor:"pointer"};function ln({options:e,variants:t,value:r,syncUrl:n=!0,onChange:i,onVariantChange:o,className:g,style:p,optionClassName:y,optionLabelClassName:l,valueClassName:f,selectedValueClassName:a,unavailableValueClassName:h}){let m=r!==void 0,[c,v]=tn(r??{}),_=m?r:c,R=St(!1);bt(()=>{if(!n||m||R.current||e.length===0||typeof window>"u"||(R.current=!0,Object.keys(c).length>0))return;let s=Re({options:e},window.location.search);Object.keys(s).length!==0&&(v(s),i?.(s))},[n,m,e]);let S=en(()=>e.length>0?t.filter(s=>s.option_values.length===e.length):t,[t,e]),I=St(void 0);if(bt(()=>{let s=H(S,_),u=s?.id??null;I.current!==u&&(I.current=u,o?.(s))},[S,_]),e.length===0)return null;let b=(s,u)=>{let d=Pe(S,_,s,u);m||(v(d),n&&Ie({options:e},d)),i?.(d)};return be("div",{className:g,style:p,children:e.map(s=>cn("div",{className:y,style:y?void 0:nn,children:[be("span",{className:l,style:l?void 0:rn,children:s.title}),be("div",{style:on,children:s.values.map(u=>{let d=_[s.id]===u.id,C=_e(S,_,s.id,u.id),x=C||we(S,s.id,u.id),O=[f,d?a:void 0,C?void 0:h].filter(Boolean).join(" ")||void 0,w=f?void 0:{...an,...d?sn:{},...C?{}:x?un:vt};return be("button",{type:"button",className:O,style:w,disabled:!x,"aria-pressed":d,"data-selected":d?"true":void 0,"data-available":C?"true":"false",onClick:()=>b(s.id,u.id),children:u.value},u.id)})})]},s.id))})}import{useEffect as dn}from"react";import{Fragment as Ke,jsx as X,jsxs as le}from"react/jsx-runtime";var pn={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"},fn={background:"none",border:"none",padding:0,marginLeft:"0.35em",font:"inherit",color:"inherit",textDecoration:"underline",cursor:"pointer"};function kt(){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 mn({productId:e,variantId:t,quantity:r,amount:n,metadata:i,successUrl:o,cancelUrl:g,customerEmail:p,apiUrl:y,disabled:l,className:f,style:a,errorClassName:h,spinner:m=!0,children:c}){let{product:v,loading:_,error:R,refresh:S}=Z(e,{apiUrl:y}),{startCheckout:I,loading:b,error:s,priceChange:u}=Ne({apiUrl:y});dn(()=>{u&&S()},[u,S]);let d=v!==null&&!v.payments_ready,C=v!==null&&!v.active,x=v!==null&&v.purchasable===!1,O=v!==null&&ie(v),w=v!==null?W(v):[],P=t!==void 0?w.find(A=>A.id===t)??null:!O&&w.length===1?w[0]:null,E=O&&!P,U=P!==null&&!P.in_stock,Q=!!l||_||!v||d||C||x||E||U||b,M;b?M=le(Ke,{children:[m&&X(kt,{}),"Processing\u2026"]}):_?M=le(Ke,{children:[m&&X(kt,{}),c??"Buy now"]}):d?M="Payments not set up":C||x?M="Unavailable":E?M="Select options":U?M="Out of stock":c!==void 0?M=c:M="Buy now";let k=s??R;return le(Ke,{children:[X("button",{type:"button",className:f,style:a,disabled:Q,onClick:()=>{let A=n===void 0&&N()===null&&P!==null&&!P.allow_custom_amount&&typeof P.unit_amount=="number"?{expectedUnitAmount:P.unit_amount,expectedCurrency:P.currency}:{};I({productId:e,variantId:t,quantity:r,amount:n,metadata:i,successUrl:o,cancelUrl:g,customerEmail:p,...A})},children:M}),k&&le("div",{role:"alert",className:h,style:h?void 0:pn,children:[k,v===null&&!_&&R!==null&&X("button",{type:"button",onClick:S,style:fn,children:"Tap to retry"})]})]})}import{useEffect as gn,useRef as yn,useState as _t}from"react";import{Fragment as wt,jsx as ne,jsxs as Se}from"react/jsx-runtime";var hn={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"},bn=1500;function Sn(){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:[ne("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"3"}),ne("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:ne("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.8s",repeatCount:"indefinite"})})]})}function vn(e){let t={};for(let r of e.option_values)t[r.option_id]=r.value_id;return t}function kn({productId:e,variantId:t,selection:r,quantity:n,apiUrl:i,disabled:o,className:g,style:p,errorClassName:y,spinner:l=!0,children:f}){let{product:a,loading:h,error:m,refresh:c}=Z(e,{apiUrl:i}),{add:v}=z(),[_,R]=_t(!1),[S,I]=_t(!1),b=yn(void 0);gn(()=>()=>{b.current&&clearTimeout(b.current)},[]);let s=a!==null&&!a.payments_ready,u=a!==null&&!a.active,d=a!==null&&a.purchasable===!1,C=a!==null&&!h&&W(a).length===0,x=a!==null&&a.allow_custom_amount,O=a!==null&&ie(a),w=a!==null?W(a):[],P=t!==void 0?w.find(q=>q.id===t)??null:r!==void 0&&O?H(w,r):!O&&w.length===1?w[0]:null,E=a!==null&&!C&&!P,U=P!==null&&!P.in_stock,Q=!!o||h||!a||s||u||d||C||x||E||U,M=()=>{if(!a||!P)return;let q=r??vn(P);if(!v({productId:e,variantId:P.id,quantity:n,selection:q,display:{name:a.name,variantTitle:P.title,image:oe(a,q)[0]??null}}).ok){R(!0);return}R(!1),I(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>I(!1),bn)},k;h?k=Se(wt,{children:[l&&ne(Sn,{}),f??"Add to cart"]}):s?k="Payments not set up":u||d||C||x?k="Unavailable":E?k="Select options":U?k="Out of stock":S?k="Added to cart":f!==void 0?k=f:k="Add to cart";let T=_?"Your cart is full \u2014 remove an item before adding another.":m;return Se(wt,{children:[ne("button",{type:"button",className:g,style:p,disabled:Q,"data-added":S?"true":void 0,onClick:M,children:k}),T&&Se("div",{role:"alert",className:y,style:y?void 0:hn,children:[T,a===null&&!h&&m!==null&&!_&&ne("button",{type:"button",onClick:c,style:Cn,children:"Tap to retry"})]})]})}import{Fragment as We,jsx as J,jsxs as ve}from"react/jsx-runtime";var Pt={color:"#b91c1c",fontSize:"0.875rem",marginTop:"0.5rem"};function xt(){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 _n({apiUrl:e,successUrl:t,cancelUrl:r,customerEmail:n,metadata:i,shippingOption:o,disabled:g,className:p,style:y,errorClassName:l,spinner:f=!0,children:a}){let{items:h,hydrated:m}=z(),{lines:c}=Be({apiUrl:e}),{startCheckout:v,loading:_,error:R,conflicts:S}=$e({apiUrl:e}),I=m&&h.length===0,b=c.some(C=>C.status==="unavailable"),s=!!g||!m||I||b||_,u;_?u=ve(We,{children:[f&&J(xt,{}),"Processing\u2026"]}):m?I?u="Cart is empty":b?u="Remove unavailable items":a!==void 0?u=a:u="Checkout":u=ve(We,{children:[f&&J(xt,{}),a??"Checkout"]});let d=S?Object.keys(S).length:0;return ve(We,{children:[J("button",{type:"button",className:p,style:y,disabled:s,onClick:()=>v(c,{successUrl:t,cancelUrl:r,customerEmail:n,metadata:i,shippingOption:o}),children:u}),d>0&&J("div",{role:"alert",className:l,style:l?void 0:Pt,children:d===1?"An item in your cart changed \u2014 please review your cart and try again.":`${d} items in your cart changed \u2014 please review your cart and try again.`}),R&&J("div",{role:"alert",className:l,style:l?void 0:Pt,children:R})]})}import{useEffect as ke,useRef as Rt,useState as Ye}from"react";import{Fragment as ce,jsx as L,jsxs as G}from"react/jsx-runtime";var Je="af_order_confirmation_session",wn=1800*1e3;function Pn({apiUrl:e="https://aifeatures.dev",className:t,style:r,sessionId:n,pollIntervalMs:i=2e3,pollTimeoutMs:o=6e4,followRedirect:g=!0,redirectDelayMs:p=1500,renderNoSession:y,renderPending:l,renderPaid:f,renderFailed:a}){let[h,m]=Ye(n),[c,v]=Ye(null),[_,R]=Ye(!1),S=Rt(void 0);ke(()=>{if(n!==void 0){m(n);return}if(S.current!==void 0){m(S.current);return}let u=new URL(window.location.href),d=u.searchParams.get("session_id");if(d){u.searchParams.delete("session_id"),window.history.replaceState(window.history.state,"",u.toString());try{sessionStorage.setItem(Je,JSON.stringify({id:d,ts:Date.now()}))}catch{}}else try{let C=sessionStorage.getItem(Je);if(C){let x=JSON.parse(C);typeof x.id=="string"&&typeof x.ts=="number"&&Date.now()-x.ts<=wn?d=x.id:sessionStorage.removeItem(Je)}}catch{}S.current=d,m(d)},[n]),ke(()=>{if(!h)return;let u=!1,d,C=Date.now(),x=async()=>{try{let O=await fetch(`${e}/v1/o/session/${encodeURIComponent(h)}`);if(O.ok){let w=await O.json();if(u||(v(w),w.status!=="pending"))return}}catch{}if(!u){if(Date.now()-C>=o){R(!0);return}d=setTimeout(x,i)}};return x(),()=>{u=!0,d&&clearTimeout(d)}},[h,e,i,o]);let I=c!==null&&(c.status==="paid"||c.status==="partially_refunded"),b=Rt(!1);ke(()=>{if(!h||c===null||b.current||!(c.status==="paid"||c.status==="partially_refunded"||c.is_test===!0)||(b.current=!0,!at(h)))return;let d=(c.line_items??[]).filter(C=>typeof C.variant_id=="string"&&C.variant_id.length>0).map(C=>({variantId:C.variant_id,quantity:C.quantity}));d.length>0&&it(d)},[h,c]);let s=I&&c.fulfillment.type==="redirect"?c.fulfillment.redirect_url:void 0;if(ke(()=>{if(!s||!g)return;let u=setTimeout(()=>{window.location.href=s},p);return()=>clearTimeout(u)},[s,g,p]),h===void 0)return null;if(h===null)return y?L(ce,{children:y()}):G("div",{className:t,style:r,children:[L("h2",{children:"Thank you for your order!"}),L("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(!c||c.status==="pending")return l?L(ce,{children:l({timedOut:_})}):L("div",{className:t,style:r,role:"status",children:L("p",{children:_?"This is taking longer than expected. You will receive an email confirmation once your payment is processed.":"Confirming your payment\u2026"})});if(I){if(f)return L(ce,{children:f(c)});let{fulfillment:u}=c,d=c.amount_total!==void 0&&c.currency?D(c.amount_total,c.currency):null,C=u.files??[],x=C.length===0?u.download_url:void 0;return G("div",{className:t,style:r,children:[L("h2",{children:"Thank you for your purchase!"}),c.is_test&&G("p",{children:[L("strong",{children:"Test purchase"})," \u2014 no payment was collected."]}),c.line_items&&c.line_items.length>0&&L("ul",{children:c.line_items.map((O,w)=>G("li",{children:[O.quantity>1?`${O.quantity} \xD7 `:"",O.name,O.refunded&&L("em",{children:O.refund_reason==="oversold"?" \u2014 sold out and refunded; check your email for details":" \u2014 refunded"})]},w))}),d&&G("p",{children:["Total paid: ",d]}),C.length>0&&G(ce,{children:[L("p",{children:"Your downloads:"}),L("ul",{children:C.map((O,w)=>L("li",{children:L("a",{href:O.download_url,children:O.name})},w))})]}),x&&L("p",{children:L("a",{href:x,children:"Download your file"})}),s?G("p",{children:["Taking you to your content\u2026"," ",L("a",{href:s,children:"Continue if you are not redirected"})]}):u.redirect_url?L("p",{children:L("a",{href:u.redirect_url,children:"Continue to your content"})}):null,C.length===0&&!x&&!u.redirect_url&&L("p",{children:"A confirmation email is on its way to you."}),c.order_id&&G("p",{children:["Order reference: ",L("code",{children:c.order_id})," \u2014 keep this if you ever need help with your order."]})]})}return a?L(ce,{children:a(c)}):L("div",{className:t,style:r,children:L("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{kn as AddToCartButton,Tt as AifeaturesCaptcha,mn as BuyButton,_n as CartCheckoutButton,je as MARKET_COUNTRIES,dt as MAX_CART_LINES,Pn as OrderConfirmation,Ht as ProductPrice,ln as VariantPicker,Xe as ZERO_DECIMAL_CURRENCIES,Ie as applySelectionToUrl,D as formatPrice,ee as getOptions,W as getVariants,ie as isMultiVariant,_e as isValueAvailable,we as isValueInCatalog,Pe as reanchorSelection,H as resolveVariant,me as searchFromSelection,oe as selectedImages,et as selectedValues,Re as selectionFromSearch,z as useCart,$e as useCartCheckout,Be as useCartItems,Wt as useCartSummary,Ne as useCheckout,Qt as useMarket,Z as useProduct,j as valueSlug,xe as variantPriceRange};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aifeatures/react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "React
|
|
3
|
+
"version": "0.3.0",
|
|
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",
|
|
7
7
|
"module": "./dist/index.js",
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/AifeaturesCaptcha.tsx"],"sourcesContent":["export { AifeaturesCaptcha } from './AifeaturesCaptcha';\nexport type { AifeaturesCaptchaProps } from './AifeaturesCaptcha';\n","import { useState, useEffect } from 'react';\nimport { Turnstile } from '@marsidev/react-turnstile';\n\nexport interface AifeaturesCaptchaProps {\n /** Form ID from aifeatures - used to fetch the Turnstile sitekey */\n formId: string;\n /** Base URL for the aifeatures API (defaults to https://aifeatures.dev) */\n apiUrl?: string;\n /** Called when CAPTCHA verification succeeds */\n onVerify?: (token: string) => void;\n /** Called when CAPTCHA verification fails or expires */\n onError?: () => void;\n /** Additional class name for the container */\n className?: string;\n}\n\ninterface FormConfig {\n id: string;\n name: string;\n endpoint_url: string;\n turnstile_sitekey: string | null;\n}\n\n/**\n * A CAPTCHA component that handles Turnstile verification for aifeatures forms.\n *\n * Drop this into any form to add CAPTCHA protection. The Turnstile widget\n * automatically adds a hidden `cf-turnstile-response` input to the form.\n *\n * @example\n * ```tsx\n * <form action={`https://aifeatures.dev/f/${formId}`} method=\"POST\">\n * <input name=\"email\" type=\"email\" required />\n * <textarea name=\"message\" />\n * <AifeaturesCaptcha formId={formId} />\n * <button type=\"submit\">Send</button>\n * </form>\n * ```\n */\nexport function AifeaturesCaptcha({\n formId,\n apiUrl = 'https://aifeatures.dev',\n onVerify,\n onError,\n className,\n}: AifeaturesCaptchaProps) {\n const [sitekey, setSitekey] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n setIsLoading(true);\n fetch(`${apiUrl}/f/${formId}/config`)\n .then((r) => r.json())\n .then((config: FormConfig) => {\n setSitekey(config.turnstile_sitekey);\n setIsLoading(false);\n })\n .catch(() => {\n setIsLoading(false);\n });\n }, [formId, apiUrl]);\n\n if (isLoading || !sitekey) {\n return null;\n }\n\n return (\n <div className={className}>\n <Turnstile\n siteKey={sitekey}\n onSuccess={onVerify}\n onError={onError}\n onExpire={onError}\n options={{ theme: 'light' }}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAoC;AACpC,6BAA0B;AAmEpB;AA7BC,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AACF,GAA2B;AACzB,QAAM,CAAC,SAAS,UAAU,QAAI,uBAAwB,IAAI;AAC1D,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAS,IAAI;AAE/C,8BAAU,MAAM;AACd,iBAAa,IAAI;AACjB,UAAM,GAAG,MAAM,MAAM,MAAM,SAAS,EACjC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,EACpB,KAAK,CAAC,WAAuB;AAC5B,iBAAW,OAAO,iBAAiB;AACnC,mBAAa,KAAK;AAAA,IACpB,CAAC,EACA,MAAM,MAAM;AACX,mBAAa,KAAK;AAAA,IACpB,CAAC;AAAA,EACL,GAAG,CAAC,QAAQ,MAAM,CAAC;AAEnB,MAAI,aAAa,CAAC,SAAS;AACzB,WAAO;AAAA,EACT;AAEA,SACE,4CAAC,SAAI,WACH;AAAA,IAAC;AAAA;AAAA,MACC,SAAS;AAAA,MACT,WAAW;AAAA,MACX;AAAA,MACA,UAAU;AAAA,MACV,SAAS,EAAE,OAAO,QAAQ;AAAA;AAAA,EAC5B,GACF;AAEJ;","names":[]}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/AifeaturesCaptcha.tsx"],"sourcesContent":["import { useState, useEffect } from 'react';\nimport { Turnstile } from '@marsidev/react-turnstile';\n\nexport interface AifeaturesCaptchaProps {\n /** Form ID from aifeatures - used to fetch the Turnstile sitekey */\n formId: string;\n /** Base URL for the aifeatures API (defaults to https://aifeatures.dev) */\n apiUrl?: string;\n /** Called when CAPTCHA verification succeeds */\n onVerify?: (token: string) => void;\n /** Called when CAPTCHA verification fails or expires */\n onError?: () => void;\n /** Additional class name for the container */\n className?: string;\n}\n\ninterface FormConfig {\n id: string;\n name: string;\n endpoint_url: string;\n turnstile_sitekey: string | null;\n}\n\n/**\n * A CAPTCHA component that handles Turnstile verification for aifeatures forms.\n *\n * Drop this into any form to add CAPTCHA protection. The Turnstile widget\n * automatically adds a hidden `cf-turnstile-response` input to the form.\n *\n * @example\n * ```tsx\n * <form action={`https://aifeatures.dev/f/${formId}`} method=\"POST\">\n * <input name=\"email\" type=\"email\" required />\n * <textarea name=\"message\" />\n * <AifeaturesCaptcha formId={formId} />\n * <button type=\"submit\">Send</button>\n * </form>\n * ```\n */\nexport function AifeaturesCaptcha({\n formId,\n apiUrl = 'https://aifeatures.dev',\n onVerify,\n onError,\n className,\n}: AifeaturesCaptchaProps) {\n const [sitekey, setSitekey] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n setIsLoading(true);\n fetch(`${apiUrl}/f/${formId}/config`)\n .then((r) => r.json())\n .then((config: FormConfig) => {\n setSitekey(config.turnstile_sitekey);\n setIsLoading(false);\n })\n .catch(() => {\n setIsLoading(false);\n });\n }, [formId, apiUrl]);\n\n if (isLoading || !sitekey) {\n return null;\n }\n\n return (\n <div className={className}>\n <Turnstile\n siteKey={sitekey}\n onSuccess={onVerify}\n onError={onError}\n onExpire={onError}\n options={{ theme: 'light' }}\n />\n </div>\n );\n}\n"],"mappings":";;;AAAA,SAAS,UAAU,iBAAiB;AACpC,SAAS,iBAAiB;AAmEpB;AA7BC,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AACF,GAA2B;AACzB,QAAM,CAAC,SAAS,UAAU,IAAI,SAAwB,IAAI;AAC1D,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,IAAI;AAE/C,YAAU,MAAM;AACd,iBAAa,IAAI;AACjB,UAAM,GAAG,MAAM,MAAM,MAAM,SAAS,EACjC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,EACpB,KAAK,CAAC,WAAuB;AAC5B,iBAAW,OAAO,iBAAiB;AACnC,mBAAa,KAAK;AAAA,IACpB,CAAC,EACA,MAAM,MAAM;AACX,mBAAa,KAAK;AAAA,IACpB,CAAC;AAAA,EACL,GAAG,CAAC,QAAQ,MAAM,CAAC;AAEnB,MAAI,aAAa,CAAC,SAAS;AACzB,WAAO;AAAA,EACT;AAEA,SACE,oBAAC,SAAI,WACH;AAAA,IAAC;AAAA;AAAA,MACC,SAAS;AAAA,MACT,WAAW;AAAA,MACX;AAAA,MACA,UAAU;AAAA,MACV,SAAS,EAAE,OAAO,QAAQ;AAAA;AAAA,EAC5B,GACF;AAEJ;","names":[]}
|