@tinkerlandai/longplay-sdk 0.10.21-rc.2 → 0.10.21
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/{chunk-2QSCQD6Q.js → chunk-53C6LI3D.js} +1 -1
- package/dist/{chunk-CKOTDDP7.js → chunk-AX2PJEJP.js} +1 -1
- package/dist/{chunk-H6PIJ4WG.js → chunk-BP6G3YGP.js} +1 -1
- package/dist/{chunk-DZUPXUMV.js → chunk-CHQUGYMS.js} +1 -1
- package/dist/{chunk-6SPHXEK4.js → chunk-JNML7SY4.js} +1 -1
- package/dist/{chunk-ZC6PDVLR.js → chunk-JXNNWCEB.js} +1 -1
- package/dist/{chunk-RXJC2LV5.js → chunk-LBGCSWVF.js} +1 -1
- package/dist/chunk-M4LTOSLT.js +1 -0
- package/dist/{chunk-FJCDYAPZ.js → chunk-YDWAT2ID.js} +1 -1
- package/dist/{chunk-KOFZECHE.js → chunk-Z5CW2N7E.js} +1 -1
- package/dist/{content-NQHRLJQT.js → content-JS7M7A3P.js} +1 -1
- package/dist/funnel-runtime-host-XYUJ4WFW.js +1 -0
- package/dist/index.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-YBC5XAB7.js → paywall-VHDTE2N2.js} +1 -1
- package/dist/react-native.js +1 -1
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-UCOKLDSW.js +0 -1
- package/dist/funnel-runtime-host-TO43LOMU.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as Je,c as Ke}from"./chunk-JGG4R75K.js";import{c as ze,d as He,e as Be,f as le,g as Qe,h as je,i as Ge,k as We}from"./chunk-6DTGBDYG.js";import{c as qe,f as Ve,g as Ie,h as Fe}from"./chunk-YAVWELIV.js";import"./chunk-H6PIJ4WG.js";import{a as S}from"./chunk-QVGTHPWT.js";import{Z}from"./chunk-ZC6PDVLR.js";import{a as z}from"./chunk-DSPLGTQI.js";import{La as ee,Na as _e,j as J,o as ke,z as X}from"./chunk-HDVLCRC6.js";async function Ye(o,n,C){if(n.status!=="complete")throw new S("INVALID_RESPONSE","A verified completed purchase is required");let y=o?X.parse(o):null;if(await C.onComplete?.(n),!y||!C.check)return;let m=X.parse(await C.check());if(m.internal_feature_id!==y.internal_feature_id||m.quantity!==y.quantity||y.observation!==void 0&&(m.observation===void 0||m.observation.requirementDigest!==y.observation.requirementDigest||m.observation.authority!==y.observation.authority||ke(m.observation.subject)!==ke(y.observation.subject)))throw new S("INVALID_RESPONSE","The access requirement changed");m.allowed&&await C.onAccessGranted?.(m)}var at={none:0,sm:4,md:8,lg:14,full:9999},ot={system:"system-ui,sans-serif",serif:"Georgia,serif",rounded:"ui-rounded,system-ui,sans-serif",mono:"ui-monospace,monospace"};function st(o){let[n,C,y]=[1,3,5].map(m=>{let g=Number.parseInt(o.slice(m,m+2),16)/255;return g<=.03928?g/12.92:((g+.055)/1.055)**2.4});return .2126*n+.7152*C+.0722*y}function Xe(o){let n=st(o.primary),C=(n+.05)/.05>1.05/(n+.05)?"#111318":"#FFFFFF",y=`color-mix(in srgb, ${o.text} 22%, ${o.background})`,m=`${at[o.radius]}px`,g=`appearance:none;margin:0;min-height:44px;padding:10px 18px;border:0;border-radius:${m};font:inherit;font-size:15px;font-weight:600;line-height:1.25;cursor:pointer;touch-action:manipulation`;return{root:`width:100%;box-sizing:border-box;background:${o.background};color:${o.text};font:14px/1.5 ${ot[o.font]}`,controls:"display:flex;gap:12px;padding:0 20px 12px;align-items:center;flex-wrap:wrap",message:"flex:1 1 200px;min-width:0;margin:0;font-size:13px",panel:`flex:1 0 100%;box-sizing:border-box;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid ${y};border-radius:${m}`,summary:"margin:0;font-size:15px;font-weight:600",terms:"display:flex;flex-direction:column;gap:4px;font-size:13px;opacity:.72",actions:"display:flex;gap:8px;flex-wrap:wrap;margin-top:4px",primary:`${g};background:${o.primary};color:${C}`,secondary:`${g};background:transparent;color:${o.text};box-shadow:inset 0 0 0 1px ${y}`,link:`${g};background:transparent;color:${o.text};opacity:.72;font-weight:500`}}function Ae(o){o.style.opacity=o.disabled?".55":"",o.style.cursor=o.disabled?"not-allowed":"pointer"}function Re(o){return Object.entries(o.document.buttons).filter(([,n])=>n.type==="checkout"&&n.product.type==="fixed"&&!Z(n.product,{},o.capabilities)).map(([n])=>n)}async function It(o,n,C){let y=We(o.ownerDocument),m=()=>{v.finish("dismissed"),y()},g=()=>m(),v=Qe(o,n,"paywall",()=>{m(),z(n.onDismiss)});n.signal?.throwIfAborted(),n.signal?.addEventListener("abort",g,{once:!0});let H=null,$,w,Se;try{if(v.start(!0),v.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(H=n.check?X.parse(await v.wait(n.check(),le)):null,H?.allowed)return v.finish("skipped"),n.signal?.removeEventListener("abort",g),y(),await n.onAccessGranted?.(H),{check:H,host:null};let[e,t]=await Promise.allSettled([v.wait(import("./screen-renderer-TEVGVUT5.js")),v.wait(n.start().then(i=>(v.cancelled&&i.destroy(),i)),le)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;Se=e.value,$=t.value,n.signal?.throwIfAborted(),$.signal?.throwIfAborted(),$.signal?.addEventListener("abort",g,{once:!0});let u=$.view??await v.wait($.refresh(),le);if(!u)throw new S("INVALID_RESPONSE","Paywall presentation is missing");$.signal?.throwIfAborted(),w=u}catch(e){throw v.finish("error",e),n.signal?.removeEventListener("abort",g),$?.signal?.removeEventListener("abort",g),$?.destroy(),y(),e}let r=$,{mountScreenPreview:Ze}=Se,l=o.ownerDocument,ue=new AbortController,L=l.createElement("section"),de=l.createElement("div"),_=l.createElement("div"),x=l.createElement("p"),p=l.createElement("button"),P=l.createElement("button"),h=l.createElement("dialog"),a=w.document.screen.strings.defaultLocale.startsWith("zh"),Te=a?"\u6B63\u5728\u5904\u7406\u2026":"Processing\u2026",T=Xe(w.document.screen.theme);L.dataset.indianaPaywall="",L.setAttribute("aria-label",w.document.name),L.style.cssText=T.root,_.style.cssText=T.controls,x.style.cssText=T.message,x.setAttribute("role","status"),P.style.cssText=T.link,P.textContent=a?"\u5173\u95ED":"Close",p.style.cssText=T.secondary,p.textContent=a?"\u91CD\u8BD5":"Retry",p.hidden=!0,_.append(x,p,P),L.append(de,_);let B=w.document.presentation,Q,Oe,pe=!1,De=JSON.stringify(w.capabilities);function fe(e){if(d)return;w=e;let t=JSON.stringify(e.capabilities);t!==De&&(Q?.updateCapabilities(e.capabilities,Re(e)),De=t),tt(e)}let k;function $e(){let e=l.defaultView;k?.responsive&&e&&Q?.resizeViewport?.(e.innerHeight,e.innerWidth)}let d=!1,te=!1,I=null,ne=!1,Le=!1,q=!1,me,he=!1,M,j;function et(){return te||d||M||he?{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}:Ie(r)}let A=()=>!d&&!ne&&!M&&n.canInteract?.()!==!1,ye=!1,s=null,U=null;function tt(e){r.quote||r.operation||(x.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":a?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let we=new Map;async function be(e){if(!(!A()||!e.checkoutUrl||we.get(e.operationId)===e.checkoutUrl)){we.set(e.operationId,e.checkoutUrl);try{n.onCheckoutUrl?await n.onCheckoutUrl(e.checkoutUrl):l.defaultView?.location.assign(e.checkoutUrl)}catch(t){throw we.delete(e.operationId),t}}}let G=e=>{x.textContent=e instanceof Error?e.message:a?"\u8BF7\u6C42\u5931\u8D25":"Request failed",z(n.onError,e),p.hidden=s===null},re=new WeakMap;function ie(e){te=e;for(let t of U?.querySelectorAll("button")??[])e?(re.set(t,t.disabled),t.disabled=!0):re.has(t)&&(t.disabled=re.get(t),re.delete(t)),Ae(t)}function ge(){x.textContent=a?"\u6682\u65F6\u65E0\u6CD5\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"This action is unavailable right now. Try again in a moment."}async function nt(e){if(n.beforeAction)try{await n.beforeAction()}catch(t){throw s=e,t}}async function N(e){if(!(te||d)){if(!A()){ge();return}ie(!0),p.hidden=!0,x.textContent=Te;try{if(await nt(e),d)return;if(!A()){s=e,p.hidden=!1,ge();return}await e()}catch(t){d||G(t)}finally{ie(!1),x.textContent===Te&&(x.textContent="")}}}async function rt(e){await Ye(H,e,n)}function Ue(e){return Ie(r).type==="recording"||Ve({quote:r.quote,operation:e,requestId:null,pending:!1,destroyed:!1,canReselect:r.canReselect}).type==="recording"}async function O(e){if(d)return;if(!A()){s=async()=>O(await r.read()),p.hidden=!1;return}if(x.textContent=Ke(e.status,a),Ue(e)){let i=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";x.textContent=i?a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u4F46\u4EA4\u6613\u8BB0\u5F55\u5931\u8D25\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u4FEE\u590D\uFF0C\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u786E\u8BA4\u4EA4\u6613\u8BB0\u5F55\u3002\u8BF7\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",p.textContent=a?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",s=async()=>O(await r.read()),p.hidden=!1;return}if(e.problem){let i=e.problem;s=ae,p.textContent=a?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",G(new S(i.code,i.reason==="RESULT_UNKNOWN"?a?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":i.phase==="fulfillment"?a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":i.code==="CAPABILITY_UNAVAILABLE"?a?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":i.code==="NOT_CONFIGURED"?a?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":a?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,i));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(x.textContent=a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){s=null,await rt(e);return}if(e.status!=="pending"){if(r.canReselect===!1){x.textContent=a?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",p.textContent=a?"\u67E5\u8BE2\u7ED3\u679C":"Check result",s=async()=>O(await r.read()),p.hidden=!1;return}p.textContent=a?"\u91CD\u8BD5":"Retry",s=null,I=null;return}await be(e);let t=Date.now()+6e5,u=2e3;pe=!0,z(n.onObservationChange,!0);try{for(;!d&&Date.now()<t;){if(await Je(u,l,ue.signal),d)return;if(!A()){s=async()=>O(await r.read()),p.hidden=!1;return}let i=await r.read();if(!i.problem&&i.status==="pending"&&await be(i),i.status!=="pending"||i.problem||Ue(i)){await O(i);return}u=Math.min(u*1.5,3e4)}}finally{pe=!1,z(n.onObservationChange,!1)}s=async()=>O(await r.read()),p.hidden=!1}async function ve(){let e=await r.read();if(d)return;if(!A()){s=ve,p.hidden=!1;return}let t=r.quote;if(t&&qe(e,{operationId:t.operationId,currency:t.currency},"The original purchase operation changed"),t&&e.status==="pending"&&e.quoteFinalized===!1&&!e.confirmedAt&&!e.checkoutUrl&&!e.nativePurchase&&!e.merchantExecution&&!e.problem&&!r.pendingCancellation){Ne(t);return}await O(e)}async function ae(){U?.remove(),U=null,s=ae;let e=await r.confirm();if(!A()){s=ae,p.hidden=!1;return}if(e.problem){await O(e);return}if(e.status==="pending"){if(e.checkoutUrl)await be(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!n.onPurchase)throw new S("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await n.onPurchase({operation:e,signal:ue.signal})}}s=async()=>O(await r.read()),await O(e)}function Ne(e){U?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());x.textContent=t?a?"\u6B64\u62A5\u4EF7\u5DF2\u8FC7\u671F\u3002\u8BF7\u5148\u53D6\u6D88\uFF0C\u518D\u91CD\u65B0\u9009\u62E9\u3002":"This quote has expired. Cancel it, then choose again.":"";let u=l.createElement("div"),i=l.createElement("button"),b=l.createElement("button"),V=l.createElement("div"),K=l.createElement("p"),R=e.merchantTerms,oe=R?R.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),se=a?"zh-CN":"en",ce=R?.subscriptionTerms?.items??[],Y=R?ce.length===1&&ce[0]?.amountMinor===oe&&ce[0]:e.lines.length===1&&e.lines[0]?.catalogAmountMinor===oe&&e.lines[0];K.textContent=e.lines.map(c=>c.productName).join(", ")+" \xB7 "+(oe===null?a?`${J(R.subtotalMinor-R.discountMinor,e.currency)} + \u5F85\u786E\u8BA4\u7A0E\u8D39`:`${J(R.subtotalMinor-R.discountMinor,e.currency)} + tax confirmed at checkout`:J(oe,e.currency)+(Y?ee(Y.interval,se,Y.intervalCount??1):"")),i.textContent=a?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",i.disabled=t,b.textContent=a?"\u53D6\u6D88":"Cancel",u.style.cssText=T.panel,K.style.cssText=T.summary,V.style.cssText=T.actions,i.style.cssText=T.primary,b.style.cssText=T.secondary,Ae(i),i.onclick=()=>{N(ae)};let Me=async()=>{let c=await r.cancel();d||(u.remove(),U=null,await O(c))};b.onclick=()=>{s=Me,N(Me)};let D=l.createElement("div");if(D.style.cssText=T.terms,R){for(let f of ce){if(f===Y)continue;let E=l.createElement("p");E.textContent=J(f.amountMinor,e.currency)+ee(f.interval,se,f.intervalCount),D.append(E)}let c=R.subscriptionTerms?.trial;if(c){let f=l.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.days} \u5929\uFF1B${c.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.days}; ${c.cardRequired?"a payment method is required":"no payment method is required"}`,D.append(f)}for(let f of[...R.expectedEffects.map(E=>E.description),...R.requiredConsents.map(E=>E.summary)]){let E=l.createElement("p");E.textContent=f,D.append(E)}}else{for(let c of e.lines){if(c!==Y){let f=l.createElement("p");f.textContent=`${c.productName} \xB7 ${J(c.catalogAmountMinor,e.currency)}${ee(c.interval,se,c.intervalCount??1)}`,D.append(f)}for(let f of c.prepaid??[]){let E=l.createElement("p"),F=r.view?.capabilities.plans[c.productVersionId]?.prepaid?.find(it=>it.internalFeatureId===f.internal_feature_id);E.textContent=`${F?.name??f.internal_feature_id} \xB7 ${f.quantity} ${a?"\u4EFD":"packs"} \xD7 ${f.terms.units}`,F&&(E.textContent+=ee(F.reset==="week"||F.reset==="month"||F.reset==="year"?F.reset:"one_time",se,F.resetCount)),D.append(E)}if(c.trial){let f=l.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.trial.days} \u5929\uFF1B${c.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.trial.days}; ${c.trial.cardRequired?"a payment method is required":"no payment method is required"}`,D.append(f)}}if(!e.charge){let c=l.createElement("p");c.textContent=a?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",D.append(c)}}for(let c of D.children)c.style.margin="0";V.append(i,b),u.append(K,...D.childElementCount?[D]:[],V),_.prepend(u),u.scrollIntoView?.({block:"nearest"}),i.focus({preventScroll:!0}),U=u,s=null}async function xe(){if(!I)return;if(s=xe,!ye){let t=r.view,u=t?.document.buttons[I.actionId],i=t&&u?.type==="checkout"?Z(u.product,I.selection,t.capabilities):null;if(!i)throw new S("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let b=await n.resolveOfferId?.({actionId:I.actionId,productVersionId:i});if(d)return;b!==void 0&&(I.offerId=b),ye=!0}if(!A()){p.hidden=!1;return}let e=await r.preview(I);d||Ne(e)}function W(e="destroy"){d||(d=!0,n.signal?.removeEventListener("abort",g),r.signal?.removeEventListener("abort",g),v.finish("dismissed"),Oe?.(),ue.abort(),k?.destroy(),Q?.destroy(),r.destroy(),h.open&&h.close(),h.remove(),L.remove(),y(),e==="dismiss"&&z(n.onDismiss))}m=W;async function Ce(){if(!q||d||ne||M==="closing"||!M&&!A())return;if(!C){W("dismiss");return}let e=l.createElement("p");e.setAttribute("role","status"),e.textContent=a?"\u6B63\u5728\u5173\u95ED\u2026":"Closing\u2026",j||(j=l.createElement("div"),j.style.cssText=_.style.cssText,_.replaceWith(j),de.inert=!0),j.replaceChildren(e,P),M="closing",P.setAttribute("aria-disabled","true"),P.focus({preventScroll:!0});try{await C.dismiss()}catch(t){d||z(n.onError,t)}d||(M="retry",e.textContent=a?"\u672A\u80FD\u786E\u8BA4\u5173\u95ED\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not confirm closure. Try again.",P.textContent=a?"\u91CD\u8BD5\u5173\u95ED":"Retry closing",P.removeAttribute("aria-disabled"))}P.onclick=()=>{Ce()},h.addEventListener("cancel",e=>{e.preventDefault(),Ce()}),p.onclick=()=>{s&&N(s)};function Pe(e){v.finish("error",e),W()}function Ee(){if(!(!Le||q||d||ne||k&&!A()))try{let e=t=>{me?.(),k&&(h.showModal(),k.responsive&&h.focus({preventScroll:!0}),!t&&n.loading!=="host"&&He(h,k.type,k.responsive)),q=!0};C?C.present(()=>v.present(()=>e(!0))):v.present(e)}catch(e){Pe(e),G(e)}}try{if(B.type==="inline")me=Ge(L,o),o.append(L);else{let t={sm:420,md:640,lg:900};h.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in B?t[B.size]+"px":"100vw"}`,h.setAttribute("aria-label",w.document.name),P.textContent="\xD7",P.setAttribute("aria-label",a?"\u5173\u95ED":"Close"),Be(P,w.document.screen.theme),h.append(P,L),o.append(h),k=ze(h,{...w.document.screen,presentation:B},$e),k.latch(),me=je(h)}Q=Ze(de,{mode:"live",rendererUrl:r.webViewUrl,title:w.document.name,hostPresentation:()=>k?.type??B.type,onResize:t=>{k?.responsive&&k.setContentHeight(t+(j??_).getBoundingClientRect().height)},onAction(t,u={}){if(!q||d||M)return;if(!A()){ge();return}let i=r.view,b=i?.document.buttons[t];if(!b)return;if(b.type==="close"){N(async()=>{await n.onAction?.(t),W(n.onAction?"action":"dismiss")});return}if(b.type==="action"){s=async()=>{if(b.action.type==="event"){if(!n.onEvent)throw new S("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(b.action.event)}else n.onOpenUrl?await n.onOpenUrl(b.action.url):l.defaultView?.location.assign(b.action.url);await n.onAction?.(t),s=null},N(s);return}if(U&&r.canReselect===!1){x.textContent=a?"\u8BF7\u5148\u786E\u8BA4\u6216\u53D6\u6D88\u5F53\u524D\u8D2D\u4E70\u3002":"Confirm or cancel the current purchase first.",U.scrollIntoView?.({block:"nearest"}),U.querySelector("button")?.focus({preventScroll:!0});return}if((r.quote||I)&&r.canReselect===!1){s=r.quote?ve:xe,N(s);return}let V=i&&Z(b.product,u,i.capabilities);if(!i||!V){G(new S("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(n.onPurchaseIntent){s=null,N(async()=>{let K={actionId:t,productVersionId:V,selection:structuredClone(u),featureQuantities:_e(i.document.screen,V,u,i.capabilities)};he=!0,await n.onPurchaseIntent(K)});return}if(I&&I.actionId!==t){G(new S("COMMAND_PENDING","Finish the current purchase"));return}I||(I={requestId:crypto.randomUUID(),actionId:t,selection:u},ye=!1),N(xe)},onEscape:()=>{Ce()},onError:t=>{let u=new Error(t);!q&&!d&&Pe(u),G(u)},onRendered:t=>{t&&h.setAttribute("aria-label",t),Le=!0,Ee()}}),$e(),Q.update(w.document.screen,w.document.screen.strings.defaultLocale,{capabilities:w.capabilities,unavailableActions:Re(w),serverInput:{bindings:[],answers:{}}}),Oe=r.subscribe?.(fe),fe(r.view??w),await v.wait(Q.ready);let e=r.operation;(r.quote||e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete"))&&(s=ve,N(s))}catch(e){throw Pe(e),e}return{check:H,host:{get observing(){return pe},get recovery(){return et()},async prepareFallback(){if(te||d||M||he)return{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null};ie(!0);try{let e=await Fe(r);return e.type==="native"&&W(),e}finally{ie(!1)}},setSuspended(e){ne=e,L.hidden=e,e&&h.open?h.close():!e&&!q?Ee():!e&&!d&&q&&B.type!=="inline"&&!h.open&&h.showModal()},destroy:W,refresh:async()=>{if(!A()){if(r.view)return r.view;throw new S("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await r.refresh();return fe(e),Ee(),e}}}}export{It as showPaywall};
|
|
1
|
+
import{b as Je,c as Ke}from"./chunk-JGG4R75K.js";import{c as ze,d as He,e as Be,f as le,g as Qe,h as je,i as Ge,k as We}from"./chunk-6DTGBDYG.js";import{c as qe,f as Ve,g as Ie,h as Fe}from"./chunk-YAVWELIV.js";import"./chunk-BP6G3YGP.js";import{a as S}from"./chunk-QVGTHPWT.js";import{Z}from"./chunk-JXNNWCEB.js";import{a as z}from"./chunk-DSPLGTQI.js";import{La as ee,Na as _e,j as J,o as ke,z as X}from"./chunk-HDVLCRC6.js";async function Ye(o,n,C){if(n.status!=="complete")throw new S("INVALID_RESPONSE","A verified completed purchase is required");let y=o?X.parse(o):null;if(await C.onComplete?.(n),!y||!C.check)return;let m=X.parse(await C.check());if(m.internal_feature_id!==y.internal_feature_id||m.quantity!==y.quantity||y.observation!==void 0&&(m.observation===void 0||m.observation.requirementDigest!==y.observation.requirementDigest||m.observation.authority!==y.observation.authority||ke(m.observation.subject)!==ke(y.observation.subject)))throw new S("INVALID_RESPONSE","The access requirement changed");m.allowed&&await C.onAccessGranted?.(m)}var at={none:0,sm:4,md:8,lg:14,full:9999},ot={system:"system-ui,sans-serif",serif:"Georgia,serif",rounded:"ui-rounded,system-ui,sans-serif",mono:"ui-monospace,monospace"};function st(o){let[n,C,y]=[1,3,5].map(m=>{let g=Number.parseInt(o.slice(m,m+2),16)/255;return g<=.03928?g/12.92:((g+.055)/1.055)**2.4});return .2126*n+.7152*C+.0722*y}function Xe(o){let n=st(o.primary),C=(n+.05)/.05>1.05/(n+.05)?"#111318":"#FFFFFF",y=`color-mix(in srgb, ${o.text} 22%, ${o.background})`,m=`${at[o.radius]}px`,g=`appearance:none;margin:0;min-height:44px;padding:10px 18px;border:0;border-radius:${m};font:inherit;font-size:15px;font-weight:600;line-height:1.25;cursor:pointer;touch-action:manipulation`;return{root:`width:100%;box-sizing:border-box;background:${o.background};color:${o.text};font:14px/1.5 ${ot[o.font]}`,controls:"display:flex;gap:12px;padding:0 20px 12px;align-items:center;flex-wrap:wrap",message:"flex:1 1 200px;min-width:0;margin:0;font-size:13px",panel:`flex:1 0 100%;box-sizing:border-box;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid ${y};border-radius:${m}`,summary:"margin:0;font-size:15px;font-weight:600",terms:"display:flex;flex-direction:column;gap:4px;font-size:13px;opacity:.72",actions:"display:flex;gap:8px;flex-wrap:wrap;margin-top:4px",primary:`${g};background:${o.primary};color:${C}`,secondary:`${g};background:transparent;color:${o.text};box-shadow:inset 0 0 0 1px ${y}`,link:`${g};background:transparent;color:${o.text};opacity:.72;font-weight:500`}}function Ae(o){o.style.opacity=o.disabled?".55":"",o.style.cursor=o.disabled?"not-allowed":"pointer"}function Re(o){return Object.entries(o.document.buttons).filter(([,n])=>n.type==="checkout"&&n.product.type==="fixed"&&!Z(n.product,{},o.capabilities)).map(([n])=>n)}async function It(o,n,C){let y=We(o.ownerDocument),m=()=>{v.finish("dismissed"),y()},g=()=>m(),v=Qe(o,n,"paywall",()=>{m(),z(n.onDismiss)});n.signal?.throwIfAborted(),n.signal?.addEventListener("abort",g,{once:!0});let H=null,$,w,Se;try{if(v.start(!0),v.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(H=n.check?X.parse(await v.wait(n.check(),le)):null,H?.allowed)return v.finish("skipped"),n.signal?.removeEventListener("abort",g),y(),await n.onAccessGranted?.(H),{check:H,host:null};let[e,t]=await Promise.allSettled([v.wait(import("./screen-renderer-TEVGVUT5.js")),v.wait(n.start().then(i=>(v.cancelled&&i.destroy(),i)),le)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;Se=e.value,$=t.value,n.signal?.throwIfAborted(),$.signal?.throwIfAborted(),$.signal?.addEventListener("abort",g,{once:!0});let u=$.view??await v.wait($.refresh(),le);if(!u)throw new S("INVALID_RESPONSE","Paywall presentation is missing");$.signal?.throwIfAborted(),w=u}catch(e){throw v.finish("error",e),n.signal?.removeEventListener("abort",g),$?.signal?.removeEventListener("abort",g),$?.destroy(),y(),e}let r=$,{mountScreenPreview:Ze}=Se,l=o.ownerDocument,ue=new AbortController,L=l.createElement("section"),de=l.createElement("div"),_=l.createElement("div"),x=l.createElement("p"),p=l.createElement("button"),P=l.createElement("button"),h=l.createElement("dialog"),a=w.document.screen.strings.defaultLocale.startsWith("zh"),Te=a?"\u6B63\u5728\u5904\u7406\u2026":"Processing\u2026",T=Xe(w.document.screen.theme);L.dataset.indianaPaywall="",L.setAttribute("aria-label",w.document.name),L.style.cssText=T.root,_.style.cssText=T.controls,x.style.cssText=T.message,x.setAttribute("role","status"),P.style.cssText=T.link,P.textContent=a?"\u5173\u95ED":"Close",p.style.cssText=T.secondary,p.textContent=a?"\u91CD\u8BD5":"Retry",p.hidden=!0,_.append(x,p,P),L.append(de,_);let B=w.document.presentation,Q,Oe,pe=!1,De=JSON.stringify(w.capabilities);function fe(e){if(d)return;w=e;let t=JSON.stringify(e.capabilities);t!==De&&(Q?.updateCapabilities(e.capabilities,Re(e)),De=t),tt(e)}let k;function $e(){let e=l.defaultView;k?.responsive&&e&&Q?.resizeViewport?.(e.innerHeight,e.innerWidth)}let d=!1,te=!1,I=null,ne=!1,Le=!1,q=!1,me,he=!1,M,j;function et(){return te||d||M||he?{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}:Ie(r)}let A=()=>!d&&!ne&&!M&&n.canInteract?.()!==!1,ye=!1,s=null,U=null;function tt(e){r.quote||r.operation||(x.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":a?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let we=new Map;async function be(e){if(!(!A()||!e.checkoutUrl||we.get(e.operationId)===e.checkoutUrl)){we.set(e.operationId,e.checkoutUrl);try{n.onCheckoutUrl?await n.onCheckoutUrl(e.checkoutUrl):l.defaultView?.location.assign(e.checkoutUrl)}catch(t){throw we.delete(e.operationId),t}}}let G=e=>{x.textContent=e instanceof Error?e.message:a?"\u8BF7\u6C42\u5931\u8D25":"Request failed",z(n.onError,e),p.hidden=s===null},re=new WeakMap;function ie(e){te=e;for(let t of U?.querySelectorAll("button")??[])e?(re.set(t,t.disabled),t.disabled=!0):re.has(t)&&(t.disabled=re.get(t),re.delete(t)),Ae(t)}function ge(){x.textContent=a?"\u6682\u65F6\u65E0\u6CD5\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"This action is unavailable right now. Try again in a moment."}async function nt(e){if(n.beforeAction)try{await n.beforeAction()}catch(t){throw s=e,t}}async function N(e){if(!(te||d)){if(!A()){ge();return}ie(!0),p.hidden=!0,x.textContent=Te;try{if(await nt(e),d)return;if(!A()){s=e,p.hidden=!1,ge();return}await e()}catch(t){d||G(t)}finally{ie(!1),x.textContent===Te&&(x.textContent="")}}}async function rt(e){await Ye(H,e,n)}function Ue(e){return Ie(r).type==="recording"||Ve({quote:r.quote,operation:e,requestId:null,pending:!1,destroyed:!1,canReselect:r.canReselect}).type==="recording"}async function O(e){if(d)return;if(!A()){s=async()=>O(await r.read()),p.hidden=!1;return}if(x.textContent=Ke(e.status,a),Ue(e)){let i=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";x.textContent=i?a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u4F46\u4EA4\u6613\u8BB0\u5F55\u5931\u8D25\u3002\u8BF7\u8054\u7CFB\u5546\u6237\u4FEE\u590D\uFF0C\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":a?"\u4ED8\u6B3E\u548C\u5546\u6237\u5904\u7406\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u786E\u8BA4\u4EA4\u6613\u8BB0\u5F55\u3002\u8BF7\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",p.textContent=a?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",s=async()=>O(await r.read()),p.hidden=!1;return}if(e.problem){let i=e.problem;s=ae,p.textContent=a?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",G(new S(i.code,i.reason==="RESULT_UNKNOWN"?a?"\u4ED8\u6B3E\u7ED3\u679C\u5C1A\u672A\u786E\u5B9A\uFF0C\u8BF7\u6062\u590D\u539F\u64CD\u4F5C\uFF0C\u6682\u52FF\u91CD\u590D\u8D2D\u4E70\u3002":"The payment result is unknown. Recover the original purchase before buying again.":i.phase==="fulfillment"?a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":i.code==="CAPABILITY_UNAVAILABLE"?a?"\u5546\u6237\u5C1A\u4E0D\u652F\u6301\u672C\u6B21\u8D2D\u4E70\u6240\u9700\u7684\u5B8C\u6574\u80FD\u529B\uFF0C\u8BF7\u5904\u7406\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":i.code==="NOT_CONFIGURED"?a?"\u4ED8\u6B3E\u670D\u52A1\u8FDE\u63A5\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u8054\u7CFB\u5546\u6237\u540E\u6062\u590D\u539F\u64CD\u4F5C\u3002":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":a?"\u539F\u8D2D\u4E70\u64CD\u4F5C\u9700\u8981\u5904\u7406\uFF0C\u8BF7\u67E5\u8BE2\u6216\u6062\u590D\u6B64\u64CD\u4F5C\u3002":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,i));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(x.textContent=a?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u6B63\u5728\u7B49\u5F85\u5546\u6237\u5B8C\u6210\u5904\u7406\u3002":"Payment was recorded. Waiting for merchant fulfillment."),e.status==="complete"){s=null,await rt(e);return}if(e.status!=="pending"){if(r.canReselect===!1){x.textContent=a?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",p.textContent=a?"\u67E5\u8BE2\u7ED3\u679C":"Check result",s=async()=>O(await r.read()),p.hidden=!1;return}p.textContent=a?"\u91CD\u8BD5":"Retry",s=null,I=null;return}await be(e);let t=Date.now()+6e5,u=2e3;pe=!0,z(n.onObservationChange,!0);try{for(;!d&&Date.now()<t;){if(await Je(u,l,ue.signal),d)return;if(!A()){s=async()=>O(await r.read()),p.hidden=!1;return}let i=await r.read();if(!i.problem&&i.status==="pending"&&await be(i),i.status!=="pending"||i.problem||Ue(i)){await O(i);return}u=Math.min(u*1.5,3e4)}}finally{pe=!1,z(n.onObservationChange,!1)}s=async()=>O(await r.read()),p.hidden=!1}async function ve(){let e=await r.read();if(d)return;if(!A()){s=ve,p.hidden=!1;return}let t=r.quote;if(t&&qe(e,{operationId:t.operationId,currency:t.currency},"The original purchase operation changed"),t&&e.status==="pending"&&e.quoteFinalized===!1&&!e.confirmedAt&&!e.checkoutUrl&&!e.nativePurchase&&!e.merchantExecution&&!e.problem&&!r.pendingCancellation){Ne(t);return}await O(e)}async function ae(){U?.remove(),U=null,s=ae;let e=await r.confirm();if(!A()){s=ae,p.hidden=!1;return}if(e.problem){await O(e);return}if(e.status==="pending"){if(e.checkoutUrl)await be(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!n.onPurchase)throw new S("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await n.onPurchase({operation:e,signal:ue.signal})}}s=async()=>O(await r.read()),await O(e)}function Ne(e){U?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());x.textContent=t?a?"\u6B64\u62A5\u4EF7\u5DF2\u8FC7\u671F\u3002\u8BF7\u5148\u53D6\u6D88\uFF0C\u518D\u91CD\u65B0\u9009\u62E9\u3002":"This quote has expired. Cancel it, then choose again.":"";let u=l.createElement("div"),i=l.createElement("button"),b=l.createElement("button"),V=l.createElement("div"),K=l.createElement("p"),R=e.merchantTerms,oe=R?R.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),se=a?"zh-CN":"en",ce=R?.subscriptionTerms?.items??[],Y=R?ce.length===1&&ce[0]?.amountMinor===oe&&ce[0]:e.lines.length===1&&e.lines[0]?.catalogAmountMinor===oe&&e.lines[0];K.textContent=e.lines.map(c=>c.productName).join(", ")+" \xB7 "+(oe===null?a?`${J(R.subtotalMinor-R.discountMinor,e.currency)} + \u5F85\u786E\u8BA4\u7A0E\u8D39`:`${J(R.subtotalMinor-R.discountMinor,e.currency)} + tax confirmed at checkout`:J(oe,e.currency)+(Y?ee(Y.interval,se,Y.intervalCount??1):"")),i.textContent=a?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",i.disabled=t,b.textContent=a?"\u53D6\u6D88":"Cancel",u.style.cssText=T.panel,K.style.cssText=T.summary,V.style.cssText=T.actions,i.style.cssText=T.primary,b.style.cssText=T.secondary,Ae(i),i.onclick=()=>{N(ae)};let Me=async()=>{let c=await r.cancel();d||(u.remove(),U=null,await O(c))};b.onclick=()=>{s=Me,N(Me)};let D=l.createElement("div");if(D.style.cssText=T.terms,R){for(let f of ce){if(f===Y)continue;let E=l.createElement("p");E.textContent=J(f.amountMinor,e.currency)+ee(f.interval,se,f.intervalCount),D.append(E)}let c=R.subscriptionTerms?.trial;if(c){let f=l.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.days} \u5929\uFF1B${c.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.days}; ${c.cardRequired?"a payment method is required":"no payment method is required"}`,D.append(f)}for(let f of[...R.expectedEffects.map(E=>E.description),...R.requiredConsents.map(E=>E.summary)]){let E=l.createElement("p");E.textContent=f,D.append(E)}}else{for(let c of e.lines){if(c!==Y){let f=l.createElement("p");f.textContent=`${c.productName} \xB7 ${J(c.catalogAmountMinor,e.currency)}${ee(c.interval,se,c.intervalCount??1)}`,D.append(f)}for(let f of c.prepaid??[]){let E=l.createElement("p"),F=r.view?.capabilities.plans[c.productVersionId]?.prepaid?.find(it=>it.internalFeatureId===f.internal_feature_id);E.textContent=`${F?.name??f.internal_feature_id} \xB7 ${f.quantity} ${a?"\u4EFD":"packs"} \xD7 ${f.terms.units}`,F&&(E.textContent+=ee(F.reset==="week"||F.reset==="month"||F.reset==="year"?F.reset:"one_time",se,F.resetCount)),D.append(E)}if(c.trial){let f=l.createElement("p");f.textContent=a?`\u8BD5\u7528 ${c.trial.days} \u5929\uFF1B${c.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${c.trial.days}; ${c.trial.cardRequired?"a payment method is required":"no payment method is required"}`,D.append(f)}}if(!e.charge){let c=l.createElement("p");c.textContent=a?"\u76EE\u5F55\u4EF7\u683C\uFF1B\u6700\u7EC8\u91D1\u989D\u4EE5\u7ED3\u8D26\u65F6\u7A0E\u8D39\u548C\u8BD5\u7528\u89C4\u5219\u4E3A\u51C6\u3002":"Catalog price; the final charge depends on checkout taxes and trial terms.",D.append(c)}}for(let c of D.children)c.style.margin="0";V.append(i,b),u.append(K,...D.childElementCount?[D]:[],V),_.prepend(u),u.scrollIntoView?.({block:"nearest"}),i.focus({preventScroll:!0}),U=u,s=null}async function xe(){if(!I)return;if(s=xe,!ye){let t=r.view,u=t?.document.buttons[I.actionId],i=t&&u?.type==="checkout"?Z(u.product,I.selection,t.capabilities):null;if(!i)throw new S("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let b=await n.resolveOfferId?.({actionId:I.actionId,productVersionId:i});if(d)return;b!==void 0&&(I.offerId=b),ye=!0}if(!A()){p.hidden=!1;return}let e=await r.preview(I);d||Ne(e)}function W(e="destroy"){d||(d=!0,n.signal?.removeEventListener("abort",g),r.signal?.removeEventListener("abort",g),v.finish("dismissed"),Oe?.(),ue.abort(),k?.destroy(),Q?.destroy(),r.destroy(),h.open&&h.close(),h.remove(),L.remove(),y(),e==="dismiss"&&z(n.onDismiss))}m=W;async function Ce(){if(!q||d||ne||M==="closing"||!M&&!A())return;if(!C){W("dismiss");return}let e=l.createElement("p");e.setAttribute("role","status"),e.textContent=a?"\u6B63\u5728\u5173\u95ED\u2026":"Closing\u2026",j||(j=l.createElement("div"),j.style.cssText=_.style.cssText,_.replaceWith(j),de.inert=!0),j.replaceChildren(e,P),M="closing",P.setAttribute("aria-disabled","true"),P.focus({preventScroll:!0});try{await C.dismiss()}catch(t){d||z(n.onError,t)}d||(M="retry",e.textContent=a?"\u672A\u80FD\u786E\u8BA4\u5173\u95ED\uFF0C\u8BF7\u91CD\u8BD5\u3002":"Could not confirm closure. Try again.",P.textContent=a?"\u91CD\u8BD5\u5173\u95ED":"Retry closing",P.removeAttribute("aria-disabled"))}P.onclick=()=>{Ce()},h.addEventListener("cancel",e=>{e.preventDefault(),Ce()}),p.onclick=()=>{s&&N(s)};function Pe(e){v.finish("error",e),W()}function Ee(){if(!(!Le||q||d||ne||k&&!A()))try{let e=t=>{me?.(),k&&(h.showModal(),k.responsive&&h.focus({preventScroll:!0}),!t&&n.loading!=="host"&&He(h,k.type,k.responsive)),q=!0};C?C.present(()=>v.present(()=>e(!0))):v.present(e)}catch(e){Pe(e),G(e)}}try{if(B.type==="inline")me=Ge(L,o),o.append(L);else{let t={sm:420,md:640,lg:900};h.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in B?t[B.size]+"px":"100vw"}`,h.setAttribute("aria-label",w.document.name),P.textContent="\xD7",P.setAttribute("aria-label",a?"\u5173\u95ED":"Close"),Be(P,w.document.screen.theme),h.append(P,L),o.append(h),k=ze(h,{...w.document.screen,presentation:B},$e),k.latch(),me=je(h)}Q=Ze(de,{mode:"live",rendererUrl:r.webViewUrl,title:w.document.name,hostPresentation:()=>k?.type??B.type,onResize:t=>{k?.responsive&&k.setContentHeight(t+(j??_).getBoundingClientRect().height)},onAction(t,u={}){if(!q||d||M)return;if(!A()){ge();return}let i=r.view,b=i?.document.buttons[t];if(!b)return;if(b.type==="close"){N(async()=>{await n.onAction?.(t),W(n.onAction?"action":"dismiss")});return}if(b.type==="action"){s=async()=>{if(b.action.type==="event"){if(!n.onEvent)throw new S("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(b.action.event)}else n.onOpenUrl?await n.onOpenUrl(b.action.url):l.defaultView?.location.assign(b.action.url);await n.onAction?.(t),s=null},N(s);return}if(U&&r.canReselect===!1){x.textContent=a?"\u8BF7\u5148\u786E\u8BA4\u6216\u53D6\u6D88\u5F53\u524D\u8D2D\u4E70\u3002":"Confirm or cancel the current purchase first.",U.scrollIntoView?.({block:"nearest"}),U.querySelector("button")?.focus({preventScroll:!0});return}if((r.quote||I)&&r.canReselect===!1){s=r.quote?ve:xe,N(s);return}let V=i&&Z(b.product,u,i.capabilities);if(!i||!V){G(new S("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(n.onPurchaseIntent){s=null,N(async()=>{let K={actionId:t,productVersionId:V,selection:structuredClone(u),featureQuantities:_e(i.document.screen,V,u,i.capabilities)};he=!0,await n.onPurchaseIntent(K)});return}if(I&&I.actionId!==t){G(new S("COMMAND_PENDING","Finish the current purchase"));return}I||(I={requestId:crypto.randomUUID(),actionId:t,selection:u},ye=!1),N(xe)},onEscape:()=>{Ce()},onError:t=>{let u=new Error(t);!q&&!d&&Pe(u),G(u)},onRendered:t=>{t&&h.setAttribute("aria-label",t),Le=!0,Ee()}}),$e(),Q.update(w.document.screen,w.document.screen.strings.defaultLocale,{capabilities:w.capabilities,unavailableActions:Re(w),serverInput:{bindings:[],answers:{}}}),Oe=r.subscribe?.(fe),fe(r.view??w),await v.wait(Q.ready);let e=r.operation;(r.quote||e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete"))&&(s=ve,N(s))}catch(e){throw Pe(e),e}return{check:H,host:{get observing(){return pe},get recovery(){return et()},async prepareFallback(){if(te||d||M||he)return{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null};ie(!0);try{let e=await Fe(r);return e.type==="native"&&W(),e}finally{ie(!1)}},setSuspended(e){ne=e,L.hidden=e,e&&h.open?h.close():!e&&!q?Ee():!e&&!d&&q&&B.type!=="inline"&&!h.open&&h.showModal()},destroy:W,refresh:async()=>{if(!A()){if(r.view)return r.view;throw new S("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await r.refresh();return fe(e),Ee(),e}}}}export{It as showPaywall};
|
package/dist/react-native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as S,c as A,d as T}from"./chunk-
|
|
1
|
+
import{b as S,c as A,d as T}from"./chunk-LBGCSWVF.js";import{d as b,n as C,o as E,p as x,r as L}from"./chunk-JNML7SY4.js";import"./chunk-YAVWELIV.js";import"./chunk-BP6G3YGP.js";import{a as r}from"./chunk-QVGTHPWT.js";import"./chunk-Z5CW2N7E.js";import{Da as P}from"./chunk-JXNNWCEB.js";import"./chunk-DSPLGTQI.js";import{a as R}from"./chunk-HDVLCRC6.js";function k(t,d){let n,a=0,m=-1,l,i=!1,y=()=>{if(i)throw new r("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new r("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new r("IDENTITY_CHANGED","Customer identity changed during the native operation"),h=d.subscribeIdentity(()=>{a++,m=-1;let e=a;n&&t.nativeModule&&n.then(c=>t.nativeModule.reset(c,e)).catch(()=>{})}),I=t.nativeEvents?.(e=>{!n||!t.nativeModule||typeof e?.requestId!="string"||(async()=>{let c=await n;if(e.instanceId!==c)return;if(e.kind==="credential"){let w=a,f=null;try{if(!i&&e.revision===w){let N=await d.access();!i&&a===w&&(f=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,f)}return}let s=!1,u=a;try{if(i||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!i&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=y();if(d.snapshot()&&!t.nativeEvents)throw new r("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(i||a!==u)throw o();if(!n){let v=s.create(JSON.stringify({baseUrl:t.baseUrl??"https://api.longplayai.com",scope:t.scope,timeout:(t.timeoutMs??15e3)/1e3,credentialEvents:!!t.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let f=await n;if(i||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let O=(async()=>{if(await s.identify(f,JSON.stringify({revision:u,credentials:w})),i||a!==u)throw await s.reset(f,u),o();m=u})();l={epoch:u,task:O}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(f,e,JSON.stringify(c));if(i||a!==u)throw o();try{return JSON.parse(N)}catch{throw new r("INVALID_RESPONSE","Native host returned invalid JSON")}}async function g(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new r("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return g("showFunnel",{runToken:e})},showPaywall(e){return g("showPaywall",e)},showContent(e){return g("showContent",e)},purchaseSubscription(e,c){return p("purchaseSubscription",{operationId:e,accepted:c})},switchSubscription(e,c){return p("switchSubscription",{operationId:e,accepted:c})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(e){return p("manageSubscriptions",e?{productId:e}:{})},async dismiss(){a++,m=-1,n&&await y().reset(await n,a)},async destroy(){i||(i=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var M=P.trackUsage.request.shape.command,U=P.trackUsage.response;function F(t){let d=R.parse(t.scope),n=S({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,i=!1;n.subscribeIdentity(()=>{l++});let y=()=>{if(i)throw new r("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new r("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){i||(i=!0,l++,n.destroy(),await m.destroy())},funnel(){return A({...a,customerToken:y()})},resumeFunnel(o){return y(),C({...a,runToken:o})},paywall(o){return E(a,{...o,customerToken:y()})},async trackUsage(o){if(y(),!t.usageReporter)throw new r("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=M.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new r("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new r("IDENTITY_CHANGED","Customer identity changed during usage reporting");let g=U.parse(p);if(g.scope.projectId!==d.projectId||g.scope.environment!==d.environment)throw new r("INVALID_RESPONSE","Usage response scope differs");return g}}}export{r as LongplayError,x as createConfigurationSync,b as createFeatureClient,T as createFunnelProcess,L as createLocalFunnelClient,F as createLongplayReactNative};
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as xn}from"./chunk-UCOKLDSW.js";import{a as Bn,b as Ln,c as Un,d as Vn}from"./chunk-DZUPXUMV.js";import{a as m,b as cn,c as we,d as ve,e as un,f as dn,g as pn,h as ln,j as te,k as mn,l as U,m as N,o as fn,p as kn,q as Dn,r as Nn}from"./chunk-6SPHXEK4.js";import"./chunk-YAVWELIV.js";import"./chunk-H6PIJ4WG.js";import{a as s}from"./chunk-QVGTHPWT.js";import"./chunk-KOFZECHE.js";import{$ as He,$a as tn,D as Z,Da as p,E as ee,Ea as he,F as Me,I as le,J as Pe,K as _e,L as ke,M as xe,N as De,O as Ne,Oa as Je,P as Y,Pa as ge,Q as j,Qa as $,R as z,Ra as Ye,Sa as $e,Ta as We,Ua as ye,V as me,Va as Xe,W as Ve,Wa as Ze,X as qe,Xa as en,Ya as Ie,Za as nn,_a as W,cb as rn,da as V,db as on,ea as Ge,fa as fe,ga as ze,ha as Ke,hb as an,j as Ce,ja as ne,jb as sn,k as Ae,ka as K,l as ce,la as Qe,m as Mn,n as Pn,p as _n,r as Oe,s as de,t as X,u as J,v as pe,w as Te,y as be}from"./chunk-ZC6PDVLR.js";import"./chunk-DSPLGTQI.js";import{C as Fe,H as Be,Ia as je,P as Le,S as Ue,a as Re,o as ue,y as Fn}from"./chunk-HDVLCRC6.js";function re(e){return{async getCustomer(t){let n=p.getCustomer;return m(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=p.listCustomers;return m(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=p.updateCustomer;return m(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=p.createGuestCustomer;return m(e,n,t)},async resumeGuestSession(t){let n=p.resumeGuestSession;return m(e,n,t)},async claimGuestCustomer(t){let n=p.claimGuestCustomer;return m(e,n,t)},async revokeCustomerSessions(t){let n=p.revokeSessions;return m(e,n,t)},async createCustomerSession(t){return m(e,p.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return m(e,p.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function y(e,t){try{return e.parse(t)}catch{throw new s("INVALID_RESPONSE","Invalid gateway response")}}function hn(e){return{async checkEntitlement(t){let n=p.checkEntitlement,a=n.request.parse(t),r=await m(e,n,a,y);return cn(a.requirement,r.check,a.customerId,r.scope),r},async readHoldings(t){let n=p.readHoldings;return m(e,n,t,y)},async readSeats(t){let n=p.readSeats;return m(e,n,t,y)},async manageSeat(t){let n=p.manageSeat;return m(e,n,t,y)}}}function gn(e){return{async readAiPricing(t){let n=p.readAiPricing;return m(e,n,t,y)},async readUsage(t){let n=p.readUsage;return m(e,n,t,y)},async setUsage(t){let n=p.setUsage;return m(e,n,t,y)},async manageBalanceGrant(t){let n=p.manageBalanceGrant;return m(e,n,t,y)},async readBalanceSource(t){let n=p.readBalanceSource;return m(e,n,t,y)},async adjustBalance(t){let n=p.adjustBalance;return m(e,n,t,y)},async listBalanceGrants(t){let n=p.listBalanceGrants;return m(e,n,t,y)},async manageBillingLimits(t){let n=p.manageBillingLimits;return m(e,n,t,y)},async manageUsageEntity(t){let n=p.manageUsageEntity;return m(e,n,t,y)},async readUsageAnalytics(t){let n=p.readUsageAnalytics;return m(e,n,t,y)},async readCreditAnalytics(t){let n=p.readCreditAnalytics;return m(e,n,t,y)},async submitUsageBatch(t){let n=p.submitUsageBatch;return m(e,n,t,y)},async readUsageBatch(t){let n=p.readUsageBatch;return m(e,n,t,y)},async readLedger(t){let n=p.readLedger;return m(e,n,t,y)},async readCreditStatement(t){let n=p.readCreditStatement;return m(e,n,t,y)},async quoteBalance(t){let n=p.quoteBalance;return m(e,n,t,y)},async trackUsage(t){let n=p.trackUsage;return m(e,n,t,y)},async mutateBalance(t){let n=p.mutateBalance;return m(e,n,t,y)}}}function yn(e){return{async listInvoiceTemplates(t={}){let n=p.listInvoiceTemplates;return m(e,n,t,y)},async previewInvoice(t){let n=p.previewInvoice;return m(e,n,t,y)},async createInvoice(t){let n=p.createInvoice;return m(e,n,t,y)},async prepareBillingAdjustment(t){let n=p.prepareBillingAdjustment;return m(e,n,t,y)},async manageInvoice(t){let n=p.manageInvoice;return m(e,n,t,y)},async readInvoiceOperation(t){let n=p.readInvoiceOperation;return m(e,n,t,y)},async listInvoices(t){let n=p.listInvoices;return m(e,n,t,y)},async getInvoice(t){let n=p.getInvoice;return m(e,n,t,y)},async setupPayment(t){let n=p.setupPayment;return m(e,n,t,y)},async readPaymentSetup(t){let n=p.readPaymentSetup;return m(e,n,t,y)},async readBillingInvoice(t){let n=p.readBillingInvoice;return m(e,n,t,y)},async previewRefund(t){let n=p.previewRefund;return m(e,n,t,y)},async refund(t){let n=p.refund;return m(e,n,t,y)},async readRefund(t){let n=p.readRefund;return m(e,n,t,y)}}}function In(e){return{async previewSubscriptionBatch(t){let n=p.previewSubscriptionBatch;return m(e,n,t,y)},async confirmSubscriptionBatch(t){let n=p.confirmSubscriptionBatch;return m(e,n,t,y)},async readSubscriptionBatch(t){let n=p.readSubscriptionBatch;return m(e,n,t,y)},async abandonSubscriptionBatch(t){let n=p.abandonSubscriptionBatch;return m(e,n,t,y)},async manageSubscriptionTrial(t){let n=p.manageSubscriptionTrial;return m(e,n,t,y)},async readSubscriptionTrial(t){let n=p.readSubscriptionTrial;return m(e,n,t,y)},async listSubscriptions(t){let n=p.listSubscriptions;return m(e,n,t,y)},async listPurchases(t){let n=p.listPurchases;return m(e,n,t,y)},async listSubscriptionConflicts(t){let n=p.listSubscriptionConflicts;return m(e,n,t,y)},async retrySubscriptionConflict(t){let n=p.retrySubscriptionConflict;return m(e,n,t,y)},async previewUpdate(t){let n=p.previewUpdate;return m(e,n,t,y)},async update(t){let n=p.update;return m(e,n,t,y)},async readSubscriptionUpdate(t){let n=p.readSubscriptionUpdate;return m(e,n,t,y)},async restoreNativePurchase(t){let n=p.restoreNativePurchase;return m(e,n,t,y)},async verifySubscriptions(t){let n=p.verifySubscriptions;return m(e,n,t,y)},async previewAttach(t){let n=p.previewAttach;return m(e,n,t,y)},async recordMerchantEvent(t){return m(e,p.recordMerchantEvent,t,{request:"Invalid merchant event",parseResponse:y})},async attach(t){let n=p.attach;return m(e,n,t,y)},async readSubscriptionOperation(t){let n=p.readSubscriptionOperation;return m(e,n,t,y)}}}function wn(e){return{async grantModelBenefit(t){return m(e,p.grantModelBenefit,t,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(t){return m(e,p.readModelBenefit,t,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(t){let n=p.grantOffer;return m(e,{...n,request:n.request.refine(a=>!!a.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function vn(e){return{...hn(e),...gn(e),...yn(e),...In(e),...wn(e)}}function Sn(e){return{async getFeatures(t={}){let n=p.getFeatures;return m(e,n,t,y)},async evaluateFeatures(t){let n=p.evaluateFeatures;return m(e,n,t,y)}}}function En(e){return{async trackEvents(t){let n=p.trackEvents;return m(e,n,t,y)}}}function Rn(e){return{async resolveContent(t){let n=p.resolveContent;return m(e,n,t,y)},async resolvePaywall(t){let n=p.resolvePaywall,a=n.request.parse(t),r=await m(e,n,a,y);return we(a,r.paywall.check,r.scope),r},async resolveOffering(t){let n=p.resolveOffering,a=n.request.parse(t),r=await m(e,n,a,y);return we(a,r.check,r.scope),r}}}function qn(e){U(e.apiKey,"Secret API keys must stay on your backend");let n=N(e).request;return{async sendMessage(a){let r=p.sendMessage;return r.response.parse(await n(r.path,r.request.parse(a)))},async readMessage(a){let r=p.readMessage;return r.response.parse(await n(r.path,r.request.parse(a)))},...re(n),...vn(n),...Sn(n),...En(n),...Rn(n)}}function Se(){if(typeof window<"u")throw new s("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var Cn=()=>new s("CONFLICT","Process synchronization is in progress",425),B=()=>new s("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Hn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),oe=class extends s{constructor(n){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:n.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=n}result};function Gn(e){if(U(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new s("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=N(e),n=re(t.request),a=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(h){let o=await e.resolveUser(h);if(o!==null&&(typeof o?.externalUserId!="string"||!o.externalUserId||o.externalUserId!==o.externalUserId.trim()||o.externalUserId.startsWith("gg_guest_")))throw new s("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return o}async function i(h){let o=await e.resolveContext(h);if(o?.confirmed!==!0||!o.processKey||!o.guestKey)throw new s("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:a+"run:"+o.processKey,guest:a+"guest:"+o.guestKey}}async function u(h,o){for(let I=0;I<8;I++){let R=await e.store.read(h),S=o(R?structuredClone(R.value):null);if(R&&Hn(R.value,S)||await e.store.compareAndSwap(h,R?.revision??null,S))return S}throw Cn()}async function l(h){let o=await e.store.read(h);if(!o)throw new s("NOT_FOUND","Open the process before continuing",404);return o.value}async function d(h){let o=await l(h);for(let I of o.revocations??[])await n.revokeCustomerSessions(I),await u(h,R=>{if(!R)throw B();return R.revocations=R.revocations?.filter(S=>S.sessionId!==I.sessionId),R})}async function w(h,o){let I=ge.parse(h);return o?t.requestWithCredential("funnel-processes",I,o):t.request("funnel-processes",I)}function E(h,o){if(o.scope.projectId!==e.scope.projectId||o.scope.environment!==e.scope.environment||h.run&&(h.run.id!==o.run.id||h.run.source.versionId!==o.run.source.versionId||h.run.source.id!==o.run.source.id||h.run.runExpiresAt!==o.run.runExpiresAt||h.run.identity.startedAs!==o.run.identity.startedAs||h.run.identity.participantId!==o.run.identity.participantId||h.run.identity.binding&&h.run.identity.binding.id!==o.run.identity.binding?.id)||h.runToken&&o.runToken&&h.runToken!==o.runToken)throw new s("INVALID_RESPONSE","Process identity or Run changed")}async function C(h,o,I){return u(h,R=>{if(!R)throw new s("NOT_FOUND","Process handle is missing",404);return E(R,o),(!R.run||o.run.revision>=R.run.revision)&&(R.run=o.run),R.runToken??=o.runToken,I!==void 0&&(R.target=I),R})}async function c(h,o){if(o.detached)throw new s("UNAUTHENTICATED","The process is detached",401);let I=o.run?.identity.binding?.customerId??o.run?.identity.participantId;if(!I)throw new s("INVALID_RESPONSE","Process participant is missing");if(o.session?.customerId===I&&Date.parse(o.session.expiresAt)>Date.now()+3e4)return o.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},S=await u(h,O=>{if(!O||O.detached||O.run?.id!==o.run?.id)throw B();if(O.sessionLease&&O.sessionLease.until>Date.now())throw Cn();return O.sessionLease=R,O}),A;try{if(S.session?.customerId===I&&Date.parse(S.session.refreshExpiresAt)>Date.now())try{if(A=Oe.parse(await t.requestWithCredential("customer-sessions/refresh",{},S.session.refreshToken)),A.sessionId!==S.session.sessionId)throw new s("INVALID_RESPONSE","Refresh changed the logical session")}catch(P){if(!(P instanceof s)||P.status!==401)throw P}if(A??=S.run?.identity.binding?await n.createCustomerSession(I):await n.resumeGuestSession({guestToken:S.guest.token}),A.customerId!==I)throw new s("INVALID_RESPONSE","Session Customer changed");let O=A;return await u(h,P=>{if(!P||P.detached||P.sessionLease?.id!==R.id||P.run?.identity.binding?.id!==o.run?.identity.binding?.id)throw new s("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return P.session=O,delete P.sessionLease,P}),A}catch(O){throw A&&A.sessionId!==S.session?.sessionId&&await n.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await u(h,P=>{if(!P)throw B();return P.sessionLease?.id===R.id&&delete P.sessionLease,P}).catch(()=>{}),O}}let f;async function g(){if(f??=Xe.parse(await w({contract:V,operation:"describe"})),f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment)throw B();return f}async function v(h,o,I=!1){let R=await r(h),S=await l(o);if(S.issuingKeyId!==(await g()).keyId)throw new s("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!S.runToken||!S.run)throw new s("CONFLICT","Recover the original start first",425);if(S.detached){if(!I)throw new s("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(S.run.identity.binding&&(!R||S.target&&S.target!==R.externalUserId))throw B();await d(o),S=await u(o,A=>{if(!A||A.run?.id!==S.run?.id)throw B();return delete A.detached,A})}if(!S.runToken||!S.run)throw new s("INVALID_RESPONSE","Process identity is missing");if(S.run.identity.binding){if(R&&!S.target){let A=ye.parse(await w({contract:V,operation:"binding_status",runToken:S.runToken,requestId:S.bindingIntent?.requestId??S.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==S.run.identity.binding.id)throw B();S=await u(o,O=>{if(!O)throw B();return O.target=R.externalUserId,O})}if(!R||S.target!==R.externalUserId)throw B()}else if(R){if(!S.guest)throw B();S=await u(o,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw B();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=S.bindingIntent;try{let O=We.parse(await w({contract:V,operation:"bind_customer",...A,runToken:S.runToken,guestToken:S.guest.token,claimRequestId:S.guest.claimRequestId,expectedBindingId:null}));S=await C(o,O,R.externalUserId)}catch(O){let P=ye.parse(await w({contract:V,operation:"binding_status",...A,runToken:S.runToken,guestToken:S.guest.token}));if(P.state!=="bound")throw O;S=await u(o,D=>{if(!D?.run||D.run.id!==P.binding.runId)throw B();return D.run.identity.binding={id:P.binding.id,customerId:P.binding.customerId,acceptedAt:P.binding.acceptedAt},D.target=R.externalUserId,D})}}return{state:S,session:await c(o,S)}}async function _(h,o,I,R){try{return await R(I)}catch(S){if(!(S instanceof s)||S.status!==401)throw S;return await u(o,A=>{if(!A||A.detached)throw S;return A.session?.accessToken===I.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await v(h,o))}}async function x(h,o,I=!1){let R=await i(h),S=await v(h,R.process,I),A=$.parse(await _(h,R.process,S,O=>w({...o,customerToken:O.session.accessToken},O.state.runToken)));return await C(R.process,A),A}return{async open(h,o){o=$e.parse(o);let I=await i(h),R=await g(),S=I.guest+":"+R.keyId,A=await e.store.read(I.process);if(!A){let F=await r(h),T,M,k;if(F)T={type:"customer",customer:{type:"externalUserId",value:F.externalUserId}};else{let q=await e.store.read(S);if(q)try{k=await n.resumeGuestSession({guestToken:q.value.token}),M=q.value}catch(L){if(!(L instanceof s)||L.status!==401)throw L}let H={token:Se(),claimRequestId:crypto.randomUUID()};M=await u(S,L=>M??(L&&L.token!==q?.value.token?L:H)),T={type:"guest",guestToken:M.token}}await u(I.process,q=>q??{issuingKeyId:R.keyId,start:ge.parse({...o,contract:V,requestId:crypto.randomUUID(),source:T}),...M?{guest:M}:{},...F?{target:F.externalUserId}:{},...k?{session:k}:{}}),A=await e.store.read(I.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new s("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==o.funnelId||O.start.operation!==o.operation)throw new s("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let k=await r(h);if(!k||k.externalUserId!==O.target)throw B()}let F=await w(O.start),T=Ye.safeParse(F);if(T.success)throw new oe(T.data);let M=$.parse(F);if(!M.runToken)throw new s("INVALID_RESPONSE","Process credential is missing");O=await C(I.process,M)}let P=await v(h,I.process,!0),D=$.parse(await _(h,I.process,P,F=>w({contract:V,operation:"get",customerToken:F.session.accessToken},F.state.runToken)));return await C(I.process,D),{...D,runToken:O.runToken}},async syncIdentity(h){return x(h,{contract:V,operation:"get",customerToken:""},!0)},async get(h,o={}){return x(h,{...o,contract:V,operation:"get",customerToken:""})},async review(h,o){return x(h,{contract:V,operation:"review",customerToken:"",...o?{receiptId:o}:{}})},async command(h,o,I){let R=await i(h),S=await v(h,R.process),A=$.parse(await _(h,R.process,S,O=>w({contract:V,operation:"command",command:o,identity:{bindingId:I},customerToken:O.session.accessToken},O.state.runToken)));return await C(R.process,A),A},async pageExperiments(h,o,I=[]){let R=await i(h),S=await v(h,R.process);return Je.parse(await _(h,R.process,S,A=>w({contract:V,operation:"page_experiments",release:o,usedReceiptIds:I,customerToken:A.session.accessToken},A.state.runToken)))},async detach(h){let o=await i(h);await u(o.process,I=>{if(!I)throw B();return I.session&&!I.revocations?.some(R=>R.sessionId===I.session.sessionId)&&(I.revocations??=[]).push({customerId:I.session.customerId,sessionId:I.session.sessionId}),I.detached=!0,delete I.session,delete I.sessionLease,I}),await d(o.process)},destroy(){t.dispose()}}}async function jn(e,t){U(e.apiKey,"Renewal requires your backend");let n=N(e),a=en.parse(un(e,await n.request("funnels",Ze.parse({...t,operation:"renew_run"}))));if(a.run.id!==t.runId)throw new s("INVALID_RESPONSE","Run renewal identity changed");return a}function An(e){let t=pn(e),n=l=>{throw new s("INVALID_RESPONSE",l)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let a=new Set(["entry","condition","feature","split","end","output"]);for(let l of t.nodes.values()){if(!a.has(l.type))throw new s("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&n("Local next exit is unavailable"),l.type==="feature"){let d=l.resources.featureKey;(!d||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(t.features,d))&&n("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let d=e.conditions[l.id];(!d||!l.outputs.default||d.some((w,E)=>w.port!==`case:${E}`||!l.outputs[w.port]))&&n("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let d=e.evaluation.terminals[l.id];if(!d)throw new s("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&n("A terminal cannot have outgoing edges"),d.output?.type==="feature"&&!Object.hasOwn(t.features,d.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let d of Object.values(l.outputs))t.nodes.has(d)||n("Local target is unavailable")}let r=new Set,i=new Set;function u(l){if(i.has(l)&&n("Local graph contains a cycle"),!r.has(l)){i.add(l);for(let d of Object.values(t.nodes.get(l).outputs))u(d);i.delete(l),r.add(l)}}return u(e.topology.entry),r.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(l){let d={},w=l.context;w.features=t.features,w.savedGroups=t.savedGroups;let E=()=>{w.attributes=Ge({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:d,savedGroups:t.savedGroups})};E();let C=e.topology.entry,c=0;for(;;){let f=t.nodes.get(C);if(f.type==="end"||f.type==="output"){let g=e.evaluation.terminals[C],v=g.output,_=v?.type==="feature"?t.feature(v.featureKey,w):v?.type==="variable"?qe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:d,parameters:l.parameters,attributes:l.attributes,savedGroups:t.savedGroups}):v?.value??null;return me(e.evaluation.outputSchema,_)||n("Local output does not match its declaration"),{outcome:g.outcome,value:_}}if(c++>=e.evaluation.maxTransitions)throw new s("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(f.type==="entry")C=f.outputs.next;else{let g=t.evaluate(C,w);if(f.type==="feature"){let v=f.writes.value,_=g.value??null;me(e.evaluation.variables[v],_)||n("Local Feature value does not match its declaration"),Ve(e.evaluation.variables,{writes:f.writes},{[v]:_}),d[v]=_,E()}C=g.target}}}}}import{z as On}from"zod";function Tn(e,t,n){let a=Le.parse(e.attributes);if(["parameters","answers","results"].some(h=>Object.hasOwn(a,h)))throw new s("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=je.parse(e.parameters??{}),i=On.record(On.string(),Ue).parse(e.stickyBucketAssignmentDocs??{});for(let[h,o]of Object.entries(i))if(h!==`${o.attributeName}||${o.attributeValue}`||!Object.hasOwn(a,o.attributeName)||Be(a[o.attributeName])!==o.attributeValue)throw new s("INVALID_REQUEST","Sticky document identity does not match this session");let u=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,d=e.onExperimentViewed,w=e.onError,E=new Map,C=new Set,c={},f=Promise.resolve();function g(h){let o=f.then(()=>(n(),h()));return f=o.catch(()=>{}),o}function v(h){try{w?.(h)}catch{}}function _(h){try{let o=h();o&&typeof o.catch=="function"&&o.catch(v)}catch(o){v(o)}}async function x(){for(let[h,o]of E){if(n(),u)try{await u(structuredClone(o))}catch{throw new s("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),E.delete(h)}}return{evaluate(h={}){let o=h.track===!0;return g(async()=>{let I=await t();n(I);let R=new Set(C),S={...c},A=new Map,O=[],P={stickyBucketAssignmentDocs:structuredClone(i),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...o?{trackedExperiments:R,trackedFeatureUsage:S,onExperimentViewed(T,M){let k=structuredClone(T),q=structuredClone(M);d&&O.push(()=>d(structuredClone(k),structuredClone(q)))},onFeatureUsage(T,M){let k=structuredClone(M);l&&O.push(()=>l(T,structuredClone(k)))}}:{}},D=I.program.evaluate({attributes:a,parameters:r,context:P});n(I);for(let[T,M]of A)i[T]=M,E.set(T,M);await x(),n(I),o&&(C=R,c=S);for(let T of O)_(T);let F=I.configuration;return structuredClone({evaluationMode:"local",scope:F.scope,funnelId:F.funnelId,versionId:F.versionId,evaluationRevision:F.evaluationRevision,generation:F.growth.generation,...D})})},flush:()=>g(x),get stickyBucketAssignmentDocs(){return n(),structuredClone(i)}}}var zn=6e4;function ae(e){if(typeof window<"u")throw new s("SERVER_ONLY","Local Funnel sessions run on your backend");let t=Re.parse(e.scope),n=e.funnelId,a=e.load,r,i,u,l=0,d=C=>Date.now()>=C.expiresAt;async function w(){if(i)return i;let C=l;r=void 0;let c=(async()=>{let f=await a();if(C!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(f&&typeof f=="object"&&"evaluationMode"in f&&f.evaluationMode==="remote")throw y(W,f),new s("EVALUATION_MODE","This Funnel requires remote decide");let g=y(tn,f);if(C!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(g.scope.projectId!==t.projectId||g.scope.environment!==t.environment||g.funnelId!==n)throw new s("SCOPE_MISMATCH","Local configuration scope changed");if(g.growth.scope.projectId!==t.projectId||g.growth.scope.environment!==t.environment||g.growth.expiresAt!==g.expiresAt)throw new s("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+zn,g.expiresAt?Date.parse(g.expiresAt):1/0);if(Date.now()>=v)throw new s("CONFIGURATION_EXPIRED","Refresh expired local rules");let _=JSON.stringify([t.projectId,t.environment,n,g.versionId,g.evaluationRevision,g.growth.generation]),x=[g.topology,g.conditions,g.evaluation,g.growth.features,g.growth.experiments,g.growth.savedGroups];if(u?.key===_&&!mn(u.body,x))throw new s("INVALID_RESPONSE","Immutable local configuration identity changed");return u?.key!==_&&(u={key:_,body:x,program:An(g)}),r={key:_,configuration:g,expiresAt:v,program:u.program},r})();i=c;try{return await c}finally{i===c&&(i=void 0)}}function E(){return i??(r&&!d(r)?Promise.resolve(r):w())}return{session(C){let c=l;return Tn(C,E,f=>{if(e.assertUsable?.(),c!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(f&&(d(f)||r?.key!==f.key))throw new s("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await w()).configuration)},reset(){l++,r=void 0,i=void 0,u=void 0}}}function Kn(e,t){let n=e.snapshot?.generation,a=ae({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),r=e.subscribe(()=>{let u=e.snapshot?.generation;e.fresh&&u!==n&&(n=u,a.refresh().catch(()=>{}))}),i=a.session;return Object.assign(a,{session(u){let l=i(u),d=l.evaluate;return Object.assign(l,{async evaluate(...w){return e.fresh||await e.refresh(),d(...w)}})},destroy(){r(),a.reset()}})}function Qn(e){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>fn(e,t)}}var Q=class extends s{constructor(n,a){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,a);this.decisionId=n;this.decisionRequestId=a}decisionId;decisionRequestId};async function ie(e,t,n,a){let{decisionId:r,requestId:i}=e,u=e,l=250,d=0;for(;;){if(u.decisionId!==r||u.requestId!==i||u.decision&&!te(u.decision,t))throw new s("INVALID_RESPONSE","Decision request or customer changed");if(u.decision)return u.decision;if(u.status==="failed")throw new s("DECISION_FAILED","Decision execution failed",503,i);if(Date.now()>=n)throw new Q(r,i);if(await new Promise(w=>setTimeout(w,Math.min(Math.max(l,d-Date.now()),n-Date.now()))),Date.now()>=n)throw new Q(r,i);l=Math.min(1e3,l*2);try{u=await a(r,n)}catch(w){if(w instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(w.code)){d=Date.now()+(w.retryAfterSeconds??0)*1e3;continue}throw w}}}function Ee(e){if("remoteEval"in e)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Funnel decisions are requested by your backend");let t,n,a=new Map;async function r(d,w){let E=d;E.status!=="pending"&&a.delete(E.decisionId);for(let C=0;C<32&&E.evaluation;C++){let c=E.evaluation;if(c.runId!==E.decisionId)throw new s("INVALID_RESPONSE","Local evaluation Run changed");let f=a.get(E.decisionId);if(!f&&c.type==="evaluate_segment"){let v=sn.parse(await i({operation:"segment_configuration",funnelId:e.funnelId,versionId:c.versionId},w));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==c.versionId||v.configuration.evaluationRevision!==c.policyRevision)throw new s("SCOPE_MISMATCH","Original decision segment configuration changed");if(a.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding decisions first");f={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:he(E.decisionId,c.visit,`segment:${c.revision}`),nodeId:c.nodeId,visit:c.visit,revision:c.revision,policyRevision:c.policyRevision,generation:v.configuration.growth.generation,...ln(v.configuration,v.document,c)},a.set(E.decisionId,f)}if(!f){if(c.type!=="evaluate")throw new s("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==c.versionId||n.evaluationRevision!==c.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=W.parse(await i({operation:"configuration",funnelId:e.funnelId,versionId:c.versionId},w))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new s("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==c.versionId||n.evaluationRevision!==c.policyRevision)throw new s("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(a.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding Local decisions first");f={operation:"evaluate_decision",decisionId:E.decisionId,requestId:he(E.decisionId,c.visit,"evaluation"),nodeId:c.nodeId,visit:c.visit,revision:c.revision,receiptId:c.receiptId,policyRevision:c.policyRevision,generation:n.growth.generation,result:an(n,c.nodeId,c,dn)},a.set(E.decisionId,f)}let g=K.parse(await i(f,w));if(g.decisionId!==d.decisionId||g.requestId!==d.requestId)throw new s("INVALID_RESPONSE","Decision identity changed during local evaluation");a.delete(E.decisionId),E=g}return E}async function i(d,w,E=!1){return N({...e,fetch:(c,f)=>{let g=new Headers(f?.headers);return g.set("Accept-Encoding","identity"),E&&g.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(c,{...f,headers:g})},timeoutMs:Math.min(e.timeoutMs??1e4,w?Math.max(1,w-Date.now()):12e4)}).request("funnels",d)}async function u(d,w){let E=K.parse(await i(ne.parse({operation:"read_decision",decisionId:d}),w));if(E.decisionId!==d)throw new s("INVALID_RESPONSE","Decision identity changed");return r(E,w)}async function l(d,w,E=!1){let C=ne.options[0].parse({...d,operation:"decide",funnelId:e.funnelId}),c;try{c=K.parse(await i(C,w,E))}catch(f){throw f instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(f.code)?new s("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",f.status,d.requestId):f}if(c.requestId!==d.requestId||c.decision&&!te(c.decision,C.customer))throw new s("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(c,w),customer:C.customer}}return{local(){return t??=ae({scope:e.scope,funnelId:e.funnelId,load:()=>i({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let d=W.parse(await i({operation:"configuration",funnelId:e.funnelId}));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment||d.funnelId!==e.funnelId)throw new s("SCOPE_MISMATCH","Configuration scope changed");return d},features(d={}){return ve({...d,scope:e.scope,load:async()=>He.parse(await i({operation:"feature_config",funnelId:e.funnelId}))})},read:d=>u(d),async submit(d){return(await l(d,void 0,!0)).response},async decide(d){let w=Date.now()+3e4,E=await l(d,w);return ie(E.response,E.customer,w,u)},async reportUsed(d){let w=Qe.parse(await i(ne.parse({...d,operation:"report_used"})));if(w.decisionId!==d.decisionId||w.eventId!==d.eventId)throw new s("INVALID_RESPONSE","Usage receipt identity changed");return w}}}function Jn(e){U(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let a=rn.parse(n);if(a.orderId!==a.receiptId)throw new s("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=a.nativeEvidence,i={requestId:a.requestId,customerToken:a.customerToken,purchaseIntentId:a.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},u=p.restoreNativePurchase.response.parse(await t.request(p.restoreNativePurchase.path,i));if(u.operation.requestId!==a.requestId||u.operation.purchaseIntentId!==a.orderId)throw new s("INVALID_RESPONSE","Native receipt request identity changed");let l=on.parse({scope:u.scope,requestId:a.requestId,orderId:u.operation.orderId,receiptId:u.operation.orderId,orderStatus:u.operation.status,refunded:u.operation.refunded,...u.operation.completion===null?{}:{nativeCompletion:{orderId:u.operation.orderId,receiptId:u.operation.orderId,...u.operation.completion}}});if(l.requestId!==a.requestId||l.orderId!==a.orderId||l.receiptId!==a.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Current order receipt scope changed");return l}}}import{z as Yn}from"zod";var G=Yn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function $n(e,t){let n=G.parse(e.inputTokens.total),a=G.parse(e.outputTokens.total),r=G.parse(e.inputTokens.cacheRead??0),i=G.parse(e.inputTokens.cacheWrite??0),u=G.parse(e.outputTokens.reasoning??0);if(r+i>n||u>a||e.inputTokens.noCache!==void 0&&G.parse(e.inputTokens.noCache)!==n-r-i||e.outputTokens.text!==void 0&&G.parse(e.outputTokens.text)!==a-u)throw new s("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-r-i,cache_read:r,cache_write:i,output:t==="output"?a:a-u,reasoning:t==="separate"?u:0,input_audio:0,output_audio:0}}function Wn(e){if(typeof window<"u")throw new s("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new s("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(a){await e.persist({context:a,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(a,r){let i={context:a,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(i);let u=e.mapTokens?e.mapTokens(r):$n(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:u});await e.persist({...i,tokens:u,quote:l,phase:"quoted"});let d=await e.pricing.trackTokens(e.client,{...a,quote:l});if(!d.receipt.accepted)throw new s("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...i,tokens:u,quote:l,receipt:d,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:a}){let r=await e.context(),i;try{i=await a()}catch(u){throw await t(r),u}return await n(r,i.usage),i},async wrapStream({doStream:a}){let r=await e.context(),i;try{i=await a()}catch(E){throw await t(r),E}let u=!1,l=!1,d=i.stream.getReader();async function w(){u||l||(l=!0,await t(r))}return{...i,stream:new ReadableStream({async pull(E){try{let{value:C,done:c}=await d.read();if(c){if(!u)throw await w(),new s("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(C.type==="finish"){if(u)throw new s("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");u=!0,await n(r,C.usage)}E.enqueue(C)}catch(C){try{await w()}finally{E.error(C),await d.cancel(C)}}},async cancel(E){try{await w()}finally{await d.cancel(E)}}})}}}}function Xn(e){U(e.apiKey,"Funnel receipts are sent by your backend");let t=N(e);return{async signal(n){let a=fe.parse({...n,operation:"signal"}),r=ze.parse(await t.request("funnels",a));if(r.runId!==n.runId||r.eventId!==n.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(n){let a=fe.parse({operation:"read_results",runId:n}),r=Ke.parse(await t.request("funnels",a));if(r.runId!==n||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Result identity changed");return r}}}function Zn(e){if("remoteEval"in e)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Campaign entry requires your backend");let t=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let a=Date.now()+(e.timeoutMs??3e4),r=Ie.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),i=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,a-Date.now()))}),u=K.parse(await i.request("funnels",r));if(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");return ie(u,r.customer,a,(l,d)=>Ee({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,d-Date.now()))}).read(l))},async start(n){let a=Ie.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),r=nn.parse(await t.request("funnels",a));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||a.customer.type==="id"&&r.customerId!==a.customer.value))throw new s("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}import{z as et}from"zod";var b=class extends Error{constructor(n,a=409,r=!1,i="fix_request"){super(n);this.code=n;this.status=a;this.retryable=r;this.recovery=i}code;status;retryable;recovery};function nt(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=be.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},a=t.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,i]of Object.entries(pe))if(i.command&&t.capabilities.includes(r)&&!(r==="catalog"&&t.catalog==="static")&&!e.handlers[i.command])throw new Error(`Missing merchant command handler: ${i.command}`);if(a&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(i){let u=crypto.randomUUID(),l="bridge.ping",d,w=async(E,C,c=!1)=>{let f=JSON.stringify({bridgeVersion:de,requestId:u,command:l,scope:n,[c?"error":"data"]:E});if(new TextEncoder().encode(f).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(f,{status:C,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":u,...d?await j(f,d,"response"):{}}})};try{if(i.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(de)||i.method!=="POST"||new URL(i.url).pathname!==X)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(i.headers.get("Content-Type")??""))throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=i.body?.getReader();if(!E)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let C=new TextDecoder("utf-8",{fatal:!0}),c="",f=0;try{for(;;){let M=await E.read();if(M.done)break;if(f+=M.value.byteLength,f>16384)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",413);c+=C.decode(M.value,{stream:!0})}c+=C.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let g=_e.safeParse(JSON.parse(c));if(!g.success)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=g.data;if(u=v.requestId,l=v.command,Object.keys(n).some(M=>v.scope[M]!==n[M]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let _=v.command==="bridge.ping"||v.command==="bridge.describe",x=v.command==="catalog.read";if((_||x||i.headers.has(Y))&&(d=e.authentication.find(M=>M.keyId===i.headers.get(Y)),!d||!await z(c,i.headers,d,"request")))throw d=void 0,new b("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return w(le["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return w(t,200);let h=Object.entries(pe).find(([,M])=>M.command===v.command);if(!h||!t.capabilities.includes(h[0]))throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let o=e.handlers[v.command];if(!o)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!x&&i.headers.has("Cookie")&&(i.headers.get("Origin")!==new URL(i.url).origin||["cross-site","same-site"].includes(i.headers.get("Sec-Fetch-Site")??"")))throw new b("MERCHANT_BRIDGE_FORBIDDEN",403);let I=x?{kind:"service"}:await e.authorize(i,v),R=I.kind,S=["purchase.execute","subscription.change","refund.execute"].includes(v.command),A=S||v.command==="operation.read";if(!(A&&d!==void 0&&R==="service")&&(v.command==="refund.execute"?R!=="administrator":!x&&R!=="user"))throw new b("MERCHANT_BRIDGE_FORBIDDEN",403);if(I.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!et.uuid().safeParse(I.customerId).success)throw new b("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let P=o,D=le[v.command].parse(v.data),F={request:i,command:v.command,scope:n,principal:I},T;if(A){let M=Z.parse(D);if(I.kind==="user"&&I.customerId!==M.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let k=ee.parse(await e.resolveOperationAuthority(M,F));if(k.operationId!==M.operationId||k.customerId!==M.customerId||Object.keys(n).some(H=>k.scope[H]!==n[H]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);F.authority=k;let q=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":k.instruction.type;if(k.instruction.type!==q)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!S)T=ce.parse(await P(D,F));else{if(k.confirmedAt===null)throw new b("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=ce.parse(await e.handlers["operation.read"](M,{...F,command:"operation.read"}));if(H.operationId!==M.operationId||H.customerId!==M.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!k.initialExecutionAllowed)throw new b("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(k.instruction.expiresAt)<=Date.now())throw new b("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||Ae(k.instruction).some(L=>!t.billingEvents.some(bn=>bn===L))||Ce(k.instruction).some(L=>!t.profiles.includes(L)))throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Me.parse(await P(D,F))}catch(L){throw L instanceof b?L:new b("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==q)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Pe[v.command].parse(await P(D,F));if(I.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==I.nativeUserId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&I.customerId&&T.session.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&I.customerId&&T.presentation.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Z.parse(v.data).operationId||T.customerId!==Z.parse(v.data).customerId))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w(T,S&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let C=E instanceof b?E:E instanceof SyntaxError?new b("MERCHANT_BRIDGE_INVALID_REQUEST",400):new b("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return w({code:C.code,message:C.code,retryable:C.retryable,recovery:C.recovery},C.status,!0)}}}function tt(e){return async(t,n)=>{let a=()=>e.readSubscriptionOperation(t),r=()=>e.readSubscriptionUpdate(t),i=()=>e.readRefund(t),u=n.command==="purchase.execute"?[a]:n.command==="subscription.change"?[r]:n.command==="refund.execute"?[i]:[a,r,i];for(let l of u)try{let d=await l(),w="authority"in d.operation?d.operation.authority:void 0;if(!w)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ee.parse(w);if(E.customerId!==t.customerId||E.operationId!==t.operationId||Object.keys(n.scope).some(C=>E.scope[C]!==n.scope[C]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(d){if(n.command==="operation.read"&&d instanceof s&&d.code==="NOT_FOUND")continue;throw d}throw new b("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}import"zod";function rt(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let t=ke.parse(e.manifest),n=Te.parse(e.authentication),a={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},r=e.now??Date.now,i=c=>{throw new s("INVALID_RESPONSE",c)},u=(c,f)=>ue(c)===ue(f);function l(c){new TextEncoder().encode(c).byteLength>262144&&i("Merchant protocol body exceeds limit");try{return JSON.parse(c)}catch{return i("Invalid merchant protocol JSON")}}function d(c){let f=xe.parse(c);return u(f.scope,a)||i("Merchant protocol scope mismatch"),f.command==="requirement.check"&&(t.capabilities.includes("requirement_checks")||i("Merchant Check capability unavailable"),u(f.data.subject.scope,a)||i("Merchant Check subject crosses scope")),f.command==="operation.prepare"&&(!t.capabilities.includes("preparations")||!u(f.data.request.subject.scope,a))&&i("Merchant preparation capability unavailable"),f}function w(c){if(c.command!=="operation.prepare")return;let f=c.data;return(!u(f.request.subject.scope,a)||!f.preparationAllowed||Date.parse(f.requestedAt)>r()||Date.parse(f.request.expiresAt)<=r()||!t.preparationActions.includes(f.request.action))&&i("Merchant preparation requires fresh scoped authority"),f}function E(c,f){let g=Ne(c.command).parse(f);if((g.requestId!==c.requestId||!u(g.scope,a))&&i("Merchant reply correlation mismatch"),"error"in g)return g;if(c.command==="bridge.ping"&&"challenge"in g.data&&g.data.challenge!==c.data.challenge&&i("Merchant ping challenge mismatch"),c.command==="bridge.describe"&&"bridgeVersion"in g.data&&!u({projectId:g.data.projectId,environmentId:g.data.environmentId,environment:g.data.environment},a)&&i("Merchant declaration crosses scope"),c.command==="requirement.check"&&"observation"in g.data&&(!u(g.data.observation.subject,c.data.subject)||!Fe(c.data.requirement,g.data)||!t.checkKinds.includes(g.data.kind))&&i("Merchant Check changed the original requirement or subject"),c.command==="operation.prepare"&&"quoteTermsDigest"in g.data){let v=w(c);(!u(g.data.request,v.request)||Date.parse(g.data.expiresAt)<=r()||Date.parse(g.data.observedAt)<Date.parse(v.requestedAt)||Date.parse(g.data.observedAt)>r())&&i("Merchant quote changed its authorized request or validity")}return g}let C=async c=>{let f=JSON.stringify(c);return l(f),{body:f,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[J]:"4",...await j(f,n,"response",r(),4)})}};return{version:4,path:X,async encodeRequest(c,f){let g=d({bridgeVersion:4,requestId:crypto.randomUUID(),scope:a,command:c,data:f});w(g);let v=JSON.stringify(g);l(v);let _=new Headers({"Content-Type":"application/json",[J]:"4",...await j(v,n,"request",r(),4)});return{body:v,headers:_,async readResponse(x,h){l(x),(h.get(J)!=="4"||!await z(x,h,n,"response",r(),4))&&i("Merchant response authentication failed");let o=E(g,l(x));if("error"in o)throw new se(o.error);return o.data}}},async decodeRequest(c,f){l(c),(f.get(J)!=="4"||f.get(Y)!==n.keyId||!await z(c,f,n,"request",r(),4))&&i("Merchant request authentication failed");let g=d(l(c));return w(g),g},async encodeResponse(c,f){let g=d(c),v=E(g,{...g,data:f});return C(v)},async encodeError(c,f){let g=d(c),{data:v,..._}=g;return C(E(g,{..._,error:De.parse(f)}))}}}var se=class extends Error{constructor(n){super(n.message);this.problem=n}problem};export{Q as FunnelDecisionTimeoutError,oe as FunnelProcessEntrySuppressedError,s as LongplayError,b as MerchantBridgeHandlerError,se as MerchantBridgeProtocolError,Bn as aiPriceSnapshotSchema,Ln as aiTokenQuoteSchema,Un as createAiPricing,Wn as createAiUsageMiddleware,kn as createConfigurationSync,Vn as createConfiguredAiPricing,ve as createFeatureClient,Zn as createFunnelCampaignClient,Ee as createFunnelDecisionClient,ae as createFunnelLocalEvaluator,Xn as createFunnelOrchestrationClient,Gn as createFunnelProcessAdapter,Dn as createFunnelStartClient,Se as createGuestToken,Nn as createLocalFunnelClient,qn as createLongplayServer,tt as createMerchantBridgeAuthorityResolver,nt as createMerchantBridgeHandler,rt as createMerchantBridgeProtocol,Jn as createNativeReceiptClient,Qn as createPaywallStartClient,Kn as createSynchronizedFunnelLocalEvaluator,Fn as entitlementRequirementDigest,xn as evaluateFunnelNode,_n as merchantConfirmationMatchesTerms,Mn as merchantPreparationRequestDigest,Pn as merchantQuoteTermsDigest,jn as renewFunnelRun,j as signMerchantBridgeMessage,z as verifyMerchantBridgeMessage};
|
|
1
|
+
import{a as xn}from"./chunk-M4LTOSLT.js";import{a as Bn,b as Ln,c as Un,d as Vn}from"./chunk-CHQUGYMS.js";import{a as m,b as cn,c as we,d as ve,e as un,f as dn,g as pn,h as ln,j as te,k as mn,l as U,m as N,o as fn,p as kn,q as Dn,r as Nn}from"./chunk-JNML7SY4.js";import"./chunk-YAVWELIV.js";import"./chunk-BP6G3YGP.js";import{a as s}from"./chunk-QVGTHPWT.js";import"./chunk-Z5CW2N7E.js";import{$ as He,$a as tn,D as Z,Da as p,E as ee,Ea as he,F as Me,I as le,J as Pe,K as _e,L as ke,M as xe,N as De,O as Ne,Oa as Je,P as Y,Pa as ge,Q as j,Qa as $,R as z,Ra as Ye,Sa as $e,Ta as We,Ua as ye,V as me,Va as Xe,W as Ve,Wa as Ze,X as qe,Xa as en,Ya as Ie,Za as nn,_a as W,cb as rn,da as V,db as on,ea as Ge,fa as fe,ga as ze,ha as Ke,hb as an,j as Ce,ja as ne,jb as sn,k as Ae,ka as K,l as ce,la as Qe,m as Mn,n as Pn,p as _n,r as Oe,s as de,t as X,u as J,v as pe,w as Te,y as be}from"./chunk-JXNNWCEB.js";import"./chunk-DSPLGTQI.js";import{C as Fe,H as Be,Ia as je,P as Le,S as Ue,a as Re,o as ue,y as Fn}from"./chunk-HDVLCRC6.js";function re(e){return{async getCustomer(t){let n=p.getCustomer;return m(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=p.listCustomers;return m(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=p.updateCustomer;return m(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=p.createGuestCustomer;return m(e,n,t)},async resumeGuestSession(t){let n=p.resumeGuestSession;return m(e,n,t)},async claimGuestCustomer(t){let n=p.claimGuestCustomer;return m(e,n,t)},async revokeCustomerSessions(t){let n=p.revokeSessions;return m(e,n,t)},async createCustomerSession(t){return m(e,p.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return m(e,p.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function y(e,t){try{return e.parse(t)}catch{throw new s("INVALID_RESPONSE","Invalid gateway response")}}function hn(e){return{async checkEntitlement(t){let n=p.checkEntitlement,a=n.request.parse(t),r=await m(e,n,a,y);return cn(a.requirement,r.check,a.customerId,r.scope),r},async readHoldings(t){let n=p.readHoldings;return m(e,n,t,y)},async readSeats(t){let n=p.readSeats;return m(e,n,t,y)},async manageSeat(t){let n=p.manageSeat;return m(e,n,t,y)}}}function gn(e){return{async readAiPricing(t){let n=p.readAiPricing;return m(e,n,t,y)},async readUsage(t){let n=p.readUsage;return m(e,n,t,y)},async setUsage(t){let n=p.setUsage;return m(e,n,t,y)},async manageBalanceGrant(t){let n=p.manageBalanceGrant;return m(e,n,t,y)},async readBalanceSource(t){let n=p.readBalanceSource;return m(e,n,t,y)},async adjustBalance(t){let n=p.adjustBalance;return m(e,n,t,y)},async listBalanceGrants(t){let n=p.listBalanceGrants;return m(e,n,t,y)},async manageBillingLimits(t){let n=p.manageBillingLimits;return m(e,n,t,y)},async manageUsageEntity(t){let n=p.manageUsageEntity;return m(e,n,t,y)},async readUsageAnalytics(t){let n=p.readUsageAnalytics;return m(e,n,t,y)},async readCreditAnalytics(t){let n=p.readCreditAnalytics;return m(e,n,t,y)},async submitUsageBatch(t){let n=p.submitUsageBatch;return m(e,n,t,y)},async readUsageBatch(t){let n=p.readUsageBatch;return m(e,n,t,y)},async readLedger(t){let n=p.readLedger;return m(e,n,t,y)},async readCreditStatement(t){let n=p.readCreditStatement;return m(e,n,t,y)},async quoteBalance(t){let n=p.quoteBalance;return m(e,n,t,y)},async trackUsage(t){let n=p.trackUsage;return m(e,n,t,y)},async mutateBalance(t){let n=p.mutateBalance;return m(e,n,t,y)}}}function yn(e){return{async listInvoiceTemplates(t={}){let n=p.listInvoiceTemplates;return m(e,n,t,y)},async previewInvoice(t){let n=p.previewInvoice;return m(e,n,t,y)},async createInvoice(t){let n=p.createInvoice;return m(e,n,t,y)},async prepareBillingAdjustment(t){let n=p.prepareBillingAdjustment;return m(e,n,t,y)},async manageInvoice(t){let n=p.manageInvoice;return m(e,n,t,y)},async readInvoiceOperation(t){let n=p.readInvoiceOperation;return m(e,n,t,y)},async listInvoices(t){let n=p.listInvoices;return m(e,n,t,y)},async getInvoice(t){let n=p.getInvoice;return m(e,n,t,y)},async setupPayment(t){let n=p.setupPayment;return m(e,n,t,y)},async readPaymentSetup(t){let n=p.readPaymentSetup;return m(e,n,t,y)},async readBillingInvoice(t){let n=p.readBillingInvoice;return m(e,n,t,y)},async previewRefund(t){let n=p.previewRefund;return m(e,n,t,y)},async refund(t){let n=p.refund;return m(e,n,t,y)},async readRefund(t){let n=p.readRefund;return m(e,n,t,y)}}}function In(e){return{async previewSubscriptionBatch(t){let n=p.previewSubscriptionBatch;return m(e,n,t,y)},async confirmSubscriptionBatch(t){let n=p.confirmSubscriptionBatch;return m(e,n,t,y)},async readSubscriptionBatch(t){let n=p.readSubscriptionBatch;return m(e,n,t,y)},async abandonSubscriptionBatch(t){let n=p.abandonSubscriptionBatch;return m(e,n,t,y)},async manageSubscriptionTrial(t){let n=p.manageSubscriptionTrial;return m(e,n,t,y)},async readSubscriptionTrial(t){let n=p.readSubscriptionTrial;return m(e,n,t,y)},async listSubscriptions(t){let n=p.listSubscriptions;return m(e,n,t,y)},async listPurchases(t){let n=p.listPurchases;return m(e,n,t,y)},async listSubscriptionConflicts(t){let n=p.listSubscriptionConflicts;return m(e,n,t,y)},async retrySubscriptionConflict(t){let n=p.retrySubscriptionConflict;return m(e,n,t,y)},async previewUpdate(t){let n=p.previewUpdate;return m(e,n,t,y)},async update(t){let n=p.update;return m(e,n,t,y)},async readSubscriptionUpdate(t){let n=p.readSubscriptionUpdate;return m(e,n,t,y)},async restoreNativePurchase(t){let n=p.restoreNativePurchase;return m(e,n,t,y)},async verifySubscriptions(t){let n=p.verifySubscriptions;return m(e,n,t,y)},async previewAttach(t){let n=p.previewAttach;return m(e,n,t,y)},async recordMerchantEvent(t){return m(e,p.recordMerchantEvent,t,{request:"Invalid merchant event",parseResponse:y})},async attach(t){let n=p.attach;return m(e,n,t,y)},async readSubscriptionOperation(t){let n=p.readSubscriptionOperation;return m(e,n,t,y)}}}function wn(e){return{async grantModelBenefit(t){return m(e,p.grantModelBenefit,t,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(t){return m(e,p.readModelBenefit,t,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(t){let n=p.grantOffer;return m(e,{...n,request:n.request.refine(a=>!!a.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function vn(e){return{...hn(e),...gn(e),...yn(e),...In(e),...wn(e)}}function Sn(e){return{async getFeatures(t={}){let n=p.getFeatures;return m(e,n,t,y)},async evaluateFeatures(t){let n=p.evaluateFeatures;return m(e,n,t,y)}}}function En(e){return{async trackEvents(t){let n=p.trackEvents;return m(e,n,t,y)}}}function Rn(e){return{async resolveContent(t){let n=p.resolveContent;return m(e,n,t,y)},async resolvePaywall(t){let n=p.resolvePaywall,a=n.request.parse(t),r=await m(e,n,a,y);return we(a,r.paywall.check,r.scope),r},async resolveOffering(t){let n=p.resolveOffering,a=n.request.parse(t),r=await m(e,n,a,y);return we(a,r.check,r.scope),r}}}function qn(e){U(e.apiKey,"Secret API keys must stay on your backend");let n=N(e).request;return{async sendMessage(a){let r=p.sendMessage;return r.response.parse(await n(r.path,r.request.parse(a)))},async readMessage(a){let r=p.readMessage;return r.response.parse(await n(r.path,r.request.parse(a)))},...re(n),...vn(n),...Sn(n),...En(n),...Rn(n)}}function Se(){if(typeof window<"u")throw new s("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var Cn=()=>new s("CONFLICT","Process synchronization is in progress",425),B=()=>new s("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Hn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),oe=class extends s{constructor(n){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:n.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=n}result};function Gn(e){if(U(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new s("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=N(e),n=re(t.request),a=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(h){let o=await e.resolveUser(h);if(o!==null&&(typeof o?.externalUserId!="string"||!o.externalUserId||o.externalUserId!==o.externalUserId.trim()||o.externalUserId.startsWith("gg_guest_")))throw new s("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return o}async function i(h){let o=await e.resolveContext(h);if(o?.confirmed!==!0||!o.processKey||!o.guestKey)throw new s("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:a+"run:"+o.processKey,guest:a+"guest:"+o.guestKey}}async function u(h,o){for(let I=0;I<8;I++){let R=await e.store.read(h),S=o(R?structuredClone(R.value):null);if(R&&Hn(R.value,S)||await e.store.compareAndSwap(h,R?.revision??null,S))return S}throw Cn()}async function l(h){let o=await e.store.read(h);if(!o)throw new s("NOT_FOUND","Open the process before continuing",404);return o.value}async function d(h){let o=await l(h);for(let I of o.revocations??[])await n.revokeCustomerSessions(I),await u(h,R=>{if(!R)throw B();return R.revocations=R.revocations?.filter(S=>S.sessionId!==I.sessionId),R})}async function w(h,o){let I=ge.parse(h);return o?t.requestWithCredential("funnel-processes",I,o):t.request("funnel-processes",I)}function E(h,o){if(o.scope.projectId!==e.scope.projectId||o.scope.environment!==e.scope.environment||h.run&&(h.run.id!==o.run.id||h.run.source.versionId!==o.run.source.versionId||h.run.source.id!==o.run.source.id||h.run.runExpiresAt!==o.run.runExpiresAt||h.run.identity.startedAs!==o.run.identity.startedAs||h.run.identity.participantId!==o.run.identity.participantId||h.run.identity.binding&&h.run.identity.binding.id!==o.run.identity.binding?.id)||h.runToken&&o.runToken&&h.runToken!==o.runToken)throw new s("INVALID_RESPONSE","Process identity or Run changed")}async function C(h,o,I){return u(h,R=>{if(!R)throw new s("NOT_FOUND","Process handle is missing",404);return E(R,o),(!R.run||o.run.revision>=R.run.revision)&&(R.run=o.run),R.runToken??=o.runToken,I!==void 0&&(R.target=I),R})}async function c(h,o){if(o.detached)throw new s("UNAUTHENTICATED","The process is detached",401);let I=o.run?.identity.binding?.customerId??o.run?.identity.participantId;if(!I)throw new s("INVALID_RESPONSE","Process participant is missing");if(o.session?.customerId===I&&Date.parse(o.session.expiresAt)>Date.now()+3e4)return o.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},S=await u(h,O=>{if(!O||O.detached||O.run?.id!==o.run?.id)throw B();if(O.sessionLease&&O.sessionLease.until>Date.now())throw Cn();return O.sessionLease=R,O}),A;try{if(S.session?.customerId===I&&Date.parse(S.session.refreshExpiresAt)>Date.now())try{if(A=Oe.parse(await t.requestWithCredential("customer-sessions/refresh",{},S.session.refreshToken)),A.sessionId!==S.session.sessionId)throw new s("INVALID_RESPONSE","Refresh changed the logical session")}catch(P){if(!(P instanceof s)||P.status!==401)throw P}if(A??=S.run?.identity.binding?await n.createCustomerSession(I):await n.resumeGuestSession({guestToken:S.guest.token}),A.customerId!==I)throw new s("INVALID_RESPONSE","Session Customer changed");let O=A;return await u(h,P=>{if(!P||P.detached||P.sessionLease?.id!==R.id||P.run?.identity.binding?.id!==o.run?.identity.binding?.id)throw new s("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return P.session=O,delete P.sessionLease,P}),A}catch(O){throw A&&A.sessionId!==S.session?.sessionId&&await n.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await u(h,P=>{if(!P)throw B();return P.sessionLease?.id===R.id&&delete P.sessionLease,P}).catch(()=>{}),O}}let f;async function g(){if(f??=Xe.parse(await w({contract:V,operation:"describe"})),f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment)throw B();return f}async function v(h,o,I=!1){let R=await r(h),S=await l(o);if(S.issuingKeyId!==(await g()).keyId)throw new s("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!S.runToken||!S.run)throw new s("CONFLICT","Recover the original start first",425);if(S.detached){if(!I)throw new s("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(S.run.identity.binding&&(!R||S.target&&S.target!==R.externalUserId))throw B();await d(o),S=await u(o,A=>{if(!A||A.run?.id!==S.run?.id)throw B();return delete A.detached,A})}if(!S.runToken||!S.run)throw new s("INVALID_RESPONSE","Process identity is missing");if(S.run.identity.binding){if(R&&!S.target){let A=ye.parse(await w({contract:V,operation:"binding_status",runToken:S.runToken,requestId:S.bindingIntent?.requestId??S.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==S.run.identity.binding.id)throw B();S=await u(o,O=>{if(!O)throw B();return O.target=R.externalUserId,O})}if(!R||S.target!==R.externalUserId)throw B()}else if(R){if(!S.guest)throw B();S=await u(o,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw B();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=S.bindingIntent;try{let O=We.parse(await w({contract:V,operation:"bind_customer",...A,runToken:S.runToken,guestToken:S.guest.token,claimRequestId:S.guest.claimRequestId,expectedBindingId:null}));S=await C(o,O,R.externalUserId)}catch(O){let P=ye.parse(await w({contract:V,operation:"binding_status",...A,runToken:S.runToken,guestToken:S.guest.token}));if(P.state!=="bound")throw O;S=await u(o,D=>{if(!D?.run||D.run.id!==P.binding.runId)throw B();return D.run.identity.binding={id:P.binding.id,customerId:P.binding.customerId,acceptedAt:P.binding.acceptedAt},D.target=R.externalUserId,D})}}return{state:S,session:await c(o,S)}}async function _(h,o,I,R){try{return await R(I)}catch(S){if(!(S instanceof s)||S.status!==401)throw S;return await u(o,A=>{if(!A||A.detached)throw S;return A.session?.accessToken===I.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await v(h,o))}}async function x(h,o,I=!1){let R=await i(h),S=await v(h,R.process,I),A=$.parse(await _(h,R.process,S,O=>w({...o,customerToken:O.session.accessToken},O.state.runToken)));return await C(R.process,A),A}return{async open(h,o){o=$e.parse(o);let I=await i(h),R=await g(),S=I.guest+":"+R.keyId,A=await e.store.read(I.process);if(!A){let F=await r(h),T,M,k;if(F)T={type:"customer",customer:{type:"externalUserId",value:F.externalUserId}};else{let q=await e.store.read(S);if(q)try{k=await n.resumeGuestSession({guestToken:q.value.token}),M=q.value}catch(L){if(!(L instanceof s)||L.status!==401)throw L}let H={token:Se(),claimRequestId:crypto.randomUUID()};M=await u(S,L=>M??(L&&L.token!==q?.value.token?L:H)),T={type:"guest",guestToken:M.token}}await u(I.process,q=>q??{issuingKeyId:R.keyId,start:ge.parse({...o,contract:V,requestId:crypto.randomUUID(),source:T}),...M?{guest:M}:{},...F?{target:F.externalUserId}:{},...k?{session:k}:{}}),A=await e.store.read(I.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new s("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==o.funnelId||O.start.operation!==o.operation)throw new s("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let k=await r(h);if(!k||k.externalUserId!==O.target)throw B()}let F=await w(O.start),T=Ye.safeParse(F);if(T.success)throw new oe(T.data);let M=$.parse(F);if(!M.runToken)throw new s("INVALID_RESPONSE","Process credential is missing");O=await C(I.process,M)}let P=await v(h,I.process,!0),D=$.parse(await _(h,I.process,P,F=>w({contract:V,operation:"get",customerToken:F.session.accessToken},F.state.runToken)));return await C(I.process,D),{...D,runToken:O.runToken}},async syncIdentity(h){return x(h,{contract:V,operation:"get",customerToken:""},!0)},async get(h,o={}){return x(h,{...o,contract:V,operation:"get",customerToken:""})},async review(h,o){return x(h,{contract:V,operation:"review",customerToken:"",...o?{receiptId:o}:{}})},async command(h,o,I){let R=await i(h),S=await v(h,R.process),A=$.parse(await _(h,R.process,S,O=>w({contract:V,operation:"command",command:o,identity:{bindingId:I},customerToken:O.session.accessToken},O.state.runToken)));return await C(R.process,A),A},async pageExperiments(h,o,I=[]){let R=await i(h),S=await v(h,R.process);return Je.parse(await _(h,R.process,S,A=>w({contract:V,operation:"page_experiments",release:o,usedReceiptIds:I,customerToken:A.session.accessToken},A.state.runToken)))},async detach(h){let o=await i(h);await u(o.process,I=>{if(!I)throw B();return I.session&&!I.revocations?.some(R=>R.sessionId===I.session.sessionId)&&(I.revocations??=[]).push({customerId:I.session.customerId,sessionId:I.session.sessionId}),I.detached=!0,delete I.session,delete I.sessionLease,I}),await d(o.process)},destroy(){t.dispose()}}}async function jn(e,t){U(e.apiKey,"Renewal requires your backend");let n=N(e),a=en.parse(un(e,await n.request("funnels",Ze.parse({...t,operation:"renew_run"}))));if(a.run.id!==t.runId)throw new s("INVALID_RESPONSE","Run renewal identity changed");return a}function An(e){let t=pn(e),n=l=>{throw new s("INVALID_RESPONSE",l)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let a=new Set(["entry","condition","feature","split","end","output"]);for(let l of t.nodes.values()){if(!a.has(l.type))throw new s("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&n("Local next exit is unavailable"),l.type==="feature"){let d=l.resources.featureKey;(!d||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(t.features,d))&&n("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let d=e.conditions[l.id];(!d||!l.outputs.default||d.some((w,E)=>w.port!==`case:${E}`||!l.outputs[w.port]))&&n("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let d=e.evaluation.terminals[l.id];if(!d)throw new s("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&n("A terminal cannot have outgoing edges"),d.output?.type==="feature"&&!Object.hasOwn(t.features,d.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let d of Object.values(l.outputs))t.nodes.has(d)||n("Local target is unavailable")}let r=new Set,i=new Set;function u(l){if(i.has(l)&&n("Local graph contains a cycle"),!r.has(l)){i.add(l);for(let d of Object.values(t.nodes.get(l).outputs))u(d);i.delete(l),r.add(l)}}return u(e.topology.entry),r.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(l){let d={},w=l.context;w.features=t.features,w.savedGroups=t.savedGroups;let E=()=>{w.attributes=Ge({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:d,savedGroups:t.savedGroups})};E();let C=e.topology.entry,c=0;for(;;){let f=t.nodes.get(C);if(f.type==="end"||f.type==="output"){let g=e.evaluation.terminals[C],v=g.output,_=v?.type==="feature"?t.feature(v.featureKey,w):v?.type==="variable"?qe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:d,parameters:l.parameters,attributes:l.attributes,savedGroups:t.savedGroups}):v?.value??null;return me(e.evaluation.outputSchema,_)||n("Local output does not match its declaration"),{outcome:g.outcome,value:_}}if(c++>=e.evaluation.maxTransitions)throw new s("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(f.type==="entry")C=f.outputs.next;else{let g=t.evaluate(C,w);if(f.type==="feature"){let v=f.writes.value,_=g.value??null;me(e.evaluation.variables[v],_)||n("Local Feature value does not match its declaration"),Ve(e.evaluation.variables,{writes:f.writes},{[v]:_}),d[v]=_,E()}C=g.target}}}}}import{z as On}from"zod";function Tn(e,t,n){let a=Le.parse(e.attributes);if(["parameters","answers","results"].some(h=>Object.hasOwn(a,h)))throw new s("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=je.parse(e.parameters??{}),i=On.record(On.string(),Ue).parse(e.stickyBucketAssignmentDocs??{});for(let[h,o]of Object.entries(i))if(h!==`${o.attributeName}||${o.attributeValue}`||!Object.hasOwn(a,o.attributeName)||Be(a[o.attributeName])!==o.attributeValue)throw new s("INVALID_REQUEST","Sticky document identity does not match this session");let u=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,d=e.onExperimentViewed,w=e.onError,E=new Map,C=new Set,c={},f=Promise.resolve();function g(h){let o=f.then(()=>(n(),h()));return f=o.catch(()=>{}),o}function v(h){try{w?.(h)}catch{}}function _(h){try{let o=h();o&&typeof o.catch=="function"&&o.catch(v)}catch(o){v(o)}}async function x(){for(let[h,o]of E){if(n(),u)try{await u(structuredClone(o))}catch{throw new s("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),E.delete(h)}}return{evaluate(h={}){let o=h.track===!0;return g(async()=>{let I=await t();n(I);let R=new Set(C),S={...c},A=new Map,O=[],P={stickyBucketAssignmentDocs:structuredClone(i),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...o?{trackedExperiments:R,trackedFeatureUsage:S,onExperimentViewed(T,M){let k=structuredClone(T),q=structuredClone(M);d&&O.push(()=>d(structuredClone(k),structuredClone(q)))},onFeatureUsage(T,M){let k=structuredClone(M);l&&O.push(()=>l(T,structuredClone(k)))}}:{}},D=I.program.evaluate({attributes:a,parameters:r,context:P});n(I);for(let[T,M]of A)i[T]=M,E.set(T,M);await x(),n(I),o&&(C=R,c=S);for(let T of O)_(T);let F=I.configuration;return structuredClone({evaluationMode:"local",scope:F.scope,funnelId:F.funnelId,versionId:F.versionId,evaluationRevision:F.evaluationRevision,generation:F.growth.generation,...D})})},flush:()=>g(x),get stickyBucketAssignmentDocs(){return n(),structuredClone(i)}}}var zn=6e4;function ae(e){if(typeof window<"u")throw new s("SERVER_ONLY","Local Funnel sessions run on your backend");let t=Re.parse(e.scope),n=e.funnelId,a=e.load,r,i,u,l=0,d=C=>Date.now()>=C.expiresAt;async function w(){if(i)return i;let C=l;r=void 0;let c=(async()=>{let f=await a();if(C!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(f&&typeof f=="object"&&"evaluationMode"in f&&f.evaluationMode==="remote")throw y(W,f),new s("EVALUATION_MODE","This Funnel requires remote decide");let g=y(tn,f);if(C!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(g.scope.projectId!==t.projectId||g.scope.environment!==t.environment||g.funnelId!==n)throw new s("SCOPE_MISMATCH","Local configuration scope changed");if(g.growth.scope.projectId!==t.projectId||g.growth.scope.environment!==t.environment||g.growth.expiresAt!==g.expiresAt)throw new s("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+zn,g.expiresAt?Date.parse(g.expiresAt):1/0);if(Date.now()>=v)throw new s("CONFIGURATION_EXPIRED","Refresh expired local rules");let _=JSON.stringify([t.projectId,t.environment,n,g.versionId,g.evaluationRevision,g.growth.generation]),x=[g.topology,g.conditions,g.evaluation,g.growth.features,g.growth.experiments,g.growth.savedGroups];if(u?.key===_&&!mn(u.body,x))throw new s("INVALID_RESPONSE","Immutable local configuration identity changed");return u?.key!==_&&(u={key:_,body:x,program:An(g)}),r={key:_,configuration:g,expiresAt:v,program:u.program},r})();i=c;try{return await c}finally{i===c&&(i=void 0)}}function E(){return i??(r&&!d(r)?Promise.resolve(r):w())}return{session(C){let c=l;return Tn(C,E,f=>{if(e.assertUsable?.(),c!==l)throw new s("IDENTITY_CHANGED","Local evaluator was reset");if(f&&(d(f)||r?.key!==f.key))throw new s("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await w()).configuration)},reset(){l++,r=void 0,i=void 0,u=void 0}}}function Kn(e,t){let n=e.snapshot?.generation,a=ae({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),r=e.subscribe(()=>{let u=e.snapshot?.generation;e.fresh&&u!==n&&(n=u,a.refresh().catch(()=>{}))}),i=a.session;return Object.assign(a,{session(u){let l=i(u),d=l.evaluate;return Object.assign(l,{async evaluate(...w){return e.fresh||await e.refresh(),d(...w)}})},destroy(){r(),a.reset()}})}function Qn(e){if(typeof window<"u")throw new s("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>fn(e,t)}}var Q=class extends s{constructor(n,a){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,a);this.decisionId=n;this.decisionRequestId=a}decisionId;decisionRequestId};async function ie(e,t,n,a){let{decisionId:r,requestId:i}=e,u=e,l=250,d=0;for(;;){if(u.decisionId!==r||u.requestId!==i||u.decision&&!te(u.decision,t))throw new s("INVALID_RESPONSE","Decision request or customer changed");if(u.decision)return u.decision;if(u.status==="failed")throw new s("DECISION_FAILED","Decision execution failed",503,i);if(Date.now()>=n)throw new Q(r,i);if(await new Promise(w=>setTimeout(w,Math.min(Math.max(l,d-Date.now()),n-Date.now()))),Date.now()>=n)throw new Q(r,i);l=Math.min(1e3,l*2);try{u=await a(r,n)}catch(w){if(w instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(w.code)){d=Date.now()+(w.retryAfterSeconds??0)*1e3;continue}throw w}}}function Ee(e){if("remoteEval"in e)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Funnel decisions are requested by your backend");let t,n,a=new Map;async function r(d,w){let E=d;E.status!=="pending"&&a.delete(E.decisionId);for(let C=0;C<32&&E.evaluation;C++){let c=E.evaluation;if(c.runId!==E.decisionId)throw new s("INVALID_RESPONSE","Local evaluation Run changed");let f=a.get(E.decisionId);if(!f&&c.type==="evaluate_segment"){let v=sn.parse(await i({operation:"segment_configuration",funnelId:e.funnelId,versionId:c.versionId},w));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==c.versionId||v.configuration.evaluationRevision!==c.policyRevision)throw new s("SCOPE_MISMATCH","Original decision segment configuration changed");if(a.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding decisions first");f={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:he(E.decisionId,c.visit,`segment:${c.revision}`),nodeId:c.nodeId,visit:c.visit,revision:c.revision,policyRevision:c.policyRevision,generation:v.configuration.growth.generation,...ln(v.configuration,v.document,c)},a.set(E.decisionId,f)}if(!f){if(c.type!=="evaluate")throw new s("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==c.versionId||n.evaluationRevision!==c.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=W.parse(await i({operation:"configuration",funnelId:e.funnelId,versionId:c.versionId},w))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new s("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==c.versionId||n.evaluationRevision!==c.policyRevision)throw new s("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(a.size>=128)throw new s("COMMAND_PENDING","Reconcile outstanding Local decisions first");f={operation:"evaluate_decision",decisionId:E.decisionId,requestId:he(E.decisionId,c.visit,"evaluation"),nodeId:c.nodeId,visit:c.visit,revision:c.revision,receiptId:c.receiptId,policyRevision:c.policyRevision,generation:n.growth.generation,result:an(n,c.nodeId,c,dn)},a.set(E.decisionId,f)}let g=K.parse(await i(f,w));if(g.decisionId!==d.decisionId||g.requestId!==d.requestId)throw new s("INVALID_RESPONSE","Decision identity changed during local evaluation");a.delete(E.decisionId),E=g}return E}async function i(d,w,E=!1){return N({...e,fetch:(c,f)=>{let g=new Headers(f?.headers);return g.set("Accept-Encoding","identity"),E&&g.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(c,{...f,headers:g})},timeoutMs:Math.min(e.timeoutMs??1e4,w?Math.max(1,w-Date.now()):12e4)}).request("funnels",d)}async function u(d,w){let E=K.parse(await i(ne.parse({operation:"read_decision",decisionId:d}),w));if(E.decisionId!==d)throw new s("INVALID_RESPONSE","Decision identity changed");return r(E,w)}async function l(d,w,E=!1){let C=ne.options[0].parse({...d,operation:"decide",funnelId:e.funnelId}),c;try{c=K.parse(await i(C,w,E))}catch(f){throw f instanceof s&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(f.code)?new s("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",f.status,d.requestId):f}if(c.requestId!==d.requestId||c.decision&&!te(c.decision,C.customer))throw new s("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(c,w),customer:C.customer}}return{local(){return t??=ae({scope:e.scope,funnelId:e.funnelId,load:()=>i({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let d=W.parse(await i({operation:"configuration",funnelId:e.funnelId}));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment||d.funnelId!==e.funnelId)throw new s("SCOPE_MISMATCH","Configuration scope changed");return d},features(d={}){return ve({...d,scope:e.scope,load:async()=>He.parse(await i({operation:"feature_config",funnelId:e.funnelId}))})},read:d=>u(d),async submit(d){return(await l(d,void 0,!0)).response},async decide(d){let w=Date.now()+3e4,E=await l(d,w);return ie(E.response,E.customer,w,u)},async reportUsed(d){let w=Qe.parse(await i(ne.parse({...d,operation:"report_used"})));if(w.decisionId!==d.decisionId||w.eventId!==d.eventId)throw new s("INVALID_RESPONSE","Usage receipt identity changed");return w}}}function Jn(e){U(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let a=rn.parse(n);if(a.orderId!==a.receiptId)throw new s("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=a.nativeEvidence,i={requestId:a.requestId,customerToken:a.customerToken,purchaseIntentId:a.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},u=p.restoreNativePurchase.response.parse(await t.request(p.restoreNativePurchase.path,i));if(u.operation.requestId!==a.requestId||u.operation.purchaseIntentId!==a.orderId)throw new s("INVALID_RESPONSE","Native receipt request identity changed");let l=on.parse({scope:u.scope,requestId:a.requestId,orderId:u.operation.orderId,receiptId:u.operation.orderId,orderStatus:u.operation.status,refunded:u.operation.refunded,...u.operation.completion===null?{}:{nativeCompletion:{orderId:u.operation.orderId,receiptId:u.operation.orderId,...u.operation.completion}}});if(l.requestId!==a.requestId||l.orderId!==a.orderId||l.receiptId!==a.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Current order receipt scope changed");return l}}}import{z as Yn}from"zod";var G=Yn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function $n(e,t){let n=G.parse(e.inputTokens.total),a=G.parse(e.outputTokens.total),r=G.parse(e.inputTokens.cacheRead??0),i=G.parse(e.inputTokens.cacheWrite??0),u=G.parse(e.outputTokens.reasoning??0);if(r+i>n||u>a||e.inputTokens.noCache!==void 0&&G.parse(e.inputTokens.noCache)!==n-r-i||e.outputTokens.text!==void 0&&G.parse(e.outputTokens.text)!==a-u)throw new s("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-r-i,cache_read:r,cache_write:i,output:t==="output"?a:a-u,reasoning:t==="separate"?u:0,input_audio:0,output_audio:0}}function Wn(e){if(typeof window<"u")throw new s("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new s("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(a){await e.persist({context:a,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(a,r){let i={context:a,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(i);let u=e.mapTokens?e.mapTokens(r):$n(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:u});await e.persist({...i,tokens:u,quote:l,phase:"quoted"});let d=await e.pricing.trackTokens(e.client,{...a,quote:l});if(!d.receipt.accepted)throw new s("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...i,tokens:u,quote:l,receipt:d,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:a}){let r=await e.context(),i;try{i=await a()}catch(u){throw await t(r),u}return await n(r,i.usage),i},async wrapStream({doStream:a}){let r=await e.context(),i;try{i=await a()}catch(E){throw await t(r),E}let u=!1,l=!1,d=i.stream.getReader();async function w(){u||l||(l=!0,await t(r))}return{...i,stream:new ReadableStream({async pull(E){try{let{value:C,done:c}=await d.read();if(c){if(!u)throw await w(),new s("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(C.type==="finish"){if(u)throw new s("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");u=!0,await n(r,C.usage)}E.enqueue(C)}catch(C){try{await w()}finally{E.error(C),await d.cancel(C)}}},async cancel(E){try{await w()}finally{await d.cancel(E)}}})}}}}function Xn(e){U(e.apiKey,"Funnel receipts are sent by your backend");let t=N(e);return{async signal(n){let a=fe.parse({...n,operation:"signal"}),r=ze.parse(await t.request("funnels",a));if(r.runId!==n.runId||r.eventId!==n.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(n){let a=fe.parse({operation:"read_results",runId:n}),r=Ke.parse(await t.request("funnels",a));if(r.runId!==n||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("INVALID_RESPONSE","Result identity changed");return r}}}function Zn(e){if("remoteEval"in e)throw new s("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");U(e.apiKey,"Campaign entry requires your backend");let t=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let a=Date.now()+(e.timeoutMs??3e4),r=Ie.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),i=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,a-Date.now()))}),u=K.parse(await i.request("funnels",r));if(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");return ie(u,r.customer,a,(l,d)=>Ee({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,d-Date.now()))}).read(l))},async start(n){let a=Ie.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),r=nn.parse(await t.request("funnels",a));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new s("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||a.customer.type==="id"&&r.customerId!==a.customer.value))throw new s("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}import{z as et}from"zod";var b=class extends Error{constructor(n,a=409,r=!1,i="fix_request"){super(n);this.code=n;this.status=a;this.retryable=r;this.recovery=i}code;status;retryable;recovery};function nt(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=be.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},a=t.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,i]of Object.entries(pe))if(i.command&&t.capabilities.includes(r)&&!(r==="catalog"&&t.catalog==="static")&&!e.handlers[i.command])throw new Error(`Missing merchant command handler: ${i.command}`);if(a&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(i){let u=crypto.randomUUID(),l="bridge.ping",d,w=async(E,C,c=!1)=>{let f=JSON.stringify({bridgeVersion:de,requestId:u,command:l,scope:n,[c?"error":"data"]:E});if(new TextEncoder().encode(f).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(f,{status:C,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":u,...d?await j(f,d,"response"):{}}})};try{if(i.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(de)||i.method!=="POST"||new URL(i.url).pathname!==X)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(i.headers.get("Content-Type")??""))throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=i.body?.getReader();if(!E)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let C=new TextDecoder("utf-8",{fatal:!0}),c="",f=0;try{for(;;){let M=await E.read();if(M.done)break;if(f+=M.value.byteLength,f>16384)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",413);c+=C.decode(M.value,{stream:!0})}c+=C.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let g=_e.safeParse(JSON.parse(c));if(!g.success)throw new b("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=g.data;if(u=v.requestId,l=v.command,Object.keys(n).some(M=>v.scope[M]!==n[M]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let _=v.command==="bridge.ping"||v.command==="bridge.describe",x=v.command==="catalog.read";if((_||x||i.headers.has(Y))&&(d=e.authentication.find(M=>M.keyId===i.headers.get(Y)),!d||!await z(c,i.headers,d,"request")))throw d=void 0,new b("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return w(le["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return w(t,200);let h=Object.entries(pe).find(([,M])=>M.command===v.command);if(!h||!t.capabilities.includes(h[0]))throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let o=e.handlers[v.command];if(!o)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!x&&i.headers.has("Cookie")&&(i.headers.get("Origin")!==new URL(i.url).origin||["cross-site","same-site"].includes(i.headers.get("Sec-Fetch-Site")??"")))throw new b("MERCHANT_BRIDGE_FORBIDDEN",403);let I=x?{kind:"service"}:await e.authorize(i,v),R=I.kind,S=["purchase.execute","subscription.change","refund.execute"].includes(v.command),A=S||v.command==="operation.read";if(!(A&&d!==void 0&&R==="service")&&(v.command==="refund.execute"?R!=="administrator":!x&&R!=="user"))throw new b("MERCHANT_BRIDGE_FORBIDDEN",403);if(I.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!et.uuid().safeParse(I.customerId).success)throw new b("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let P=o,D=le[v.command].parse(v.data),F={request:i,command:v.command,scope:n,principal:I},T;if(A){let M=Z.parse(D);if(I.kind==="user"&&I.customerId!==M.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let k=ee.parse(await e.resolveOperationAuthority(M,F));if(k.operationId!==M.operationId||k.customerId!==M.customerId||Object.keys(n).some(H=>k.scope[H]!==n[H]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);F.authority=k;let q=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":k.instruction.type;if(k.instruction.type!==q)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!S)T=ce.parse(await P(D,F));else{if(k.confirmedAt===null)throw new b("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=ce.parse(await e.handlers["operation.read"](M,{...F,command:"operation.read"}));if(H.operationId!==M.operationId||H.customerId!==M.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!k.initialExecutionAllowed)throw new b("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(k.instruction.expiresAt)<=Date.now())throw new b("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||Ae(k.instruction).some(L=>!t.billingEvents.some(bn=>bn===L))||Ce(k.instruction).some(L=>!t.profiles.includes(L)))throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Me.parse(await P(D,F))}catch(L){throw L instanceof b?L:new b("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==q)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Pe[v.command].parse(await P(D,F));if(I.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==I.nativeUserId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&I.customerId&&T.session.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&I.customerId&&T.presentation.customerId!==I.customerId)throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Z.parse(v.data).operationId||T.customerId!==Z.parse(v.data).customerId))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w(T,S&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let C=E instanceof b?E:E instanceof SyntaxError?new b("MERCHANT_BRIDGE_INVALID_REQUEST",400):new b("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return w({code:C.code,message:C.code,retryable:C.retryable,recovery:C.recovery},C.status,!0)}}}function tt(e){return async(t,n)=>{let a=()=>e.readSubscriptionOperation(t),r=()=>e.readSubscriptionUpdate(t),i=()=>e.readRefund(t),u=n.command==="purchase.execute"?[a]:n.command==="subscription.change"?[r]:n.command==="refund.execute"?[i]:[a,r,i];for(let l of u)try{let d=await l(),w="authority"in d.operation?d.operation.authority:void 0;if(!w)throw new b("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ee.parse(w);if(E.customerId!==t.customerId||E.operationId!==t.operationId||Object.keys(n.scope).some(C=>E.scope[C]!==n.scope[C]))throw new b("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(d){if(n.command==="operation.read"&&d instanceof s&&d.code==="NOT_FOUND")continue;throw d}throw new b("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}import"zod";function rt(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let t=ke.parse(e.manifest),n=Te.parse(e.authentication),a={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},r=e.now??Date.now,i=c=>{throw new s("INVALID_RESPONSE",c)},u=(c,f)=>ue(c)===ue(f);function l(c){new TextEncoder().encode(c).byteLength>262144&&i("Merchant protocol body exceeds limit");try{return JSON.parse(c)}catch{return i("Invalid merchant protocol JSON")}}function d(c){let f=xe.parse(c);return u(f.scope,a)||i("Merchant protocol scope mismatch"),f.command==="requirement.check"&&(t.capabilities.includes("requirement_checks")||i("Merchant Check capability unavailable"),u(f.data.subject.scope,a)||i("Merchant Check subject crosses scope")),f.command==="operation.prepare"&&(!t.capabilities.includes("preparations")||!u(f.data.request.subject.scope,a))&&i("Merchant preparation capability unavailable"),f}function w(c){if(c.command!=="operation.prepare")return;let f=c.data;return(!u(f.request.subject.scope,a)||!f.preparationAllowed||Date.parse(f.requestedAt)>r()||Date.parse(f.request.expiresAt)<=r()||!t.preparationActions.includes(f.request.action))&&i("Merchant preparation requires fresh scoped authority"),f}function E(c,f){let g=Ne(c.command).parse(f);if((g.requestId!==c.requestId||!u(g.scope,a))&&i("Merchant reply correlation mismatch"),"error"in g)return g;if(c.command==="bridge.ping"&&"challenge"in g.data&&g.data.challenge!==c.data.challenge&&i("Merchant ping challenge mismatch"),c.command==="bridge.describe"&&"bridgeVersion"in g.data&&!u({projectId:g.data.projectId,environmentId:g.data.environmentId,environment:g.data.environment},a)&&i("Merchant declaration crosses scope"),c.command==="requirement.check"&&"observation"in g.data&&(!u(g.data.observation.subject,c.data.subject)||!Fe(c.data.requirement,g.data)||!t.checkKinds.includes(g.data.kind))&&i("Merchant Check changed the original requirement or subject"),c.command==="operation.prepare"&&"quoteTermsDigest"in g.data){let v=w(c);(!u(g.data.request,v.request)||Date.parse(g.data.expiresAt)<=r()||Date.parse(g.data.observedAt)<Date.parse(v.requestedAt)||Date.parse(g.data.observedAt)>r())&&i("Merchant quote changed its authorized request or validity")}return g}let C=async c=>{let f=JSON.stringify(c);return l(f),{body:f,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[J]:"4",...await j(f,n,"response",r(),4)})}};return{version:4,path:X,async encodeRequest(c,f){let g=d({bridgeVersion:4,requestId:crypto.randomUUID(),scope:a,command:c,data:f});w(g);let v=JSON.stringify(g);l(v);let _=new Headers({"Content-Type":"application/json",[J]:"4",...await j(v,n,"request",r(),4)});return{body:v,headers:_,async readResponse(x,h){l(x),(h.get(J)!=="4"||!await z(x,h,n,"response",r(),4))&&i("Merchant response authentication failed");let o=E(g,l(x));if("error"in o)throw new se(o.error);return o.data}}},async decodeRequest(c,f){l(c),(f.get(J)!=="4"||f.get(Y)!==n.keyId||!await z(c,f,n,"request",r(),4))&&i("Merchant request authentication failed");let g=d(l(c));return w(g),g},async encodeResponse(c,f){let g=d(c),v=E(g,{...g,data:f});return C(v)},async encodeError(c,f){let g=d(c),{data:v,..._}=g;return C(E(g,{..._,error:De.parse(f)}))}}}var se=class extends Error{constructor(n){super(n.message);this.problem=n}problem};export{Q as FunnelDecisionTimeoutError,oe as FunnelProcessEntrySuppressedError,s as LongplayError,b as MerchantBridgeHandlerError,se as MerchantBridgeProtocolError,Bn as aiPriceSnapshotSchema,Ln as aiTokenQuoteSchema,Un as createAiPricing,Wn as createAiUsageMiddleware,kn as createConfigurationSync,Vn as createConfiguredAiPricing,ve as createFeatureClient,Zn as createFunnelCampaignClient,Ee as createFunnelDecisionClient,ae as createFunnelLocalEvaluator,Xn as createFunnelOrchestrationClient,Gn as createFunnelProcessAdapter,Dn as createFunnelStartClient,Se as createGuestToken,Nn as createLocalFunnelClient,qn as createLongplayServer,tt as createMerchantBridgeAuthorityResolver,nt as createMerchantBridgeHandler,rt as createMerchantBridgeProtocol,Jn as createNativeReceiptClient,Qn as createPaywallStartClient,Kn as createSynchronizedFunnelLocalEvaluator,Fn as entitlementRequirementDigest,xn as evaluateFunnelNode,_n as merchantConfirmationMatchesTerms,Mn as merchantPreparationRequestDigest,Pn as merchantQuoteTermsDigest,jn as renewFunnelRun,j as signMerchantBridgeMessage,z as verifyMerchantBridgeMessage};
|
package/dist/visual.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-
|
|
1
|
+
import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-AX2PJEJP.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-53C6LI3D.js";import"./chunk-Z5CW2N7E.js";import"./chunk-JXNNWCEB.js";import"./chunk-DSPLGTQI.js";import{J as te,L as ie,N as M}from"./chunk-HDVLCRC6.js";import{z as o}from"zod";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,k=0,T=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==K||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:ue(e.renderGuard)}}}function q(e){if(!R(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=oe(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=ae(e.deviceIdCookie??"indiana_did"),T=se(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ce(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=le(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=de(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=re(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tinkerlandai/longplay-sdk",
|
|
3
|
-
"version": "0.10.21
|
|
3
|
+
"version": "0.10.21",
|
|
4
4
|
"description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
package/dist/chunk-UCOKLDSW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as t}from"./chunk-6SPHXEK4.js";import{gb as n}from"./chunk-ZC6PDVLR.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./chunk-FJCDYAPZ.js";import"./chunk-JGG4R75K.js";import"./chunk-6DTGBDYG.js";import"./chunk-YAVWELIV.js";import"./chunk-H6PIJ4WG.js";import"./chunk-QVGTHPWT.js";import"./chunk-SLUA7ABW.js";import"./chunk-2QSCQD6Q.js";import"./chunk-ZC6PDVLR.js";import"./chunk-DSPLGTQI.js";import"./chunk-HDVLCRC6.js";export{a as showFunnelRun};
|