@tinkerlandai/longplay-sdk 0.10.17 → 0.10.18

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.
@@ -1 +1 @@
1
- import"./chunk-F2CMJYA5.js";import"./chunk-T5YZS64H.js";import{a as i}from"./chunk-26HU2HXU.js";import"./chunk-7LIABANC.js";import"./chunk-PFHS7HK3.js";import{z as k}from"zod";var c=k.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:A}=await w.read();if(A){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
1
+ import"./chunk-P6HCD5OQ.js";import"./chunk-E4LUW6KP.js";import{a as i}from"./chunk-26HU2HXU.js";import"./chunk-JVQVQHV2.js";import"./chunk-PFHS7HK3.js";import{z as k}from"zod";var c=k.number().int().min(0).max(1e9);function R(e,o){let a=c.parse(e.promptTokens),p=c.parse(e.completionTokens),s=c.parse(e.promptTokensDetails?.cachedTokens??0),t=c.parse(e.promptTokensDetails?.cacheWriteTokens??0),r=c.parse(e.promptTokensDetails?.audioTokens??0),l=c.parse(e.completionTokensDetails?.audioTokens??0),n=c.parse(e.completionTokensDetails?.reasoningTokens??0);if(c.parse(e.totalTokens)!==a+p||s+t+r>a||n+l>p||(e.promptTokensDetails?.videoTokens??0)>0)throw new i("AI_USAGE_UNAVAILABLE","Token pools must conserve usage; video needs an explicit token mapper");return{input:a-s-t-r,output:p-l-(o==="separate"?n:0),cache_read:s,cache_write:t,input_audio:r,output_audio:l,reasoning:o==="separate"?n:0}}function I(e){if(!Number.isFinite(e)||e<0)throw new i("AI_USAGE_UNAVAILABLE","Provider cost must be a nonnegative USD amount");let o=String(e),a=o.includes("e")?e.toFixed(18).replace(/0+$/,"").replace(/\.$/,""):o;if(!/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/.test(a)||Number(a)!==e)throw new i("AI_USAGE_UNAVAILABLE","Provider cost exceeds the supported precision");return a}async function f(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning)||!e.modelId||!e.generationId)throw new i("INVALID_REQUEST","Actual model, generation ID and reasoning pricing are required");let o={context:e.context,generationId:e.generationId,modelId:`openrouter/${e.modelId}`,usage:e.usage,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let a=e.mapTokens?e.mapTokens(e.usage):R(e.usage,e.reasoning),p=e.usage.cost==null?void 0:I(e.usage.cost),s=e.quote??await e.pricing.quoteTokens({modelId:o.modelId,tokens:a});if(s.pricing.modelId!==o.modelId||Object.keys(a).some(l=>a[l]!==s.tokens[l]))throw new i("INVALID_REQUEST","Saved quote must match the provider model and token pools");await e.persist({...o,tokens:a,quote:s,phase:"quoted"});let t=await e.pricing.trackTokens(e.client,{...e.context,quote:s,providerCostUsd:p,generationId:e.generationId});if(!t.receipt.accepted)throw new i("AI_BALANCE_REJECTED","OpenRouter usage was saved but the balance request was rejected");let r={...o,tokens:a,quote:s,receipt:t,phase:"settled"};return await e.persist(r),r}function T(e){if(typeof window<"u")throw new i("SERVER_ONLY","OpenRouter accounting requires your backend");if(!["output","separate"].includes(e.reasoning))throw new i("INVALID_REQUEST","Reasoning pricing is required");let o=e.openRouter.chat;async function a(t){if(!t.usage||!t.modelId||!t.generationId)throw new i("AI_USAGE_UNAVAILABLE","OpenRouter did not return final usage and the actual model");await f({...e,context:t.context,generationId:t.generationId,modelId:t.modelId.slice(11),usage:t.usage})}let p=async(t,r)=>{let n={context:await e.context(),generationId:null,modelId:null,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"},d;try{d=await o.send(t,r)}catch(g){throw await e.persist(n),g}if(!(d instanceof ReadableStream)){if(n={...n,generationId:d.id,modelId:d.model?`openrouter/${d.model}`:null,usage:d.usage??null},!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter omitted final accounting");return await a(n),d}let w=d.getReader(),m=!1;return new ReadableStream({async pull(g){try{let{value:u,done:A}=await w.read();if(A){if(m=!0,!n.usage||!n.modelId)throw await e.persist(n),new i("AI_USAGE_UNAVAILABLE","OpenRouter stream ended without final accounting");await a(n),g.close();return}if(u.error)throw new i("AI_PROVIDER_ERROR",u.error.message);u.usage&&(n={...n,generationId:u.id,modelId:u.model?`openrouter/${u.model}`:null,usage:u.usage}),g.enqueue(u)}catch(u){m||(m=!0,await e.persist(n)),await w.cancel(u),g.error(u)}},async cancel(g){m||(m=!0,await e.persist(n)),await w.cancel(g)}})},s=new Proxy(o,{get(t,r){return r==="send"?p:Reflect.get(t,r,t)}});return new Proxy(e.openRouter,{get(t,r){return r==="chat"?s:Reflect.get(t,r,t)}})}export{T as createOpenRouterUsageClient,f as trackOpenRouterUsage};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{d as o,e as r,f as e,g as f}from"./chunk-MILFPPP4.js";import"./chunk-3DGJ2X3U.js";import"./chunk-DSPLGTQI.js";import"./chunk-FVX3AVDI.js";import"./chunk-7LIABANC.js";import"./chunk-PFHS7HK3.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
1
+ import{d as o,e as r,f as e,g as f}from"./chunk-OMHZBCS3.js";import"./chunk-6HWNW6FJ.js";import"./chunk-DSPLGTQI.js";import"./chunk-LHBBSD77.js";import"./chunk-JVQVQHV2.js";import"./chunk-PFHS7HK3.js";export{f as createPageExperiments,o as mergeQueryStrings,r as pageAttributes,e as readPayload};
@@ -1 +1 @@
1
- import{b as ue}from"./chunk-SSLZKIIU.js";import{b as se,c as le}from"./chunk-T5COWMDA.js";import{a as oe,b as Y,c as ce}from"./chunk-EEZLS2YP.js";import"./chunk-T5YZS64H.js";import{a as v}from"./chunk-26HU2HXU.js";import{a as J}from"./chunk-DSPLGTQI.js";import{R as V}from"./chunk-7LIABANC.js";import{Da as K,Fa as ie,Z as $,i as j}from"./chunk-PFHS7HK3.js";async function de(g,r,b){if(r.status!=="complete")throw new v("INVALID_RESPONSE","A verified completed purchase is required");if(await b.onComplete?.(r),!g||!b.check)return;let x=$.parse(await b.check());if(x.internal_feature_id!==g.internal_feature_id||x.quantity!==g.quantity)throw new v("INVALID_RESPONSE","The access requirement changed");x.allowed&&await b.onAccessGranted?.(x)}function X(g){return Object.entries(g.document.buttons).filter(([,r])=>r.type==="checkout"&&r.product.type==="fixed"&&!V(r.product,{},g.capabilities)).map(([r])=>r)}async function Oe(g,r){let b=r.check?$.parse(await r.check()):null;if(b?.allowed)return await r.onAccessGranted?.(b),{check:b,host:null};let x=ue(g.ownerDocument),{mountScreenPreview:pe}=await import("./screen-renderer-IZ3VJGU6.js"),t=await r.start(),m;try{let e=t.view??await t.refresh();if(!e)throw new v("INVALID_RESPONSE","Paywall presentation is missing");m=e}catch(e){throw t.destroy(),x(),e}let c=g.ownerDocument,q=new AbortController,R=c.createElement("section"),Z=c.createElement("div"),D=c.createElement("div"),C=c.createElement("p"),l=c.createElement("button"),z=c.createElement("button"),u=c.createElement("dialog"),o=m.document.screen.strings.defaultLocale.startsWith("zh");R.dataset.indianaPaywall="",R.setAttribute("aria-label",m.document.name),R.style.cssText="width:100%;box-sizing:border-box;background:#fff;color:#172033;font:14px/1.5 system-ui,sans-serif",D.style.cssText="display:flex;gap:12px;padding:12px 20px;align-items:center;flex-wrap:wrap",C.setAttribute("role","status"),z.textContent=o?"\u5173\u95ED":"Close",l.textContent=o?"\u91CD\u8BD5":"Retry",l.hidden=!0,D.append(C,l,z),R.append(Z,D);let N=m.document.presentation,_,P;function ee(){let e=c.defaultView;P?.responsive&&e&&_?.resizeViewport?.(e.innerHeight,e.innerWidth)}let f=!1,A=!1,h=null,te=!1,H=!1;function fe(){return A||f||H?{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}:Y(t)}let w=()=>!te&&r.canInteract?.()!==!1,Q=!1,i=null,T=null;function ne(e){t.quote||t.operation||(C.textContent=Object.values(e.capabilities.plans).some(n=>n.available)?"":o?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let F=new Map;async function B(e){if(!(!w()||!e.checkoutUrl||F.get(e.operationId)===e.checkoutUrl)){F.set(e.operationId,e.checkoutUrl);try{r.onCheckoutUrl?await r.onCheckoutUrl(e.checkoutUrl):c.defaultView?.location.assign(e.checkoutUrl)}catch(n){throw F.delete(e.operationId),n}}}let L=e=>{C.textContent=e instanceof Error?e.message:o?"\u8BF7\u6C42\u5931\u8D25":"Request failed",J(r.onError,e),l.hidden=i===null};async function k(e){if(!(A||f||!w())){A=!0,l.hidden=!0,C.textContent="";try{await e()}catch(n){f||L(n)}finally{A=!1}}}async function me(e){await de(b,e,r)}function re(e){return Y(t).type==="recording"||oe({quote:t.quote,operation:e,requestId:null,pending:!1,destroyed:!1,canReselect:t.canReselect}).type==="recording"}async function y(e){if(f)return;if(!w()){i=async()=>y(await t.read()),l.hidden=!1;return}if(C.textContent=e.status,re(e)){let a=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";C.textContent=a?o?"\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.":o?"\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.",l.textContent=o?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",i=async()=>y(await t.read()),l.hidden=!1;return}if(e.problem){let a=e.problem;i=M,l.textContent=o?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",L(new v(a.code,a.reason==="RESULT_UNKNOWN"?o?"\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.":a.phase==="fulfillment"?o?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":a.code==="CAPABILITY_UNAVAILABLE"?o?"\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.":a.code==="NOT_CONFIGURED"?o?"\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.":o?"\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,a));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(C.textContent=o?"\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"){i=null,await me(e);return}if(e.status!=="pending"){if(t.canReselect===!1){C.textContent=o?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",l.textContent=o?"\u67E5\u8BE2\u7ED3\u679C":"Check result",i=async()=>y(await t.read()),l.hidden=!1;return}l.textContent=o?"\u91CD\u8BD5":"Retry",i=null,h=null;return}await B(e);let n=Date.now()+6e5,p=2e3;for(;!f&&Date.now()<n;){if(await new Promise(d=>{let E=()=>{clearTimeout(I),d()},I=setTimeout(()=>{q.signal.removeEventListener("abort",E),d()},p);q.signal.addEventListener("abort",E,{once:!0})}),f)return;if(!w()){i=async()=>y(await t.read()),l.hidden=!1;return}let a=await t.read();if(!a.problem&&a.status==="pending"&&await B(a),a.status!=="pending"||a.problem||re(a)){await y(a);return}p=Math.min(p*1.5,3e4)}i=async()=>y(await t.read()),l.hidden=!1}async function M(){T?.remove(),T=null,i=M;let e=await t.confirm();if(!w()){i=M,l.hidden=!1;return}if(e.problem){await y(e);return}if(e.status==="pending"){if(e.checkoutUrl)await B(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!r.onPurchase)throw new v("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await r.onPurchase({operation:e,signal:q.signal})}}i=async()=>y(await t.read()),await y(e)}function he(e){T?.remove();let n=c.createElement("div"),p=c.createElement("button"),a=c.createElement("button"),d=c.createElement("p");d.textContent=e.lines.map(s=>s.productName).join(", ")+" \xB7 "+j(e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),e.currency),p.textContent=o?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",a.textContent=o?"\u53D6\u6D88":"Cancel",p.onclick=()=>{k(M)};let E=async()=>{let s=await t.cancel();f||(n.remove(),T=null,await y(s))};a.onclick=()=>{i=E,k(E)};let I=c.createElement("div");for(let s of e.lines){let ae=c.createElement("p");ae.textContent=`${s.productName} \xB7 ${j(s.catalogAmountMinor,e.currency)}${K(s.interval,o?"zh-CN":"en",s.intervalCount??1)}`,I.append(ae);for(let O of s.prepaid??[]){let W=c.createElement("p"),U=t.view?.capabilities.plans[s.productVersionId]?.prepaid?.find(we=>we.internalFeatureId===O.internal_feature_id);W.textContent=`${U?.name??O.internal_feature_id} \xB7 ${O.quantity} ${o?"\u4EFD":"packs"} \xD7 ${O.terms.units}`,U&&(W.textContent+=K(U.reset==="week"||U.reset==="month"||U.reset==="year"?U.reset:"one_time",o?"zh-CN":"en",U.resetCount)),I.append(W)}if(s.trial){let O=c.createElement("p");O.textContent=o?`\u8BD5\u7528 ${s.trial.days} \u5929\uFF1B${s.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${s.trial.days}; ${s.trial.cardRequired?"a payment method is required":"no payment method is required"}`,I.append(O)}}if(!e.charge){let s=c.createElement("p");s.textContent=o?"\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.",I.append(s)}n.append(d,I,p,a),D.prepend(n),n.scrollIntoView?.({block:"nearest"}),p.focus({preventScroll:!0}),T=n,i=null}async function G(){if(!h)return;if(i=G,!Q){let n=t.view,p=n?.document.buttons[h.actionId],a=n&&p?.type==="checkout"?V(p.product,h.selection,n.capabilities):null;if(!a)throw new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let d=await r.resolveOfferId?.({actionId:h.actionId,productVersionId:a});if(f)return;d!==void 0&&(h.offerId=d),Q=!0}if(!w()){l.hidden=!1;return}let e=await t.preview(h);f||he(e)}function S(e="destroy"){f||(f=!0,q.abort(),P?.destroy(),_?.destroy(),t.destroy(),u.open&&u.close(),u.remove(),R.remove(),x(),e==="dismiss"&&J(r.onDismiss))}z.onclick=()=>{w()&&S("dismiss")},u.addEventListener("cancel",e=>{e.preventDefault(),w()&&S("dismiss")}),l.onclick=()=>{i&&k(i)};try{if(N.type==="inline")g.append(R);else{let n={sm:420,md:640,lg:900};u.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in N?n[N.size]+"px":"100vw"}`,u.setAttribute("aria-label",m.document.name),u.append(R),g.append(u),P=se(u,{...m.document.screen,presentation:N},ee),P.latch(),w()&&(u.showModal(),P.responsive&&u.focus({preventScroll:!0}),le(u,P.type,P.responsive))}_=pe(Z,{mode:"live",rendererUrl:t.webViewUrl,title:m.document.name,hostPresentation:()=>P?.type??N.type,onResize:n=>{P?.responsive&&P.setContentHeight(n+D.getBoundingClientRect().height)},onAction(n,p={}){if(!w())return;let a=t.view,d=a?.document.buttons[n];if(!d)return;if(d.type==="close"){k(async()=>{await r.onAction?.(n),S(r.onAction?"action":"dismiss")});return}if(d.type==="action"){i=async()=>{if(d.action.type==="event"){if(!r.onEvent)throw new v("EVENT_HANDLER_REQUIRED","Provide the event handler");await r.onEvent(d.action.event)}else r.onOpenUrl?await r.onOpenUrl(d.action.url):c.defaultView?.location.assign(d.action.url);await r.onAction?.(n),i=null},k(i);return}if((t.quote||h)&&t.canReselect===!1){i=t.quote?async()=>y(await t.read()):G,k(i);return}let E=a&&V(d.product,p,a.capabilities);if(!a||!E){L(new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(r.onPurchaseIntent){i=null,k(async()=>{let I={actionId:n,productVersionId:E,selection:structuredClone(p),featureQuantities:ie(a.document.screen,E,p,a.capabilities)};H=!0,await r.onPurchaseIntent(I)});return}if(h&&h.actionId!==n){L(new v("COMMAND_PENDING","Finish the current purchase"));return}h||(h={requestId:crypto.randomUUID(),actionId:n,selection:p},Q=!1),k(G)},onEscape:()=>{w()&&S("dismiss")},onError:n=>L(new Error(n)),onRendered:n=>{n&&u.setAttribute("aria-label",n)}}),ee(),_.update(m.document.screen,m.document.screen.strings.defaultLocale,{capabilities:m.capabilities,unavailableActions:X(m),serverInput:{bindings:[],answers:{}}}),await _.ready,ne(m);let e=t.operation;e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete")&&(i=async()=>y(await t.read()),k(i))}catch(e){throw S(),e}return{check:b,host:{get recovery(){return fe()},async prepareFallback(){if(A||f||H)return{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null};A=!0;try{let e=await ce(t);return e.type==="native"&&S(),e}finally{A=!1}},setSuspended(e){te=e,R.hidden=e,e&&u.open?u.close():!e&&!f&&N.type!=="inline"&&!u.open&&u.showModal()},destroy:S,refresh:async()=>{if(!w()){if(t.view)return t.view;throw new v("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await t.refresh();return f||(_?.updateCapabilities(e.capabilities,X(e)),ne(e)),e}}}}export{Oe as showPaywall};
1
+ import{b as ue}from"./chunk-SSLZKIIU.js";import{b as se,c as le}from"./chunk-T5COWMDA.js";import{a as oe,b as Y,c as ce}from"./chunk-EEZLS2YP.js";import"./chunk-E4LUW6KP.js";import{a as v}from"./chunk-26HU2HXU.js";import{a as J}from"./chunk-DSPLGTQI.js";import{R as V}from"./chunk-JVQVQHV2.js";import{Da as K,Fa as ie,Z as $,i as j}from"./chunk-PFHS7HK3.js";async function de(g,r,b){if(r.status!=="complete")throw new v("INVALID_RESPONSE","A verified completed purchase is required");if(await b.onComplete?.(r),!g||!b.check)return;let x=$.parse(await b.check());if(x.internal_feature_id!==g.internal_feature_id||x.quantity!==g.quantity)throw new v("INVALID_RESPONSE","The access requirement changed");x.allowed&&await b.onAccessGranted?.(x)}function X(g){return Object.entries(g.document.buttons).filter(([,r])=>r.type==="checkout"&&r.product.type==="fixed"&&!V(r.product,{},g.capabilities)).map(([r])=>r)}async function Oe(g,r){let b=r.check?$.parse(await r.check()):null;if(b?.allowed)return await r.onAccessGranted?.(b),{check:b,host:null};let x=ue(g.ownerDocument),{mountScreenPreview:pe}=await import("./screen-renderer-IZ3VJGU6.js"),t=await r.start(),m;try{let e=t.view??await t.refresh();if(!e)throw new v("INVALID_RESPONSE","Paywall presentation is missing");m=e}catch(e){throw t.destroy(),x(),e}let c=g.ownerDocument,q=new AbortController,R=c.createElement("section"),Z=c.createElement("div"),D=c.createElement("div"),C=c.createElement("p"),l=c.createElement("button"),z=c.createElement("button"),u=c.createElement("dialog"),o=m.document.screen.strings.defaultLocale.startsWith("zh");R.dataset.indianaPaywall="",R.setAttribute("aria-label",m.document.name),R.style.cssText="width:100%;box-sizing:border-box;background:#fff;color:#172033;font:14px/1.5 system-ui,sans-serif",D.style.cssText="display:flex;gap:12px;padding:12px 20px;align-items:center;flex-wrap:wrap",C.setAttribute("role","status"),z.textContent=o?"\u5173\u95ED":"Close",l.textContent=o?"\u91CD\u8BD5":"Retry",l.hidden=!0,D.append(C,l,z),R.append(Z,D);let N=m.document.presentation,_,P;function ee(){let e=c.defaultView;P?.responsive&&e&&_?.resizeViewport?.(e.innerHeight,e.innerWidth)}let f=!1,A=!1,h=null,te=!1,H=!1;function fe(){return A||f||H?{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}:Y(t)}let w=()=>!te&&r.canInteract?.()!==!1,Q=!1,i=null,T=null;function ne(e){t.quote||t.operation||(C.textContent=Object.values(e.capabilities.plans).some(n=>n.available)?"":o?"\u5F53\u524D\u8D26\u53F7\u6682\u65E0\u53EF\u8D2D\u4E70\u7684\u65B9\u6848\u3002":"No plans are currently available for this account.")}let F=new Map;async function B(e){if(!(!w()||!e.checkoutUrl||F.get(e.operationId)===e.checkoutUrl)){F.set(e.operationId,e.checkoutUrl);try{r.onCheckoutUrl?await r.onCheckoutUrl(e.checkoutUrl):c.defaultView?.location.assign(e.checkoutUrl)}catch(n){throw F.delete(e.operationId),n}}}let L=e=>{C.textContent=e instanceof Error?e.message:o?"\u8BF7\u6C42\u5931\u8D25":"Request failed",J(r.onError,e),l.hidden=i===null};async function k(e){if(!(A||f||!w())){A=!0,l.hidden=!0,C.textContent="";try{await e()}catch(n){f||L(n)}finally{A=!1}}}async function me(e){await de(b,e,r)}function re(e){return Y(t).type==="recording"||oe({quote:t.quote,operation:e,requestId:null,pending:!1,destroyed:!1,canReselect:t.canReselect}).type==="recording"}async function y(e){if(f)return;if(!w()){i=async()=>y(await t.read()),l.hidden=!1;return}if(C.textContent=e.status,re(e)){let a=e.merchantExecution?.type==="purchase"&&e.merchantExecution.recordingStatus==="failed";C.textContent=a?o?"\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.":o?"\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.",l.textContent=o?"\u67E5\u8BE2\u8BB0\u5F55":"Check recording",i=async()=>y(await t.read()),l.hidden=!1;return}if(e.problem){let a=e.problem;i=M,l.textContent=o?"\u68C0\u67E5\u5E76\u6062\u590D\u539F\u64CD\u4F5C":"Check and recover original purchase",L(new v(a.code,a.reason==="RESULT_UNKNOWN"?o?"\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.":a.phase==="fulfillment"?o?"\u4ED8\u6B3E\u5DF2\u8BB0\u5F55\uFF0C\u5546\u6237\u6743\u76CA\u5904\u7406\u9700\u8981\u6838\u5BF9\u3002":"Payment was recorded. Access fulfillment needs attention.":a.code==="CAPABILITY_UNAVAILABLE"?o?"\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.":a.code==="NOT_CONFIGURED"?o?"\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.":o?"\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,a));return}if(e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(C.textContent=o?"\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"){i=null,await me(e);return}if(e.status!=="pending"){if(t.canReselect===!1){C.textContent=o?"\u6B63\u5728\u6838\u5BF9\u539F\u8D2D\u4E70\u7ED3\u679C":"Checking the original purchase result",l.textContent=o?"\u67E5\u8BE2\u7ED3\u679C":"Check result",i=async()=>y(await t.read()),l.hidden=!1;return}l.textContent=o?"\u91CD\u8BD5":"Retry",i=null,h=null;return}await B(e);let n=Date.now()+6e5,p=2e3;for(;!f&&Date.now()<n;){if(await new Promise(d=>{let E=()=>{clearTimeout(I),d()},I=setTimeout(()=>{q.signal.removeEventListener("abort",E),d()},p);q.signal.addEventListener("abort",E,{once:!0})}),f)return;if(!w()){i=async()=>y(await t.read()),l.hidden=!1;return}let a=await t.read();if(!a.problem&&a.status==="pending"&&await B(a),a.status!=="pending"||a.problem||re(a)){await y(a);return}p=Math.min(p*1.5,3e4)}i=async()=>y(await t.read()),l.hidden=!1}async function M(){T?.remove(),T=null,i=M;let e=await t.confirm();if(!w()){i=M,l.hidden=!1;return}if(e.problem){await y(e);return}if(e.status==="pending"){if(e.checkoutUrl)await B(e);else if(e.execution&&e.execution.provider!=="merchant"||e.nativePurchase){if(!r.onPurchase)throw new v("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await r.onPurchase({operation:e,signal:q.signal})}}i=async()=>y(await t.read()),await y(e)}function he(e){T?.remove();let n=c.createElement("div"),p=c.createElement("button"),a=c.createElement("button"),d=c.createElement("p");d.textContent=e.lines.map(s=>s.productName).join(", ")+" \xB7 "+j(e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),e.currency),p.textContent=o?"\u786E\u8BA4\u8D2D\u4E70":"Confirm purchase",a.textContent=o?"\u53D6\u6D88":"Cancel",p.onclick=()=>{k(M)};let E=async()=>{let s=await t.cancel();f||(n.remove(),T=null,await y(s))};a.onclick=()=>{i=E,k(E)};let I=c.createElement("div");for(let s of e.lines){let ae=c.createElement("p");ae.textContent=`${s.productName} \xB7 ${j(s.catalogAmountMinor,e.currency)}${K(s.interval,o?"zh-CN":"en",s.intervalCount??1)}`,I.append(ae);for(let O of s.prepaid??[]){let W=c.createElement("p"),U=t.view?.capabilities.plans[s.productVersionId]?.prepaid?.find(we=>we.internalFeatureId===O.internal_feature_id);W.textContent=`${U?.name??O.internal_feature_id} \xB7 ${O.quantity} ${o?"\u4EFD":"packs"} \xD7 ${O.terms.units}`,U&&(W.textContent+=K(U.reset==="week"||U.reset==="month"||U.reset==="year"?U.reset:"one_time",o?"zh-CN":"en",U.resetCount)),I.append(W)}if(s.trial){let O=c.createElement("p");O.textContent=o?`\u8BD5\u7528 ${s.trial.days} \u5929\uFF1B${s.trial.cardRequired?"\u9700\u8981\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F":"\u65E0\u9700\u63D0\u4F9B\u4ED8\u6B3E\u65B9\u5F0F"}`:`Trial days: ${s.trial.days}; ${s.trial.cardRequired?"a payment method is required":"no payment method is required"}`,I.append(O)}}if(!e.charge){let s=c.createElement("p");s.textContent=o?"\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.",I.append(s)}n.append(d,I,p,a),D.prepend(n),n.scrollIntoView?.({block:"nearest"}),p.focus({preventScroll:!0}),T=n,i=null}async function G(){if(!h)return;if(i=G,!Q){let n=t.view,p=n?.document.buttons[h.actionId],a=n&&p?.type==="checkout"?V(p.product,h.selection,n.capabilities):null;if(!a)throw new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");let d=await r.resolveOfferId?.({actionId:h.actionId,productVersionId:a});if(f)return;d!==void 0&&(h.offerId=d),Q=!0}if(!w()){l.hidden=!1;return}let e=await t.preview(h);f||he(e)}function S(e="destroy"){f||(f=!0,q.abort(),P?.destroy(),_?.destroy(),t.destroy(),u.open&&u.close(),u.remove(),R.remove(),x(),e==="dismiss"&&J(r.onDismiss))}z.onclick=()=>{w()&&S("dismiss")},u.addEventListener("cancel",e=>{e.preventDefault(),w()&&S("dismiss")}),l.onclick=()=>{i&&k(i)};try{if(N.type==="inline")g.append(R);else{let n={sm:420,md:640,lg:900};u.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in N?n[N.size]+"px":"100vw"}`,u.setAttribute("aria-label",m.document.name),u.append(R),g.append(u),P=se(u,{...m.document.screen,presentation:N},ee),P.latch(),w()&&(u.showModal(),P.responsive&&u.focus({preventScroll:!0}),le(u,P.type,P.responsive))}_=pe(Z,{mode:"live",rendererUrl:t.webViewUrl,title:m.document.name,hostPresentation:()=>P?.type??N.type,onResize:n=>{P?.responsive&&P.setContentHeight(n+D.getBoundingClientRect().height)},onAction(n,p={}){if(!w())return;let a=t.view,d=a?.document.buttons[n];if(!d)return;if(d.type==="close"){k(async()=>{await r.onAction?.(n),S(r.onAction?"action":"dismiss")});return}if(d.type==="action"){i=async()=>{if(d.action.type==="event"){if(!r.onEvent)throw new v("EVENT_HANDLER_REQUIRED","Provide the event handler");await r.onEvent(d.action.event)}else r.onOpenUrl?await r.onOpenUrl(d.action.url):c.defaultView?.location.assign(d.action.url);await r.onAction?.(n),i=null},k(i);return}if((t.quote||h)&&t.canReselect===!1){i=t.quote?async()=>y(await t.read()):G,k(i);return}let E=a&&V(d.product,p,a.capabilities);if(!a||!E){L(new v("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(r.onPurchaseIntent){i=null,k(async()=>{let I={actionId:n,productVersionId:E,selection:structuredClone(p),featureQuantities:ie(a.document.screen,E,p,a.capabilities)};H=!0,await r.onPurchaseIntent(I)});return}if(h&&h.actionId!==n){L(new v("COMMAND_PENDING","Finish the current purchase"));return}h||(h={requestId:crypto.randomUUID(),actionId:n,selection:p},Q=!1),k(G)},onEscape:()=>{w()&&S("dismiss")},onError:n=>L(new Error(n)),onRendered:n=>{n&&u.setAttribute("aria-label",n)}}),ee(),_.update(m.document.screen,m.document.screen.strings.defaultLocale,{capabilities:m.capabilities,unavailableActions:X(m),serverInput:{bindings:[],answers:{}}}),await _.ready,ne(m);let e=t.operation;e&&(e.confirmedAt||e.checkoutUrl||e.status==="complete")&&(i=async()=>y(await t.read()),k(i))}catch(e){throw S(),e}return{check:b,host:{get recovery(){return fe()},async prepareFallback(){if(A||f||H)return{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null};A=!0;try{let e=await ce(t);return e.type==="native"&&S(),e}finally{A=!1}},setSuspended(e){te=e,R.hidden=e,e&&u.open?u.close():!e&&!f&&N.type!=="inline"&&!u.open&&u.showModal()},destroy:S,refresh:async()=>{if(!w()){if(t.view)return t.view;throw new v("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await t.refresh();return f||(_?.updateCapabilities(e.capabilities,X(e)),ne(e)),e}}}}export{Oe as showPaywall};
@@ -1 +1 @@
1
- import{b as C,c as A,d as L}from"./chunk-DM2WGIRX.js";import{b as O,l as R,m as E,n as x,p as M}from"./chunk-FBLAWSUN.js";import"./chunk-LC2VUKYM.js";import"./chunk-EEZLS2YP.js";import"./chunk-T5YZS64H.js";import{a as i}from"./chunk-26HU2HXU.js";import"./chunk-DSPLGTQI.js";import"./chunk-FVX3AVDI.js";import{a as S,ua as P}from"./chunk-7LIABANC.js";import"./chunk-PFHS7HK3.js";function k(t,d){let n,a=0,m=-1,l,r=!1,g=()=>{if(r)throw new i("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new i("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new i("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,y=null;try{if(!r&&e.revision===w){let N=await d.access();!r&&a===w&&(y=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,y)}return}let s=!1,u=a;try{if(r||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!r&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=g();if(d.snapshot()&&!t.nativeEvents)throw new i("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(r||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 y=await n;if(r||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let b=(async()=>{if(await s.identify(y,JSON.stringify({revision:u,credentials:w})),r||a!==u)throw await s.reset(y,u),o();m=u})();l={epoch:u,task:b}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(y,e,JSON.stringify(c));if(r||a!==u)throw o();try{return JSON.parse(N)}catch{throw new i("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new i("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return f("showFunnel",{runToken:e})},showPaywall(e){return f("showPaywall",e)},showContent(e){return f("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 g().reset(await n,a)},async destroy(){r||(r=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var J=P.trackUsage.request.shape.command,V=P.trackUsage.response;function T(t){let d=S.parse(t.scope),n=C({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,r=!1;n.subscribeIdentity(()=>{l++});let g=()=>{if(r)throw new i("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new i("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){r||(r=!0,l++,n.destroy(),await m.destroy())},funnel(){return A({...a,customerToken:g()})},resumeFunnel(o){return g(),R({...a,runToken:o})},paywall(o){return E(a,{...o,customerToken:g()})},async trackUsage(o){if(g(),!t.usageReporter)throw new i("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=J.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new i("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new i("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=V.parse(p);if(f.scope.projectId!==d.projectId||f.scope.environment!==d.environment)throw new i("INVALID_RESPONSE","Usage response scope differs");return f}}}export{i as LongplayError,x as createConfigurationSync,O as createFeatureClient,L as createFunnelProcess,M as createLocalFunnelClient,T as createLongplayReactNative};
1
+ import{b as C,c as A,d as L}from"./chunk-KYXX676W.js";import{b as O,l as R,m as E,n as x,p as M}from"./chunk-N4HZ55YU.js";import"./chunk-LC2VUKYM.js";import"./chunk-EEZLS2YP.js";import"./chunk-E4LUW6KP.js";import{a as i}from"./chunk-26HU2HXU.js";import"./chunk-DSPLGTQI.js";import"./chunk-LHBBSD77.js";import{a as S,ua as P}from"./chunk-JVQVQHV2.js";import"./chunk-PFHS7HK3.js";function k(t,d){let n,a=0,m=-1,l,r=!1,g=()=>{if(r)throw new i("CLOSED","Native host was destroyed");if(!t.nativeModule)throw new i("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return t.nativeModule},o=()=>new i("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,y=null;try{if(!r&&e.revision===w){let N=await d.access();!r&&a===w&&(y=N)}}finally{await t.nativeModule.provideCredential(c,e.requestId,y)}return}let s=!1,u=a;try{if(r||e.revision!==u||!t.onNativeAction)throw o();await t.onNativeAction(e.action),s=!r&&a===u}finally{await t.nativeModule.acknowledge(c,e.requestId,s)}})().catch(()=>{})});async function p(e,c={}){let s=g();if(d.snapshot()&&!t.nativeEvents)throw new i("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let u=a,w=await d.access();if(r||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 y=await n;if(r||a!==u)throw o();if(m!==u){if(!l||l.epoch!==u){let b=(async()=>{if(await s.identify(y,JSON.stringify({revision:u,credentials:w})),r||a!==u)throw await s.reset(y,u),o();m=u})();l={epoch:u,task:b}}let v=l;try{await v.task}finally{l===v&&(l=void 0)}}let N=await s.invoke(y,e,JSON.stringify(c));if(r||a!==u)throw o();try{return JSON.parse(N)}catch{throw new i("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(e,c){let s=await p(e,c);if(!s||typeof s!="object"||Array.isArray(s)||s.status!=="complete"&&s.status!=="dismissed")throw new i("INVALID_RESPONSE","Native presentation returned an invalid result");return s}return{showFunnel(e){return f("showFunnel",{runToken:e})},showPaywall(e){return f("showPaywall",e)},showContent(e){return f("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 g().reset(await n,a)},async destroy(){r||(r=!0,a++,h(),I?.(),n&&t.nativeModule&&await t.nativeModule.destroy(await n))}}}var J=P.trackUsage.request.shape.command,V=P.trackUsage.response;function T(t){let d=S.parse(t.scope),n=C({...t,scope:d}),a={...t,scope:d,session:n.session},m=k(t,n.session),l=0,r=!1;n.subscribeIdentity(()=>{l++});let g=()=>{if(r)throw new i("CLOSED","SDK client was destroyed");let o=n.session.peek();if(!o)throw new i("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:m,async destroy(){r||(r=!0,l++,n.destroy(),await m.destroy())},funnel(){return A({...a,customerToken:g()})},resumeFunnel(o){return g(),R({...a,runToken:o})},paywall(o){return E(a,{...o,customerToken:g()})},async trackUsage(o){if(g(),!t.usageReporter)throw new i("INVALID_REQUEST","Configure your authenticated backend usageReporter");let h=J.parse(o),I=l,p;try{p=await t.usageReporter(h)}catch(e){throw I!==l?new i("IDENTITY_CHANGED","Customer identity changed during usage reporting"):e}if(I!==l)throw new i("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=V.parse(p);if(f.scope.projectId!==d.projectId||f.scope.environment!==d.environment)throw new i("INVALID_RESPONSE","Usage response scope differs");return f}}}export{i as LongplayError,x as createConfigurationSync,O as createFeatureClient,L as createFunnelProcess,M as createLocalFunnelClient,T as createLongplayReactNative};
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{a as wn}from"./chunk-C4EMRGWJ.js";import{a as En,b as Rn,c as Cn,d as An}from"./chunk-F2CMJYA5.js";import{a as l,b as ye,c as We,d as Xe,e as Ze,f as en,h as W,i as nn,j as B,k as D,m as tn,n as hn,o as vn,p as Sn}from"./chunk-FBLAWSUN.js";import"./chunk-LC2VUKYM.js";import"./chunk-EEZLS2YP.js";import"./chunk-T5YZS64H.js";import{a as o}from"./chunk-26HU2HXU.js";import"./chunk-FVX3AVDI.js";import{$ as Me,A as J,B as Ce,E as ae,F as Ae,Fa as Ue,G as Oe,Ga as le,H as ie,Ha as z,I as se,Ia as Be,J as ce,Ja as Ge,Ka as Ve,La as me,Ma as He,N as ue,Na as qe,O as be,Oa as je,P as Pe,Pa as fe,Qa as Ke,Ra as Q,Sa as ze,T as Ne,Va as Qe,Wa as Ye,X as G,Y as ke,Z as de,_ as De,_a as Je,a as he,aa as $,ab as $e,ba as j,ca as Le,k as we,l as ve,m as te,o as Se,p as re,q as Ee,s as oe,u as Re,ua as i,va as pe,z as Y}from"./chunk-7LIABANC.js";import{Aa as xe,B as Fe,E as _e,r as Te}from"./chunk-PFHS7HK3.js";function X(e){return{async getCustomer(t){let n=i.getCustomer;return l(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=i.listCustomers;return l(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=i.updateCustomer;return l(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=i.createGuestCustomer;return l(e,n,t)},async resumeGuestSession(t){let n=i.resumeGuestSession;return l(e,n,t)},async claimGuestCustomer(t){let n=i.claimGuestCustomer;return l(e,n,t)},async revokeCustomerSessions(t){let n=i.revokeSessions;return l(e,n,t)},async createCustomerSession(t){return l(e,i.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return l(e,i.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function f(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function rn(e){return{async checkEntitlement(t){let n=i.checkEntitlement;return l(e,n,t,f)},async readHoldings(t){let n=i.readHoldings;return l(e,n,t,f)},async readSeats(t){let n=i.readSeats;return l(e,n,t,f)},async manageSeat(t){let n=i.manageSeat;return l(e,n,t,f)}}}function on(e){return{async readAiPricing(t){let n=i.readAiPricing;return l(e,n,t,f)},async readUsage(t){let n=i.readUsage;return l(e,n,t,f)},async setUsage(t){let n=i.setUsage;return l(e,n,t,f)},async manageBalanceGrant(t){let n=i.manageBalanceGrant;return l(e,n,t,f)},async readBalanceSource(t){let n=i.readBalanceSource;return l(e,n,t,f)},async adjustBalance(t){let n=i.adjustBalance;return l(e,n,t,f)},async listBalanceGrants(t){let n=i.listBalanceGrants;return l(e,n,t,f)},async manageBillingLimits(t){let n=i.manageBillingLimits;return l(e,n,t,f)},async manageUsageEntity(t){let n=i.manageUsageEntity;return l(e,n,t,f)},async readUsageAnalytics(t){let n=i.readUsageAnalytics;return l(e,n,t,f)},async readCreditAnalytics(t){let n=i.readCreditAnalytics;return l(e,n,t,f)},async submitUsageBatch(t){let n=i.submitUsageBatch;return l(e,n,t,f)},async readUsageBatch(t){let n=i.readUsageBatch;return l(e,n,t,f)},async readLedger(t){let n=i.readLedger;return l(e,n,t,f)},async readCreditStatement(t){let n=i.readCreditStatement;return l(e,n,t,f)},async quoteBalance(t){let n=i.quoteBalance;return l(e,n,t,f)},async trackUsage(t){let n=i.trackUsage;return l(e,n,t,f)},async mutateBalance(t){let n=i.mutateBalance;return l(e,n,t,f)}}}function an(e){return{async listInvoiceTemplates(t={}){let n=i.listInvoiceTemplates;return l(e,n,t,f)},async previewInvoice(t){let n=i.previewInvoice;return l(e,n,t,f)},async createInvoice(t){let n=i.createInvoice;return l(e,n,t,f)},async prepareBillingAdjustment(t){let n=i.prepareBillingAdjustment;return l(e,n,t,f)},async manageInvoice(t){let n=i.manageInvoice;return l(e,n,t,f)},async readInvoiceOperation(t){let n=i.readInvoiceOperation;return l(e,n,t,f)},async listInvoices(t){let n=i.listInvoices;return l(e,n,t,f)},async getInvoice(t){let n=i.getInvoice;return l(e,n,t,f)},async setupPayment(t){let n=i.setupPayment;return l(e,n,t,f)},async readPaymentSetup(t){let n=i.readPaymentSetup;return l(e,n,t,f)},async readBillingInvoice(t){let n=i.readBillingInvoice;return l(e,n,t,f)},async previewRefund(t){let n=i.previewRefund;return l(e,n,t,f)},async refund(t){let n=i.refund;return l(e,n,t,f)},async readRefund(t){let n=i.readRefund;return l(e,n,t,f)}}}function sn(e){return{async previewSubscriptionBatch(t){let n=i.previewSubscriptionBatch;return l(e,n,t,f)},async confirmSubscriptionBatch(t){let n=i.confirmSubscriptionBatch;return l(e,n,t,f)},async readSubscriptionBatch(t){let n=i.readSubscriptionBatch;return l(e,n,t,f)},async abandonSubscriptionBatch(t){let n=i.abandonSubscriptionBatch;return l(e,n,t,f)},async manageSubscriptionTrial(t){let n=i.manageSubscriptionTrial;return l(e,n,t,f)},async readSubscriptionTrial(t){let n=i.readSubscriptionTrial;return l(e,n,t,f)},async listSubscriptions(t){let n=i.listSubscriptions;return l(e,n,t,f)},async listPurchases(t){let n=i.listPurchases;return l(e,n,t,f)},async listSubscriptionConflicts(t){let n=i.listSubscriptionConflicts;return l(e,n,t,f)},async retrySubscriptionConflict(t){let n=i.retrySubscriptionConflict;return l(e,n,t,f)},async previewUpdate(t){let n=i.previewUpdate;return l(e,n,t,f)},async update(t){let n=i.update;return l(e,n,t,f)},async readSubscriptionUpdate(t){let n=i.readSubscriptionUpdate;return l(e,n,t,f)},async restoreNativePurchase(t){let n=i.restoreNativePurchase;return l(e,n,t,f)},async verifySubscriptions(t){let n=i.verifySubscriptions;return l(e,n,t,f)},async previewAttach(t){let n=i.previewAttach;return l(e,n,t,f)},async recordMerchantEvent(t){return l(e,i.recordMerchantEvent,t,{request:"Invalid merchant event",parseResponse:f})},async attach(t){let n=i.attach;return l(e,n,t,f)},async readSubscriptionOperation(t){let n=i.readSubscriptionOperation;return l(e,n,t,f)}}}function cn(e){return{async grantOffer(t){let n=i.grantOffer;return l(e,{...n,request:n.request.refine(u=>!!u.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function un(e){return{...rn(e),...on(e),...an(e),...sn(e),...cn(e)}}function dn(e){return{async getFeatures(t={}){let n=i.getFeatures;return l(e,n,t,f)},async evaluateFeatures(t){let n=i.evaluateFeatures;return l(e,n,t,f)}}}function pn(e){return{async trackEvents(t){let n=i.trackEvents;return l(e,n,t,f)}}}function ln(e){return{async resolveContent(t){let n=i.resolveContent;return l(e,n,t,f)},async resolvePaywall(t){let n=i.resolvePaywall;return l(e,n,t,f)},async resolveOffering(t){let n=i.resolveOffering;return l(e,n,t,f)}}}function On(e){B(e.apiKey,"Secret API keys must stay on your backend");let n=D(e).request;return{async sendMessage(u){let a=i.sendMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},async readMessage(u){let a=i.readMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},...X(n),...un(n),...dn(n),...pn(n),...ln(n)}}function Ie(){if(typeof window<"u")throw new o("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 mn=()=>new o("CONFLICT","Process synchronization is in progress",425),M=()=>new o("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Tn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=class extends o{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 Fn(e){if(B(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new o("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=D(e),n=X(t.request),u=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function a(m){let r=await e.resolveUser(m);if(r!==null&&(typeof r?.externalUserId!="string"||!r.externalUserId||r.externalUserId!==r.externalUserId.trim()||r.externalUserId.startsWith("gg_guest_")))throw new o("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return r}async function c(m){let r=await e.resolveContext(m);if(r?.confirmed!==!0||!r.processKey||!r.guestKey)throw new o("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:u+"run:"+r.processKey,guest:u+"guest:"+r.guestKey}}async function d(m,r){for(let y=0;y<8;y++){let h=await e.store.read(m),I=r(h?structuredClone(h.value):null);if(h&&Tn(h.value,I)||await e.store.compareAndSwap(m,h?.revision??null,I))return I}throw mn()}async function p(m){let r=await e.store.read(m);if(!r)throw new o("NOT_FOUND","Open the process before continuing",404);return r.value}async function s(m){let r=await p(m);for(let y of r.revocations??[])await n.revokeCustomerSessions(y),await d(m,h=>{if(!h)throw M();return h.revocations=h.revocations?.filter(I=>I.sessionId!==y.sessionId),h})}async function g(m,r){let y=le.parse(m);return r?t.requestWithCredential("funnel-processes",y,r):t.request("funnel-processes",y)}function w(m,r){if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment||m.run&&(m.run.id!==r.run.id||m.run.source.versionId!==r.run.source.versionId||m.run.source.id!==r.run.source.id||m.run.runExpiresAt!==r.run.runExpiresAt||m.run.identity.startedAs!==r.run.identity.startedAs||m.run.identity.participantId!==r.run.identity.participantId||m.run.identity.binding&&m.run.identity.binding.id!==r.run.identity.binding?.id)||m.runToken&&r.runToken&&m.runToken!==r.runToken)throw new o("INVALID_RESPONSE","Process identity or Run changed")}async function E(m,r,y){return d(m,h=>{if(!h)throw new o("NOT_FOUND","Process handle is missing",404);return w(h,r),(!h.run||r.run.revision>=h.run.revision)&&(h.run=r.run),h.runToken??=r.runToken,y!==void 0&&(h.target=y),h})}async function S(m,r){if(r.detached)throw new o("UNAUTHENTICATED","The process is detached",401);let y=r.run?.identity.binding?.customerId??r.run?.identity.participantId;if(!y)throw new o("INVALID_RESPONSE","Process participant is missing");if(r.session?.customerId===y&&Date.parse(r.session.expiresAt)>Date.now()+3e4)return r.session;let h={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},I=await d(m,A=>{if(!A||A.detached||A.run?.id!==r.run?.id)throw M();if(A.sessionLease&&A.sessionLease.until>Date.now())throw mn();return A.sessionLease=h,A}),C;try{if(I.session?.customerId===y&&Date.parse(I.session.refreshExpiresAt)>Date.now())try{if(C=Se.parse(await t.requestWithCredential("customer-sessions/refresh",{},I.session.refreshToken)),C.sessionId!==I.session.sessionId)throw new o("INVALID_RESPONSE","Refresh changed the logical session")}catch(b){if(!(b instanceof o)||b.status!==401)throw b}if(C??=I.run?.identity.binding?await n.createCustomerSession(y):await n.resumeGuestSession({guestToken:I.guest.token}),C.customerId!==y)throw new o("INVALID_RESPONSE","Session Customer changed");let A=C;return await d(m,b=>{if(!b||b.detached||b.sessionLease?.id!==h.id||b.run?.identity.binding?.id!==r.run?.identity.binding?.id)throw new o("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return b.session=A,delete b.sessionLease,b}),C}catch(A){throw C&&C.sessionId!==I.session?.sessionId&&await n.revokeCustomerSessions({customerId:C.customerId,sessionId:C.sessionId}).catch(()=>{}),await d(m,b=>{if(!b)throw M();return b.sessionLease?.id===h.id&&delete b.sessionLease,b}).catch(()=>{}),A}}let R;async function O(){if(R??=He.parse(await g({contract:G,operation:"describe"})),R.scope.projectId!==e.scope.projectId||R.scope.environment!==e.scope.environment)throw M();return R}async function v(m,r,y=!1){let h=await a(m),I=await p(r);if(I.issuingKeyId!==(await O()).keyId)throw new o("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!I.runToken||!I.run)throw new o("CONFLICT","Recover the original start first",425);if(I.detached){if(!y)throw new o("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(I.run.identity.binding&&(!h||I.target&&I.target!==h.externalUserId))throw M();await s(r),I=await d(r,C=>{if(!C||C.run?.id!==I.run?.id)throw M();return delete C.detached,C})}if(!I.runToken||!I.run)throw new o("INVALID_RESPONSE","Process identity is missing");if(I.run.identity.binding){if(h&&!I.target){let C=me.parse(await g({contract:G,operation:"binding_status",runToken:I.runToken,requestId:I.bindingIntent?.requestId??I.start.requestId,externalUserId:h.externalUserId}));if(C.state!=="bound"||C.binding.id!==I.run.identity.binding.id)throw M();I=await d(r,A=>{if(!A)throw M();return A.target=h.externalUserId,A})}if(!h||I.target!==h.externalUserId)throw M()}else if(h){if(!I.guest)throw M();I=await d(r,A=>{if(!A||A.bindingIntent&&A.bindingIntent.externalUserId!==h.externalUserId)throw M();return A.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:h.externalUserId},A});let C=I.bindingIntent;try{let A=Ve.parse(await g({contract:G,operation:"bind_customer",...C,runToken:I.runToken,guestToken:I.guest.token,claimRequestId:I.guest.claimRequestId,expectedBindingId:null}));I=await E(r,A,h.externalUserId)}catch(A){let b=me.parse(await g({contract:G,operation:"binding_status",...C,runToken:I.runToken,guestToken:I.guest.token}));if(b.state!=="bound")throw A;I=await d(r,x=>{if(!x?.run||x.run.id!==b.binding.runId)throw M();return x.run.identity.binding={id:b.binding.id,customerId:b.binding.customerId,acceptedAt:b.binding.acceptedAt},x.target=h.externalUserId,x})}}return{state:I,session:await S(r,I)}}async function k(m,r,y,h){try{return await h(y)}catch(I){if(!(I instanceof o)||I.status!==401)throw I;return await d(r,C=>{if(!C||C.detached)throw I;return C.session?.accessToken===y.session.accessToken&&(C.session.expiresAt=new Date(0).toISOString()),C}),h(await v(m,r))}}async function L(m,r,y=!1){let h=await c(m),I=await v(m,h.process,y),C=z.parse(await k(m,h.process,I,A=>g({...r,customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C}return{async open(m,r){r=Ge.parse(r);let y=await c(m),h=await O(),I=y.guest+":"+h.keyId,C=await e.store.read(y.process);if(!C){let P=await a(m),T,_,N;if(P)T={type:"customer",customer:{type:"externalUserId",value:P.externalUserId}};else{let V=await e.store.read(I);if(V)try{N=await n.resumeGuestSession({guestToken:V.value.token}),_=V.value}catch(U){if(!(U instanceof o)||U.status!==401)throw U}let H={token:Ie(),claimRequestId:crypto.randomUUID()};_=await d(I,U=>_??(U&&U.token!==V?.value.token?U:H)),T={type:"guest",guestToken:_.token}}await d(y.process,V=>V??{issuingKeyId:h.keyId,start:le.parse({...r,contract:G,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...P?{target:P.externalUserId}:{},...N?{session:N}:{}}),C=await e.store.read(y.process)}let A=C.value;if(A.issuingKeyId!==h.keyId)throw new o("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(A.start.funnelId!==r.funnelId||A.start.operation!==r.operation)throw new o("CONFLICT","This handle already owns another process",409);if(!A.runToken){if(A.start.source.type==="customer"){let N=await a(m);if(!N||N.externalUserId!==A.target)throw M()}let P=await g(A.start),T=Be.safeParse(P);if(T.success)throw new Z(T.data);let _=z.parse(P);if(!_.runToken)throw new o("INVALID_RESPONSE","Process credential is missing");A=await E(y.process,_)}let b=await v(m,y.process,!0),x=z.parse(await k(m,y.process,b,P=>g({contract:G,operation:"get",customerToken:P.session.accessToken},P.state.runToken)));return await E(y.process,x),{...x,runToken:A.runToken}},async syncIdentity(m){return L(m,{contract:G,operation:"get",customerToken:""},!0)},async get(m,r={}){return L(m,{...r,contract:G,operation:"get",customerToken:""})},async review(m,r){return L(m,{contract:G,operation:"review",customerToken:"",...r?{receiptId:r}:{}})},async command(m,r,y){let h=await c(m),I=await v(m,h.process),C=z.parse(await k(m,h.process,I,A=>g({contract:G,operation:"command",command:r,identity:{bindingId:y},customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C},async pageExperiments(m,r,y=[]){let h=await c(m),I=await v(m,h.process);return Ue.parse(await k(m,h.process,I,C=>g({contract:G,operation:"page_experiments",release:r,usedReceiptIds:y,customerToken:C.session.accessToken},C.state.runToken)))},async detach(m){let r=await c(m);await d(r.process,y=>{if(!y)throw M();return y.session&&!y.revocations?.some(h=>h.sessionId===y.session.sessionId)&&(y.revocations??=[]).push({customerId:y.session.customerId,sessionId:y.session.sessionId}),y.detached=!0,delete y.session,delete y.sessionLease,y}),await s(r.process)},destroy(){t.dispose()}}}async function _n(e,t){B(e.apiKey,"Renewal requires your backend");let n=D(e),u=je.parse(We(e,await n.request("funnels",qe.parse({...t,operation:"renew_run"}))));if(u.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return u}function fn(e){let t=Ze(e),n=p=>{throw new o("INVALID_RESPONSE",p)};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 u=new Set(["entry","condition","feature","split","end","output"]);for(let p of t.nodes.values()){if(!u.has(p.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(p.type==="entry"&&p.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(p.type)&&!p.outputs.next&&n("Local next exit is unavailable"),p.type==="feature"){let s=p.resources.featureKey;(!s||!Object.hasOwn(e.evaluation.variables,p.writes.value)||!Object.hasOwn(t.features,s))&&n("Local Feature definition or declaration is unavailable")}if(p.type==="condition"){let s=e.conditions[p.id];(!s||!p.outputs.default||s.some((g,w)=>g.port!==`case:${w}`||!p.outputs[g.port]))&&n("Local Condition exits are unavailable")}if(p.type==="split"&&(!p.resources.experimentId||!Object.hasOwn(e.growth.experiments,p.resources.experimentId)||!p.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),p.type==="end"||p.type==="output"){let s=e.evaluation.terminals[p.id];if(!s)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(p.outputs).length&&n("A terminal cannot have outgoing edges"),s.output?.type==="feature"&&!Object.hasOwn(t.features,s.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let s of Object.values(p.outputs))t.nodes.has(s)||n("Local target is unavailable")}let a=new Set,c=new Set;function d(p){if(c.has(p)&&n("Local graph contains a cycle"),!a.has(p)){c.add(p);for(let s of Object.values(t.nodes.get(p).outputs))d(s);c.delete(p),a.add(p)}}return d(e.topology.entry),a.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(p){let s={},g=p.context;g.features=t.features,g.savedGroups=t.savedGroups;let w=()=>{g.attributes=ke({declarations:e.evaluation.variables,attributes:p.attributes,parameters:p.parameters,answers:{},results:s,savedGroups:t.savedGroups})};w();let E=e.topology.entry,S=0;for(;;){let R=t.nodes.get(E);if(R.type==="end"||R.type==="output"){let O=e.evaluation.terminals[E],v=O.output,k=v?.type==="feature"?t.feature(v.featureKey,g):v?.type==="variable"?Pe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:s,parameters:p.parameters,attributes:p.attributes,savedGroups:t.savedGroups}):v?.value??null;return ue(e.evaluation.outputSchema,k)||n("Local output does not match its declaration"),{outcome:O.outcome,value:k}}if(S++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(R.type==="entry")E=R.outputs.next;else{let O=t.evaluate(E,g);if(R.type==="feature"){let v=R.writes.value,k=O.value??null;ue(e.evaluation.variables[v],k)||n("Local Feature value does not match its declaration"),be(e.evaluation.variables,{writes:R.writes},{[v]:k}),s[v]=k,w()}E=O.target}}}}}import{z as yn}from"zod";function In(e,t,n){let u=Fe.parse(e.attributes);if(["parameters","answers","results"].some(m=>Object.hasOwn(u,m)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=xe.parse(e.parameters??{}),c=yn.record(yn.string(),_e).parse(e.stickyBucketAssignmentDocs??{});for(let[m,r]of Object.entries(c))if(m!==`${r.attributeName}||${r.attributeValue}`||!Object.hasOwn(u,r.attributeName)||Te(u[r.attributeName])!==r.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,p=e.onFeatureUsage,s=e.onExperimentViewed,g=e.onError,w=new Map,E=new Set,S={},R=Promise.resolve();function O(m){let r=R.then(()=>(n(),m()));return R=r.catch(()=>{}),r}function v(m){try{g?.(m)}catch{}}function k(m){try{let r=m();r&&typeof r.catch=="function"&&r.catch(v)}catch(r){v(r)}}async function L(){for(let[m,r]of w){if(n(),d)try{await d(structuredClone(r))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),w.delete(m)}}return{evaluate(m={}){let r=m.track===!0;return O(async()=>{let y=await t();n(y);let h=new Set(E),I={...S},C=new Map,A=[],b={stickyBucketAssignmentDocs:structuredClone(c),saveStickyBucketAssignmentDoc(T){C.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...r?{trackedExperiments:h,trackedFeatureUsage:I,onExperimentViewed(T,_){let N=structuredClone(T),V=structuredClone(_);s&&A.push(()=>s(structuredClone(N),structuredClone(V)))},onFeatureUsage(T,_){let N=structuredClone(_);p&&A.push(()=>p(T,structuredClone(N)))}}:{}},x=y.program.evaluate({attributes:u,parameters:a,context:b});n(y);for(let[T,_]of C)c[T]=_,w.set(T,_);await L(),n(y),r&&(E=h,S=I);for(let T of A)k(T);let P=y.configuration;return structuredClone({evaluationMode:"local",scope:P.scope,funnelId:P.funnelId,versionId:P.versionId,evaluationRevision:P.evaluationRevision,generation:P.growth.generation,...x})})},flush:()=>O(L),get stickyBucketAssignmentDocs(){return n(),structuredClone(c)}}}var bn=6e4;function ee(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=he.parse(e.scope),n=e.funnelId,u=e.load,a,c,d,p=0,s=E=>Date.now()>=E.expiresAt;async function g(){if(c)return c;let E=p;a=void 0;let S=(async()=>{let R=await u();if(E!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&typeof R=="object"&&"evaluationMode"in R&&R.evaluationMode==="remote")throw f(Q,R),new o("EVALUATION_MODE","This Funnel requires remote decide");let O=f(ze,R);if(E!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(O.scope.projectId!==t.projectId||O.scope.environment!==t.environment||O.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(O.growth.scope.projectId!==t.projectId||O.growth.scope.environment!==t.environment||O.growth.expiresAt!==O.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+bn,O.expiresAt?Date.parse(O.expiresAt):1/0);if(Date.now()>=v)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([t.projectId,t.environment,n,O.versionId,O.evaluationRevision,O.growth.generation]),L=[O.topology,O.conditions,O.evaluation,O.growth.features,O.growth.experiments,O.growth.savedGroups];if(d?.key===k&&!nn(d.body,L))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==k&&(d={key:k,body:L,program:fn(O)}),a={key:k,configuration:O,expiresAt:v,program:d.program},a})();c=S;try{return await S}finally{c===S&&(c=void 0)}}function w(){return c??(a&&!s(a)?Promise.resolve(a):g())}return{session(E){let S=p;return In(E,w,R=>{if(e.assertUsable?.(),S!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&(s(R)||a?.key!==R.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await g()).configuration)},reset(){p++,a=void 0,c=void 0,d=void 0}}}function Pn(e,t){let n=e.snapshot?.generation,u=ee({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),a=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,u.refresh().catch(()=>{}))}),c=u.session;return Object.assign(u,{session(d){let p=c(d),s=p.evaluate;return Object.assign(p,{async evaluate(...g){return e.fresh||await e.refresh(),s(...g)}})},destroy(){a(),u.reset()}})}function Nn(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>tn(e,t)}}var K=class extends o{constructor(n,u){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,u);this.decisionId=n;this.decisionRequestId=u}decisionId;decisionRequestId};async function ne(e,t,n,u){let{decisionId:a,requestId:c}=e,d=e,p=250,s=0;for(;;){if(d.decisionId!==a||d.requestId!==c||d.decision&&!W(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,c);if(Date.now()>=n)throw new K(a,c);if(await new Promise(g=>setTimeout(g,Math.min(Math.max(p,s-Date.now()),n-Date.now()))),Date.now()>=n)throw new K(a,c);p=Math.min(1e3,p*2);try{d=await u(a,n)}catch(g){if(g instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(g.code)){s=Date.now()+(g.retryAfterSeconds??0)*1e3;continue}throw g}}}function ge(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");B(e.apiKey,"Funnel decisions are requested by your backend");let t,n,u=new Map;async function a(s,g){let w=s;w.status!=="pending"&&u.delete(w.decisionId);for(let E=0;E<32&&w.evaluation;E++){let S=w.evaluation;if(S.runId!==w.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let R=u.get(w.decisionId);if(!R&&S.type==="evaluate_segment"){let v=$e.parse(await c({operation:"segment_configuration",funnelId:e.funnelId,versionId:S.versionId},g));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==S.versionId||v.configuration.evaluationRevision!==S.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");R={operation:"commit_decision_segment",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,policyRevision:S.policyRevision,generation:v.configuration.growth.generation,...en(v.configuration,v.document,S)},u.set(w.decisionId,R)}if(!R){if(S.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=Q.parse(await c({operation:"configuration",funnelId:e.funnelId,versionId:S.versionId},g))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");R={operation:"evaluate_decision",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,"evaluation"),nodeId:S.nodeId,visit:S.visit,revision:S.revision,receiptId:S.receiptId,policyRevision:S.policyRevision,generation:n.growth.generation,result:Je(n,S.nodeId,S,Xe)},u.set(w.decisionId,R)}let O=j.parse(await c(R,g));if(O.decisionId!==s.decisionId||O.requestId!==s.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");u.delete(w.decisionId),w=O}return w}async function c(s,g,w=!1){return D({...e,fetch:(S,R)=>{let O=new Headers(R?.headers);return O.set("Accept-Encoding","identity"),w&&O.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(S,{...R,headers:O})},timeoutMs:Math.min(e.timeoutMs??1e4,g?Math.max(1,g-Date.now()):12e4)}).request("funnels",s)}async function d(s,g){let w=j.parse(await c($.parse({operation:"read_decision",decisionId:s}),g));if(w.decisionId!==s)throw new o("INVALID_RESPONSE","Decision identity changed");return a(w,g)}async function p(s,g,w=!1){let E=$.options[0].parse({...s,operation:"decide",funnelId:e.funnelId}),S;try{S=j.parse(await c(E,g,w))}catch(R){throw R instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(R.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",R.status,s.requestId):R}if(S.requestId!==s.requestId||S.decision&&!W(S.decision,E.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(S,g),customer:E.customer}}return{local(){return t??=ee({scope:e.scope,funnelId:e.funnelId,load:()=>c({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let s=Q.parse(await c({operation:"configuration",funnelId:e.funnelId}));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment||s.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return s},features(s={}){return ye({...s,scope:e.scope,load:async()=>Ne.parse(await c({operation:"feature_config",funnelId:e.funnelId}))})},read:s=>d(s),async submit(s){return(await p(s,void 0,!0)).response},async decide(s){let g=Date.now()+3e4,w=await p(s,g);return ne(w.response,w.customer,g,d)},async reportUsed(s){let g=Le.parse(await c($.parse({...s,operation:"report_used"})));if(g.decisionId!==s.decisionId||g.eventId!==s.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return g}}}function kn(e){B(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let u=Qe.parse(n);if(u.orderId!==u.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=u.nativeEvidence,c={requestId:u.requestId,customerToken:u.customerToken,purchaseIntentId:u.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},d=i.restoreNativePurchase.response.parse(await t.request(i.restoreNativePurchase.path,c));if(d.operation.requestId!==u.requestId||d.operation.purchaseIntentId!==u.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let p=Ye.parse({scope:d.scope,requestId:u.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(p.requestId!==u.requestId||p.orderId!==u.orderId||p.receiptId!==u.receiptId||p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return p}}}import{z as xn}from"zod";var q=xn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Dn(e,t){let n=q.parse(e.inputTokens.total),u=q.parse(e.outputTokens.total),a=q.parse(e.inputTokens.cacheRead??0),c=q.parse(e.inputTokens.cacheWrite??0),d=q.parse(e.outputTokens.reasoning??0);if(a+c>n||d>u||e.inputTokens.noCache!==void 0&&q.parse(e.inputTokens.noCache)!==n-a-c||e.outputTokens.text!==void 0&&q.parse(e.outputTokens.text)!==u-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-a-c,cache_read:a,cache_write:c,output:t==="output"?u:u-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(u){await e.persist({context:u,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(u,a){let c={context:u,modelId:e.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(c);let d=e.mapTokens?e.mapTokens(a):Dn(a,e.reasoning),p=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...c,tokens:d,quote:p,phase:"quoted"});let s=await e.pricing.trackTokens(e.client,{...u,quote:p});if(!s.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...c,tokens:d,quote:p,receipt:s,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:u}){let a=await e.context(),c;try{c=await u()}catch(d){throw await t(a),d}return await n(a,c.usage),c},async wrapStream({doStream:u}){let a=await e.context(),c;try{c=await u()}catch(w){throw await t(a),w}let d=!1,p=!1,s=c.stream.getReader();async function g(){d||p||(p=!0,await t(a))}return{...c,stream:new ReadableStream({async pull(w){try{let{value:E,done:S}=await s.read();if(S){if(!d)throw await g(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");w.close();return}if(E.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(a,E.usage)}w.enqueue(E)}catch(E){try{await g()}finally{w.error(E),await s.cancel(E)}}},async cancel(w){try{await g()}finally{await s.cancel(w)}}})}}}}function Ln(e){B(e.apiKey,"Funnel receipts are sent by your backend");let t=D(e);return{async signal(n){let u=de.parse({...n,operation:"signal"}),a=De.parse(await t.request("funnels",u));if(a.runId!==n.runId||a.eventId!==n.eventId||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(n){let u=de.parse({operation:"read_results",runId:n}),a=Me.parse(await t.request("funnels",u));if(a.runId!==n||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return a}}}function Un(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");B(e.apiKey,"Campaign entry requires your backend");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let u=Date.now()+(e.timeoutMs??3e4),a=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),c=D({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,u-Date.now()))}),d=j.parse(await c.request("funnels",a));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return ne(d,a.customer,u,(p,s)=>ge({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,s-Date.now()))}).read(p))},async start(n){let u=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),a=Ke.parse(await t.request("funnels",u));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==e.funnelId||!a.customerId||u.customer.type==="id"&&a.customerId!==u.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}import{z as Bn}from"zod";var F=class extends Error{constructor(n,u=409,a=!1,c="fix_request"){super(n);this.code=n;this.status=u;this.retryable=a;this.recovery=c}code;status;retryable;recovery};function Gn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=Re.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},u=t.capabilities.some(a=>["purchases","subscription_changes","refunds","operation_status"].includes(a));for(let[a,c]of Object.entries(oe))if(c.command&&t.capabilities.includes(a)&&!(a==="catalog"&&t.catalog==="static")&&!e.handlers[c.command])throw new Error(`Missing merchant command handler: ${c.command}`);if(u&&(!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(c){let d=crypto.randomUUID(),p="bridge.ping",s,g=async(w,E,S=!1)=>{let R=JSON.stringify({bridgeVersion:re,requestId:d,command:p,scope:n,[S?"error":"data"]:w});if(new TextEncoder().encode(R).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(R,{status:E,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":d,...s?await se(R,s,"response"):{}}})};try{if(c.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(re)||c.method!=="POST"||new URL(c.url).pathname!==Ee)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(c.headers.get("Content-Type")??""))throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let w=c.body?.getReader();if(!w)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=new TextDecoder("utf-8",{fatal:!0}),S="",R=0;try{for(;;){let _=await w.read();if(_.done)break;if(R+=_.value.byteLength,R>16384)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",413);S+=E.decode(_.value,{stream:!0})}S+=E.decode()}finally{await w.cancel().catch(()=>{}),w.releaseLock()}let O=Oe.safeParse(JSON.parse(S));if(!O.success)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=O.data;if(d=v.requestId,p=v.command,Object.keys(n).some(_=>v.scope[_]!==n[_]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=v.command==="bridge.ping"||v.command==="bridge.describe",L=v.command==="catalog.read";if((k||L||c.headers.has(ie))&&(s=e.authentication.find(_=>_.keyId===c.headers.get(ie)),!s||!await ce(S,c.headers,s,"request")))throw s=void 0,new F("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return g(ae["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return g(t,200);let m=Object.entries(oe).find(([,_])=>_.command===v.command);if(!m||!t.capabilities.includes(m[0]))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let r=e.handlers[v.command];if(!r)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!L&&c.headers.has("Cookie")&&(c.headers.get("Origin")!==new URL(c.url).origin||["cross-site","same-site"].includes(c.headers.get("Sec-Fetch-Site")??"")))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);let y=L?{kind:"service"}:await e.authorize(c,v),h=y.kind,I=["purchase.execute","subscription.change","refund.execute"].includes(v.command),C=I||v.command==="operation.read";if(!(C&&s!==void 0&&h==="service")&&(v.command==="refund.execute"?h!=="administrator":!L&&h!=="user"))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);if(y.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!Bn.uuid().safeParse(y.customerId).success)throw new F("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let b=r,x=ae[v.command].parse(v.data),P={request:c,command:v.command,scope:n,principal:y},T;if(C){let _=Y.parse(x);if(y.kind==="user"&&y.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let N=J.parse(await e.resolveOperationAuthority(_,P));if(N.operationId!==_.operationId||N.customerId!==_.customerId||Object.keys(n).some(H=>N.scope[H]!==n[H]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);P.authority=N;let V=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":N.instruction.type;if(N.instruction.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!I)T=te.parse(await b(x,P));else{if(N.confirmedAt===null)throw new F("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=te.parse(await e.handlers["operation.read"](_,{...P,command:"operation.read"}));if(H.operationId!==_.operationId||H.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!N.initialExecutionAllowed)throw new F("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(N.instruction.expiresAt)<=Date.now())throw new F("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||ve(N.instruction).some(U=>!t.billingEvents.some(gn=>gn===U))||we(N.instruction).some(U=>!t.profiles.includes(U)))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Ce.parse(await b(x,P))}catch(U){throw U instanceof F?U:new F("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Ae[v.command].parse(await b(x,P));if(y.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==y.nativeUserId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&y.customerId&&T.session.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&y.customerId&&T.presentation.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Y.parse(v.data).operationId||T.customerId!==Y.parse(v.data).customerId))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return g(T,I&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(w){let E=w instanceof F?w:w instanceof SyntaxError?new F("MERCHANT_BRIDGE_INVALID_REQUEST",400):new F("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return g({code:E.code,message:E.code,retryable:E.retryable,recovery:E.recovery},E.status,!0)}}}function Vn(e){return async(t,n)=>{let u=()=>e.readSubscriptionOperation(t),a=()=>e.readSubscriptionUpdate(t),c=()=>e.readRefund(t),d=n.command==="purchase.execute"?[u]:n.command==="subscription.change"?[a]:n.command==="refund.execute"?[c]:[u,a,c];for(let p of d)try{let s=await p(),g="authority"in s.operation?s.operation.authority:void 0;if(!g)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let w=J.parse(g);if(w.customerId!==t.customerId||w.operationId!==t.operationId||Object.keys(n.scope).some(E=>w.scope[E]!==n.scope[E]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w}catch(s){if(n.command==="operation.read"&&s instanceof o&&s.code==="NOT_FOUND")continue;throw s}throw new F("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{K as FunnelDecisionTimeoutError,Z as FunnelProcessEntrySuppressedError,o as LongplayError,F as MerchantBridgeHandlerError,En as aiPriceSnapshotSchema,Rn as aiTokenQuoteSchema,Cn as createAiPricing,Mn as createAiUsageMiddleware,hn as createConfigurationSync,An as createConfiguredAiPricing,ye as createFeatureClient,Un as createFunnelCampaignClient,ge as createFunnelDecisionClient,ee as createFunnelLocalEvaluator,Ln as createFunnelOrchestrationClient,Fn as createFunnelProcessAdapter,vn as createFunnelStartClient,Ie as createGuestToken,Sn as createLocalFunnelClient,On as createLongplayServer,Vn as createMerchantBridgeAuthorityResolver,Gn as createMerchantBridgeHandler,kn as createNativeReceiptClient,Nn as createPaywallStartClient,Pn as createSynchronizedFunnelLocalEvaluator,wn as evaluateFunnelNode,_n as renewFunnelRun,se as signMerchantBridgeMessage,ce as verifyMerchantBridgeMessage};
1
+ import{a as wn}from"./chunk-4ZUMMPHV.js";import{a as En,b as Rn,c as Cn,d as An}from"./chunk-P6HCD5OQ.js";import{a as l,b as ye,c as We,d as Xe,e as Ze,f as en,h as W,i as nn,j as B,k as D,m as tn,n as hn,o as vn,p as Sn}from"./chunk-N4HZ55YU.js";import"./chunk-LC2VUKYM.js";import"./chunk-EEZLS2YP.js";import"./chunk-E4LUW6KP.js";import{a as o}from"./chunk-26HU2HXU.js";import"./chunk-LHBBSD77.js";import{$ as Me,A as J,B as Ce,E as ae,F as Ae,Fa as Ue,G as Oe,Ga as le,H as ie,Ha as z,I as se,Ia as Be,J as ce,Ja as Ge,Ka as Ve,La as me,Ma as He,N as ue,Na as qe,O as be,Oa as je,P as Pe,Pa as fe,Qa as Ke,Ra as Q,Sa as ze,T as Ne,Va as Qe,Wa as Ye,X as G,Y as ke,Z as de,_ as De,_a as Je,a as he,aa as $,ab as $e,ba as j,ca as Le,k as we,l as ve,m as te,o as Se,p as re,q as Ee,s as oe,u as Re,ua as i,va as pe,z as Y}from"./chunk-JVQVQHV2.js";import{Aa as xe,B as Fe,E as _e,r as Te}from"./chunk-PFHS7HK3.js";function X(e){return{async getCustomer(t){let n=i.getCustomer;return l(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=i.listCustomers;return l(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=i.updateCustomer;return l(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=i.createGuestCustomer;return l(e,n,t)},async resumeGuestSession(t){let n=i.resumeGuestSession;return l(e,n,t)},async claimGuestCustomer(t){let n=i.claimGuestCustomer;return l(e,n,t)},async revokeCustomerSessions(t){let n=i.revokeSessions;return l(e,n,t)},async createCustomerSession(t){return l(e,i.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return l(e,i.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function f(e,t){try{return e.parse(t)}catch{throw new o("INVALID_RESPONSE","Invalid gateway response")}}function rn(e){return{async checkEntitlement(t){let n=i.checkEntitlement;return l(e,n,t,f)},async readHoldings(t){let n=i.readHoldings;return l(e,n,t,f)},async readSeats(t){let n=i.readSeats;return l(e,n,t,f)},async manageSeat(t){let n=i.manageSeat;return l(e,n,t,f)}}}function on(e){return{async readAiPricing(t){let n=i.readAiPricing;return l(e,n,t,f)},async readUsage(t){let n=i.readUsage;return l(e,n,t,f)},async setUsage(t){let n=i.setUsage;return l(e,n,t,f)},async manageBalanceGrant(t){let n=i.manageBalanceGrant;return l(e,n,t,f)},async readBalanceSource(t){let n=i.readBalanceSource;return l(e,n,t,f)},async adjustBalance(t){let n=i.adjustBalance;return l(e,n,t,f)},async listBalanceGrants(t){let n=i.listBalanceGrants;return l(e,n,t,f)},async manageBillingLimits(t){let n=i.manageBillingLimits;return l(e,n,t,f)},async manageUsageEntity(t){let n=i.manageUsageEntity;return l(e,n,t,f)},async readUsageAnalytics(t){let n=i.readUsageAnalytics;return l(e,n,t,f)},async readCreditAnalytics(t){let n=i.readCreditAnalytics;return l(e,n,t,f)},async submitUsageBatch(t){let n=i.submitUsageBatch;return l(e,n,t,f)},async readUsageBatch(t){let n=i.readUsageBatch;return l(e,n,t,f)},async readLedger(t){let n=i.readLedger;return l(e,n,t,f)},async readCreditStatement(t){let n=i.readCreditStatement;return l(e,n,t,f)},async quoteBalance(t){let n=i.quoteBalance;return l(e,n,t,f)},async trackUsage(t){let n=i.trackUsage;return l(e,n,t,f)},async mutateBalance(t){let n=i.mutateBalance;return l(e,n,t,f)}}}function an(e){return{async listInvoiceTemplates(t={}){let n=i.listInvoiceTemplates;return l(e,n,t,f)},async previewInvoice(t){let n=i.previewInvoice;return l(e,n,t,f)},async createInvoice(t){let n=i.createInvoice;return l(e,n,t,f)},async prepareBillingAdjustment(t){let n=i.prepareBillingAdjustment;return l(e,n,t,f)},async manageInvoice(t){let n=i.manageInvoice;return l(e,n,t,f)},async readInvoiceOperation(t){let n=i.readInvoiceOperation;return l(e,n,t,f)},async listInvoices(t){let n=i.listInvoices;return l(e,n,t,f)},async getInvoice(t){let n=i.getInvoice;return l(e,n,t,f)},async setupPayment(t){let n=i.setupPayment;return l(e,n,t,f)},async readPaymentSetup(t){let n=i.readPaymentSetup;return l(e,n,t,f)},async readBillingInvoice(t){let n=i.readBillingInvoice;return l(e,n,t,f)},async previewRefund(t){let n=i.previewRefund;return l(e,n,t,f)},async refund(t){let n=i.refund;return l(e,n,t,f)},async readRefund(t){let n=i.readRefund;return l(e,n,t,f)}}}function sn(e){return{async previewSubscriptionBatch(t){let n=i.previewSubscriptionBatch;return l(e,n,t,f)},async confirmSubscriptionBatch(t){let n=i.confirmSubscriptionBatch;return l(e,n,t,f)},async readSubscriptionBatch(t){let n=i.readSubscriptionBatch;return l(e,n,t,f)},async abandonSubscriptionBatch(t){let n=i.abandonSubscriptionBatch;return l(e,n,t,f)},async manageSubscriptionTrial(t){let n=i.manageSubscriptionTrial;return l(e,n,t,f)},async readSubscriptionTrial(t){let n=i.readSubscriptionTrial;return l(e,n,t,f)},async listSubscriptions(t){let n=i.listSubscriptions;return l(e,n,t,f)},async listPurchases(t){let n=i.listPurchases;return l(e,n,t,f)},async listSubscriptionConflicts(t){let n=i.listSubscriptionConflicts;return l(e,n,t,f)},async retrySubscriptionConflict(t){let n=i.retrySubscriptionConflict;return l(e,n,t,f)},async previewUpdate(t){let n=i.previewUpdate;return l(e,n,t,f)},async update(t){let n=i.update;return l(e,n,t,f)},async readSubscriptionUpdate(t){let n=i.readSubscriptionUpdate;return l(e,n,t,f)},async restoreNativePurchase(t){let n=i.restoreNativePurchase;return l(e,n,t,f)},async verifySubscriptions(t){let n=i.verifySubscriptions;return l(e,n,t,f)},async previewAttach(t){let n=i.previewAttach;return l(e,n,t,f)},async recordMerchantEvent(t){return l(e,i.recordMerchantEvent,t,{request:"Invalid merchant event",parseResponse:f})},async attach(t){let n=i.attach;return l(e,n,t,f)},async readSubscriptionOperation(t){let n=i.readSubscriptionOperation;return l(e,n,t,f)}}}function cn(e){return{async grantOffer(t){let n=i.grantOffer;return l(e,{...n,request:n.request.refine(u=>!!u.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function un(e){return{...rn(e),...on(e),...an(e),...sn(e),...cn(e)}}function dn(e){return{async getFeatures(t={}){let n=i.getFeatures;return l(e,n,t,f)},async evaluateFeatures(t){let n=i.evaluateFeatures;return l(e,n,t,f)}}}function pn(e){return{async trackEvents(t){let n=i.trackEvents;return l(e,n,t,f)}}}function ln(e){return{async resolveContent(t){let n=i.resolveContent;return l(e,n,t,f)},async resolvePaywall(t){let n=i.resolvePaywall;return l(e,n,t,f)},async resolveOffering(t){let n=i.resolveOffering;return l(e,n,t,f)}}}function On(e){B(e.apiKey,"Secret API keys must stay on your backend");let n=D(e).request;return{async sendMessage(u){let a=i.sendMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},async readMessage(u){let a=i.readMessage;return a.response.parse(await n(a.path,a.request.parse(u)))},...X(n),...un(n),...dn(n),...pn(n),...ln(n)}}function Ie(){if(typeof window<"u")throw new o("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 mn=()=>new o("CONFLICT","Process synchronization is in progress",425),M=()=>new o("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),Tn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Z=class extends o{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 Fn(e){if(B(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new o("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let t=D(e),n=X(t.request),u=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function a(m){let r=await e.resolveUser(m);if(r!==null&&(typeof r?.externalUserId!="string"||!r.externalUserId||r.externalUserId!==r.externalUserId.trim()||r.externalUserId.startsWith("gg_guest_")))throw new o("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return r}async function c(m){let r=await e.resolveContext(m);if(r?.confirmed!==!0||!r.processKey||!r.guestKey)throw new o("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:u+"run:"+r.processKey,guest:u+"guest:"+r.guestKey}}async function d(m,r){for(let y=0;y<8;y++){let h=await e.store.read(m),I=r(h?structuredClone(h.value):null);if(h&&Tn(h.value,I)||await e.store.compareAndSwap(m,h?.revision??null,I))return I}throw mn()}async function p(m){let r=await e.store.read(m);if(!r)throw new o("NOT_FOUND","Open the process before continuing",404);return r.value}async function s(m){let r=await p(m);for(let y of r.revocations??[])await n.revokeCustomerSessions(y),await d(m,h=>{if(!h)throw M();return h.revocations=h.revocations?.filter(I=>I.sessionId!==y.sessionId),h})}async function g(m,r){let y=le.parse(m);return r?t.requestWithCredential("funnel-processes",y,r):t.request("funnel-processes",y)}function w(m,r){if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment||m.run&&(m.run.id!==r.run.id||m.run.source.versionId!==r.run.source.versionId||m.run.source.id!==r.run.source.id||m.run.runExpiresAt!==r.run.runExpiresAt||m.run.identity.startedAs!==r.run.identity.startedAs||m.run.identity.participantId!==r.run.identity.participantId||m.run.identity.binding&&m.run.identity.binding.id!==r.run.identity.binding?.id)||m.runToken&&r.runToken&&m.runToken!==r.runToken)throw new o("INVALID_RESPONSE","Process identity or Run changed")}async function E(m,r,y){return d(m,h=>{if(!h)throw new o("NOT_FOUND","Process handle is missing",404);return w(h,r),(!h.run||r.run.revision>=h.run.revision)&&(h.run=r.run),h.runToken??=r.runToken,y!==void 0&&(h.target=y),h})}async function S(m,r){if(r.detached)throw new o("UNAUTHENTICATED","The process is detached",401);let y=r.run?.identity.binding?.customerId??r.run?.identity.participantId;if(!y)throw new o("INVALID_RESPONSE","Process participant is missing");if(r.session?.customerId===y&&Date.parse(r.session.expiresAt)>Date.now()+3e4)return r.session;let h={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},I=await d(m,A=>{if(!A||A.detached||A.run?.id!==r.run?.id)throw M();if(A.sessionLease&&A.sessionLease.until>Date.now())throw mn();return A.sessionLease=h,A}),C;try{if(I.session?.customerId===y&&Date.parse(I.session.refreshExpiresAt)>Date.now())try{if(C=Se.parse(await t.requestWithCredential("customer-sessions/refresh",{},I.session.refreshToken)),C.sessionId!==I.session.sessionId)throw new o("INVALID_RESPONSE","Refresh changed the logical session")}catch(b){if(!(b instanceof o)||b.status!==401)throw b}if(C??=I.run?.identity.binding?await n.createCustomerSession(y):await n.resumeGuestSession({guestToken:I.guest.token}),C.customerId!==y)throw new o("INVALID_RESPONSE","Session Customer changed");let A=C;return await d(m,b=>{if(!b||b.detached||b.sessionLease?.id!==h.id||b.run?.identity.binding?.id!==r.run?.identity.binding?.id)throw new o("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return b.session=A,delete b.sessionLease,b}),C}catch(A){throw C&&C.sessionId!==I.session?.sessionId&&await n.revokeCustomerSessions({customerId:C.customerId,sessionId:C.sessionId}).catch(()=>{}),await d(m,b=>{if(!b)throw M();return b.sessionLease?.id===h.id&&delete b.sessionLease,b}).catch(()=>{}),A}}let R;async function O(){if(R??=He.parse(await g({contract:G,operation:"describe"})),R.scope.projectId!==e.scope.projectId||R.scope.environment!==e.scope.environment)throw M();return R}async function v(m,r,y=!1){let h=await a(m),I=await p(r);if(I.issuingKeyId!==(await O()).keyId)throw new o("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!I.runToken||!I.run)throw new o("CONFLICT","Recover the original start first",425);if(I.detached){if(!y)throw new o("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(I.run.identity.binding&&(!h||I.target&&I.target!==h.externalUserId))throw M();await s(r),I=await d(r,C=>{if(!C||C.run?.id!==I.run?.id)throw M();return delete C.detached,C})}if(!I.runToken||!I.run)throw new o("INVALID_RESPONSE","Process identity is missing");if(I.run.identity.binding){if(h&&!I.target){let C=me.parse(await g({contract:G,operation:"binding_status",runToken:I.runToken,requestId:I.bindingIntent?.requestId??I.start.requestId,externalUserId:h.externalUserId}));if(C.state!=="bound"||C.binding.id!==I.run.identity.binding.id)throw M();I=await d(r,A=>{if(!A)throw M();return A.target=h.externalUserId,A})}if(!h||I.target!==h.externalUserId)throw M()}else if(h){if(!I.guest)throw M();I=await d(r,A=>{if(!A||A.bindingIntent&&A.bindingIntent.externalUserId!==h.externalUserId)throw M();return A.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:h.externalUserId},A});let C=I.bindingIntent;try{let A=Ve.parse(await g({contract:G,operation:"bind_customer",...C,runToken:I.runToken,guestToken:I.guest.token,claimRequestId:I.guest.claimRequestId,expectedBindingId:null}));I=await E(r,A,h.externalUserId)}catch(A){let b=me.parse(await g({contract:G,operation:"binding_status",...C,runToken:I.runToken,guestToken:I.guest.token}));if(b.state!=="bound")throw A;I=await d(r,x=>{if(!x?.run||x.run.id!==b.binding.runId)throw M();return x.run.identity.binding={id:b.binding.id,customerId:b.binding.customerId,acceptedAt:b.binding.acceptedAt},x.target=h.externalUserId,x})}}return{state:I,session:await S(r,I)}}async function k(m,r,y,h){try{return await h(y)}catch(I){if(!(I instanceof o)||I.status!==401)throw I;return await d(r,C=>{if(!C||C.detached)throw I;return C.session?.accessToken===y.session.accessToken&&(C.session.expiresAt=new Date(0).toISOString()),C}),h(await v(m,r))}}async function L(m,r,y=!1){let h=await c(m),I=await v(m,h.process,y),C=z.parse(await k(m,h.process,I,A=>g({...r,customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C}return{async open(m,r){r=Ge.parse(r);let y=await c(m),h=await O(),I=y.guest+":"+h.keyId,C=await e.store.read(y.process);if(!C){let P=await a(m),T,_,N;if(P)T={type:"customer",customer:{type:"externalUserId",value:P.externalUserId}};else{let V=await e.store.read(I);if(V)try{N=await n.resumeGuestSession({guestToken:V.value.token}),_=V.value}catch(U){if(!(U instanceof o)||U.status!==401)throw U}let H={token:Ie(),claimRequestId:crypto.randomUUID()};_=await d(I,U=>_??(U&&U.token!==V?.value.token?U:H)),T={type:"guest",guestToken:_.token}}await d(y.process,V=>V??{issuingKeyId:h.keyId,start:le.parse({...r,contract:G,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...P?{target:P.externalUserId}:{},...N?{session:N}:{}}),C=await e.store.read(y.process)}let A=C.value;if(A.issuingKeyId!==h.keyId)throw new o("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(A.start.funnelId!==r.funnelId||A.start.operation!==r.operation)throw new o("CONFLICT","This handle already owns another process",409);if(!A.runToken){if(A.start.source.type==="customer"){let N=await a(m);if(!N||N.externalUserId!==A.target)throw M()}let P=await g(A.start),T=Be.safeParse(P);if(T.success)throw new Z(T.data);let _=z.parse(P);if(!_.runToken)throw new o("INVALID_RESPONSE","Process credential is missing");A=await E(y.process,_)}let b=await v(m,y.process,!0),x=z.parse(await k(m,y.process,b,P=>g({contract:G,operation:"get",customerToken:P.session.accessToken},P.state.runToken)));return await E(y.process,x),{...x,runToken:A.runToken}},async syncIdentity(m){return L(m,{contract:G,operation:"get",customerToken:""},!0)},async get(m,r={}){return L(m,{...r,contract:G,operation:"get",customerToken:""})},async review(m,r){return L(m,{contract:G,operation:"review",customerToken:"",...r?{receiptId:r}:{}})},async command(m,r,y){let h=await c(m),I=await v(m,h.process),C=z.parse(await k(m,h.process,I,A=>g({contract:G,operation:"command",command:r,identity:{bindingId:y},customerToken:A.session.accessToken},A.state.runToken)));return await E(h.process,C),C},async pageExperiments(m,r,y=[]){let h=await c(m),I=await v(m,h.process);return Ue.parse(await k(m,h.process,I,C=>g({contract:G,operation:"page_experiments",release:r,usedReceiptIds:y,customerToken:C.session.accessToken},C.state.runToken)))},async detach(m){let r=await c(m);await d(r.process,y=>{if(!y)throw M();return y.session&&!y.revocations?.some(h=>h.sessionId===y.session.sessionId)&&(y.revocations??=[]).push({customerId:y.session.customerId,sessionId:y.session.sessionId}),y.detached=!0,delete y.session,delete y.sessionLease,y}),await s(r.process)},destroy(){t.dispose()}}}async function _n(e,t){B(e.apiKey,"Renewal requires your backend");let n=D(e),u=je.parse(We(e,await n.request("funnels",qe.parse({...t,operation:"renew_run"}))));if(u.run.id!==t.runId)throw new o("INVALID_RESPONSE","Run renewal identity changed");return u}function fn(e){let t=Ze(e),n=p=>{throw new o("INVALID_RESPONSE",p)};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 u=new Set(["entry","condition","feature","split","end","output"]);for(let p of t.nodes.values()){if(!u.has(p.type))throw new o("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(p.type==="entry"&&p.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(p.type)&&!p.outputs.next&&n("Local next exit is unavailable"),p.type==="feature"){let s=p.resources.featureKey;(!s||!Object.hasOwn(e.evaluation.variables,p.writes.value)||!Object.hasOwn(t.features,s))&&n("Local Feature definition or declaration is unavailable")}if(p.type==="condition"){let s=e.conditions[p.id];(!s||!p.outputs.default||s.some((g,w)=>g.port!==`case:${w}`||!p.outputs[g.port]))&&n("Local Condition exits are unavailable")}if(p.type==="split"&&(!p.resources.experimentId||!Object.hasOwn(e.growth.experiments,p.resources.experimentId)||!p.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),p.type==="end"||p.type==="output"){let s=e.evaluation.terminals[p.id];if(!s)throw new o("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(p.outputs).length&&n("A terminal cannot have outgoing edges"),s.output?.type==="feature"&&!Object.hasOwn(t.features,s.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let s of Object.values(p.outputs))t.nodes.has(s)||n("Local target is unavailable")}let a=new Set,c=new Set;function d(p){if(c.has(p)&&n("Local graph contains a cycle"),!a.has(p)){c.add(p);for(let s of Object.values(t.nodes.get(p).outputs))d(s);c.delete(p),a.add(p)}}return d(e.topology.entry),a.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(p){let s={},g=p.context;g.features=t.features,g.savedGroups=t.savedGroups;let w=()=>{g.attributes=ke({declarations:e.evaluation.variables,attributes:p.attributes,parameters:p.parameters,answers:{},results:s,savedGroups:t.savedGroups})};w();let E=e.topology.entry,S=0;for(;;){let R=t.nodes.get(E);if(R.type==="end"||R.type==="output"){let O=e.evaluation.terminals[E],v=O.output,k=v?.type==="feature"?t.feature(v.featureKey,g):v?.type==="variable"?Pe({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:e.evaluation.variables,answers:{},results:s,parameters:p.parameters,attributes:p.attributes,savedGroups:t.savedGroups}):v?.value??null;return ue(e.evaluation.outputSchema,k)||n("Local output does not match its declaration"),{outcome:O.outcome,value:k}}if(S++>=e.evaluation.maxTransitions)throw new o("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(R.type==="entry")E=R.outputs.next;else{let O=t.evaluate(E,g);if(R.type==="feature"){let v=R.writes.value,k=O.value??null;ue(e.evaluation.variables[v],k)||n("Local Feature value does not match its declaration"),be(e.evaluation.variables,{writes:R.writes},{[v]:k}),s[v]=k,w()}E=O.target}}}}}import{z as yn}from"zod";function In(e,t,n){let u=Fe.parse(e.attributes);if(["parameters","answers","results"].some(m=>Object.hasOwn(u,m)))throw new o("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let a=xe.parse(e.parameters??{}),c=yn.record(yn.string(),_e).parse(e.stickyBucketAssignmentDocs??{});for(let[m,r]of Object.entries(c))if(m!==`${r.attributeName}||${r.attributeValue}`||!Object.hasOwn(u,r.attributeName)||Te(u[r.attributeName])!==r.attributeValue)throw new o("INVALID_REQUEST","Sticky document identity does not match this session");let d=e.saveStickyBucketAssignmentDoc,p=e.onFeatureUsage,s=e.onExperimentViewed,g=e.onError,w=new Map,E=new Set,S={},R=Promise.resolve();function O(m){let r=R.then(()=>(n(),m()));return R=r.catch(()=>{}),r}function v(m){try{g?.(m)}catch{}}function k(m){try{let r=m();r&&typeof r.catch=="function"&&r.catch(v)}catch(r){v(r)}}async function L(){for(let[m,r]of w){if(n(),d)try{await d(structuredClone(r))}catch{throw new o("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),w.delete(m)}}return{evaluate(m={}){let r=m.track===!0;return O(async()=>{let y=await t();n(y);let h=new Set(E),I={...S},C=new Map,A=[],b={stickyBucketAssignmentDocs:structuredClone(c),saveStickyBucketAssignmentDoc(T){C.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...r?{trackedExperiments:h,trackedFeatureUsage:I,onExperimentViewed(T,_){let N=structuredClone(T),V=structuredClone(_);s&&A.push(()=>s(structuredClone(N),structuredClone(V)))},onFeatureUsage(T,_){let N=structuredClone(_);p&&A.push(()=>p(T,structuredClone(N)))}}:{}},x=y.program.evaluate({attributes:u,parameters:a,context:b});n(y);for(let[T,_]of C)c[T]=_,w.set(T,_);await L(),n(y),r&&(E=h,S=I);for(let T of A)k(T);let P=y.configuration;return structuredClone({evaluationMode:"local",scope:P.scope,funnelId:P.funnelId,versionId:P.versionId,evaluationRevision:P.evaluationRevision,generation:P.growth.generation,...x})})},flush:()=>O(L),get stickyBucketAssignmentDocs(){return n(),structuredClone(c)}}}var bn=6e4;function ee(e){if(typeof window<"u")throw new o("SERVER_ONLY","Local Funnel sessions run on your backend");let t=he.parse(e.scope),n=e.funnelId,u=e.load,a,c,d,p=0,s=E=>Date.now()>=E.expiresAt;async function g(){if(c)return c;let E=p;a=void 0;let S=(async()=>{let R=await u();if(E!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&typeof R=="object"&&"evaluationMode"in R&&R.evaluationMode==="remote")throw f(Q,R),new o("EVALUATION_MODE","This Funnel requires remote decide");let O=f(ze,R);if(E!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(O.scope.projectId!==t.projectId||O.scope.environment!==t.environment||O.funnelId!==n)throw new o("SCOPE_MISMATCH","Local configuration scope changed");if(O.growth.scope.projectId!==t.projectId||O.growth.scope.environment!==t.environment||O.growth.expiresAt!==O.expiresAt)throw new o("INVALID_RESPONSE","GB configuration scope or expiry changed");let v=Math.min(Date.now()+bn,O.expiresAt?Date.parse(O.expiresAt):1/0);if(Date.now()>=v)throw new o("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([t.projectId,t.environment,n,O.versionId,O.evaluationRevision,O.growth.generation]),L=[O.topology,O.conditions,O.evaluation,O.growth.features,O.growth.experiments,O.growth.savedGroups];if(d?.key===k&&!nn(d.body,L))throw new o("INVALID_RESPONSE","Immutable local configuration identity changed");return d?.key!==k&&(d={key:k,body:L,program:fn(O)}),a={key:k,configuration:O,expiresAt:v,program:d.program},a})();c=S;try{return await S}finally{c===S&&(c=void 0)}}function w(){return c??(a&&!s(a)?Promise.resolve(a):g())}return{session(E){let S=p;return In(E,w,R=>{if(e.assertUsable?.(),S!==p)throw new o("IDENTITY_CHANGED","Local evaluator was reset");if(R&&(s(R)||a?.key!==R.key))throw new o("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await g()).configuration)},reset(){p++,a=void 0,c=void 0,d=void 0}}}function Pn(e,t){let n=e.snapshot?.generation,u=ee({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),a=e.subscribe(()=>{let d=e.snapshot?.generation;e.fresh&&d!==n&&(n=d,u.refresh().catch(()=>{}))}),c=u.session;return Object.assign(u,{session(d){let p=c(d),s=p.evaluate;return Object.assign(p,{async evaluate(...g){return e.fresh||await e.refresh(),s(...g)}})},destroy(){a(),u.reset()}})}function Nn(e){if(typeof window<"u")throw new o("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>tn(e,t)}}var K=class extends o{constructor(n,u){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,u);this.decisionId=n;this.decisionRequestId=u}decisionId;decisionRequestId};async function ne(e,t,n,u){let{decisionId:a,requestId:c}=e,d=e,p=250,s=0;for(;;){if(d.decisionId!==a||d.requestId!==c||d.decision&&!W(d.decision,t))throw new o("INVALID_RESPONSE","Decision request or customer changed");if(d.decision)return d.decision;if(d.status==="failed")throw new o("DECISION_FAILED","Decision execution failed",503,c);if(Date.now()>=n)throw new K(a,c);if(await new Promise(g=>setTimeout(g,Math.min(Math.max(p,s-Date.now()),n-Date.now()))),Date.now()>=n)throw new K(a,c);p=Math.min(1e3,p*2);try{d=await u(a,n)}catch(g){if(g instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(g.code)){s=Date.now()+(g.retryAfterSeconds??0)*1e3;continue}throw g}}}function ge(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");B(e.apiKey,"Funnel decisions are requested by your backend");let t,n,u=new Map;async function a(s,g){let w=s;w.status!=="pending"&&u.delete(w.decisionId);for(let E=0;E<32&&w.evaluation;E++){let S=w.evaluation;if(S.runId!==w.decisionId)throw new o("INVALID_RESPONSE","Local evaluation Run changed");let R=u.get(w.decisionId);if(!R&&S.type==="evaluate_segment"){let v=$e.parse(await c({operation:"segment_configuration",funnelId:e.funnelId,versionId:S.versionId},g));if(v.configuration.scope.projectId!==e.scope.projectId||v.configuration.scope.environment!==e.scope.environment||v.configuration.funnelId!==e.funnelId||v.configuration.versionId!==S.versionId||v.configuration.evaluationRevision!==S.policyRevision)throw new o("SCOPE_MISMATCH","Original decision segment configuration changed");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding decisions first");R={operation:"commit_decision_segment",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,`segment:${S.revision}`),nodeId:S.nodeId,visit:S.visit,revision:S.revision,policyRevision:S.policyRevision,generation:v.configuration.growth.generation,...en(v.configuration,v.document,S)},u.set(w.decisionId,R)}if(!R){if(S.type!=="evaluate")throw new o("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=Q.parse(await c({operation:"configuration",funnelId:e.funnelId,versionId:S.versionId},g))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==S.versionId||n.evaluationRevision!==S.policyRevision)throw new o("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(u.size>=128)throw new o("COMMAND_PENDING","Reconcile outstanding Local decisions first");R={operation:"evaluate_decision",decisionId:w.decisionId,requestId:pe(w.decisionId,S.visit,"evaluation"),nodeId:S.nodeId,visit:S.visit,revision:S.revision,receiptId:S.receiptId,policyRevision:S.policyRevision,generation:n.growth.generation,result:Je(n,S.nodeId,S,Xe)},u.set(w.decisionId,R)}let O=j.parse(await c(R,g));if(O.decisionId!==s.decisionId||O.requestId!==s.requestId)throw new o("INVALID_RESPONSE","Decision identity changed during local evaluation");u.delete(w.decisionId),w=O}return w}async function c(s,g,w=!1){return D({...e,fetch:(S,R)=>{let O=new Headers(R?.headers);return O.set("Accept-Encoding","identity"),w&&O.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(S,{...R,headers:O})},timeoutMs:Math.min(e.timeoutMs??1e4,g?Math.max(1,g-Date.now()):12e4)}).request("funnels",s)}async function d(s,g){let w=j.parse(await c($.parse({operation:"read_decision",decisionId:s}),g));if(w.decisionId!==s)throw new o("INVALID_RESPONSE","Decision identity changed");return a(w,g)}async function p(s,g,w=!1){let E=$.options[0].parse({...s,operation:"decide",funnelId:e.funnelId}),S;try{S=j.parse(await c(E,g,w))}catch(R){throw R instanceof o&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(R.code)?new o("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",R.status,s.requestId):R}if(S.requestId!==s.requestId||S.decision&&!W(S.decision,E.customer))throw new o("INVALID_RESPONSE","Decision request or customer changed");return{response:await a(S,g),customer:E.customer}}return{local(){return t??=ee({scope:e.scope,funnelId:e.funnelId,load:()=>c({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let s=Q.parse(await c({operation:"configuration",funnelId:e.funnelId}));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment||s.funnelId!==e.funnelId)throw new o("SCOPE_MISMATCH","Configuration scope changed");return s},features(s={}){return ye({...s,scope:e.scope,load:async()=>Ne.parse(await c({operation:"feature_config",funnelId:e.funnelId}))})},read:s=>d(s),async submit(s){return(await p(s,void 0,!0)).response},async decide(s){let g=Date.now()+3e4,w=await p(s,g);return ne(w.response,w.customer,g,d)},async reportUsed(s){let g=Le.parse(await c($.parse({...s,operation:"report_used"})));if(g.decisionId!==s.decisionId||g.eventId!==s.eventId)throw new o("INVALID_RESPONSE","Usage receipt identity changed");return g}}}function kn(e){B(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let u=Qe.parse(n);if(u.orderId!==u.receiptId)throw new o("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let a=u.nativeEvidence,c={requestId:u.requestId,customerToken:u.customerToken,purchaseIntentId:u.orderId,...a===null?{intent:"read"}:a.provider==="apple"?{provider:"apple",signedTransaction:a.signedTransaction}:{provider:"google",purchaseToken:a.purchaseToken}},d=i.restoreNativePurchase.response.parse(await t.request(i.restoreNativePurchase.path,c));if(d.operation.requestId!==u.requestId||d.operation.purchaseIntentId!==u.orderId)throw new o("INVALID_RESPONSE","Native receipt request identity changed");let p=Ye.parse({scope:d.scope,requestId:u.requestId,orderId:d.operation.orderId,receiptId:d.operation.orderId,orderStatus:d.operation.status,refunded:d.operation.refunded,...d.operation.completion===null?{}:{nativeCompletion:{orderId:d.operation.orderId,receiptId:d.operation.orderId,...d.operation.completion}}});if(p.requestId!==u.requestId||p.orderId!==u.orderId||p.receiptId!==u.receiptId||p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Current order receipt scope changed");return p}}}import{z as xn}from"zod";var q=xn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Dn(e,t){let n=q.parse(e.inputTokens.total),u=q.parse(e.outputTokens.total),a=q.parse(e.inputTokens.cacheRead??0),c=q.parse(e.inputTokens.cacheWrite??0),d=q.parse(e.outputTokens.reasoning??0);if(a+c>n||d>u||e.inputTokens.noCache!==void 0&&q.parse(e.inputTokens.noCache)!==n-a-c||e.outputTokens.text!==void 0&&q.parse(e.outputTokens.text)!==u-d)throw new o("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-a-c,cache_read:a,cache_write:c,output:t==="output"?u:u-d,reasoning:t==="separate"?d:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new o("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new o("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(u){await e.persist({context:u,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(u,a){let c={context:u,modelId:e.modelId,usage:a,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(c);let d=e.mapTokens?e.mapTokens(a):Dn(a,e.reasoning),p=await e.pricing.quoteTokens({modelId:e.modelId,tokens:d});await e.persist({...c,tokens:d,quote:p,phase:"quoted"});let s=await e.pricing.trackTokens(e.client,{...u,quote:p});if(!s.receipt.accepted)throw new o("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...c,tokens:d,quote:p,receipt:s,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:u}){let a=await e.context(),c;try{c=await u()}catch(d){throw await t(a),d}return await n(a,c.usage),c},async wrapStream({doStream:u}){let a=await e.context(),c;try{c=await u()}catch(w){throw await t(a),w}let d=!1,p=!1,s=c.stream.getReader();async function g(){d||p||(p=!0,await t(a))}return{...c,stream:new ReadableStream({async pull(w){try{let{value:E,done:S}=await s.read();if(S){if(!d)throw await g(),new o("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");w.close();return}if(E.type==="finish"){if(d)throw new o("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");d=!0,await n(a,E.usage)}w.enqueue(E)}catch(E){try{await g()}finally{w.error(E),await s.cancel(E)}}},async cancel(w){try{await g()}finally{await s.cancel(w)}}})}}}}function Ln(e){B(e.apiKey,"Funnel receipts are sent by your backend");let t=D(e);return{async signal(n){let u=de.parse({...n,operation:"signal"}),a=De.parse(await t.request("funnels",u));if(a.runId!==n.runId||a.eventId!==n.eventId||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Receipt identity changed");return a},async readResults(n){let u=de.parse({operation:"read_results",runId:n}),a=Me.parse(await t.request("funnels",u));if(a.runId!==n||a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("INVALID_RESPONSE","Result identity changed");return a}}}function Un(e){if("remoteEval"in e)throw new o("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");B(e.apiKey,"Campaign entry requires your backend");let t=D({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let u=Date.now()+(e.timeoutMs??3e4),a=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),c=D({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,u-Date.now()))}),d=j.parse(await c.request("funnels",a));if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");return ne(d,a.customer,u,(p,s)=>ge({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,s-Date.now()))}).read(p))},async start(n){let u=fe.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),a=Ke.parse(await t.request("funnels",u));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment)throw new o("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in a)&&(a.run.source.id!==e.funnelId||!a.customerId||u.customer.type==="id"&&a.customerId!==u.customer.value))throw new o("INVALID_RESPONSE","Campaign Funnel or Customer changed");return a}}}import{z as Bn}from"zod";var F=class extends Error{constructor(n,u=409,a=!1,c="fix_request"){super(n);this.code=n;this.status=u;this.retryable=a;this.recovery=c}code;status;retryable;recovery};function Gn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=Re.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},u=t.capabilities.some(a=>["purchases","subscription_changes","refunds","operation_status"].includes(a));for(let[a,c]of Object.entries(oe))if(c.command&&t.capabilities.includes(a)&&!(a==="catalog"&&t.catalog==="static")&&!e.handlers[c.command])throw new Error(`Missing merchant command handler: ${c.command}`);if(u&&(!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(c){let d=crypto.randomUUID(),p="bridge.ping",s,g=async(w,E,S=!1)=>{let R=JSON.stringify({bridgeVersion:re,requestId:d,command:p,scope:n,[S?"error":"data"]:w});if(new TextEncoder().encode(R).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(R,{status:E,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":d,...s?await se(R,s,"response"):{}}})};try{if(c.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(re)||c.method!=="POST"||new URL(c.url).pathname!==Ee)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(c.headers.get("Content-Type")??""))throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let w=c.body?.getReader();if(!w)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=new TextDecoder("utf-8",{fatal:!0}),S="",R=0;try{for(;;){let _=await w.read();if(_.done)break;if(R+=_.value.byteLength,R>16384)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",413);S+=E.decode(_.value,{stream:!0})}S+=E.decode()}finally{await w.cancel().catch(()=>{}),w.releaseLock()}let O=Oe.safeParse(JSON.parse(S));if(!O.success)throw new F("MERCHANT_BRIDGE_INVALID_REQUEST",400);let v=O.data;if(d=v.requestId,p=v.command,Object.keys(n).some(_=>v.scope[_]!==n[_]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=v.command==="bridge.ping"||v.command==="bridge.describe",L=v.command==="catalog.read";if((k||L||c.headers.has(ie))&&(s=e.authentication.find(_=>_.keyId===c.headers.get(ie)),!s||!await ce(S,c.headers,s,"request")))throw s=void 0,new F("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(v.command==="bridge.ping")return g(ae["bridge.ping"].parse(v.data),200);if(v.command==="bridge.describe")return g(t,200);let m=Object.entries(oe).find(([,_])=>_.command===v.command);if(!m||!t.capabilities.includes(m[0]))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let r=e.handlers[v.command];if(!r)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!L&&c.headers.has("Cookie")&&(c.headers.get("Origin")!==new URL(c.url).origin||["cross-site","same-site"].includes(c.headers.get("Sec-Fetch-Site")??"")))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);let y=L?{kind:"service"}:await e.authorize(c,v),h=y.kind,I=["purchase.execute","subscription.change","refund.execute"].includes(v.command),C=I||v.command==="operation.read";if(!(C&&s!==void 0&&h==="service")&&(v.command==="refund.execute"?h!=="administrator":!L&&h!=="user"))throw new F("MERCHANT_BRIDGE_FORBIDDEN",403);if(y.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(v.command)&&!Bn.uuid().safeParse(y.customerId).success)throw new F("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let b=r,x=ae[v.command].parse(v.data),P={request:c,command:v.command,scope:n,principal:y},T;if(C){let _=Y.parse(x);if(y.kind==="user"&&y.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let N=J.parse(await e.resolveOperationAuthority(_,P));if(N.operationId!==_.operationId||N.customerId!==_.customerId||Object.keys(n).some(H=>N.scope[H]!==n[H]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);P.authority=N;let V=v.command==="purchase.execute"?"purchase":v.command==="subscription.change"?"subscription_change":v.command==="refund.execute"?"refund":N.instruction.type;if(N.instruction.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!I)T=te.parse(await b(x,P));else{if(N.confirmedAt===null)throw new F("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let H=te.parse(await e.handlers["operation.read"](_,{...P,command:"operation.read"}));if(H.operationId!==_.operationId||H.customerId!==_.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(H.lookup==="found")T=H.execution;else{if(!N.initialExecutionAllowed)throw new F("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(N.instruction.expiresAt)<=Date.now())throw new F("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||ve(N.instruction).some(U=>!t.billingEvents.some(gn=>gn===U))||we(N.instruction).some(U=>!t.profiles.includes(U)))throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=Ce.parse(await b(x,P))}catch(U){throw U instanceof F?U:new F("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==V)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=Ae[v.command].parse(await b(x,P));if(y.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==y.nativeUserId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&y.customerId&&T.session.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&y.customerId&&T.presentation.customerId!==y.customerId)throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==Y.parse(v.data).operationId||T.customerId!==Y.parse(v.data).customerId))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return g(T,I&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(w){let E=w instanceof F?w:w instanceof SyntaxError?new F("MERCHANT_BRIDGE_INVALID_REQUEST",400):new F("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return g({code:E.code,message:E.code,retryable:E.retryable,recovery:E.recovery},E.status,!0)}}}function Vn(e){return async(t,n)=>{let u=()=>e.readSubscriptionOperation(t),a=()=>e.readSubscriptionUpdate(t),c=()=>e.readRefund(t),d=n.command==="purchase.execute"?[u]:n.command==="subscription.change"?[a]:n.command==="refund.execute"?[c]:[u,a,c];for(let p of d)try{let s=await p(),g="authority"in s.operation?s.operation.authority:void 0;if(!g)throw new F("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let w=J.parse(g);if(w.customerId!==t.customerId||w.operationId!==t.operationId||Object.keys(n.scope).some(E=>w.scope[E]!==n.scope[E]))throw new F("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return w}catch(s){if(n.command==="operation.read"&&s instanceof o&&s.code==="NOT_FOUND")continue;throw s}throw new F("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{K as FunnelDecisionTimeoutError,Z as FunnelProcessEntrySuppressedError,o as LongplayError,F as MerchantBridgeHandlerError,En as aiPriceSnapshotSchema,Rn as aiTokenQuoteSchema,Cn as createAiPricing,Mn as createAiUsageMiddleware,hn as createConfigurationSync,An as createConfiguredAiPricing,ye as createFeatureClient,Un as createFunnelCampaignClient,ge as createFunnelDecisionClient,ee as createFunnelLocalEvaluator,Ln as createFunnelOrchestrationClient,Fn as createFunnelProcessAdapter,vn as createFunnelStartClient,Ie as createGuestToken,Sn as createLocalFunnelClient,On as createLongplayServer,Vn as createMerchantBridgeAuthorityResolver,Gn as createMerchantBridgeHandler,kn as createNativeReceiptClient,Nn as createPaywallStartClient,Pn as createSynchronizedFunnelLocalEvaluator,wn as evaluateFunnelNode,_n as renewFunnelRun,se as signMerchantBridgeMessage,ce 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-MILFPPP4.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-3DGJ2X3U.js";import"./chunk-DSPLGTQI.js";import"./chunk-FVX3AVDI.js";import"./chunk-7LIABANC.js";import{v as te,x as ie,z as M}from"./chunk-PFHS7HK3.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};
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-OMHZBCS3.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-6HWNW6FJ.js";import"./chunk-DSPLGTQI.js";import"./chunk-LHBBSD77.js";import"./chunk-JVQVQHV2.js";import{v as te,x as ie,z as M}from"./chunk-PFHS7HK3.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.17",
3
+ "version": "0.10.18",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- import{d as t}from"./chunk-FBLAWSUN.js";import{Za as n}from"./chunk-7LIABANC.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1 +0,0 @@
1
- import{b as dn,c as fn,d as mn,e as pn}from"./chunk-LC2VUKYM.js";import{a as gn}from"./chunk-EEZLS2YP.js";import{a as te,b as Y}from"./chunk-T5YZS64H.js";import{a as m}from"./chunk-26HU2HXU.js";import{a as ln,b as cn,c as Ce}from"./chunk-FVX3AVDI.js";import{$a as un,Ea as Te,Fa as tn,R as Ge,T as Re,Ta as rn,U as Be,Ua as on,V as Je,W as je,Xa as an,Ya as sn,a as qe,cb as le,da as Q,ea as ze,fa as J,ga as Ke,ha as Oe,ia as M,ka as Qe,la as Ye,ma as $e,n as ue,na as We,oa as Ze,ua as ne,va as Xe,ya as en,za as nn}from"./chunk-7LIABANC.js";import{B as ve,Fa as He,v as Ue,y as ke}from"./chunk-PFHS7HK3.js";function qn(e){let n=null,t=null,s=0,d=0,w=new Set,f=null,o=null,g=new Set,i=()=>{for(let a of g)try{a()}catch{}},l={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(a,r)=>{!w.has(a)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(a,structuredClone(r),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(a,r)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(a),structuredClone(r),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?a=>e.saveStickyBucketAssignmentDoc(structuredClone(a)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},u=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function c(a,r=new Set){return w.has(a)?!f||!f.features[a]||["unknownFeature","cyclicPrerequisite"].includes(f.features[a].source):r.has(a)?!1:(r.add(a),(n?.features[a]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>c(v.id,r))))}let h=a=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,l.features=n.features),w.has(a)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?u():structuredClone(f.features[a]??u()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!f||c(a)?u():structuredClone(ke(a,l))};async function F(){if(!n||!w.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(w.size)throw new Error("Remote Feature evaluation requires a server loader");return}let a=d;if(o?.revision===a)return o.loading;let r=s,p=n,v=[...w],C=(async()=>{let S=je.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(r!==s||a!==d||p!==n)){if(e.assertUsable?.(p.generation),S.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(R=>!Object.hasOwn(S.features,R))||Object.keys(S.features).some(R=>!w.has(R)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!S.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ve.parse({...l.attributes,...S.merchandiseContext})}f=structuredClone(S),l.features={...p.features,...Object.fromEntries(Object.entries(f.features).map(([R,O])=>[R,{defaultValue:O.value}]))},i()}})();o={revision:a,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function N(){F().catch(a=>{try{e.onError?.(a)}catch{}})}async function L(){if(t)return t;let a=s,r=(async()=>{let p=await e.load(),v="remoteFeatures"in p?Be.parse(p):null,C=v??Re.parse(p);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(a!==s)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:R,expiresAt:O,...D}=n,{evaluatedAt:x,expiresAt:k,...G}=C;if(M(D)!==M(G))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,i(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&N(),structuredClone(n)}let S=new Set(v?.remoteFeatures??[]);if([...S].some(R=>Object.hasOwn(C.features,R)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),w=S,f=null,o=null,d++,l.features=n.features,l.savedGroups=Ue(n.savedGroups),l.trackedFeatureUsage={},i(),N(),structuredClone(n)})();t=r;try{return await r}finally{t===r&&(t=null)}}return{init:L,refresh:L,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(a){return g.add(a),()=>{g.delete(a)}},setAttributes(a){let r=ve.parse(a);(l.attributes?.merchandise||l.attributes?.merchandiseId||a.merchandise||a.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=r,d++,f=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},i(),N()},evalFeature:h,isOn(a){return h(a).on},isOff(a){return h(a).off},getFeatureValue(a,r){let p=h(a).value;return structuredClone(p===null?r:p)},reset(){s++,d++,t=null,o=null,n=null,f=null,w.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),i()}}}function yn(e){let n,t,s=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw s();let o=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),g=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(g,i=>i.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function w(o){try{let g=await d;return await t.request(g,{mode:"exclusive"},()=>o(g))}catch(g){throw g instanceof m?g:s()}}function f(o){let g=n.getItem(o);if(g===null)return{revision:0,entry:null};if(g.length>1048576)throw s();let i=JSON.parse(g);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw s();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>w(f),write:(o,g)=>w(i=>{if(f(i).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw s();return n.setItem(i,JSON.stringify({revision:o+1,entry:g})),o+1})}}function be(e,n){let t=en.safeParse(n);if(!t.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let s=t.data;if(e.scope&&(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(e,n){let t=We.parse(n),{artifact:s,environmentId:d}=t.content,w=new te(e.baseUrl??le).origin,f=new te(s.url,w);if(f.origin!==w||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${d}/artifacts/${s.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,g,i=new Promise((u,c)=>{g=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");o.abort(h),c(h)},J.initializationMs)}),l=(async()=>{let u=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(u.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>s.byteLength)throw u.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let c=await ln(u,s.byteLength,{signal:o.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(c,s))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return Ze(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))})();try{return await Promise.race([l,i])}finally{clearTimeout(g)}}var _e=(e,n)=>new m(e,n);function et(e){return sn(e,_e)}async function De(e,n,{predict:t=!0}={}){let s=n.instruction;if(s?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==s.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let d=null,w;if(t)try{let f=await e.funnel(n.source.id,n.source.versionId);w=f.manifest.generation,d=Nn(e,n,f)}catch{d=null}return w??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:s.policyRevision,generation:w},prediction:d}}function Nn(e,n,t){let s=n.instruction;if(s?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==s.policyRevision)return null;let{analyticsConfig:d,remoteFeatures:w,...f}=t.growth,o=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:s.policyRevision,document:t.document,payload:Re.parse(f)}),g=On(o,t.document,{...n,...s}),i=g.steps.at(-1),l=g.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:n.visit+g.steps.length-1}:null);return l?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:l.nodeId,visit:l.visit,terminal:!g.boundary}:null}function On(e,n,t){return un(e,n,t,_e)}import{z as j}from"zod";var wn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),In=j.strictObject({schemaVersion:j.literal(1),scope:qe,runId:j.uuid(),funnelId:j.uuid(),versionId:j.uuid(),processBindingIds:j.record(j.uuid(),j.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid(),generation:j.number().int().nonnegative()}).optional(),closed:j.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),U=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function hn(e){let n=0,t=null,s=i=>JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]),d=Promise.resolve();async function w(){let i=await e.read();if(!Number.isSafeInteger(i.revision)||i.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:i.revision,entry:i.entry===null?null:In.parse(i.entry)}}function f(i){let l=d.then(i);return d=l.catch(()=>{}),l}async function o(i){for(let l=0;l<4;l++){let u=await w();if(u.entry&&t!==null&&s(u.entry)!==t)throw U();let c=i(u.entry,u.revision);if(Se(u.entry,c)){n=u.revision;return}let h=await e.write(u.revision,c);if(h!==null){if(!Number.isSafeInteger(h)||h<=u.revision)throw U();n=h;return}}throw U()}function g(i,l){if(!i||!l)return i;if(i.processBindingIds&&Object.hasOwn(i.processBindingIds,l)){let u={...i.processBindingIds};delete u[l],i={...i,processBindingIds:u}}return i.command?.requestId===l?i.closeCommand?{...i,command:i.closeCommand,closeCommand:void 0}:i.purchase?{...i,command:void 0}:null:i.closeCommand?.requestId===l?{...i,closeCommand:void 0}:i}return{bind(i){let l=JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]);if(t!==null&&t!==l)throw U();t=l},async load(){let i=await w();return n=i.revision,t=i.entry?s(i.entry):null,i.entry},retain(i){let l=In.parse(i),u=l.command;return!u||t!==null&&s(l)!==t?Promise.reject(U()):(t??=s(l),f(()=>o((c,h)=>{if(c&&!Se(s(c),s(l)))throw U();if(c&&l.processBindingIds){for(let[F,N]of Object.entries(l.processBindingIds))if(c.processBindingIds&&Object.hasOwn(c.processBindingIds,F)&&c.processBindingIds[F]!==N)throw U();c={...c,processBindingIds:{...c.processBindingIds,...l.processBindingIds}}}if(!c){if(h!==n&&u.operation!=="close")throw U();return l}if(!c.command)return{...c,command:u,...u.operation==="close"?{closed:!0}:{}};if(u.operation==="close"&&c.command.operation!=="close"){if(c.command.requestId===u.requestId||c.closeCommand&&!Se(c.closeCommand,u))throw U();return{...c,closeCommand:u,closed:!0}}if(!Se(c.command,u))throw U();return c})))},observePurchase(i,l,u,c){return f(()=>o((h,F)=>{if(!h&&F!==n||h&&s(h)!==s({...i,schemaVersion:1}))throw U();if(h?.purchase&&h.purchase.generation>l.generation)return g(h,c);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw U();return u?!h?.purchase||h.purchase.operationId!==l.operationId?g(h,c):g(h.command?{...h,purchase:void 0}:null,c):g({schemaVersion:1,...i,...h,purchase:l},c)}))},settle(i){return f(()=>o(l=>g(l,i)))}}}function ct(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((d,w)=>ce(d,n[w]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),s=Object.entries(n);return t.length===s.length&&t.every(([d,w])=>Object.hasOwn(n,d)&&ce(w,Reflect.get(n,d)))}function vn(e,n){let t=n&&{...n},s=null,d=0,w=new AbortController;function f(){d++,w.abort(new m("IDENTITY_CHANGED","Run identity changed")),w=new AbortController}let o=!1,g,i=0,l=new Set;return{get scope(){return t},bindScope(u){if(t&&(t.projectId!==u.projectId||t.environment!==u.environment))throw new m("SCOPE_MISMATCH","Run scope changed");t??={...u}},get view(){return s},get generation(){return d},get signal(){return w.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return i},nextRead(){return++i},assertCurrent(u,c="Run identity changed during the request"){if(u!==d||o)throw new m("IDENTITY_CHANGED",c)},assertRun(u){if(s&&(u.id!==s.id||u.source.type!==s.source.type||u.source.id!==s.source.id||u.source.versionId!==s.source.versionId||u.locale!==s.locale||!ce(u.parameters,s.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&u.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(u,c,h,F,N){if(!(u.operation==="review"&&s&&s!==h&&c.run.revision<=s.revision)&&!(s&&c.run.revision===s.revision&&F!==void 0&&F<i)&&(u.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&s&&c.run.nodeId===s.nodeId&&c.run.visit===s.visit&&c.run.revision===s.revision&&(c.run.screen=s.screen,(s.paywall?.quote?.operationId===c.review?.activeOperationId||!s.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=s.paywall)),!(s?.paywall&&c.run.paywall&&s.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(s.paywall.selectionGeneration??0)))){if(!s||c.run.revision>=s.revision)s=c.run;else if(!N)return;if(s)for(let L of l)try{L(structuredClone(s))}catch{}}},identify(u){if(o)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(u))throw new m("INVALID_TOKEN","Customer credential required");f(),g=u},subscribe(u){return l.add(u),()=>l.delete(u)},reset(){o||(o=!0,f(),g=void 0,s=null,l.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function wt(e,n,t="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",t)}function It(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...t}=e;return t}var Tn=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Rn({journal:e,state:n,call:t,processIdentity:s}){let d=null,w=null,f=!1,o={command:null,close:null},g=new Set,i,l=null,u=e?e.load().then(a=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=a,!a)return;if(s){if([a.command,a.closeCommand].some(p=>p&&!Object.hasOwn(a.processBindingIds??{},p.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");s.restore(a.processBindingIds??{})}if(n.scope&&(a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=a.purchase,f=a.closed===!0,!a.command)return;let r=a.command;d=r.operation==="close"?null:r,w=r.operation==="close"?r:a.closeCommand?.operation==="close"?a.closeCommand:null,w&&(f=!0);for(let p of[d,w])p&&g.add(p.requestId)}):Promise.resolve();u.catch(()=>{});async function c(a){e&&await u;let r=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(a),...s?{processBindingIds:{[a.requestId]:s.binding(a.requestId)}}:{}})}if(r!==n.generation||d!==a&&w!==a)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let p=g.has(a.requestId);g.add(a.requestId);try{return await t(a)}catch(v){throw r===n.generation&&(d===a||w===a)&&!p&&!Tn(v)&&(e&&await e.settle(a.requestId),r===n.generation&&L(a)),v}}function h(a){let r=Q.parse(a);if(r.operation==="start"||r.operation==="get"||r.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&r.operation!=="close"){if(d?.requestId===r.requestId)return N(r.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(r.operation==="close"){if(d?.requestId===r.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,w&&JSON.stringify($(w))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original Close");return w??=r,o.close?o.close:F(w,"close")}if(d){if(JSON.stringify($(d))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else d=r;return F(d,"command")}function F(a,r){let p=c(a);o[r]=p;let v=()=>{o[r]===p&&(o[r]=null)};return p.then(v,v),p}function N(a){return t({operation:"get",settlementRequestId:a})}function L(a){return!a||d!==a&&w!==a?!1:(d===a&&(d=null),w===a&&(w=null),g.delete(a.requestId),!d&&!w&&(l=null),!0)}return{ready:u,get pending(){return d},get closing(){return w},get closeRequested(){return f},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return i},assertBinding(a){if(l&&(a.run.id!==l.runId||a.run.source.id!==l.funnelId||a.run.source.versionId!==l.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(a,r,p,v){let C=a.operation==="get"?a.settlementRequestId:"requestId"in a&&a.operation!=="start"?a.requestId:void 0,S=C&&r.settlement?.state==="settled"&&r.run.pendingRequest?.requestId!==C&&(a.operation==="get"||!f||a.operation==="close"||!["running","waiting"].includes(r.run.status))?C:void 0,R=d?.requestId===S?d:w?.requestId===S?w:void 0;e?.bind({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId});let O=r.run.paywall,D=O??r.purchase,x=D?.operation,k=r.settlement&&(!O||O.purchaseRequestId===r.settlement.requestId)&&(!i||i.operationId===r.settlement.operationId)?r.settlement:void 0,G=x?.operationId??D?.quote?.operationId??k?.operationId,H=D?.receiptId??k?.receiptId,de=O?.selectionGeneration??i?.generation??0;if(e&&G&&H&&a.operation!=="review"&&(!n.view||r.run.revision>=n.view.revision)&&(v===void 0||v>=n.readSequence)&&(!i||de>=i.generation)){let Z={receiptId:H,operationId:G,generation:de},fe=x?.status==="complete"||D?.canReselect===!0;await e.observePurchase({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId},Z,fe,S),n.assertCurrent(p),(!i||Z.generation>=i.generation)&&(v===void 0||v>=n.readSequence)&&(fe?i?.operationId===Z.operationId&&(i=void 0):i=Z)}else e&&S&&await e.settle(S);return n.assertCurrent(p),S?L(R):!1},stop(){f=!0},submit:h,settle:N,reset(){f=!0,d=null,w=null,i=void 0,l=null,o.close=null,g.clear(),o.command=null}}}function Cn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=vn(e.funnelId,e.scope??e.configuration?.scope),s=e.session?.subscribeIdentity(i),d=null,w=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?yn(e):void 0),f=w&&hn(w),o=Rn({journal:f,state:t,call:l,processIdentity:e.process});async function g(r){if(e.process)return e.process.request(r);let p=t.generation;t.assertCurrent(p);let v=performance.now()+(e.timeoutMs??35e3),C=t.customerToken??("customerToken"in r?r.customerToken:void 0);if(e.session){let O=t.signal,D,x=()=>{},k=new Promise((G,H)=>{x=()=>H(O.reason),O.addEventListener("abort",x,{once:!0}),D=setTimeout(()=>H(new m("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(p),e.session.access())),k])}finally{clearTimeout(D),O.removeEventListener("abort",x)}}t.assertCurrent(p);let S={...r,...C?{customerToken:C}:{}},R=r.operation==="page_experiments"?Te.parse(S):Q.parse(S);return n.requestWithCredential("funnels",R,e.runToken,{headers:e.serverKey&&!C?{[nn]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function i(){s?.(),t.reset(),o.reset(),d=null,n.dispose()}async function l(r,p){let v=t.generation,C=()=>t.assertCurrent(v);f&&await o.ready,C();let S=t.view,R=be(e,await g(r));if(r.operation==="review"&&!R.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(C(),R.runToken&&R.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=r.operation==="get"?r.settlementRequestId:"requestId"in r&&r.operation!=="start"?r.requestId:void 0;if(O&&R.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run),t.bindScope(R.scope);let D=await o.observe(r,R,v,p);return!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r.operation==="get"&&r.settlementRequestId||(C(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(r,R,S,p,D)),R}let u=o.submit,c=null,h=new WeakMap;function F(r){let p=h.get(r);if(p)return p;let v=L(r);return h.set(r,v),v}let N=!1;async function L(r){let p=await r;if(p.run.instruction?.type!=="evaluate_segment")return p;if(c)return c;N=!0;let v=t.generation,C=(async()=>{for(let S=0;S<32&&p.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return p;let R=p.run;if(p.run.instruction?.type==="evaluate_segment"){let{advance:D}=await De(e.configuration,R,{predict:!1});if(v!==t.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return p;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return l({operation:"get"});let x=!0;De(e.configuration,R).then(({prediction:k})=>{x&&v===t.generation&&!o.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=k)}).catch(()=>{});try{p=await u({operation:"commit_segment",requestId:Xe(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...D})}finally{x=!1,d=null}}}return p})();c=C;try{return await C}finally{c===C&&(c=null)}}let a={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let r=o.closing??o.pending;return r?structuredClone($(r)):null},get pendingCommands(){return[o.pending,o.closing].filter(r=>r!==null).map(r=>structuredClone($(r)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return f!==void 0},get prediction(){let r=t.view;return d&&r&&!r.stopped&&["running","waiting"].includes(r.status)&&r.id===d.runId&&r.nodeId===d.from.nodeId&&r.visit===d.from.visit&&r.revision===d.from.revision&&!o.closeRequested?structuredClone(d):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(r){return Pe(e,r)},async pageExperiments(r,p=[]){let v=t.generation;t.assertCurrent(v);let C=t.view?.id;if(!C)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=tn.parse(await g(Te.parse({operation:"page_experiments",release:r,usedReceiptIds:p})));if(t.assertCurrent(v),S.runId!==C||S.scope.projectId!==t.scope?.projectId||S.scope.environment!==t.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(r){return l({operation:"review",...r?{receiptId:r}:{}},t.nextRead())},async get(r,p){f&&await o.ready,p??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let v=t.nextRead();return F(l({operation:"get",...r?{data:r}:{},...p?{purchase:p}:{}},v))},resume(r=t.view?.pendingRequest?.requestId){return r?o.closeRequested?a.settle(r):o.pending?.requestId===r?F(u(o.pending)):F(u({operation:"resume",requestId:r})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(r){return F(u(r))},retry(){return o.closeFlight?o.closeFlight:o.closing?u(o.closing):o.closeRequested&&o.pending?a.settle(o.pending.requestId):o.inFlight?F(o.inFlight):o.pending?F(u(o.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(r){t.identify(r),d=null,n.reset()},subscribe:t.subscribe,reset:i};return a}import{ZodError as _n}from"zod";function bn(e,n,t,s){try{return e.parse(n)}catch(d){throw s&&d instanceof _n?new m(t,s):d}}async function Ee(e,n,t,s={},d){let w=typeof s=="function"?{}:s,f=bn(n.request,t,"INVALID_REQUEST",w.request);try{let o=await e(n.path,f,n.method,d),g=typeof s=="function"?s:s.parseResponse;return g?g(n.response,o):bn(n.response,o,"INVALID_RESPONSE",w.response)}catch(o){throw o instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(o.commandRequestId??=f.requestId),o}}async function Ht(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let t=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),s=Y(e);e.session||s.identify(n.customerToken);let d=null,w=!1,f=null,o=null,g=null,i=null,l=null,u=null,c=null,h=0;function F(){if(w)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function N(){F();let p=ne.resolvePaywall,v=await Ee(s.request,p,{...t,selector:d?{type:"version",versionId:d.id}:t.selector}),C=await Pe(e,v.paywall);if(F(),n.paywallVersionId?C.id!==n.paywallVersionId:C.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(d&&(!dn(C,d)||C.paywallId!==d.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=C,structuredClone(d)}async function L(p){if(F(),i&&p!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let v=f;if(p!=="read"){if(c){if(u===p)return c;throw new m("COMMAND_PENDING","Wait for the original purchase command")}if(u&&u!==p)throw new m("COMMAND_PENDING","Read the original purchase before changing an uncertain command");u=p,h++}let C=u,S=h,R=p==="read"&&c===null,O=p==="read"?ne.readSubscriptionOperation:ne.attach,D=(async()=>{let x=await Ee(s.request,O,{operationId:v.operationId,...p==="read"?{}:{intent:p}});return fn(x.operation,{operationId:v.operationId,currency:t.commerce.currency},"The purchase operation changed"),F(),f?.operationId!==v.operationId?structuredClone(x.operation):(o=pn(o,x.operation),(p!=="read"||R&&c===null)&&h===S&&u===C&&(u=null),structuredClone(o))})();if(p!=="read"){c=D;let x=()=>{c===D&&(c=null)};D.then(x,x)}return D}let a={get view(){return d?structuredClone(d):null},get quote(){return f?structuredClone(f):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},get recovery(){return gn({quote:f,operation:o,requestId:l,pending:i!==null||u!==null,destroyed:w})},get pendingCancellation(){return!w&&u==="cancel"},refresh:N,async preview(p){if(F(),!d)throw new m("INVALID_REQUEST","Load the Paywall first");let v=d.document.buttons[p.actionId];if(v?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let C=Ge(v.product,p.selection,d.capabilities);if(!C)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let S=He(d.document.screen,C,p.selection,d.capabilities),R=ne.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:C,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:t.commerce.provider,currency:t.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),O=JSON.stringify(R);if(g&&g!==O&&(i||u||!o||o.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(g===O){if(i)return i;if(f)return structuredClone(f)}g!==O&&(f=null,o=null),g=O,l=R.requestId;let D=(async()=>{let x=ne.previewAttach,k=await Ee(s.request,x,R);return F(),mn(k.quote,{productVersionId:C,featureQuantities:S,currency:t.commerce.currency,provider:t.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=k.quote,o=null,structuredClone(f)})();i=D;try{return await D}finally{i===D&&(i=null)}},confirm:()=>L("confirm"),cancel:()=>L("cancel"),read:()=>L("read"),destroy(){w||(w=!0,r?.(),s.dispose(),d=null,f=null,o=null,g=null,l=null)}},r=e.session?.subscribeIdentity(a.destroy);try{return await N(),a}catch(p){throw a.destroy(),p}}import{z as Vn}from"zod";import{z as ge}from"zod";var Dn=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,xn=100;function Ln(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Pn(e,n){let t=n===void 0?Ln():n,s=new Map,d=0,w=!1,f=!1,o,g;async function i(u){if(!t)return null;let c;try{let h=await Promise.race([Promise.resolve().then(()=>t.getItem(u)),new Promise(F=>{c=setTimeout(()=>F(null),xn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(c)}}function l(){if(g)return g;let u=(async()=>{try{let c=await i(`${e}:artifacts`);if(c)return Dn.parse(JSON.parse(c))}catch{}return{}})();return g=u,u.finally(()=>{g===u&&(g=void 0)}),u}return{async readManifest(){return i(e)},writeManifest(u){!t||u.length>oe||new TextEncoder().encode(u).byteLength>oe||(o=u,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;o!==void 0;){let c=o;try{await t.setItem(e,c)}catch{}o===c&&(o=void 0)}}finally{f=!1}})))},async readArtifact(u){let c=(await l())[u],h=Date.now();return c&&h>=c.at&&h-c.at<=J.retentionMs?c.text:void 0},writeArtifact(u,c){if(!t||c.length>oe)return;let h=s.get(u);if(h?.text===c||!h&&s.size>=128)return;let F=new TextEncoder().encode(c).byteLength;d-(h?.byteLength??0)+F>oe||(s.set(u,{text:c,byteLength:F}),d+=F-(h?.byteLength??0),!w&&(w=!0,Promise.resolve().then(async()=>{try{for(;s.size;){let N=new Map(s);try{let L={...await l()},a=Date.now();for(let[C,S]of N)L[C]={at:a,text:S.text};let r={},p=2,v=0;for(let[C,S]of Object.entries(L).sort(([,R],[,O])=>O.at-R.at)){if(S.at>a||a-S.at>J.retentionMs)continue;let R=new TextEncoder().encode(JSON.stringify({[C]:S})).byteLength;p+R>oe||v>=128||(r[C]=S,p+=R,v++)}await t.setItem(`${e}:artifacts`,JSON.stringify(r))}catch{}finally{for(let[L,a]of N)s.get(L)===a&&(s.delete(L),d-=a.byteLength)}}}finally{w=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Sn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function rr(e){let n=Ke.parse(e.scope),t=new te(e.origin??le);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let s=new Set([t.origin,...(e.assetOrigins??[]).map(I=>{let y=new te(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),w=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${t.origin}:${M(n)}`,o=Pn(f,e.storage),g,i=0,l=0,u=!1,c=!1,h=0,F=0,N,L,a,r,p=0,v=new Set,C=new Set,S=new Map,R=new Map,O=0,D=!1;function x(){for(let I of v)try{I()}catch{}}function k(I){try{e.onError?.(I)}catch{}}let G=()=>!c&&!u&&!!g&&W()<i&&Date.now()<l;function H(){if(!G())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(I,y,b){if(!S.has(I)){for(;S.size&&(S.size>=128||O+b>J.maxCacheBytes);){let P=S.entries().next().value;O-=P[1].byteLength,S.delete(P[0])}S.set(I,{text:y,byteLength:b}),O+=b}}function Z(I,y,b){return cn(I,y,{signal:b,error:P=>E("INVALID_RESPONSE",P==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(I){let y=new te(I,t);if(!s.has(y.origin)||y.username||y.password||y.hash||y.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function Fe(I,y,b=!1){let P=await d(fe(I),{method:"GET",credentials:"omit",redirect:"error",cache:b?"default":"no-cache",signal:y,headers:{}});if(P.status===429){let T=P.headers.get("retry-after")??"";p=/^\d+$/.test(T)?Number(T)*1e3:Math.max(0,Date.parse(T)-Date.now())||15e3}if(!P.ok&&P.status!==304)throw E(`CONFIGURATION_HTTP_${P.status}`,"Configuration synchronization failed");return P}function Fn(I,y,b){let P=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),T=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(I.headers.get("date")??""),A=I.headers.get("age"),B=A!==null&&/^\d+(\.\d+)?$/.test(A)?Number(A)*1e3:NaN;if(![P,T,_,B].every(Number.isFinite)||T<=P||T-P>J.maxControlAgeMs||P>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let V=Math.min(T-P,b.maxControlAgeSeconds*1e3,J.maxControlAgeMs)-Math.max(B,_-P,0)-(W()-y);if(V<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+V}function Ae(){if(clearTimeout(a),clearTimeout(r),c||!v.size)return;G()&&(r=setTimeout(()=>{G()?Ae():x()},Math.max(1,i-W())),Sn(r));let I=F?Math.min(15e3,1e3*2**Math.min(F-1,4)):Math.min(15e3,(g?.policy.refreshIntervalSeconds??15)*1e3);a=setTimeout(()=>{ie().catch(k)},Math.max(p,I*(.8+Math.random()*.2))),Sn(a)}async function ie(){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=h,y=new AbortController;L=y;let b=(async()=>{if(!D){D=!0;try{let he=await o.readManifest();if(he&&!g){let K=Oe.parse(JSON.parse(he));M(K.scope)===M(n)&&(g=K)}}catch{}}y.signal.throwIfAborted();let A=g,B=W(),q=await Fe(w,y.signal);q.status===304&&(!A||!q.headers.has("x-indiana-config-validated-at")||!q.headers.has("x-indiana-config-valid-until")||!q.headers.has("age"))&&(q=await Fe(w,y.signal));let V=q.status===304?A:Oe.parse(JSON.parse(await Z(q,J.maxManifestBytes,y.signal))),{generation:ae,...se}=V,z=q.headers.get("etag");if(M(V.scope)!==M(n)||Qe(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(A&&(V.revision<A.revision||V.revision===A.revision&&V.generation!==A.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(A?.funnels??{})){let ee=V.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=Fn(q,B,V.policy);if(y.signal.throwIfAborted(),I!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return g=V,i=X,l=Date.now()+Math.max(0,X-W()),u=!1,F=0,p=0,o.writeManifest(M(V)),x(),structuredClone(V)})(),P=setTimeout(()=>y.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),J.initializationMs),T=new Promise((A,B)=>y.signal.addEventListener("abort",()=>B(y.signal.reason),{once:!0})),_=Promise.race([b,T]).catch(A=>{throw F++,(A instanceof Vn.ZodError||A instanceof SyntaxError||A instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(A.code))&&(i=0,u=!0,x()),A}).finally(()=>{clearTimeout(P),N===_&&(N=void 0),Ae()});return N=_,_}async function ye(I){let y=I.sha256,b=se=>Ce(se,I);fe(I.url);let P=S.get(y);if(P){if(P.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return S.delete(y),S.set(y,P),P.text}let T=R.get(y);if(T){if(T.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.promise}let _=new AbortController;C.add(_);let A=h,B=(async()=>{try{let X=await o.readArtifact(y);if(X&&b(X)){if(_.signal.throwIfAborted(),c||A!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,X,I.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Fe(I.url,_.signal,!0),z=await Z(se,I.byteLength,_.signal);if(!b(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(c||A!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,z,I.byteLength),o.writeArtifact(y,z),z})(),q=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),J.initializationMs),V=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([B,V]).finally(()=>{clearTimeout(q),C.delete(_),R.delete(y)});return R.set(y,{promise:ae,byteLength:I.byteLength}),ae}async function we(){return G()||await ie(),H(),g}async function me(I){let y,b=new Promise((P,T)=>{y=setTimeout(()=>T(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),J.initializationMs)});try{return await Promise.race([I(),b])}finally{clearTimeout(y)}}function pe(I,y){if(H(),g?.generation!==I.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&g.funnels[y]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function xe(I){let y=I.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let P=Je.parse(JSON.parse(await ye(b)));if(M(P.scope)!==M({projectId:n.projectId,environment:n.environment})||P.generation!==b.generation||P.remoteFeatures.some(T=>Object.hasOwn(P.features,T)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(I),{...P,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,i-W())).toISOString()}}async function Le(I,y){let b=await we(),P=b.funnels[I];y&&(!P||P.evaluationMode==="local"&&!P.versions[y])&&(N&&await N,b=await ie()),pe(b,I);let T=b.funnels[I];if(T.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=y??T.currentVersionId,A=T.versions[_];if(!A)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(b.artifacts[A.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[B,q]=await Promise.all([ye(b.artifacts[A.artifact]).then(V=>$e(JSON.parse(V))),T.evaluationMode==="local"?xe(b):void 0]);if(q&&M(Ye(B,q))!==M(A.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(b,I),{document:B,growth:q,versionId:_,control:structuredClone(T),manifest:structuredClone(b)}}async function Ve(I,y){try{return await Le(I,y)}catch(b){if(!(b instanceof m)||!(b.code==="CONFIGURATION_CHANGED"||b.code==="CONFIGURATION_HTTP_404"&&G()))throw b;let P=g?.generation;if(N&&await N,await ie(),b.code!=="CONFIGURATION_CHANGED"&&g?.generation===P)throw b;return Le(I,y)}}function Ne(){u=!0,x(),ie().catch(k)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function An(I){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(I),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Ae()),()=>{v.delete(I),v.size||(clearTimeout(a),clearTimeout(r),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:An,assertFresh:H,assertFeatures(I){H();let y=g.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&g.artifacts[y].generation!==I)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return g?structuredClone(g):null},get remainingMs(){return G()?Math.max(0,i-W()):0},async features(){return me(async()=>xe(await we()))},pageExperiments:()=>me(async()=>{let I=await we(),y=I.gb.pageExperiments;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let P=an.parse(JSON.parse(await ye(b)));if(P.environmentId!==n.environmentId||P.generation!==b.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(I),P}),funnel:(I,y)=>me(()=>Ve(I,y)),paywall:(I,y)=>me(async()=>{let b=await we(),P=b.paywalls?.[I];if(!P||!y&&P.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let T=y??P.currentVersionId,_=P.versions[T],A=_&&b.artifacts[_.artifact];if(!A||A.kind!=="paywall"||A.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let B=ze.parse(JSON.parse(await ye(A)));return pe(b),{document:B,versionId:T,version:_.version,control:structuredClone(P),manifest:structuredClone(b)}}),async localFunnel(I,y){let b=await me(()=>Ve(I,y));if(!b.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:P,remoteFeatures:T,..._}=b.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:b.versionId,evaluationMode:"local",evaluationRevision:b.control.evaluationRevision,document:b.document,payload:_})},assertFunnel(I,y,b){H();let P=g.funnels[I];if(!P||P.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(P.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(y!==void 0&&P.controlRevision!==y)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(b!==void 0&&!P.versions[b])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!c){c=!0,h++,i=0,L?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(a),clearTimeout(r),Me(),x(),v.clear();for(let I of C)I.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));S.clear(),O=0}}}}function En(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(t){let s=Q.safeParse({...t,operation:"start"});if(!s.success||s.data.operation!=="start"||(n?s.data.customer!==void 0:s.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let d=s.data,w=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||w.identify(e.apiKey);let f=be(e,await w.request("funnels",d));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==d.funnelId||f.run.locale!==(d.locale??"en")||!ce(f.run.parameters,d.parameters??{})||(d.customer?!f.customerId||d.customer.type==="id"&&f.customerId!==d.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{w.dispose()}}}}async function yr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(t)!==M(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=re.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let w=En({...e,scope:t,apiKey:e.credential}),f=o=>{let g=Cn({...e,scope:t,runToken:o,...d?{serverKey:e.credential}:{}});return d||g.identify(e.credential),g};return{async start(o){let g=await w.start({...o,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),i=f(g.runToken),l=await i.get();return{...g,...l,controller:i}},async restore(o){let g=f(o),i=await g.get();if(i.run.source.id!==e.funnelId)throw g.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...i,runToken:o,controller:g}}}}export{Ee as a,qn as b,be as c,_e as d,et as e,On as f,yn as g,ct as h,ce as i,wt as j,It as k,Cn as l,Ht as m,rr as n,En as o,yr as p};
@@ -1 +0,0 @@
1
- import{b as a}from"./chunk-OUBGSIYR.js";import"./chunk-T5COWMDA.js";import"./chunk-LC2VUKYM.js";import"./chunk-EEZLS2YP.js";import"./chunk-T5YZS64H.js";import"./chunk-26HU2HXU.js";import"./chunk-SLUA7ABW.js";import"./chunk-3DGJ2X3U.js";import"./chunk-DSPLGTQI.js";import"./chunk-7LIABANC.js";import"./chunk-PFHS7HK3.js";export{a as showFunnelRun};