@tinkerlandai/longplay-sdk 0.10.32 → 0.10.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +10 -6
- package/README.zh-CN.md +2 -0
- package/dist/chunk-3JJYWRA3.js +1 -0
- package/dist/chunk-4WZVC4TM.js +1 -0
- package/dist/chunk-5JWMP4YD.js +1 -0
- package/dist/{chunk-XH7RJPBV.js → chunk-6T575JKD.js} +1 -1
- package/dist/{chunk-EMVWUEW4.js → chunk-7NELM6EH.js} +1 -1
- package/dist/{chunk-KHM6IHPJ.js → chunk-7VRZYSTR.js} +1 -1
- package/dist/{chunk-P5K67CKS.js → chunk-ERJP2GBD.js} +1 -1
- package/dist/{chunk-4XC34JBS.js → chunk-I6TSQQ5N.js} +1 -1
- package/dist/{chunk-SP5AQION.js → chunk-ITGERPCJ.js} +1 -1
- package/dist/{chunk-EUVLXS2V.js → chunk-QBA3B4YK.js} +1 -1
- package/dist/chunk-RKPAIF6U.js +1 -0
- package/dist/chunk-TDSATEGE.js +10 -0
- package/dist/{chunk-GLQXJMKL.js → chunk-TYY3MUTF.js} +1 -1
- package/dist/chunk-U6UHASIB.js +1 -0
- package/dist/{chunk-CZ2RY6RG.js → chunk-WKIR2EQG.js} +1 -1
- package/dist/{chunk-ZIQENZDI.js → chunk-WTVLNUMS.js} +1 -1
- package/dist/{content-YRQSNKN7.js → content-ORU4ODJQ.js} +1 -1
- package/dist/funnel-host-purchase-BEFE3N3E.js +1 -0
- package/dist/{funnel-runtime-host-J2PQHVSO.js → funnel-runtime-host-V6TYIDX3.js} +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-HO4PS472.js +1 -0
- package/dist/{paywall-session-PPECL5XK.js → paywall-session-MZXFOPTR.js} +1 -1
- package/dist/popup.d.ts +6 -2
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-iSaRiDP2.d.ts → presentation-loading-CFSiS0VX.d.ts} +502 -3
- package/dist/react-native.js +1 -1
- package/dist/{screen-renderer-NHLIJDCW.js → screen-renderer-W7ZGBFIR.js} +1 -1
- package/dist/server.d.ts +30 -0
- package/dist/server.js +3 -3
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5UFRIIGC.js +0 -1
- package/dist/chunk-6KBCR7JJ.js +0 -10
- package/dist/chunk-EMYZUBWL.js +0 -1
- package/dist/chunk-HQPP76BS.js +0 -1
- package/dist/chunk-UESDHJRB.js +0 -1
- package/dist/chunk-Y3MQLWGD.js +0 -1
- package/dist/funnel-host-purchase-SWYFJOVN.js +0 -1
- package/dist/paywall-RQ66UZLW.js +0 -1
package/dist/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as pn}from"./chunk-
|
|
1
|
+
import{a as pn}from"./chunk-5JWMP4YD.js";import{a as I}from"./chunk-UWLEGMWX.js";import{a as fn,b as hn,c as gn,d as yn}from"./chunk-HQITRRHF.js";import{a as xt}from"./chunk-ERJP2GBD.js";import{a as Ue,b as Ve,c as qe,d as He,e as m}from"./chunk-ILEDKSRQ.js";import"./chunk-EQPEUPMG.js";import{a as Te,b as ae,c as yt,d as It,e as wt,f as xe,g as vt,h as Me,i as dn,j as ln,k as mn}from"./chunk-7VRZYSTR.js";import{a as Et,b as _e}from"./chunk-FYQXSGRT.js";import"./chunk-7MNJH5GB.js";import{A as Tt,C as V,D as N,a as Oe,e as ft,f as ht,l as gt,m as z,n as St,q as Ct,r as Rt,s as bt,t as At,u as Ot,z as pe}from"./chunk-QBA3B4YK.js";import{c as f}from"./chunk-ITGERPCJ.js";import"./chunk-THMGTRXP.js";import{e as at}from"./chunk-NAZU3EEJ.js";import{A as tt,B as Se,C as ie,E as se,F as Ce,K as j,M as ce,N as nt,P as Ee,Q as rt,R as ot,d as Ge,e as je,h as we,p as ze,q as Ke,s as an,t as sn,w as cn,x as X,y as W,z as oe}from"./chunk-SCC3O2RD.js";import{A as Re,B as st,C as ct,H as ut,I as dt,J as be,K as Ae,S as pt,T as de,U as Z,V as lt,_ as mt,d as ve,f as Ze,g as et,u as q,z as it}from"./chunk-R23IGK5U.js";import"./chunk-ZGCKQWQ5.js";import"./chunk-EHDHWYVJ.js";import"./chunk-BXPXJARS.js";import"./chunk-5HJYR6Z4.js";import"./chunk-WTVLNUMS.js";import{a as Ne,b as Le}from"./chunk-VYFSRHXM.js";import{V as Xe,Y as We,la as ue,n as un,p as $e,q as Qe,r as Je}from"./chunk-N7YXDSQL.js";import{c as Ie}from"./chunk-MIBRUDIS.js";import{a as c}from"./chunk-X4W22IH6.js";import{h as Y}from"./chunk-R4FDIYMN.js";import"./chunk-3VUPVXAV.js";import"./chunk-WKIR2EQG.js";import{b as u}from"./chunk-VF6QMMEA.js";import"./chunk-DSPLGTQI.js";import{a as Ye}from"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";var _t=4,Mt=[...tt,"requirement_checks","native_offers","preparations","benefit_claims","authorizations","business_results","checkout_termination"],In=u.enum(Mt),ee=(e,n)=>u.array(e).max(n).refine(t=>new Set(t).size===t.length,"Declarations must be unique"),ke=u.strictObject({...se.shape,bridgeVersion:u.literal(_t),capabilities:ee(In,Mt.length),checkKinds:ee(u.enum(["access","metered","credit"]),3),preparationActions:ee(u.enum(["purchase","subscription_change","refund"]),3),authorizationKinds:ee(u.enum(["auto_topup"]),1),nextActionTypes:ee(u.enum(["redirect","authenticate"]),2),resultEvents:ee(u.enum(["benefit.claimed","authorization.updated"]),2)}).superRefine((e,n)=>{e.capabilities.includes("catalog")!==(e.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(e.capabilities.includes("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare unique supported billing events"});let t=r=>e.capabilities.includes(r),o=(r,a)=>n.addIssue({code:"custom",path:[r],message:a});t("requirement_checks")!==e.checkKinds.length>0&&o("checkKinds","Declare the supported Check kinds"),t("preparations")!==e.preparationActions.length>0&&o("preparationActions","Declare the supported preparation actions"),t("authorizations")!==e.authorizationKinds.length>0&&o("authorizationKinds","Declare the supported authorization kinds"),t("business_results")!==e.resultEvents.length>0&&o("resultEvents","Declare the supported non-financial results");for(let[r,a,s]of[["purchases","purchase","purchase.completed"],["subscription_changes","subscription_change","subscription.change.completed"],["refunds","refund","refund.updated"]])t(r)&&(!t("operation_status")||!t("billing_records")||!t("preparations")||!e.preparationActions.includes(a)||!e.billingEvents.includes(s))&&o("capabilities",`${r} requires preparation, original lookup and its billing result`);t("purchases")&&!e.billingEvents.includes("purchase.closed")&&o("billingEvents","Purchase execution requires its terminal closure result"),t("checkout_termination")&&(!t("operation_status")||!t("billing_records")||!e.billingEvents.includes("purchase.closed"))&&o("capabilities","Checkout termination requires original lookup and purchase.closed"),t("subscription_changes")&&!e.billingEvents.includes("subscription.change.closed")&&o("billingEvents","Subscription change execution requires its terminal closure result");for(let[r,a]of[["benefit_claims","benefit.claimed"],["authorizations","authorization.updated"]])t(r)&&(!t("operation_status")||!t("business_results")||!e.resultEvents.includes(a))&&o("capabilities",`${r} requires original lookup and its non-financial result`)}),K={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":u.strictObject({}),"requirement.check":$e,"operation.prepare":ze,"benefit.claim":Ue,"operation.read":qe,"purchase.terminate":j},wn={"bridge.ping":u.strictObject({challenge:u.uuid()}),"bridge.describe":ke,"requirement.check":Qe,"operation.prepare":Ke,"benefit.claim":Ve,"operation.read":He,"purchase.terminate":j.extend({outcome:u.enum(["requested","already_paid"])})},Gn=u.enum(["bridge.ping","bridge.describe","requirement.check","operation.prepare","benefit.claim","operation.read","purchase.terminate"]);function $(e,n){return u.strictObject({bridgeVersion:u.literal(_t),requestId:u.uuid(),scope:Ce,command:u.literal(e),data:n})}var kt=u.discriminatedUnion("command",[$("bridge.ping",K["bridge.ping"]),$("bridge.describe",K["bridge.describe"]),$("requirement.check",K["requirement.check"]),$("operation.prepare",K["operation.prepare"]),$("benefit.claim",K["benefit.claim"]),$("operation.read",K["operation.read"]),$("purchase.terminate",K["purchase.terminate"])]),Be=u.strictObject({code:u.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:u.string().min(1).max(500),retryable:u.boolean(),recovery:u.string().min(1).max(80),effect:u.enum(["none","unknown"])}).refine(e=>e.effect!=="unknown"||!e.retryable&&e.recovery==="recover_operation","Unknown effects require original-operation recovery");function Bt(e){let n={bridgeVersion:u.literal(4),requestId:u.uuid(),scope:Ce,command:u.literal(e)};return u.union([u.strictObject({...n,data:wn[e]}),u.strictObject({...n,error:Be})])}var Pt="X-Indiana-Bridge-Signature",Q="X-Indiana-Bridge-Key-Id";function vn(e){return new TextEncoder().encode(e)}function Dt(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),n=>n.charCodeAt(0))}function Ft(e,n,t,o){return vn(`indiana-merchant-bridge:${o}
|
|
2
2
|
${n}
|
|
3
3
|
POST
|
|
4
|
-
${
|
|
4
|
+
${W}
|
|
5
5
|
${t}
|
|
6
|
-
${e}`)}async function Nt(e){let n=ae.parse(e);return crypto.subtle.importKey("raw",Dt(n.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function ee(e,n,t,o=Date.now(),r=Q){let a=String(Math.floor(o/1e3)),s=new Uint8Array(await crypto.subtle.sign("HMAC",await Nt(n),Ft(e,t,a,r))),l=btoa(String.fromCharCode(...s)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[z]:n.keyId,[Pt]:`t=${a},v1=${l}`}}async function te(e,n,t,o,r=Date.now(),a=Q){try{if(n.get(z)!==t.keyId)return!1;let s=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(n.get(Pt)??"");return!s||Math.abs(r/1e3-Number(s[1]))>300?!1:await crypto.subtle.verify("HMAC",await Nt(t),Dt(s[2]),Ft(e,o,s[1],a))}catch{return!1}}var Lt=u.strictObject({operation:u.literal("renew_run"),runId:u.uuid(),customerId:u.uuid()}),le=ft.refine(e=>!!e.runToken,"Renewal returns a credential"),Ut=ht.refine(e=>!!e.runToken,"Renewal returns a credential");var Pe=u.discriminatedUnion("operation",[u.strictObject({operation:u.literal("campaign_decide"),...pt}).refine(be,Ae),u.strictObject({operation:u.literal("campaign_start"),funnelId:u.uuid(),requestId:u.uuid(),customer:ut,customerData:dt.optional(),locale:u.string().min(1).max(35),parameters:ue,cooldownSeconds:u.number().int().min(1).max(2592e3)}).refine(be,Ae)]),Sn=u.union([u.strictObject({scope:$,suppressed:u.literal(!0),reason:u.enum(["frequency","in_progress"]),retryAt:u.iso.datetime({offset:!0})}),le]),Vt=u.union([Sn.options[0],Ut]);var qt=u.discriminatedUnion("provider",[u.strictObject({provider:u.literal("apple"),orderId:u.uuid(),receiptId:u.uuid(),signedTransaction:u.string().min(1).max(131072)}),u.strictObject({provider:u.literal("google"),orderId:u.uuid(),receiptId:u.uuid(),purchaseToken:u.string().min(1).max(16384)})]),Ht=u.strictObject({orderId:u.uuid(),receiptId:u.uuid(),transactionIds:u.array(u.string().min(1).max(255)).min(1).max(50),membership:u.boolean()});var Gt=u.strictObject({operation:u.literal("native_receipt"),requestId:u.uuid(),customerToken:u.string().regex(Ne),orderId:u.uuid(),receiptId:u.uuid(),nativeEvidence:qt.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),jt=u.strictObject({scope:$,requestId:u.uuid(),orderId:u.uuid(),receiptId:u.uuid(),orderStatus:u.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:u.boolean(),nativeCompletion:Ht.optional()});var zt=u.strictObject({document:mt,configuration:j.options[0]});function me(e){return{async getCustomer(n){let t=m.getCustomer;return f(e,t,n,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(n={}){let t=m.listCustomers;return f(e,t,n,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(n){let t=m.updateCustomer;return f(e,t,n,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(n){let t=m.createGuestCustomer;return f(e,t,n)},async resumeGuestSession(n){let t=m.resumeGuestSession;return f(e,t,n)},async claimGuestCustomer(n){let t=m.claimGuestCustomer;return f(e,t,n)},async revokeCustomerSessions(n){let t=m.revokeSessions;return f(e,t,n)},async createCustomerSession(n){return f(e,m.createSession,{customerId:n},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(n){return f(e,m.createCustomer,n,{request:"Invalid customer input",response:"Invalid customer response"})}}}function Kt(e){return{async checkEntitlement(n){let t=m.checkEntitlement,o=t.request.parse(n),r=await f(e,t,o,I);return Et(o.requirement,r.check,o.customerId,r.scope),r},async readHoldings(n){let t=m.readHoldings;return f(e,t,n,I)},async readSeats(n){let t=m.readSeats;return f(e,t,n,I)},async manageSeat(n){let t=m.manageSeat;return f(e,t,n,I)}}}function $t(e){return{async readAiPricing(n){let t=m.readAiPricing;return f(e,t,n,I)},async readUsage(n){let t=m.readUsage;return f(e,t,n,I)},async setUsage(n){let t=m.setUsage;return f(e,t,n,I)},async manageBalanceGrant(n){let t=m.manageBalanceGrant;return f(e,t,n,I)},async readBalanceSource(n){let t=m.readBalanceSource;return f(e,t,n,I)},async adjustBalance(n){let t=m.adjustBalance;return f(e,t,n,I)},async listBalanceGrants(n){let t=m.listBalanceGrants;return f(e,t,n,I)},async manageBillingLimits(n){let t=m.manageBillingLimits;return f(e,t,n,I)},async manageUsageEntity(n){let t=m.manageUsageEntity;return f(e,t,n,I)},async readUsageAnalytics(n){let t=m.readUsageAnalytics;return f(e,t,n,I)},async readCreditAnalytics(n){let t=m.readCreditAnalytics;return f(e,t,n,I)},async submitUsageBatch(n){let t=m.submitUsageBatch;return f(e,t,n,I)},async readUsageBatch(n){let t=m.readUsageBatch;return f(e,t,n,I)},async readLedger(n){let t=m.readLedger;return f(e,t,n,I)},async readCreditStatement(n){let t=m.readCreditStatement;return f(e,t,n,I)},async quoteBalance(n){let t=m.quoteBalance;return f(e,t,n,I)},async trackUsage(n){let t=m.trackUsage;return f(e,t,n,I)},async mutateBalance(n){let t=m.mutateBalance;return f(e,t,n,I)}}}function Qt(e){return{async listInvoiceTemplates(n={}){let t=m.listInvoiceTemplates;return f(e,t,n,I)},async previewInvoice(n){let t=m.previewInvoice;return f(e,t,n,I)},async createInvoice(n){let t=m.createInvoice;return f(e,t,n,I)},async prepareBillingAdjustment(n){let t=m.prepareBillingAdjustment;return f(e,t,n,I)},async manageInvoice(n){let t=m.manageInvoice;return f(e,t,n,I)},async readInvoiceOperation(n){let t=m.readInvoiceOperation;return f(e,t,n,I)},async listInvoices(n){let t=m.listInvoices;return f(e,t,n,I)},async getInvoice(n){let t=m.getInvoice;return f(e,t,n,I)},async setupPayment(n){let t=m.setupPayment;return f(e,t,n,I)},async readPaymentSetup(n){let t=m.readPaymentSetup;return f(e,t,n,I)},async readBillingInvoice(n){let t=m.readBillingInvoice;return f(e,t,n,I)},async previewRefund(n){let t=m.previewRefund;return f(e,t,n,I)},async refund(n){let t=m.refund;return f(e,t,n,I)},async readRefund(n){let t=m.readRefund;return f(e,t,n,I)}}}function Jt(e){return{async previewSubscriptionBatch(n){let t=m.previewSubscriptionBatch;return f(e,t,n,I)},async confirmSubscriptionBatch(n){let t=m.confirmSubscriptionBatch;return f(e,t,n,I)},async readSubscriptionBatch(n){let t=m.readSubscriptionBatch;return f(e,t,n,I)},async abandonSubscriptionBatch(n){let t=m.abandonSubscriptionBatch;return f(e,t,n,I)},async manageSubscriptionTrial(n){let t=m.manageSubscriptionTrial;return f(e,t,n,I)},async readSubscriptionTrial(n){let t=m.readSubscriptionTrial;return f(e,t,n,I)},async listSubscriptions(n){let t=m.listSubscriptions;return f(e,t,n,I)},async listPurchases(n){let t=m.listPurchases;return f(e,t,n,I)},async listSubscriptionConflicts(n){let t=m.listSubscriptionConflicts;return f(e,t,n,I)},async retrySubscriptionConflict(n){let t=m.retrySubscriptionConflict;return f(e,t,n,I)},async previewUpdate(n){let t=m.previewUpdate;return f(e,t,n,I)},async update(n){let t=m.update;return f(e,t,n,I)},async readSubscriptionUpdate(n){let t=m.readSubscriptionUpdate;return f(e,t,n,I)},async restoreNativePurchase(n){let t=m.restoreNativePurchase;return f(e,t,n,I)},async verifySubscriptions(n){let t=m.verifySubscriptions;return f(e,t,n,I)},async previewAttach(n){let t=m.previewAttach;return f(e,t,n,I)},async recordMerchantEvent(n){return f(e,m.recordMerchantEvent,n,{request:"Invalid merchant event",parseResponse:I})},async attach(n){let t=m.attach;return f(e,t,n,I)},async readSubscriptionOperation(n){let t=m.readSubscriptionOperation;return f(e,t,n,I)}}}function Yt(e){return{async grantModelBenefit(n){return f(e,m.grantModelBenefit,n,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(n){return f(e,m.readModelBenefit,n,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(n){let t=m.grantOffer;return f(e,{...t,request:t.request.refine(o=>!!o.customerId)},{...n,requestId:n.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function Xt(e){return{...Kt(e),...$t(e),...Qt(e),...Jt(e),...Yt(e)}}function Wt(e){return{async getFeatures(n={}){let t=m.getFeatures;return f(e,t,n,I)},async evaluateFeatures(n){let t=m.evaluateFeatures;return f(e,t,n,I)}}}function Zt(e){return{async trackEvents(n){let t=m.trackEvents;return f(e,t,n,I)}}}function en(e){return{async resolveContent(n){let t=m.resolveContent;return f(e,t,n,I)},async resolvePaywall(n){let t=m.resolvePaywall,o=t.request.parse(n),r=await f(e,t,o,I);return Me(o,r.paywall.check,r.scope),r},async resolveOffering(n){let t=m.resolveOffering,o=t.request.parse(n),r=await f(e,t,o,I);return Me(o,r.check,r.scope),r}}}function Cn(e){V(e.apiKey,"Secret API keys must stay on your backend");let t=N(e).request;return{async sendMessage(o){let r=m.sendMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},async readMessage(o){let r=m.readMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},...me(t),...Xt(t),...Wt(t),...Zt(t),...en(t)}}function De(){if(typeof window<"u")throw new c("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 tn=()=>new c("CONFLICT","Process synchronization is in progress",425),L=()=>new c("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),En=(e,n)=>JSON.stringify(e)===JSON.stringify(n),fe=class extends c{constructor(t){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:t.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=t}result};function Rn(e){if(V(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new c("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let n=N(e),t=me(n.request),o=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(g){let i=await e.resolveUser(g);if(i!==null&&(typeof i?.externalUserId!="string"||!i.externalUserId||i.externalUserId!==i.externalUserId.trim()||i.externalUserId.startsWith("gg_guest_")))throw new c("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return i}async function a(g){let i=await e.resolveContext(g);if(i?.confirmed!==!0||!i.processKey||!i.guestKey)throw new c("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:o+"run:"+i.processKey,guest:o+"guest:"+i.guestKey}}async function s(g,i){for(let w=0;w<8;w++){let R=await e.store.read(g),C=i(R?structuredClone(R.value):null);if(R&&En(R.value,C)||await e.store.compareAndSwap(g,R?.revision??null,C))return C}throw tn()}async function l(g){let i=await e.store.read(g);if(!i)throw new c("NOT_FOUND","Open the process before continuing",404);return i.value}async function p(g){let i=await l(g);for(let w of i.revocations??[])await t.revokeCustomerSessions(w),await s(g,R=>{if(!R)throw L();return R.revocations=R.revocations?.filter(C=>C.sessionId!==w.sessionId),R})}async function v(g,i){let w=Te.parse(g);return i?n.requestWithCredential("funnel-processes",w,i):n.request("funnel-processes",w)}function E(g,i){if(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment||g.run&&(g.run.id!==i.run.id||g.run.source.versionId!==i.run.source.versionId||g.run.source.id!==i.run.source.id||g.run.runExpiresAt!==i.run.runExpiresAt||g.run.identity.startedAs!==i.run.identity.startedAs||g.run.identity.participantId!==i.run.identity.participantId||g.run.identity.binding&&g.run.identity.binding.id!==i.run.identity.binding?.id)||g.runToken&&i.runToken&&g.runToken!==i.runToken)throw new c("INVALID_RESPONSE","Process identity or Run changed")}async function b(g,i,w){return s(g,R=>{if(!R)throw new c("NOT_FOUND","Process handle is missing",404);return E(R,i),(!R.run||i.run.revision>=R.run.revision)&&(R.run=i.run),R.runToken??=i.runToken,w!==void 0&&(R.target=w),R})}async function d(g,i){if(i.detached)throw new c("UNAUTHENTICATED","The process is detached",401);let w=i.run?.identity.binding?.customerId??i.run?.identity.participantId;if(!w)throw new c("INVALID_RESPONSE","Process participant is missing");if(i.session?.customerId===w&&Date.parse(i.session.expiresAt)>Date.now()+3e4)return i.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},C=await s(g,O=>{if(!O||O.detached||O.run?.id!==i.run?.id)throw L();if(O.sessionLease&&O.sessionLease.until>Date.now())throw tn();return O.sessionLease=R,O}),A;try{if(C.session?.customerId===w&&Date.parse(C.session.refreshExpiresAt)>Date.now())try{if(A=Le.parse(await n.requestWithCredential("customer-sessions/refresh",{},C.session.refreshToken)),A.sessionId!==C.session.sessionId)throw new c("INVALID_RESPONSE","Refresh changed the logical session")}catch(_){if(!(_ instanceof c)||_.status!==401)throw _}if(A??=C.run?.identity.binding?await t.createCustomerSession(w):await t.resumeGuestSession({guestToken:C.guest.token}),A.customerId!==w)throw new c("INVALID_RESPONSE","Session Customer changed");let O=A;return await s(g,_=>{if(!_||_.detached||_.sessionLease?.id!==R.id||_.run?.identity.binding?.id!==i.run?.identity.binding?.id)throw new c("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return _.session=O,delete _.sessionLease,_}),A}catch(O){throw A&&A.sessionId!==C.session?.sessionId&&await t.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await s(g,_=>{if(!_)throw L();return _.sessionLease?.id===R.id&&delete _.sessionLease,_}).catch(()=>{}),O}}let h;async function y(){if(h??=vt.parse(await v({contract:q,operation:"describe"})),h.scope.projectId!==e.scope.projectId||h.scope.environment!==e.scope.environment)throw L();return h}async function S(g,i,w=!1){let R=await r(g),C=await l(i);if(C.issuingKeyId!==(await y()).keyId)throw new c("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!C.runToken||!C.run)throw new c("CONFLICT","Recover the original start first",425);if(C.detached){if(!w)throw new c("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(C.run.identity.binding&&(!R||C.target&&C.target!==R.externalUserId))throw L();await p(i),C=await s(i,A=>{if(!A||A.run?.id!==C.run?.id)throw L();return delete A.detached,A})}if(!C.runToken||!C.run)throw new c("INVALID_RESPONSE","Process identity is missing");if(C.run.identity.binding){if(R&&!C.target){let A=xe.parse(await v({contract:q,operation:"binding_status",runToken:C.runToken,requestId:C.bindingIntent?.requestId??C.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==C.run.identity.binding.id)throw L();C=await s(i,O=>{if(!O)throw L();return O.target=R.externalUserId,O})}if(!R||C.target!==R.externalUserId)throw L()}else if(R){if(!C.guest)throw L();C=await s(i,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw L();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=C.bindingIntent;try{let O=wt.parse(await v({contract:q,operation:"bind_customer",...A,runToken:C.runToken,guestToken:C.guest.token,claimRequestId:C.guest.claimRequestId,expectedBindingId:null}));C=await b(i,O,R.externalUserId)}catch(O){let _=xe.parse(await v({contract:q,operation:"binding_status",...A,runToken:C.runToken,guestToken:C.guest.token}));if(_.state!=="bound")throw O;C=await s(i,F=>{if(!F?.run||F.run.id!==_.binding.runId)throw L();return F.run.identity.binding={id:_.binding.id,customerId:_.binding.customerId,acceptedAt:_.binding.acceptedAt},F.target=R.externalUserId,F})}}return{state:C,session:await d(i,C)}}async function k(g,i,w,R){try{return await R(w)}catch(C){if(!(C instanceof c)||C.status!==401)throw C;return await s(i,A=>{if(!A||A.detached)throw C;return A.session?.accessToken===w.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await S(g,i))}}async function D(g,i,w=!1){let R=await a(g),C=await S(g,R.process,w),A=oe.parse(await k(g,R.process,C,O=>v({...i,customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A}return{async open(g,i){i=It.parse(i);let w=await a(g),R=await y(),C=w.guest+":"+R.keyId,A=await e.store.read(w.process);if(!A){let B=await r(g),T,M,P;if(B)T={type:"customer",customer:{type:"externalUserId",value:B.externalUserId}};else{let H=await e.store.read(C);if(H)try{P=await t.resumeGuestSession({guestToken:H.value.token}),M=H.value}catch(U){if(!(U instanceof c)||U.status!==401)throw U}let G={token:De(),claimRequestId:crypto.randomUUID()};M=await s(C,U=>M??(U&&U.token!==H?.value.token?U:G)),T={type:"guest",guestToken:M.token}}await s(w.process,H=>H??{issuingKeyId:R.keyId,start:Te.parse({...i,contract:q,requestId:crypto.randomUUID(),source:T}),...M?{guest:M}:{},...B?{target:B.externalUserId}:{},...P?{session:P}:{}}),A=await e.store.read(w.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new c("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==i.funnelId||O.start.operation!==i.operation)throw new c("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let P=await r(g);if(!P||P.externalUserId!==O.target)throw L()}let B=await v(O.start),T=yt.safeParse(B);if(T.success)throw new fe(T.data);let M=oe.parse(B);if(!M.runToken)throw new c("INVALID_RESPONSE","Process credential is missing");O=await b(w.process,M)}let _=await S(g,w.process,!0),F=oe.parse(await k(g,w.process,_,B=>v({contract:q,operation:"get",customerToken:B.session.accessToken},B.state.runToken)));return await b(w.process,F),{...F,runToken:O.runToken}},async syncIdentity(g){return D(g,{contract:q,operation:"get",customerToken:""},!0)},async get(g,i={}){return D(g,{...i,contract:q,operation:"get",customerToken:""})},async review(g,i){return D(g,{contract:q,operation:"review",customerToken:"",...i?{receiptId:i}:{}})},async command(g,i,w){let R=await a(g),C=await S(g,R.process),A=oe.parse(await k(g,R.process,C,O=>v({contract:q,operation:"command",command:i,identity:{bindingId:w},customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A},async pageExperiments(g,i,w=[]){let R=await a(g),C=await S(g,R.process);return gt.parse(await k(g,R.process,C,A=>v({contract:q,operation:"page_experiments",release:i,usedReceiptIds:w,customerToken:A.session.accessToken},A.state.runToken)))},async detach(g){let i=await a(g);await s(i.process,w=>{if(!w)throw L();return w.session&&!w.revocations?.some(R=>R.sessionId===w.session.sessionId)&&(w.revocations??=[]).push({customerId:w.session.customerId,sessionId:w.session.sessionId}),w.detached=!0,delete w.session,delete w.sessionLease,w}),await p(i.process)},destroy(){n.dispose()}}}async function bn(e,n){V(e.apiKey,"Renewal requires your backend");let t=N(e),o=le.parse(Rt(e,await t.request("funnels",Lt.parse({...n,operation:"renew_run"}))));if(o.run.id!==n.runId)throw new c("INVALID_RESPONSE","Run renewal identity changed");return o}function nn(e){let n=At(e),t=l=>{throw new c("INVALID_RESPONSE",l)};n.nodes.size!==e.topology.nodes.length&&t("Duplicate local node identity"),n.nodes.get(e.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let o=new Set(["entry","condition","feature","split","end","output"]);for(let l of n.nodes.values()){if(!o.has(l.type))throw new c("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&t("Local next exit is unavailable"),l.type==="feature"){let p=l.resources.featureKey;(!p||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(n.features,p))&&t("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let p=e.conditions[l.id];(!p||!l.outputs.default||p.some((v,E)=>v.port!==`case:${E}`||!l.outputs[v.port]))&&t("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let p=e.evaluation.terminals[l.id];if(!p)throw new c("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&t("A terminal cannot have outgoing edges"),p.output?.type==="feature"&&!Object.hasOwn(n.features,p.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let p of Object.values(l.outputs))n.nodes.has(p)||t("Local target is unavailable")}let r=new Set,a=new Set;function s(l){if(a.has(l)&&t("Local graph contains a cycle"),!r.has(l)){a.add(l);for(let p of Object.values(n.nodes.get(l).outputs))s(p);a.delete(l),r.add(l)}}return s(e.topology.entry),r.size!==n.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(l){let p={},v=l.context;v.features=n.features,v.savedGroups=n.savedGroups;let E=()=>{v.attributes=it({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:p,savedGroups:n.savedGroups})};E();let b=e.topology.entry,d=0;for(;;){let h=n.nodes.get(b);if(h.type==="end"||h.type==="output"){let y=e.evaluation.terminals[b],S=y.output,k=S?.type==="feature"?n.feature(S.featureKey,v):S?.type==="variable"?et({source:"variable",key:S.key,...S.path?{path:S.path}:{}},{declarations:e.evaluation.variables,answers:{},results:p,parameters:l.parameters,attributes:l.attributes,savedGroups:n.savedGroups}):S?.value??null;return ve(e.evaluation.outputSchema,k)||t("Local output does not match its declaration"),{outcome:y.outcome,value:k}}if(d++>=e.evaluation.maxTransitions)throw new c("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(h.type==="entry")b=h.outputs.next;else{let y=n.evaluate(b,v);if(h.type==="feature"){let S=h.writes.value,k=y.value??null;ve(e.evaluation.variables[S],k)||t("Local Feature value does not match its declaration"),Ze(e.evaluation.variables,{writes:h.writes},{[S]:k}),p[S]=k,E()}b=y.target}}}}}function rn(e,n,t){let o=Xe.parse(e.attributes);if(["parameters","answers","results"].some(g=>Object.hasOwn(o,g)))throw new c("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=ue.parse(e.parameters??{}),a=u.record(u.string(),We).parse(e.stickyBucketAssignmentDocs??{});for(let[g,i]of Object.entries(a))if(g!==`${i.attributeName}||${i.attributeValue}`||!Object.hasOwn(o,i.attributeName)||Ye(o[i.attributeName])!==i.attributeValue)throw new c("INVALID_REQUEST","Sticky document identity does not match this session");let s=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,p=e.onExperimentViewed,v=e.onError,E=new Map,b=new Set,d={},h=Promise.resolve();function y(g){let i=h.then(()=>(t(),g()));return h=i.catch(()=>{}),i}function S(g){try{v?.(g)}catch{}}function k(g){try{let i=g();i&&typeof i.catch=="function"&&i.catch(S)}catch(i){S(i)}}async function D(){for(let[g,i]of E){if(t(),s)try{await s(structuredClone(i))}catch{throw new c("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),E.delete(g)}}return{evaluate(g={}){let i=g.track===!0;return y(async()=>{let w=await n();t(w);let R=new Set(b),C={...d},A=new Map,O=[],_={stickyBucketAssignmentDocs:structuredClone(a),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...i?{trackedExperiments:R,trackedFeatureUsage:C,onExperimentViewed(T,M){let P=structuredClone(T),H=structuredClone(M);p&&O.push(()=>p(structuredClone(P),structuredClone(H)))},onFeatureUsage(T,M){let P=structuredClone(M);l&&O.push(()=>l(T,structuredClone(P)))}}:{}},F=w.program.evaluate({attributes:o,parameters:r,context:_});t(w);for(let[T,M]of A)a[T]=M,E.set(T,M);await D(),t(w),i&&(b=R,d=C);for(let T of O)k(T);let B=w.configuration;return structuredClone({evaluationMode:"local",scope:B.scope,funnelId:B.funnelId,versionId:B.versionId,evaluationRevision:B.evaluationRevision,generation:B.growth.generation,...F})})},flush:()=>y(D),get stickyBucketAssignmentDocs(){return t(),structuredClone(a)}}}var An=6e4;function he(e){if(typeof window<"u")throw new c("SERVER_ONLY","Local Funnel sessions run on your backend");let n=$.parse(e.scope),t=e.funnelId,o=e.load,r,a,s,l=0,p=b=>Date.now()>=b.expiresAt;async function v(){if(a)return a;let b=l;r=void 0;let d=(async()=>{let h=await o();if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(h&&typeof h=="object"&&"evaluationMode"in h&&h.evaluationMode==="remote")throw I(j,h),new c("EVALUATION_MODE","This Funnel requires remote decide");let y=I(St,h);if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==n.projectId||y.scope.environment!==n.environment||y.funnelId!==t)throw new c("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==n.projectId||y.growth.scope.environment!==n.environment||y.growth.expiresAt!==y.expiresAt)throw new c("INVALID_RESPONSE","GB configuration scope or expiry changed");let S=Math.min(Date.now()+An,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=S)throw new c("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([n.projectId,n.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),D=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(s?.key===k&&!Tt(s.body,D))throw new c("INVALID_RESPONSE","Immutable local configuration identity changed");return s?.key!==k&&(s={key:k,body:D,program:nn(y)}),r={key:k,configuration:y,expiresAt:S,program:s.program},r})();a=d;try{return await d}finally{a===d&&(a=void 0)}}function E(){return a??(r&&!p(r)?Promise.resolve(r):v())}return{session(b){let d=l;return rn(b,E,h=>{if(e.assertUsable?.(),d!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(h&&(p(h)||r?.key!==h.key))throw new c("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await v()).configuration)},reset(){l++,r=void 0,a=void 0,s=void 0}}}function On(e,n){let t=e.snapshot?.generation,o=he({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n,load:()=>e.localFunnel(n),assertUsable:()=>e.assertFunnel(n)}),r=e.subscribe(()=>{let s=e.snapshot?.generation;e.fresh&&s!==t&&(t=s,o.refresh().catch(()=>{}))}),a=o.session;return Object.assign(o,{session(s){let l=a(s),p=l.evaluate;return Object.assign(l,{async evaluate(...v){return e.fresh||await e.refresh(),p(...v)}})},destroy(){r(),o.reset()}})}function Tn(e){if(typeof window<"u")throw new c("SERVER_ONLY","Secret API keys must stay on the backend");return{start:n=>xt(e,n)}}var ne=class extends c{constructor(t,o){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,o);this.decisionId=t;this.decisionRequestId=o}decisionId;decisionRequestId};async function ge(e,n,t,o){let{decisionId:r,requestId:a}=e,s=e,l=250,p=0;for(;;){if(s.decisionId!==r||s.requestId!==a||s.decision&&!pe(s.decision,n))throw new c("INVALID_RESPONSE","Decision request or customer changed");if(s.decision)return s.decision;if(s.status==="failed")throw new c("DECISION_FAILED","Decision execution failed",503,a);if(Date.now()>=t)throw new ne(r,a);if(await new Promise(v=>setTimeout(v,Math.min(Math.max(l,p-Date.now()),t-Date.now()))),Date.now()>=t)throw new ne(r,a);l=Math.min(1e3,l*2);try{s=await o(r,t)}catch(v){if(v instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(v.code)){p=Date.now()+(v.retryAfterSeconds??0)*1e3;continue}throw v}}}function Fe(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Funnel decisions are requested by your backend");let n,t,o=new Map;async function r(p,v){let E=p;E.status!=="pending"&&o.delete(E.decisionId);for(let b=0;b<32&&E.evaluation;b++){let d=E.evaluation;if(d.runId!==E.decisionId)throw new c("INVALID_RESPONSE","Local evaluation Run changed");let h=o.get(E.decisionId);if(!h&&d.type==="evaluate_segment"){let S=zt.parse(await a({operation:"segment_configuration",funnelId:e.funnelId,versionId:d.versionId},v));if(S.configuration.scope.projectId!==e.scope.projectId||S.configuration.scope.environment!==e.scope.environment||S.configuration.funnelId!==e.funnelId||S.configuration.versionId!==d.versionId||S.configuration.evaluationRevision!==d.policyRevision)throw new c("SCOPE_MISMATCH","Original decision segment configuration changed");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding decisions first");h={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:S.configuration.growth.generation,...Ot(S.configuration,S.document,d)},o.set(E.decisionId,h)}if(!h){if(d.type!=="evaluate")throw new c("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=j.parse(await a({operation:"configuration",funnelId:e.funnelId,versionId:d.versionId},v))),t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment||t.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new c("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding Local decisions first");h={operation:"evaluate_decision",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:Ct(t,d.nodeId,d,bt)},o.set(E.decisionId,h)}let y=Y.parse(await a(h,v));if(y.decisionId!==p.decisionId||y.requestId!==p.requestId)throw new c("INVALID_RESPONSE","Decision identity changed during local evaluation");o.delete(E.decisionId),E=y}return E}async function a(p,v,E=!1){return N({...e,fetch:(d,h)=>{let y=new Headers(h?.headers);return y.set("Accept-Encoding","identity"),E&&y.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(d,{...h,headers:y})},timeoutMs:Math.min(e.timeoutMs??1e4,v?Math.max(1,v-Date.now()):12e4)}).request("funnels",p)}async function s(p,v){let E=Y.parse(await a(de.parse({operation:"read_decision",decisionId:p}),v));if(E.decisionId!==p)throw new c("INVALID_RESPONSE","Decision identity changed");return r(E,v)}async function l(p,v,E=!1){let b=de.options[0].parse({...p,operation:"decide",funnelId:e.funnelId}),d;try{d=Y.parse(await a(b,v,E))}catch(h){throw h instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(h.code)?new c("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",h.status,p.requestId):h}if(d.requestId!==p.requestId||d.decision&&!pe(d.decision,b.customer))throw new c("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(d,v),customer:b.customer}}return{local(){return n??=he({scope:e.scope,funnelId:e.funnelId,load:()=>a({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let p=j.parse(await a({operation:"configuration",funnelId:e.funnelId}));if(p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment||p.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Configuration scope changed");return p},features(p={}){return _e({...p,scope:e.scope,load:async()=>at.parse(await a({operation:"feature_config",funnelId:e.funnelId}))})},read:p=>s(p),async submit(p){return(await l(p,void 0,!0)).response},async decide(p){let v=Date.now()+3e4,E=await l(p,v);return ge(E.response,E.customer,v,s)},async reportUsed(p){let v=lt.parse(await a(de.parse({...p,operation:"report_used"})));if(v.decisionId!==p.decisionId||v.eventId!==p.eventId)throw new c("INVALID_RESPONSE","Usage receipt identity changed");return v}}}function xn(e){V(e.apiKey,"Native receipts are verified by your backend","Server API key required");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(t){let o=Gt.parse(t);if(o.orderId!==o.receiptId)throw new c("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=o.nativeEvidence,a={requestId:o.requestId,customerToken:o.customerToken,purchaseIntentId:o.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},s=m.restoreNativePurchase.response.parse(await n.request(m.restoreNativePurchase.path,a));if(s.operation.requestId!==o.requestId||s.operation.purchaseIntentId!==o.orderId)throw new c("INVALID_RESPONSE","Native receipt request identity changed");let l=jt.parse({scope:s.scope,requestId:o.requestId,orderId:s.operation.orderId,receiptId:s.operation.orderId,orderStatus:s.operation.status,refunded:s.operation.refunded,...s.operation.completion===null?{}:{nativeCompletion:{orderId:s.operation.orderId,receiptId:s.operation.orderId,...s.operation.completion}}});if(l.requestId!==o.requestId||l.orderId!==o.orderId||l.receiptId!==o.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Current order receipt scope changed");return l}}}var K=u.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function Mn(e,n){let t=K.parse(e.inputTokens.total),o=K.parse(e.outputTokens.total),r=K.parse(e.inputTokens.cacheRead??0),a=K.parse(e.inputTokens.cacheWrite??0),s=K.parse(e.outputTokens.reasoning??0);if(r+a>t||s>o||e.inputTokens.noCache!==void 0&&K.parse(e.inputTokens.noCache)!==t-r-a||e.outputTokens.text!==void 0&&K.parse(e.outputTokens.text)!==o-s)throw new c("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-r-a,cache_read:r,cache_write:a,output:n==="output"?o:o-s,reasoning:n==="separate"?s:0,input_audio:0,output_audio:0}}function _n(e){if(typeof window<"u")throw new c("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new c("INVALID_REQUEST","Model ID and reasoning pricing are required");async function n(o){await e.persist({context:o,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(o,r){let a={context:o,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(a);let s=e.mapTokens?e.mapTokens(r):Mn(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:s});await e.persist({...a,tokens:s,quote:l,phase:"quoted"});let p=await e.pricing.trackTokens(e.client,{...o,quote:l});if(!p.receipt.accepted)throw new c("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...a,tokens:s,quote:l,receipt:p,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:o}){let r=await e.context(),a;try{a=await o()}catch(s){throw await n(r),s}return await t(r,a.usage),a},async wrapStream({doStream:o}){let r=await e.context(),a;try{a=await o()}catch(E){throw await n(r),E}let s=!1,l=!1,p=a.stream.getReader();async function v(){s||l||(l=!0,await n(r))}return{...a,stream:new ReadableStream({async pull(E){try{let{value:b,done:d}=await p.read();if(d){if(!s)throw await v(),new c("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(b.type==="finish"){if(s)throw new c("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");s=!0,await t(r,b.usage)}E.enqueue(b)}catch(b){try{await v()}finally{E.error(b),await p.cancel(b)}}},async cancel(E){try{await v()}finally{await p.cancel(E)}}})}}}}function kn(e){V(e.apiKey,"Funnel receipts are sent by your backend");let n=N(e);return{async signal(t){let o=Re.parse({...t,operation:"signal"}),r=st.parse(await n.request("funnels",o));if(r.runId!==t.runId||r.eventId!==t.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(t){let o=Re.parse({operation:"read_results",runId:t}),r=ct.parse(await n.request("funnels",o));if(r.runId!==t||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Result identity changed");return r}}}function Bn(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Campaign entry requires your backend");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(t){let o=Date.now()+(e.timeoutMs??3e4),r=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_decide"}),a=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,o-Date.now()))}),s=Y.parse(await a.request("funnels",r));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");return ge(s,r.customer,o,(l,p)=>Fe({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,p-Date.now()))}).read(l))},async start(t){let o=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_start"}),r=Vt.parse(await n.request("funnels",o));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||o.customer.type==="id"&&r.customerId!==o.customer.value))throw new c("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}var x=class extends Error{constructor(t,o=409,r=!1,a="fix_request"){super(t);this.code=t;this.status=o;this.retryable=r;this.recovery=a}code;status;retryable;recovery};function Pn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let n=ie.parse(e.manifest),t={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},o=n.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,a]of Object.entries(Se))if(a.command&&n.capabilities.includes(r)&&!(r==="catalog"&&n.catalog==="static")&&!e.handlers[a.command])throw new Error(`Missing merchant command handler: ${a.command}`);if(o&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!n.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(a){let s=crypto.randomUUID(),l="bridge.ping",p,v=async(E,b,d=!1)=>{let h=JSON.stringify({bridgeVersion:Q,requestId:s,command:l,scope:t,[d?"error":"data"]:E});if(new TextEncoder().encode(h).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(h,{status:b,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":s,...p?await ee(h,p,"response"):{}}})};try{if(a.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(Q)||a.method!=="POST"||new URL(a.url).pathname!==J)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(a.headers.get("Content-Type")??""))throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=a.body?.getReader();if(!E)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let b=new TextDecoder("utf-8",{fatal:!0}),d="",h=0;try{for(;;){let M=await E.read();if(M.done)break;if(h+=M.value.byteLength,h>16384)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",413);d+=b.decode(M.value,{stream:!0})}d+=b.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let y=ot.safeParse(JSON.parse(d));if(!y.success)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let S=y.data;if(s=S.requestId,l=S.command,Object.keys(t).some(M=>S.scope[M]!==t[M]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=S.command==="bridge.ping"||S.command==="bridge.describe",D=S.command==="catalog.read";if((k||D||a.headers.has(z))&&(p=e.authentication.find(M=>M.keyId===a.headers.get(z)),!p||!await te(d,a.headers,p,"request")))throw p=void 0,new x("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(S.command==="bridge.ping")return v(Ee["bridge.ping"].parse(S.data),200);if(S.command==="bridge.describe")return v(n,200);let g=Object.entries(Se).find(([,M])=>M.command===S.command);if(!g||!n.capabilities.includes(g[0]))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let i=e.handlers[S.command];if(!i)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!D&&a.headers.has("Cookie")&&(a.headers.get("Origin")!==new URL(a.url).origin||["cross-site","same-site"].includes(a.headers.get("Sec-Fetch-Site")??"")))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);let w=D?{kind:"service"}:await e.authorize(a,S),R=w.kind,C=["purchase.execute","subscription.change","refund.execute"].includes(S.command),A=C||S.command==="operation.read";if(!(A&&p!==void 0&&R==="service")&&(S.command==="refund.execute"?R!=="administrator":!D&&R!=="user"))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);if(w.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(S.command)&&!u.uuid().safeParse(w.customerId).success)throw new x("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let _=i,F=Ee[S.command].parse(S.data),B={request:a,command:S.command,scope:t,principal:w},T;if(A){let M=se.parse(F);if(w.kind==="user"&&w.customerId!==M.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let P=ce.parse(await e.resolveOperationAuthority(M,B));if(P.operationId!==M.operationId||P.customerId!==M.customerId||Object.keys(t).some(G=>P.scope[G]!==t[G]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);B.authority=P;let H=S.command==="purchase.execute"?"purchase":S.command==="subscription.change"?"subscription_change":S.command==="refund.execute"?"refund":P.instruction.type;if(P.instruction.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!C)T=we.parse(await _(F,B));else{if(P.confirmedAt===null)throw new x("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let G=we.parse(await e.handlers["operation.read"](M,{...B,command:"operation.read"}));if(G.operationId!==M.operationId||G.customerId!==M.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(G.lookup==="found")T=G.execution;else{if(!P.initialExecutionAllowed)throw new x("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(P.instruction.expiresAt)<=Date.now())throw new x("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!n.capabilities.includes("billing_records")||je(P.instruction).some(U=>!n.billingEvents.some(on=>on===U))||Ge(P.instruction).some(U=>!n.profiles.includes(U)))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=nt.parse(await _(F,B))}catch(U){throw U instanceof x?U:new x("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=rt[S.command].parse(await _(F,B));if(w.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==w.nativeUserId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&w.customerId&&T.session.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&w.customerId&&T.presentation.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==se.parse(S.data).operationId||T.customerId!==se.parse(S.data).customerId))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return v(T,C&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let b=E instanceof x?E:E instanceof SyntaxError?new x("MERCHANT_BRIDGE_INVALID_REQUEST",400):new x("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return v({code:b.code,message:b.code,retryable:b.retryable,recovery:b.recovery},b.status,!0)}}}function Dn(e){return async(n,t)=>{let o=()=>e.readSubscriptionOperation(n),r=()=>e.readSubscriptionUpdate(n),a=()=>e.readRefund(n),s=t.command==="purchase.execute"?[o]:t.command==="subscription.change"?[r]:t.command==="refund.execute"?[a]:[o,r,a];for(let l of s)try{let p=await l(),v="authority"in p.operation?p.operation.authority:void 0;if(!v)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ce.parse(v);if(E.customerId!==n.customerId||E.operationId!==n.operationId||Object.keys(t.scope).some(b=>E.scope[b]!==t.scope[b]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(p){if(t.command==="operation.read"&&p instanceof c&&p.code==="NOT_FOUND")continue;throw p}throw new x("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}function Fn(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let n=ke.parse(e.manifest),t=ae.parse(e.authentication),o={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},r=e.now??Date.now,a=d=>{throw new c("INVALID_RESPONSE",d)},s=(d,h)=>Ie(d)===Ie(h);function l(d){new TextEncoder().encode(d).byteLength>262144&&a("Merchant protocol body exceeds limit");try{return JSON.parse(d)}catch{return a("Invalid merchant protocol JSON")}}function p(d){let h=kt.parse(d);return s(h.scope,o)||a("Merchant protocol scope mismatch"),h.command==="requirement.check"&&(n.capabilities.includes("requirement_checks")||a("Merchant Check capability unavailable"),s(h.data.subject.scope,o)||a("Merchant Check subject crosses scope")),h.command==="operation.prepare"&&(!n.capabilities.includes("preparations")||!s(h.data.request.subject.scope,o))&&a("Merchant preparation capability unavailable"),h}function v(d){if(d.command!=="operation.prepare")return;let h=d.data;return(!s(h.request.subject.scope,o)||!h.preparationAllowed||Date.parse(h.requestedAt)>r()||Date.parse(h.request.expiresAt)<=r()||!n.preparationActions.includes(h.request.action))&&a("Merchant preparation requires fresh scoped authority"),h}function E(d,h){let y=Bt(d.command).parse(h);if((y.requestId!==d.requestId||!s(y.scope,o))&&a("Merchant reply correlation mismatch"),"error"in y)return y;if(d.command==="bridge.ping"&&"challenge"in y.data&&y.data.challenge!==d.data.challenge&&a("Merchant ping challenge mismatch"),d.command==="bridge.describe"&&"bridgeVersion"in y.data&&!s({projectId:y.data.projectId,environmentId:y.data.environmentId,environment:y.data.environment},o)&&a("Merchant declaration crosses scope"),d.command==="requirement.check"&&"observation"in y.data&&(!s(y.data.observation.subject,d.data.subject)||!Je(d.data.requirement,y.data)||!n.checkKinds.includes(y.data.kind))&&a("Merchant Check changed the original requirement or subject"),d.command==="operation.prepare"&&"quoteTermsDigest"in y.data){let S=v(d);(!s(y.data.request,S.request)||Date.parse(y.data.expiresAt)<=r()||Date.parse(y.data.observedAt)<Date.parse(S.requestedAt)||Date.parse(y.data.observedAt)>r())&&a("Merchant quote changed its authorized request or validity")}return y}let b=async d=>{let h=JSON.stringify(d);return l(h),{body:h,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[re]:"4",...await ee(h,t,"response",r(),4)})}};return{version:4,path:J,async encodeRequest(d,h){let y=p({bridgeVersion:4,requestId:crypto.randomUUID(),scope:o,command:d,data:h});v(y);let S=JSON.stringify(y);l(S);let k=new Headers({"Content-Type":"application/json",[re]:"4",...await ee(S,t,"request",r(),4)});return{body:S,headers:k,async readResponse(D,g){l(D),(g.get(re)!=="4"||!await te(D,g,t,"response",r(),4))&&a("Merchant response authentication failed");let i=E(y,l(D));if("error"in i)throw new ye(i.error);return i.data}}},async decodeRequest(d,h){l(d),(h.get(re)!=="4"||h.get(z)!==t.keyId||!await te(d,h,t,"request",r(),4))&&a("Merchant request authentication failed");let y=p(l(d));return v(y),y},async encodeResponse(d,h){let y=p(d),S=E(y,{...y,data:h});return b(S)},async encodeError(d,h){let y=p(d),{data:S,...k}=y;return b(E(y,{...k,error:Be.parse(h)}))}}}var ye=class extends Error{constructor(t){super(t.message);this.problem=t}problem};export{ne as FunnelDecisionTimeoutError,fe as FunnelProcessEntrySuppressedError,c as LongplayError,x as MerchantBridgeHandlerError,ye as MerchantBridgeProtocolError,fn as aiPriceSnapshotSchema,hn as aiTokenQuoteSchema,gn as createAiPricing,_n as createAiUsageMiddleware,dn as createConfigurationSync,yn as createConfiguredAiPricing,_e as createFeatureClient,Bn as createFunnelCampaignClient,Fe as createFunnelDecisionClient,he as createFunnelLocalEvaluator,kn as createFunnelOrchestrationClient,Rn as createFunnelProcessAdapter,ln as createFunnelStartClient,De as createGuestToken,mn as createLocalFunnelClient,Cn as createLongplayServer,Dn as createMerchantBridgeAuthorityResolver,Pn as createMerchantBridgeHandler,Fn as createMerchantBridgeProtocol,xn as createNativeReceiptClient,Tn as createPaywallStartClient,On as createSynchronizedFunnelLocalEvaluator,un as entitlementRequirementDigest,pn as evaluateFunnelNode,cn as merchantConfirmationMatchesTerms,an as merchantPreparationRequestDigest,sn as merchantQuoteTermsDigest,bn as renewFunnelRun,ee as signMerchantBridgeMessage,te as verifyMerchantBridgeMessage};
|
|
6
|
+
${e}`)}async function Nt(e){let n=ie.parse(e);return crypto.subtle.importKey("raw",Dt(n.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function te(e,n,t,o=Date.now(),r=X){let a=String(Math.floor(o/1e3)),s=new Uint8Array(await crypto.subtle.sign("HMAC",await Nt(n),Ft(e,t,a,r))),l=btoa(String.fromCharCode(...s)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Q]:n.keyId,[Pt]:`t=${a},v1=${l}`}}async function ne(e,n,t,o,r=Date.now(),a=X){try{if(n.get(Q)!==t.keyId)return!1;let s=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(n.get(Pt)??"");return!s||Math.abs(r/1e3-Number(s[1]))>300?!1:await crypto.subtle.verify("HMAC",await Nt(t),Dt(s[2]),Ft(e,o,s[1],a))}catch{return!1}}var Lt=u.strictObject({operation:u.literal("renew_run"),runId:u.uuid(),customerId:u.uuid()}),le=ft.refine(e=>!!e.runToken,"Renewal returns a credential"),Ut=ht.refine(e=>!!e.runToken,"Renewal returns a credential");var Pe=u.discriminatedUnion("operation",[u.strictObject({operation:u.literal("campaign_decide"),...pt}).refine(be,Ae),u.strictObject({operation:u.literal("campaign_start"),funnelId:u.uuid(),requestId:u.uuid(),customer:ut,customerData:dt.optional(),locale:u.string().min(1).max(35),parameters:ue,cooldownSeconds:u.number().int().min(1).max(2592e3)}).refine(be,Ae)]),Sn=u.union([u.strictObject({scope:Y,suppressed:u.literal(!0),reason:u.enum(["frequency","in_progress"]),retryAt:u.iso.datetime({offset:!0})}),le]),Vt=u.union([Sn.options[0],Ut]);var qt=u.discriminatedUnion("provider",[u.strictObject({provider:u.literal("apple"),orderId:u.uuid(),receiptId:u.uuid(),signedTransaction:u.string().min(1).max(131072)}),u.strictObject({provider:u.literal("google"),orderId:u.uuid(),receiptId:u.uuid(),purchaseToken:u.string().min(1).max(16384)})]),Ht=u.strictObject({orderId:u.uuid(),receiptId:u.uuid(),transactionIds:u.array(u.string().min(1).max(255)).min(1).max(50),membership:u.boolean()});var Gt=u.strictObject({operation:u.literal("native_receipt"),requestId:u.uuid(),customerToken:u.string().regex(Ne),orderId:u.uuid(),receiptId:u.uuid(),nativeEvidence:qt.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),jt=u.strictObject({scope:Y,requestId:u.uuid(),orderId:u.uuid(),receiptId:u.uuid(),orderStatus:u.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:u.boolean(),nativeCompletion:Ht.optional()});var zt=u.strictObject({document:mt,configuration:z.options[0]});function me(e){return{async getCustomer(n){let t=m.getCustomer;return f(e,t,n,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(n={}){let t=m.listCustomers;return f(e,t,n,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(n){let t=m.updateCustomer;return f(e,t,n,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(n){let t=m.createGuestCustomer;return f(e,t,n)},async resumeGuestSession(n){let t=m.resumeGuestSession;return f(e,t,n)},async claimGuestCustomer(n){let t=m.claimGuestCustomer;return f(e,t,n)},async revokeCustomerSessions(n){let t=m.revokeSessions;return f(e,t,n)},async createCustomerSession(n){return f(e,m.createSession,{customerId:n},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(n){return f(e,m.createCustomer,n,{request:"Invalid customer input",response:"Invalid customer response"})}}}function Kt(e){return{async checkEntitlement(n){let t=m.checkEntitlement,o=t.request.parse(n),r=await f(e,t,o,I);return Et(o.requirement,r.check,o.customerId,r.scope),r},async readHoldings(n){let t=m.readHoldings;return f(e,t,n,I)},async readSeats(n){let t=m.readSeats;return f(e,t,n,I)},async manageSeat(n){let t=m.manageSeat;return f(e,t,n,I)}}}function $t(e){return{async readAiPricing(n){let t=m.readAiPricing;return f(e,t,n,I)},async readUsage(n){let t=m.readUsage;return f(e,t,n,I)},async setUsage(n){let t=m.setUsage;return f(e,t,n,I)},async manageBalanceGrant(n){let t=m.manageBalanceGrant;return f(e,t,n,I)},async readBalanceSource(n){let t=m.readBalanceSource;return f(e,t,n,I)},async adjustBalance(n){let t=m.adjustBalance;return f(e,t,n,I)},async listBalanceGrants(n){let t=m.listBalanceGrants;return f(e,t,n,I)},async manageBillingLimits(n){let t=m.manageBillingLimits;return f(e,t,n,I)},async manageUsageEntity(n){let t=m.manageUsageEntity;return f(e,t,n,I)},async readUsageAnalytics(n){let t=m.readUsageAnalytics;return f(e,t,n,I)},async readCreditAnalytics(n){let t=m.readCreditAnalytics;return f(e,t,n,I)},async submitUsageBatch(n){let t=m.submitUsageBatch;return f(e,t,n,I)},async readUsageBatch(n){let t=m.readUsageBatch;return f(e,t,n,I)},async readLedger(n){let t=m.readLedger;return f(e,t,n,I)},async readCreditStatement(n){let t=m.readCreditStatement;return f(e,t,n,I)},async quoteBalance(n){let t=m.quoteBalance;return f(e,t,n,I)},async trackUsage(n){let t=m.trackUsage;return f(e,t,n,I)},async mutateBalance(n){let t=m.mutateBalance;return f(e,t,n,I)}}}function Qt(e){return{async listInvoiceTemplates(n={}){let t=m.listInvoiceTemplates;return f(e,t,n,I)},async previewInvoice(n){let t=m.previewInvoice;return f(e,t,n,I)},async createInvoice(n){let t=m.createInvoice;return f(e,t,n,I)},async prepareBillingAdjustment(n){let t=m.prepareBillingAdjustment;return f(e,t,n,I)},async manageInvoice(n){let t=m.manageInvoice;return f(e,t,n,I)},async readInvoiceOperation(n){let t=m.readInvoiceOperation;return f(e,t,n,I)},async listInvoices(n){let t=m.listInvoices;return f(e,t,n,I)},async getInvoice(n){let t=m.getInvoice;return f(e,t,n,I)},async setupPayment(n){let t=m.setupPayment;return f(e,t,n,I)},async readPaymentSetup(n){let t=m.readPaymentSetup;return f(e,t,n,I)},async readBillingInvoice(n){let t=m.readBillingInvoice;return f(e,t,n,I)},async previewRefund(n){let t=m.previewRefund;return f(e,t,n,I)},async refund(n){let t=m.refund;return f(e,t,n,I)},async readRefund(n){let t=m.readRefund;return f(e,t,n,I)}}}function Jt(e){return{async previewSubscriptionBatch(n){let t=m.previewSubscriptionBatch;return f(e,t,n,I)},async confirmSubscriptionBatch(n){let t=m.confirmSubscriptionBatch;return f(e,t,n,I)},async readSubscriptionBatch(n){let t=m.readSubscriptionBatch;return f(e,t,n,I)},async abandonSubscriptionBatch(n){let t=m.abandonSubscriptionBatch;return f(e,t,n,I)},async manageSubscriptionTrial(n){let t=m.manageSubscriptionTrial;return f(e,t,n,I)},async readSubscriptionTrial(n){let t=m.readSubscriptionTrial;return f(e,t,n,I)},async listSubscriptions(n){let t=m.listSubscriptions;return f(e,t,n,I)},async listPurchases(n){let t=m.listPurchases;return f(e,t,n,I)},async listSubscriptionConflicts(n){let t=m.listSubscriptionConflicts;return f(e,t,n,I)},async retrySubscriptionConflict(n){let t=m.retrySubscriptionConflict;return f(e,t,n,I)},async previewUpdate(n){let t=m.previewUpdate;return f(e,t,n,I)},async update(n){let t=m.update;return f(e,t,n,I)},async readSubscriptionUpdate(n){let t=m.readSubscriptionUpdate;return f(e,t,n,I)},async restoreNativePurchase(n){let t=m.restoreNativePurchase;return f(e,t,n,I)},async verifySubscriptions(n){let t=m.verifySubscriptions;return f(e,t,n,I)},async previewAttach(n){let t=m.previewAttach;return f(e,t,n,I)},async recordMerchantEvent(n){return f(e,m.recordMerchantEvent,n,{request:"Invalid merchant event",parseResponse:I})},async attach(n){let t=m.attach;return f(e,t,n,I)},async readSubscriptionOperation(n){let t=m.readSubscriptionOperation;return f(e,t,n,I)}}}function Yt(e){return{async grantModelBenefit(n){return f(e,m.grantModelBenefit,n,{request:"Invalid model benefit grant",response:"Invalid model benefit response"})},async readModelBenefit(n){return f(e,m.readModelBenefit,n,{request:"Invalid model benefit operation",response:"Invalid model benefit response"})},async grantOffer(n){let t=m.grantOffer;return f(e,{...t,request:t.request.refine(o=>!!o.customerId)},{...n,requestId:n.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function Xt(e){return{...Kt(e),...$t(e),...Qt(e),...Jt(e),...Yt(e)}}function Wt(e){return{async getFeatures(n={}){let t=m.getFeatures;return f(e,t,n,I)},async evaluateFeatures(n){let t=m.evaluateFeatures;return f(e,t,n,I)}}}function Zt(e){return{async trackEvents(n){let t=m.trackEvents;return f(e,t,n,I)}}}function en(e){return{async resolveContent(n){let t=m.resolveContent;return f(e,t,n,I)},async resolvePaywall(n){let t=m.resolvePaywall,o=t.request.parse(n),r=await f(e,t,o,I);return _e(o,r.paywall.check,r.scope),r},async resolveOffering(n){let t=m.resolveOffering,o=t.request.parse(n),r=await f(e,t,o,I);return _e(o,r.check,r.scope),r}}}function Cn(e){V(e.apiKey,"Secret API keys must stay on your backend");let t=N(e).request;return{async sendMessage(o){let r=m.sendMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},async readMessage(o){let r=m.readMessage;return r.response.parse(await t(r.path,r.request.parse(o)))},...me(t),...Xt(t),...Wt(t),...Zt(t),...en(t)}}function De(){if(typeof window<"u")throw new c("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 tn=()=>new c("CONFLICT","Process synchronization is in progress",425),L=()=>new c("CONFLICT","This process belongs to a different account",409,void 0,{reason:"CUSTOMER_BINDING_CONFLICT"}),En=(e,n)=>JSON.stringify(e)===JSON.stringify(n),fe=class extends c{constructor(t){super("CONFLICT","Funnel entry is suppressed",409,void 0,{reason:t.reason==="in_progress"?"OPERATION_IN_PROGRESS":"STATE_CHANGED",recovery:"check_availability"});this.result=t}result};function Rn(e){if(V(e.apiKey,"Funnel process identity belongs to your backend"),e.session)throw new c("INVALID_CONFIGURATION","The process adapter owns its credential lifecycle");let n=N(e),t=me(n.request),o=`longplay:process:${e.scope.projectId}:${e.scope.environment}:`;async function r(g){let i=await e.resolveUser(g);if(i!==null&&(typeof i?.externalUserId!="string"||!i.externalUserId||i.externalUserId!==i.externalUserId.trim()||i.externalUserId.startsWith("gg_guest_")))throw new c("INVALID_RESPONSE","The merchant identity resolver returned an invalid subject");return i}async function a(g){let i=await e.resolveContext(g);if(i?.confirmed!==!0||!i.processKey||!i.guestKey)throw new c("INVALID_CONFIGURATION","A confirmed durable process handle is required");return{process:o+"run:"+i.processKey,guest:o+"guest:"+i.guestKey}}async function s(g,i){for(let w=0;w<8;w++){let R=await e.store.read(g),C=i(R?structuredClone(R.value):null);if(R&&En(R.value,C)||await e.store.compareAndSwap(g,R?.revision??null,C))return C}throw tn()}async function l(g){let i=await e.store.read(g);if(!i)throw new c("NOT_FOUND","Open the process before continuing",404);return i.value}async function p(g){let i=await l(g);for(let w of i.revocations??[])await t.revokeCustomerSessions(w),await s(g,R=>{if(!R)throw L();return R.revocations=R.revocations?.filter(C=>C.sessionId!==w.sessionId),R})}async function v(g,i){let w=Te.parse(g);return i?n.requestWithCredential("funnel-processes",w,i):n.request("funnel-processes",w)}function E(g,i){if(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment||g.run&&(g.run.id!==i.run.id||g.run.source.versionId!==i.run.source.versionId||g.run.source.id!==i.run.source.id||g.run.runExpiresAt!==i.run.runExpiresAt||g.run.identity.startedAs!==i.run.identity.startedAs||g.run.identity.participantId!==i.run.identity.participantId||g.run.identity.binding&&g.run.identity.binding.id!==i.run.identity.binding?.id)||g.runToken&&i.runToken&&g.runToken!==i.runToken)throw new c("INVALID_RESPONSE","Process identity or Run changed")}async function b(g,i,w){return s(g,R=>{if(!R)throw new c("NOT_FOUND","Process handle is missing",404);return E(R,i),(!R.run||i.run.revision>=R.run.revision)&&(R.run=i.run),R.runToken??=i.runToken,w!==void 0&&(R.target=w),R})}async function d(g,i){if(i.detached)throw new c("UNAUTHENTICATED","The process is detached",401);let w=i.run?.identity.binding?.customerId??i.run?.identity.participantId;if(!w)throw new c("INVALID_RESPONSE","Process participant is missing");if(i.session?.customerId===w&&Date.parse(i.session.expiresAt)>Date.now()+3e4)return i.session;let R={id:crypto.randomUUID(),until:Date.now()+(e.timeoutMs??35e3)+5e3},C=await s(g,O=>{if(!O||O.detached||O.run?.id!==i.run?.id)throw L();if(O.sessionLease&&O.sessionLease.until>Date.now())throw tn();return O.sessionLease=R,O}),A;try{if(C.session?.customerId===w&&Date.parse(C.session.refreshExpiresAt)>Date.now())try{if(A=Le.parse(await n.requestWithCredential("customer-sessions/refresh",{},C.session.refreshToken)),A.sessionId!==C.session.sessionId)throw new c("INVALID_RESPONSE","Refresh changed the logical session")}catch(M){if(!(M instanceof c)||M.status!==401)throw M}if(A??=C.run?.identity.binding?await t.createCustomerSession(w):await t.resumeGuestSession({guestToken:C.guest.token}),A.customerId!==w)throw new c("INVALID_RESPONSE","Session Customer changed");let O=A;return await s(g,M=>{if(!M||M.detached||M.sessionLease?.id!==R.id||M.run?.identity.binding?.id!==i.run?.identity.binding?.id)throw new c("CONFLICT","Process identity changed during session issuance",409,void 0,{reason:"IDENTITY_CONTEXT_CHANGED",recovery:"reload_state"});return M.session=O,delete M.sessionLease,M}),A}catch(O){throw A&&A.sessionId!==C.session?.sessionId&&await t.revokeCustomerSessions({customerId:A.customerId,sessionId:A.sessionId}).catch(()=>{}),await s(g,M=>{if(!M)throw L();return M.sessionLease?.id===R.id&&delete M.sessionLease,M}).catch(()=>{}),O}}let h;async function y(){if(h??=vt.parse(await v({contract:q,operation:"describe"})),h.scope.projectId!==e.scope.projectId||h.scope.environment!==e.scope.environment)throw L();return h}async function S(g,i,w=!1){let R=await r(g),C=await l(i);if(C.issuingKeyId!==(await y()).keyId)throw new c("INVALID_CONFIGURATION","Restore this process with its original issuing Server Key");if(!C.runToken||!C.run)throw new c("CONFLICT","Recover the original start first",425);if(C.detached){if(!w)throw new c("UNAUTHENTICATED","Explicitly restore the process after sign-in",401);if(C.run.identity.binding&&(!R||C.target&&C.target!==R.externalUserId))throw L();await p(i),C=await s(i,A=>{if(!A||A.run?.id!==C.run?.id)throw L();return delete A.detached,A})}if(!C.runToken||!C.run)throw new c("INVALID_RESPONSE","Process identity is missing");if(C.run.identity.binding){if(R&&!C.target){let A=xe.parse(await v({contract:q,operation:"binding_status",runToken:C.runToken,requestId:C.bindingIntent?.requestId??C.start.requestId,externalUserId:R.externalUserId}));if(A.state!=="bound"||A.binding.id!==C.run.identity.binding.id)throw L();C=await s(i,O=>{if(!O)throw L();return O.target=R.externalUserId,O})}if(!R||C.target!==R.externalUserId)throw L()}else if(R){if(!C.guest)throw L();C=await s(i,O=>{if(!O||O.bindingIntent&&O.bindingIntent.externalUserId!==R.externalUserId)throw L();return O.bindingIntent??={requestId:crypto.randomUUID(),externalUserId:R.externalUserId},O});let A=C.bindingIntent;try{let O=wt.parse(await v({contract:q,operation:"bind_customer",...A,runToken:C.runToken,guestToken:C.guest.token,claimRequestId:C.guest.claimRequestId,expectedBindingId:null}));C=await b(i,O,R.externalUserId)}catch(O){let M=xe.parse(await v({contract:q,operation:"binding_status",...A,runToken:C.runToken,guestToken:C.guest.token}));if(M.state!=="bound")throw O;C=await s(i,F=>{if(!F?.run||F.run.id!==M.binding.runId)throw L();return F.run.identity.binding={id:M.binding.id,customerId:M.binding.customerId,acceptedAt:M.binding.acceptedAt},F.target=R.externalUserId,F})}}return{state:C,session:await d(i,C)}}async function k(g,i,w,R){try{return await R(w)}catch(C){if(!(C instanceof c)||C.status!==401)throw C;return await s(i,A=>{if(!A||A.detached)throw C;return A.session?.accessToken===w.session.accessToken&&(A.session.expiresAt=new Date(0).toISOString()),A}),R(await S(g,i))}}async function D(g,i,w=!1){let R=await a(g),C=await S(g,R.process,w),A=ae.parse(await k(g,R.process,C,O=>v({...i,customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A}return{async open(g,i){i=It.parse(i);let w=await a(g),R=await y(),C=w.guest+":"+R.keyId,A=await e.store.read(w.process);if(!A){let B=await r(g),T,_,P;if(B)T={type:"customer",customer:{type:"externalUserId",value:B.externalUserId}};else{let H=await e.store.read(C);if(H)try{P=await t.resumeGuestSession({guestToken:H.value.token}),_=H.value}catch(U){if(!(U instanceof c)||U.status!==401)throw U}let G={token:De(),claimRequestId:crypto.randomUUID()};_=await s(C,U=>_??(U&&U.token!==H?.value.token?U:G)),T={type:"guest",guestToken:_.token}}await s(w.process,H=>H??{issuingKeyId:R.keyId,start:Te.parse({...i,contract:q,requestId:crypto.randomUUID(),source:T}),..._?{guest:_}:{},...B?{target:B.externalUserId}:{},...P?{session:P}:{}}),A=await e.store.read(w.process)}let O=A.value;if(O.issuingKeyId!==R.keyId)throw new c("INVALID_CONFIGURATION","Restore the original issuing Server Key before retrying this start");if(O.start.funnelId!==i.funnelId||O.start.operation!==i.operation)throw new c("CONFLICT","This handle already owns another process",409);if(!O.runToken){if(O.start.source.type==="customer"){let P=await r(g);if(!P||P.externalUserId!==O.target)throw L()}let B=await v(O.start),T=yt.safeParse(B);if(T.success)throw new fe(T.data);let _=ae.parse(B);if(!_.runToken)throw new c("INVALID_RESPONSE","Process credential is missing");O=await b(w.process,_)}let M=await S(g,w.process,!0),F=ae.parse(await k(g,w.process,M,B=>v({contract:q,operation:"get",customerToken:B.session.accessToken},B.state.runToken)));return await b(w.process,F),{...F,runToken:O.runToken}},async syncIdentity(g){return D(g,{contract:q,operation:"get",customerToken:""},!0)},async get(g,i={}){return D(g,{...i,contract:q,operation:"get",customerToken:""})},async review(g,i){return D(g,{contract:q,operation:"review",customerToken:"",...i?{receiptId:i}:{}})},async command(g,i,w){let R=await a(g),C=await S(g,R.process),A=ae.parse(await k(g,R.process,C,O=>v({contract:q,operation:"command",command:i,identity:{bindingId:w},customerToken:O.session.accessToken},O.state.runToken)));return await b(R.process,A),A},async pageExperiments(g,i,w=[]){let R=await a(g),C=await S(g,R.process);return gt.parse(await k(g,R.process,C,A=>v({contract:q,operation:"page_experiments",release:i,usedReceiptIds:w,customerToken:A.session.accessToken},A.state.runToken)))},async detach(g){let i=await a(g);await s(i.process,w=>{if(!w)throw L();return w.session&&!w.revocations?.some(R=>R.sessionId===w.session.sessionId)&&(w.revocations??=[]).push({customerId:w.session.customerId,sessionId:w.session.sessionId}),w.detached=!0,delete w.session,delete w.sessionLease,w}),await p(i.process)},destroy(){n.dispose()}}}async function bn(e,n){V(e.apiKey,"Renewal requires your backend");let t=N(e),o=le.parse(Rt(e,await t.request("funnels",Lt.parse({...n,operation:"renew_run"}))));if(o.run.id!==n.runId)throw new c("INVALID_RESPONSE","Run renewal identity changed");return o}function nn(e){let n=At(e),t=l=>{throw new c("INVALID_RESPONSE",l)};n.nodes.size!==e.topology.nodes.length&&t("Duplicate local node identity"),n.nodes.get(e.topology.entry)?.type!=="entry"&&t("A local Funnel must start at Entry");let o=new Set(["entry","condition","feature","split","end","output"]);for(let l of n.nodes.values()){if(!o.has(l.type))throw new c("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(l.type==="entry"&&l.id!==e.topology.entry&&t("Unexpected Entry node"),["entry","feature"].includes(l.type)&&!l.outputs.next&&t("Local next exit is unavailable"),l.type==="feature"){let p=l.resources.featureKey;(!p||!Object.hasOwn(e.evaluation.variables,l.writes.value)||!Object.hasOwn(n.features,p))&&t("Local Feature definition or declaration is unavailable")}if(l.type==="condition"){let p=e.conditions[l.id];(!p||!l.outputs.default||p.some((v,E)=>v.port!==`case:${E}`||!l.outputs[v.port]))&&t("Local Condition exits are unavailable")}if(l.type==="split"&&(!l.resources.experimentId||!Object.hasOwn(e.growth.experiments,l.resources.experimentId)||!l.outputs.notParticipating)&&t("Local Experiment definition or exit is unavailable"),l.type==="end"||l.type==="output"){let p=e.evaluation.terminals[l.id];if(!p)throw new c("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(l.outputs).length&&t("A terminal cannot have outgoing edges"),p.output?.type==="feature"&&!Object.hasOwn(n.features,p.output.featureKey)&&t("Terminal Feature definition is unavailable")}for(let p of Object.values(l.outputs))n.nodes.has(p)||t("Local target is unavailable")}let r=new Set,a=new Set;function s(l){if(a.has(l)&&t("Local graph contains a cycle"),!r.has(l)){a.add(l);for(let p of Object.values(n.nodes.get(l).outputs))s(p);a.delete(l),r.add(l)}}return s(e.topology.entry),r.size!==n.nodes.size&&t("Local graph contains unreachable nodes"),{evaluate(l){let p={},v=l.context;v.features=n.features,v.savedGroups=n.savedGroups;let E=()=>{v.attributes=it({declarations:e.evaluation.variables,attributes:l.attributes,parameters:l.parameters,answers:{},results:p,savedGroups:n.savedGroups})};E();let b=e.topology.entry,d=0;for(;;){let h=n.nodes.get(b);if(h.type==="end"||h.type==="output"){let y=e.evaluation.terminals[b],S=y.output,k=S?.type==="feature"?n.feature(S.featureKey,v):S?.type==="variable"?et({source:"variable",key:S.key,...S.path?{path:S.path}:{}},{declarations:e.evaluation.variables,answers:{},results:p,parameters:l.parameters,attributes:l.attributes,savedGroups:n.savedGroups}):S?.value??null;return ve(e.evaluation.outputSchema,k)||t("Local output does not match its declaration"),{outcome:y.outcome,value:k}}if(d++>=e.evaluation.maxTransitions)throw new c("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(h.type==="entry")b=h.outputs.next;else{let y=n.evaluate(b,v);if(h.type==="feature"){let S=h.writes.value,k=y.value??null;ve(e.evaluation.variables[S],k)||t("Local Feature value does not match its declaration"),Ze(e.evaluation.variables,{writes:h.writes},{[S]:k}),p[S]=k,E()}b=y.target}}}}}function rn(e,n,t){let o=Xe.parse(e.attributes);if(["parameters","answers","results"].some(g=>Object.hasOwn(o,g)))throw new c("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let r=ue.parse(e.parameters??{}),a=u.record(u.string(),We).parse(e.stickyBucketAssignmentDocs??{});for(let[g,i]of Object.entries(a))if(g!==`${i.attributeName}||${i.attributeValue}`||!Object.hasOwn(o,i.attributeName)||Ye(o[i.attributeName])!==i.attributeValue)throw new c("INVALID_REQUEST","Sticky document identity does not match this session");let s=e.saveStickyBucketAssignmentDoc,l=e.onFeatureUsage,p=e.onExperimentViewed,v=e.onError,E=new Map,b=new Set,d={},h=Promise.resolve();function y(g){let i=h.then(()=>(t(),g()));return h=i.catch(()=>{}),i}function S(g){try{v?.(g)}catch{}}function k(g){try{let i=g();i&&typeof i.catch=="function"&&i.catch(S)}catch(i){S(i)}}async function D(){for(let[g,i]of E){if(t(),s)try{await s(structuredClone(i))}catch{throw new c("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}t(),E.delete(g)}}return{evaluate(g={}){let i=g.track===!0;return y(async()=>{let w=await n();t(w);let R=new Set(b),C={...d},A=new Map,O=[],M={stickyBucketAssignmentDocs:structuredClone(a),saveStickyBucketAssignmentDoc(T){A.set(`${T.attributeName}||${T.attributeValue}`,structuredClone(T))},...i?{trackedExperiments:R,trackedFeatureUsage:C,onExperimentViewed(T,_){let P=structuredClone(T),H=structuredClone(_);p&&O.push(()=>p(structuredClone(P),structuredClone(H)))},onFeatureUsage(T,_){let P=structuredClone(_);l&&O.push(()=>l(T,structuredClone(P)))}}:{}},F=w.program.evaluate({attributes:o,parameters:r,context:M});t(w);for(let[T,_]of A)a[T]=_,E.set(T,_);await D(),t(w),i&&(b=R,d=C);for(let T of O)k(T);let B=w.configuration;return structuredClone({evaluationMode:"local",scope:B.scope,funnelId:B.funnelId,versionId:B.versionId,evaluationRevision:B.evaluationRevision,generation:B.growth.generation,...F})})},flush:()=>y(D),get stickyBucketAssignmentDocs(){return t(),structuredClone(a)}}}var An=6e4;function he(e){if(typeof window<"u")throw new c("SERVER_ONLY","Local Funnel sessions run on your backend");let n=Y.parse(e.scope),t=e.funnelId,o=e.load,r,a,s,l=0,p=b=>Date.now()>=b.expiresAt;async function v(){if(a)return a;let b=l;r=void 0;let d=(async()=>{let h=await o();if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(h&&typeof h=="object"&&"evaluationMode"in h&&h.evaluationMode==="remote")throw I(z,h),new c("EVALUATION_MODE","This Funnel requires remote decide");let y=I(St,h);if(b!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(y.scope.projectId!==n.projectId||y.scope.environment!==n.environment||y.funnelId!==t)throw new c("SCOPE_MISMATCH","Local configuration scope changed");if(y.growth.scope.projectId!==n.projectId||y.growth.scope.environment!==n.environment||y.growth.expiresAt!==y.expiresAt)throw new c("INVALID_RESPONSE","GB configuration scope or expiry changed");let S=Math.min(Date.now()+An,y.expiresAt?Date.parse(y.expiresAt):1/0);if(Date.now()>=S)throw new c("CONFIGURATION_EXPIRED","Refresh expired local rules");let k=JSON.stringify([n.projectId,n.environment,t,y.versionId,y.evaluationRevision,y.growth.generation]),D=[y.topology,y.conditions,y.evaluation,y.growth.features,y.growth.experiments,y.growth.savedGroups];if(s?.key===k&&!Tt(s.body,D))throw new c("INVALID_RESPONSE","Immutable local configuration identity changed");return s?.key!==k&&(s={key:k,body:D,program:nn(y)}),r={key:k,configuration:y,expiresAt:S,program:s.program},r})();a=d;try{return await d}finally{a===d&&(a=void 0)}}function E(){return a??(r&&!p(r)?Promise.resolve(r):v())}return{session(b){let d=l;return rn(b,E,h=>{if(e.assertUsable?.(),d!==l)throw new c("IDENTITY_CHANGED","Local evaluator was reset");if(h&&(p(h)||r?.key!==h.key))throw new c("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await v()).configuration)},reset(){l++,r=void 0,a=void 0,s=void 0}}}function On(e,n){let t=e.snapshot?.generation,o=he({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n,load:()=>e.localFunnel(n),assertUsable:()=>e.assertFunnel(n)}),r=e.subscribe(()=>{let s=e.snapshot?.generation;e.fresh&&s!==t&&(t=s,o.refresh().catch(()=>{}))}),a=o.session;return Object.assign(o,{session(s){let l=a(s),p=l.evaluate;return Object.assign(l,{async evaluate(...v){return e.fresh||await e.refresh(),p(...v)}})},destroy(){r(),o.reset()}})}function Tn(e){if(typeof window<"u")throw new c("SERVER_ONLY","Secret API keys must stay on the backend");return{start:n=>xt(e,n)}}var re=class extends c{constructor(t,o){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,o);this.decisionId=t;this.decisionRequestId=o}decisionId;decisionRequestId};async function ge(e,n,t,o){let{decisionId:r,requestId:a}=e,s=e,l=250,p=0;for(;;){if(s.decisionId!==r||s.requestId!==a||s.decision&&!pe(s.decision,n))throw new c("INVALID_RESPONSE","Decision request or customer changed");if(s.decision)return s.decision;if(s.status==="failed")throw new c("DECISION_FAILED","Decision execution failed",503,a);if(Date.now()>=t)throw new re(r,a);if(await new Promise(v=>setTimeout(v,Math.min(Math.max(l,p-Date.now()),t-Date.now()))),Date.now()>=t)throw new re(r,a);l=Math.min(1e3,l*2);try{s=await o(r,t)}catch(v){if(v instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(v.code)){p=Date.now()+(v.retryAfterSeconds??0)*1e3;continue}throw v}}}function Fe(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Funnel decisions are requested by your backend");let n,t,o=new Map;async function r(p,v){let E=p;E.status!=="pending"&&o.delete(E.decisionId);for(let b=0;b<32&&E.evaluation;b++){let d=E.evaluation;if(d.runId!==E.decisionId)throw new c("INVALID_RESPONSE","Local evaluation Run changed");let h=o.get(E.decisionId);if(!h&&d.type==="evaluate_segment"){let S=zt.parse(await a({operation:"segment_configuration",funnelId:e.funnelId,versionId:d.versionId},v));if(S.configuration.scope.projectId!==e.scope.projectId||S.configuration.scope.environment!==e.scope.environment||S.configuration.funnelId!==e.funnelId||S.configuration.versionId!==d.versionId||S.configuration.evaluationRevision!==d.policyRevision)throw new c("SCOPE_MISMATCH","Original decision segment configuration changed");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding decisions first");h={operation:"commit_decision_segment",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,`segment:${d.revision}`),nodeId:d.nodeId,visit:d.visit,revision:d.revision,policyRevision:d.policyRevision,generation:S.configuration.growth.generation,...Ot(S.configuration,S.document,d)},o.set(E.decisionId,h)}if(!h){if(d.type!=="evaluate")throw new c("INVALID_RESPONSE","Unknown decision instruction");if((!t||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision||t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())&&(t=z.parse(await a({operation:"configuration",funnelId:e.funnelId,versionId:d.versionId},v))),t.scope.projectId!==e.scope.projectId||t.scope.environment!==e.scope.environment||t.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(t.evaluationMode!=="local"||t.versionId!==d.versionId||t.evaluationRevision!==d.policyRevision)throw new c("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(o.size>=128)throw new c("COMMAND_PENDING","Reconcile outstanding Local decisions first");h={operation:"evaluate_decision",decisionId:E.decisionId,requestId:Oe(E.decisionId,d.visit,"evaluation"),nodeId:d.nodeId,visit:d.visit,revision:d.revision,receiptId:d.receiptId,policyRevision:d.policyRevision,generation:t.growth.generation,result:Ct(t,d.nodeId,d,bt)},o.set(E.decisionId,h)}let y=Z.parse(await a(h,v));if(y.decisionId!==p.decisionId||y.requestId!==p.requestId)throw new c("INVALID_RESPONSE","Decision identity changed during local evaluation");o.delete(E.decisionId),E=y}return E}async function a(p,v,E=!1){return N({...e,fetch:(d,h)=>{let y=new Headers(h?.headers);return y.set("Accept-Encoding","identity"),E&&y.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(d,{...h,headers:y})},timeoutMs:Math.min(e.timeoutMs??1e4,v?Math.max(1,v-Date.now()):12e4)}).request("funnels",p)}async function s(p,v){let E=Z.parse(await a(de.parse({operation:"read_decision",decisionId:p}),v));if(E.decisionId!==p)throw new c("INVALID_RESPONSE","Decision identity changed");return r(E,v)}async function l(p,v,E=!1){let b=de.options[0].parse({...p,operation:"decide",funnelId:e.funnelId}),d;try{d=Z.parse(await a(b,v,E))}catch(h){throw h instanceof c&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(h.code)?new c("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",h.status,p.requestId):h}if(d.requestId!==p.requestId||d.decision&&!pe(d.decision,b.customer))throw new c("INVALID_RESPONSE","Decision request or customer changed");return{response:await r(d,v),customer:b.customer}}return{local(){return n??=he({scope:e.scope,funnelId:e.funnelId,load:()=>a({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let p=z.parse(await a({operation:"configuration",funnelId:e.funnelId}));if(p.scope.projectId!==e.scope.projectId||p.scope.environment!==e.scope.environment||p.funnelId!==e.funnelId)throw new c("SCOPE_MISMATCH","Configuration scope changed");return p},features(p={}){return Me({...p,scope:e.scope,load:async()=>at.parse(await a({operation:"feature_config",funnelId:e.funnelId}))})},read:p=>s(p),async submit(p){return(await l(p,void 0,!0)).response},async decide(p){let v=Date.now()+3e4,E=await l(p,v);return ge(E.response,E.customer,v,s)},async reportUsed(p){let v=lt.parse(await a(de.parse({...p,operation:"report_used"})));if(v.decisionId!==p.decisionId||v.eventId!==p.eventId)throw new c("INVALID_RESPONSE","Usage receipt identity changed");return v}}}function xn(e){V(e.apiKey,"Native receipts are verified by your backend","Server API key required");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(t){let o=Gt.parse(t);if(o.orderId!==o.receiptId)throw new c("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let r=o.nativeEvidence,a={requestId:o.requestId,customerToken:o.customerToken,purchaseIntentId:o.orderId,...r===null?{intent:"read"}:r.provider==="apple"?{provider:"apple",signedTransaction:r.signedTransaction}:{provider:"google",purchaseToken:r.purchaseToken}},s=m.restoreNativePurchase.response.parse(await n.request(m.restoreNativePurchase.path,a));if(s.operation.requestId!==o.requestId||s.operation.purchaseIntentId!==o.orderId)throw new c("INVALID_RESPONSE","Native receipt request identity changed");let l=jt.parse({scope:s.scope,requestId:o.requestId,orderId:s.operation.orderId,receiptId:s.operation.orderId,orderStatus:s.operation.status,refunded:s.operation.refunded,...s.operation.completion===null?{}:{nativeCompletion:{orderId:s.operation.orderId,receiptId:s.operation.orderId,...s.operation.completion}}});if(l.requestId!==o.requestId||l.orderId!==o.orderId||l.receiptId!==o.receiptId||l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Current order receipt scope changed");return l}}}var J=u.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function _n(e,n){let t=J.parse(e.inputTokens.total),o=J.parse(e.outputTokens.total),r=J.parse(e.inputTokens.cacheRead??0),a=J.parse(e.inputTokens.cacheWrite??0),s=J.parse(e.outputTokens.reasoning??0);if(r+a>t||s>o||e.inputTokens.noCache!==void 0&&J.parse(e.inputTokens.noCache)!==t-r-a||e.outputTokens.text!==void 0&&J.parse(e.outputTokens.text)!==o-s)throw new c("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:t-r-a,cache_read:r,cache_write:a,output:n==="output"?o:o-s,reasoning:n==="separate"?s:0,input_audio:0,output_audio:0}}function Mn(e){if(typeof window<"u")throw new c("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new c("INVALID_REQUEST","Model ID and reasoning pricing are required");async function n(o){await e.persist({context:o,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function t(o,r){let a={context:o,modelId:e.modelId,usage:r,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(a);let s=e.mapTokens?e.mapTokens(r):_n(r,e.reasoning),l=await e.pricing.quoteTokens({modelId:e.modelId,tokens:s});await e.persist({...a,tokens:s,quote:l,phase:"quoted"});let p=await e.pricing.trackTokens(e.client,{...o,quote:l});if(!p.receipt.accepted)throw new c("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...a,tokens:s,quote:l,receipt:p,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:o}){let r=await e.context(),a;try{a=await o()}catch(s){throw await n(r),s}return await t(r,a.usage),a},async wrapStream({doStream:o}){let r=await e.context(),a;try{a=await o()}catch(E){throw await n(r),E}let s=!1,l=!1,p=a.stream.getReader();async function v(){s||l||(l=!0,await n(r))}return{...a,stream:new ReadableStream({async pull(E){try{let{value:b,done:d}=await p.read();if(d){if(!s)throw await v(),new c("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");E.close();return}if(b.type==="finish"){if(s)throw new c("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");s=!0,await t(r,b.usage)}E.enqueue(b)}catch(b){try{await v()}finally{E.error(b),await p.cancel(b)}}},async cancel(E){try{await v()}finally{await p.cancel(E)}}})}}}}function kn(e){V(e.apiKey,"Funnel receipts are sent by your backend");let n=N(e);return{async signal(t){let o=Re.parse({...t,operation:"signal"}),r=st.parse(await n.request("funnels",o));if(r.runId!==t.runId||r.eventId!==t.eventId||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Receipt identity changed");return r},async readResults(t){let o=Re.parse({operation:"read_results",runId:t}),r=ct.parse(await n.request("funnels",o));if(r.runId!==t||r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("INVALID_RESPONSE","Result identity changed");return r}}}function Bn(e){if("remoteEval"in e)throw new c("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");V(e.apiKey,"Campaign entry requires your backend");let n=N({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(t){let o=Date.now()+(e.timeoutMs??3e4),r=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_decide"}),a=N({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,o-Date.now()))}),s=Z.parse(await a.request("funnels",r));if(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");return ge(s,r.customer,o,(l,p)=>Fe({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,p-Date.now()))}).read(l))},async start(t){let o=Pe.parse({...t,funnelId:e.funnelId,operation:"campaign_start"}),r=Vt.parse(await n.request("funnels",o));if(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment)throw new c("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in r)&&(r.run.source.id!==e.funnelId||!r.customerId||o.customer.type==="id"&&r.customerId!==o.customer.value))throw new c("INVALID_RESPONSE","Campaign Funnel or Customer changed");return r}}}var x=class extends Error{constructor(t,o=409,r=!1,a="fix_request"){super(t);this.code=t;this.status=o;this.retryable=r;this.recovery=a}code;status;retryable;recovery};function Pn(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let n=se.parse(e.manifest),t={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},o=n.capabilities.some(r=>["purchases","subscription_changes","refunds","operation_status"].includes(r));for(let[r,a]of Object.entries(Se))if(a.command&&n.capabilities.includes(r)&&!(r==="catalog"&&n.catalog==="static")&&!e.handlers[a.command])throw new Error(`Missing merchant command handler: ${a.command}`);if(o&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!n.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(a){let s=crypto.randomUUID(),l="bridge.ping",p,v=async(E,b,d=!1)=>{let h=JSON.stringify({bridgeVersion:X,requestId:s,command:l,scope:t,[d?"error":"data"]:E});if(new TextEncoder().encode(h).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(h,{status:b,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":s,...p?await te(h,p,"response"):{}}})};try{if(a.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(X)||a.method!=="POST"||new URL(a.url).pathname!==W)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(a.headers.get("Content-Type")??""))throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let E=a.body?.getReader();if(!E)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let b=new TextDecoder("utf-8",{fatal:!0}),d="",h=0;try{for(;;){let _=await E.read();if(_.done)break;if(h+=_.value.byteLength,h>16384)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",413);d+=b.decode(_.value,{stream:!0})}d+=b.decode()}finally{await E.cancel().catch(()=>{}),E.releaseLock()}let y=ot.safeParse(JSON.parse(d));if(!y.success)throw new x("MERCHANT_BRIDGE_INVALID_REQUEST",400);let S=y.data;if(s=S.requestId,l=S.command,Object.keys(t).some(_=>S.scope[_]!==t[_]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let k=S.command==="bridge.ping"||S.command==="bridge.describe",D=S.command==="catalog.read";if((k||D||a.headers.has(Q))&&(p=e.authentication.find(_=>_.keyId===a.headers.get(Q)),!p||!await ne(d,a.headers,p,"request")))throw p=void 0,new x("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(S.command==="bridge.ping")return v(Ee["bridge.ping"].parse(S.data),200);if(S.command==="bridge.describe")return v(n,200);let g=Object.entries(Se).find(([,_])=>_.command===S.command);if(!g||!n.capabilities.includes(g[0]))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let i=e.handlers[S.command];if(!i)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!D&&a.headers.has("Cookie")&&(a.headers.get("Origin")!==new URL(a.url).origin||["cross-site","same-site"].includes(a.headers.get("Sec-Fetch-Site")??"")))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);let w=D?{kind:"service"}:await e.authorize(a,S),R=w.kind,C=["purchase.execute","subscription.change","refund.execute"].includes(S.command),A=C||S.command==="operation.read";if(!(A&&p!==void 0&&R==="service")&&(S.command==="refund.execute"?R!=="administrator":!D&&R!=="user"))throw new x("MERCHANT_BRIDGE_FORBIDDEN",403);if(w.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(S.command)&&!u.uuid().safeParse(w.customerId).success)throw new x("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let M=i,F=Ee[S.command].parse(S.data),B={request:a,command:S.command,scope:t,principal:w},T;if(A){let _=j.parse(F);if(w.kind==="user"&&w.customerId!==_.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let P=ce.parse(await e.resolveOperationAuthority(_,B));if(P.operationId!==_.operationId||P.customerId!==_.customerId||Object.keys(t).some(G=>P.scope[G]!==t[G]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);B.authority=P;let H=S.command==="purchase.execute"?"purchase":S.command==="subscription.change"?"subscription_change":S.command==="refund.execute"?"refund":P.instruction.type;if(P.instruction.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!C)T=we.parse(await M(F,B));else{if(P.confirmedAt===null)throw new x("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let G=we.parse(await e.handlers["operation.read"](_,{...B,command:"operation.read"}));if(G.operationId!==_.operationId||G.customerId!==_.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(G.lookup==="found")T=G.execution;else{if(!P.initialExecutionAllowed)throw new x("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(P.instruction.expiresAt)<=Date.now())throw new x("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!n.capabilities.includes("billing_records")||je(P.instruction).some(U=>!n.billingEvents.some(on=>on===U))||Ge(P.instruction).some(U=>!n.profiles.includes(U)))throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{T=nt.parse(await M(F,B))}catch(U){throw U instanceof x?U:new x("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(T.type!==H)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else T=rt[S.command].parse(await M(F,B));if(w.kind==="user"){if("nativeUserId"in T&&T.nativeUserId!==w.nativeUserId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in T&&T.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in T&&w.customerId&&T.session.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in T&&T.presentation&&w.customerId&&T.presentation.customerId!==w.customerId)throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in T&&(T.operationId!==j.parse(S.data).operationId||T.customerId!==j.parse(S.data).customerId))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return v(T,C&&("paymentStatus"in T&&["pending","unknown"].includes(T.paymentStatus)||"status"in T&&["pending","unknown","scheduled"].includes(T.status))?202:200)}catch(E){let b=E instanceof x?E:E instanceof SyntaxError?new x("MERCHANT_BRIDGE_INVALID_REQUEST",400):new x("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return v({code:b.code,message:b.code,retryable:b.retryable,recovery:b.recovery},b.status,!0)}}}function Dn(e){return async(n,t)=>{let o=()=>e.readSubscriptionOperation(n),r=()=>e.readSubscriptionUpdate(n),a=()=>e.readRefund(n),s=t.command==="purchase.execute"?[o]:t.command==="subscription.change"?[r]:t.command==="refund.execute"?[a]:[o,r,a];for(let l of s)try{let p=await l(),v="authority"in p.operation?p.operation.authority:void 0;if(!v)throw new x("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let E=ce.parse(v);if(E.customerId!==n.customerId||E.operationId!==n.operationId||Object.keys(t.scope).some(b=>E.scope[b]!==t.scope[b]))throw new x("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return E}catch(p){if(t.command==="operation.read"&&p instanceof c&&p.code==="NOT_FOUND")continue;throw p}throw new x("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}function Fn(e){if(typeof window<"u")throw new Error("Merchant protocol credentials require a trusted server");let n=ke.parse(e.manifest),t=ie.parse(e.authentication),o={projectId:n.projectId,environmentId:n.environmentId,environment:n.environment},r=e.now??Date.now,a=d=>{throw new c("INVALID_RESPONSE",d)},s=(d,h)=>Ie(d)===Ie(h);function l(d){new TextEncoder().encode(d).byteLength>262144&&a("Merchant protocol body exceeds limit");try{return JSON.parse(d)}catch{return a("Invalid merchant protocol JSON")}}function p(d){let h=kt.parse(d);return s(h.scope,o)||a("Merchant protocol scope mismatch"),h.command==="requirement.check"&&(n.capabilities.includes("requirement_checks")||a("Merchant Check capability unavailable"),s(h.data.subject.scope,o)||a("Merchant Check subject crosses scope")),h.command==="operation.prepare"&&(!n.capabilities.includes("preparations")||!s(h.data.request.subject.scope,o))&&a("Merchant preparation capability unavailable"),h}function v(d){if(d.command!=="operation.prepare")return;let h=d.data;return(!s(h.request.subject.scope,o)||!h.preparationAllowed||Date.parse(h.requestedAt)>r()||Date.parse(h.request.expiresAt)<=r()||!n.preparationActions.includes(h.request.action))&&a("Merchant preparation requires fresh scoped authority"),h}function E(d,h){let y=Bt(d.command).parse(h);if((y.requestId!==d.requestId||!s(y.scope,o))&&a("Merchant reply correlation mismatch"),"error"in y)return y;if(d.command==="bridge.ping"&&"challenge"in y.data&&y.data.challenge!==d.data.challenge&&a("Merchant ping challenge mismatch"),d.command==="bridge.describe"&&"bridgeVersion"in y.data&&!s({projectId:y.data.projectId,environmentId:y.data.environmentId,environment:y.data.environment},o)&&a("Merchant declaration crosses scope"),d.command==="requirement.check"&&"observation"in y.data&&(!s(y.data.observation.subject,d.data.subject)||!Je(d.data.requirement,y.data)||!n.checkKinds.includes(y.data.kind))&&a("Merchant Check changed the original requirement or subject"),d.command==="operation.prepare"&&"quoteTermsDigest"in y.data){let S=v(d);(!s(y.data.request,S.request)||Date.parse(y.data.expiresAt)<=r()||Date.parse(y.data.observedAt)<Date.parse(S.requestedAt)||Date.parse(y.data.observedAt)>r())&&a("Merchant quote changed its authorized request or validity")}return y}let b=async d=>{let h=JSON.stringify(d);return l(h),{body:h,headers:new Headers({"Content-Type":"application/json","Cache-Control":"private, no-store",[oe]:"4",...await te(h,t,"response",r(),4)})}};return{version:4,path:W,async encodeRequest(d,h){let y=p({bridgeVersion:4,requestId:crypto.randomUUID(),scope:o,command:d,data:h});v(y);let S=JSON.stringify(y);l(S);let k=new Headers({"Content-Type":"application/json",[oe]:"4",...await te(S,t,"request",r(),4)});return{body:S,headers:k,async readResponse(D,g){l(D),(g.get(oe)!=="4"||!await ne(D,g,t,"response",r(),4))&&a("Merchant response authentication failed");let i=E(y,l(D));if("error"in i)throw new ye(i.error);return i.data}}},async decodeRequest(d,h){l(d),(h.get(oe)!=="4"||h.get(Q)!==t.keyId||!await ne(d,h,t,"request",r(),4))&&a("Merchant request authentication failed");let y=p(l(d));return v(y),y},async encodeResponse(d,h){let y=p(d),S=E(y,{...y,data:h});return b(S)},async encodeError(d,h){let y=p(d),{data:S,...k}=y;return b(E(y,{...k,error:Be.parse(h)}))}}}var ye=class extends Error{constructor(t){super(t.message);this.problem=t}problem};export{re as FunnelDecisionTimeoutError,fe as FunnelProcessEntrySuppressedError,c as LongplayError,x as MerchantBridgeHandlerError,ye as MerchantBridgeProtocolError,fn as aiPriceSnapshotSchema,hn as aiTokenQuoteSchema,gn as createAiPricing,Mn as createAiUsageMiddleware,dn as createConfigurationSync,yn as createConfiguredAiPricing,Me as createFeatureClient,Bn as createFunnelCampaignClient,Fe as createFunnelDecisionClient,he as createFunnelLocalEvaluator,kn as createFunnelOrchestrationClient,Rn as createFunnelProcessAdapter,ln as createFunnelStartClient,De as createGuestToken,mn as createLocalFunnelClient,Cn as createLongplayServer,Dn as createMerchantBridgeAuthorityResolver,Pn as createMerchantBridgeHandler,Fn as createMerchantBridgeProtocol,xn as createNativeReceiptClient,Tn as createPaywallStartClient,On as createSynchronizedFunnelLocalEvaluator,un as entitlementRequirementDigest,pn as evaluateFunnelNode,cn as merchantConfirmationMatchesTerms,an as merchantPreparationRequestDigest,sn as merchantQuoteTermsDigest,bn as renewFunnelRun,te as signMerchantBridgeMessage,ne as verifyMerchantBridgeMessage};
|
package/dist/visual.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as pe,c as fe}from"./chunk-UKMEW5I7.js";import{b as ue}from"./chunk-J6KIN4RH.js";import{a as Ve,b as re,c as ce,d as de}from"./chunk-SLUA7ABW.js";import{a as J,b as F,c as ge,e as me}from"./chunk-
|
|
1
|
+
import{a as pe,c as fe}from"./chunk-UKMEW5I7.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-TYY3MUTF.js";import{a as ae,b as se,c as oe,d as le}from"./chunk-6T575JKD.js";import"./chunk-3VUPVXAV.js";import"./chunk-WKIR2EQG.js";import{b as o}from"./chunk-VF6QMMEA.js";import"./chunk-DSPLGTQI.js";import{c as te,e as ie,g as M}from"./chunk-7QL4GF4C.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";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
package/dist/chunk-5UFRIIGC.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{p as n,s as t}from"./chunk-EUVLXS2V.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|