@tinkerlandai/longplay-sdk 0.10.4 → 0.10.6
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 +9 -0
- package/README.md +9 -3
- package/README.zh-CN.md +6 -4
- package/dist/chunk-5JJZSH23.js +179 -0
- package/dist/chunk-65WKEU2L.js +1 -0
- package/dist/{chunk-MRN4HP4W.js → chunk-AWZFL4HE.js} +1 -1
- package/dist/{chunk-YQHPEP4X.js → chunk-F4YCLQGU.js} +1 -1
- package/dist/{chunk-KBM7BYQY.js → chunk-FRGIXMNP.js} +1 -1
- package/dist/{chunk-HOW7NIIR.js → chunk-FXVZRIJ3.js} +1 -1
- package/dist/{chunk-JB46ZKGZ.js → chunk-HV4THS52.js} +1 -1
- package/dist/{chunk-VMM3GA3L.js → chunk-JSHLBGDY.js} +1 -1
- package/dist/chunk-MOWYD2TV.js +1 -0
- package/dist/chunk-VUWXU4FP.js +1 -0
- package/dist/{chunk-2HFA34QO.js → chunk-WCVK4OMS.js} +2 -2
- package/dist/content-ZQNYKPZT.js +1 -0
- package/dist/{funnel-local-client-CVokI0rx.d.ts → funnel-local-client-B4Z3dvNf.d.ts} +1 -1
- package/dist/{funnel-resource-client-Cv5OjfAn.d.ts → funnel-resource-client-BhbXsB2q.d.ts} +1 -1
- package/dist/funnel-runtime-host-DDBGBB5L.js +1 -0
- package/dist/index.d.ts +5 -5
- 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-XQG2D3PA.js +1 -0
- package/dist/popup.d.ts +2 -1
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +5 -5
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-NLB3FAQJ.js +1 -0
- package/dist/server.d.ts +3 -3
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-VOEFXEPP.js +0 -1
- package/dist/chunk-X6BCUINI.js +0 -173
- package/dist/chunk-ZPZVSC4J.js +0 -1
- package/dist/content-NYMIZRNR.js +0 -1
- package/dist/funnel-runtime-host-UL4DEJDU.js +0 -1
- package/dist/paywall-EJCNWDHK.js +0 -1
- package/dist/screen-renderer-JMHV4GPP.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as t}from"./chunk-HV4THS52.js";import{Ga as n}from"./chunk-WCVK4OMS.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.
|
|
1
|
+
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.6",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ia as E,ja as M,ka as j,la as O,ma as T}from"./chunk-
|
|
1
|
+
import{ia as E,ja as M,ka as j,la as O,ma as T}from"./chunk-WCVK4OMS.js";import{k as w,qa as u}from"./chunk-ACF2FBUB.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u,b as Y,l as W,o as $}from"./chunk-JB46ZKGZ.js";import{N as Q,Qa as K,a as J,b as H,c as z,d as U,e as B,f as G,j,na as i,pa as L}from"./chunk-2HFA34QO.js";import{qa as a}from"./chunk-ACF2FBUB.js";import{a as M}from"./chunk-G56XGVMS.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
|
|
1
|
+
import{a as u,b as Y,l as W,o as $}from"./chunk-HV4THS52.js";import{N as Q,Qa as K,a as J,b as H,c as z,d as U,e as B,f as G,j,na as i,pa as L}from"./chunk-WCVK4OMS.js";import{qa as a}from"./chunk-ACF2FBUB.js";import{a as M}from"./chunk-G56XGVMS.js";var x=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new a("INVALID_STATE","Installation sequence exhausted");return t+1},me=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function V(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new a("INVALID_STATE","Installation journal is invalid");return e({...n})})}function X(t,e,n){let r=null,d=0,p=0,c=0,m=Promise.resolve();if(t&&(!n||M.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new a("SCOPE_MISMATCH","Push installation belongs to another scope");let A=()=>{if(!t)throw new a("NOT_CONFIGURED","Configure this client's native Push host first");return t},h=o=>{if(o!==d)throw new a("IDENTITY_CHANGED","Identity changed during Push operation")};async function T(o){let s=A();if(!s.sha256&&!globalThis.crypto?.subtle)throw new a("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let l=s.sha256?await s.sha256(Uint8Array.from(o,f=>f.charCodeAt(0))):await me(o);if(!/^[a-f0-9]{64}$/.test(l))throw new a("INVALID_STATE","Push credential digest is invalid");return l}function C(o){let s=B.parse(o);if(s.installationId.toLowerCase()!==A().installationId.toLowerCase())throw new a("INVALID_RESPONSE","Push response belongs to another installation");return s}async function R(o,s){let l=A(),f={installationId:l.installationId,publicKey:l.publicKey,issuedAt:new Date().toISOString(),...s},g=await l.sign(G(o,l.scope,f));return{...f,signature:g}}let k=(o,s,l)=>e.requestWithCredential?e.requestWithCredential(o,s,l):e.request(o,s);async function S(){let o=A(),s=d,l=r?await(e.session?.access()??r):null,f=V(o,y=>y),g;if(f.detachSeq!==null){let y=f.detachSeq,b=J.parse(await R("detach",{sequence:y,platform:o.platform}));try{let w=await e.request("push/installations/detach",{...o.scope,...b},"POST",{installationDetach:!0});if(!w||typeof w!="object"||!("installation"in w))throw new a("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=C(w.installation);if(_.bound||_.identitySeq!==y)throw new a("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(w){if(w instanceof a&&w.status===404)g=w;else if(!(w instanceof a)||w.status!==412)throw w}g||V(o,w=>({...w,detachSeq:w.detachSeq===y?null:w.detachSeq}))}if(h(s),!l){if(g)throw g;return null}let E=i.bindPushInstallation,N=E.request.parse(await R("bind",{sequence:c,platform:o.platform,credentialDigest:await T(l)}));h(s);let D=E.response.parse(await k(E.path,N,l));h(s);let v=C(D.installation);if(!v.bound||v.identitySeq!==c)throw new a("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return g&&f.detachSeq!==null&&c>f.detachSeq&&V(o,y=>({...y,detachSeq:y.detachSeq===f.detachSeq?null:y.detachSeq})),v}async function P(){A();let o=d,s=r?await(e.session?.access()??r):null;if(!s)throw new a("NOT_IDENTIFIED","Identify before reading this installation");let l=i.readPushInstallation,f=l.request.parse(await R("read",{credentialDigest:await T(s)}));h(o);let g=l.response.parse(await k(l.path,f,s));return h(o),C(g.installation)}function O(o=S){let s=m.catch(()=>{}).then(o);return m=s,s.catch(l=>{try{t?.onError?.(l instanceof Error?l:new Error("Push synchronization failed"))}catch{}}),s}async function q(o,s,l){let f=A(),g=s.identity,E=s.observation,N=r?await(e.session?.access()??r):null;if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");if(!N)throw new a("NOT_IDENTIFIED","Identify before recovering a Push address");if(!o.connectionId||!o.kind||!o.token||!["granted","provisional"].includes(o.permission))throw new a("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await O(async()=>{if(h(g),await S(),h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let D=V(f,_=>l?_:{..._,addressSeq:x(_.addressSeq)}),y=await R(l?"recovery_confirm":"recovery_request",{...o,sequence:D.addressSeq,credentialDigest:await T(N),...l?{challenge:l}:{}}),b=l?z.parse(y):H.parse(y);if(h(g),E!==p)throw new a("INVALID_STATE","Push observation changed during recovery");let w=await k(`push/installations/recovery/${l?"confirm":"request"}`,b,N);if(h(g),E!==p||V(f,_=>_).addressSeq!==D.addressSeq)throw new a("INVALID_STATE","Push observation changed during recovery");if(l){let _=i.updatePushAddress.response.parse(w),F=C(_.installation);if(!F.bound||F.identitySeq!==c||F.addressSeq!==D.addressSeq||F.connectionId!==o.connectionId||F.addressStatus!=="active")throw new a("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return F}if(!w||typeof w!="object"||!("recovery"in w))throw new a("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return U.parse(w.recovery)})}return{recoveryObserver(){A();let o={identity:d,observation:++p};return{async request(s){return U.parse(await q(s,o))},async confirm(s,l){return B.parse(await q(l,o,s))}}},identify(o){if(!t)return;c=V(t,l=>({...l,identitySeq:x(l.identitySeq)})).identitySeq,r=o,d++,p++},reset(){if(t)try{V(t,o=>{let s=x(o.identitySeq);return{...o,identitySeq:s,detachSeq:s}})}finally{r=null,d++,p++}},start(){t&&O()},async sync(){return await O()},read:P,async recover(){let o=A(),s=d,l=c;return p++,await O(async()=>{h(s);let f=await P();return h(s),c=V(o,E=>{if(E.identitySeq!==l)throw new a("IDENTITY_CHANGED","A newer installation intent exists");return{...E,identitySeq:x(Math.max(E.identitySeq,f.identitySeq)),addressSeq:Math.max(E.addressSeq,f.addressSeq)}}).identitySeq,await S()})},tokenObserver(){A();let o=++p,s=d;return async l=>{if(o!==p||s!==d)return null;let f=A(),g=r?await(e.session?.access()??r):null;if(!g)throw new a("NOT_IDENTIFIED","Identify before registering a Push token");if(await O(),h(s),o!==p)return null;let E=V(f,y=>({...y,addressSeq:x(y.addressSeq)})),N=i.updatePushAddress,D=N.request.parse(await R("address",{...l,sequence:E.addressSeq,credentialDigest:await T(g)}));if(h(s),o!==p)return null;let v=N.response.parse(await k(N.path,D,g));return h(s),C(v.installation)}}}}function Z(t,e){return{messaging:{async preference(n){let r=i.readMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse(n))).preference}},push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){let n=i.readMessagingPreference;return n.response.parse(await t(n.path,{channel:"push"})).preference},async setPreference(n){let r=i.setMessagingPreference;return r.response.parse(await t(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}function ee(t,e,n={}){let r=!!t.session.peek(),d=new Set,p=c=>{for(let m of d)try{m(c)}catch{}};return t.session.subscribeIdentity(()=>{r=!!t.session.peek(),p(r),n.afterChange?.()},()=>{r=!1,e()}),{isIdentified:()=>r,methods:{subscribeIdentity(c){return d.add(c),()=>{d.delete(c)}},identify(c){let m=typeof c=="string"?c:c.accessToken;if(!j.test(m))throw new a("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(m),t.identify(c)},reset(){try{n.beforeReset?.()}finally{t.reset()}}}}}function I(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new a("INVALID_REQUEST","Customer requests use the verified session identity")}function te(t){return{async checkEntitlement(e){I(e);let n=i.checkEntitlement;return u(t,n,e)},async readHoldings(e={}){let n=i.readHoldings;return u(t,{...n,request:n.request.omit({customerId:!0})},e)}}}function ne(t){return{async readLedger(e){let n=i.readLedger;return u(t,n,{query:e})},async readCreditStatement(e){I(e);let n=i.readCreditStatement;return u(t,n,e)},async quoteBalance(e){I(e);let n=i.quoteBalance;return u(t,n,{command:e})}}}function re(t){return{async setupPayment(e){I(e);let n=i.setupPayment;return u(t,n,e)},async readPaymentSetup(e){I(e);let n=i.readPaymentSetup;return u(t,n,e)},async readBillingInvoice(e){I(e);let n=i.readBillingInvoice;return u(t,n,e)},async readBillingControls(e={}){I(e);let n=i.readBillingControls;return u(t,n,e)},async prepareBillingAuthorization(e){I(e);let n=i.prepareBillingAuthorization;return u(t,n,e)},async confirmBillingAuthorization(e){I(e);let n=i.confirmBillingAuthorization;return u(t,n,e)},async setBillingCoupons(e){I(e);let n=i.setBillingCoupons;return u(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){I(e);let n=i.revokeBillingAuthorization;return u(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){I(e);let n=i.listBillingInvoices;return u(t,n,e)},async confirmBillingAdjustment(e){I(e);let n=i.confirmBillingAdjustment;return u(t,n,e)}}}function ie(t){return{async previewUpdate(e){I(e);let n=i.previewUpdate;return u(t,n,e)},async update(e){I(e);let n=i.update;return u(t,n,e)},async readSubscriptionUpdate(e){I(e);let n=i.readSubscriptionUpdate;return u(t,n,e)},async restoreNativePurchase(e){I(e);let n=i.restoreNativePurchase;return u(t,n,e)},async previewAttach(e){I(e);let n=i.previewAttach;return u(t,n,e)},async attach(e){I(e);let n=i.attach;return u(t,n,e)},async readSubscriptionOperation(e){I(e);let n=i.readSubscriptionOperation;return u(t,n,e)}}}function oe(t){return{async redeemReward(e){return I(e),(await u(t,i.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return I(e),(await u(t,i.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return I(e),(await u(t,i.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await u(t,i.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await u(t,i.listOffers,{},{response:"Invalid offers response"})).offers}}}function se(t){return{...te(t),...ne(t),...re(t),...ie(t),...oe(t)}}function ae(t){return{async resolveContent(e){I(e);let n=i.resolveContent;return u(t,n,e)},async resolvePaywall(e){I(e);let n=i.resolvePaywall;return u(t,n,e)},async resolveOffering(e){I(e);let n=i.resolveOffering;return u(t,n,e)}}}var ce=t=>new TextEncoder().encode(JSON.stringify(t)).length,ue=16384;function de(t,e){let n=0,r,d=S=>{r={config:structuredClone(S),until:Date.now()+3e4}},p=[],c=null,m;function A(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}function h(){m||!p.length||(m=setTimeout(()=>{m=void 0,C().catch(()=>{}).finally(h)},5e3),typeof m=="object"&&"unref"in m&&m.unref())}function T(S,P={},O={}){if(A(),r&&Date.now()<r.until&&!Q(r.config,S))return;k();let q=i.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:S,properties:P,...O}]}).events[0];if(ce({events:[q]})>ue)throw new a("INVALID_REQUEST","Event exceeds the delivery size limit");if(p.length>=500)throw new a("EVENT_QUEUE_FULL","Flush pending events before tracking more");p.push(structuredClone(q)),h()}async function C(S=!1){if(A(),c)return c;let P=n,O=(async()=>{let q={inserted:0,duplicates:0,rejected:0,skipped:0},o=p.length;for(;o&&P===n;){let s=[];for(let g of p.slice(0,Math.min(o,100))){if(s.length&&ce({events:[...s,g]})>ue)break;s.push(g)}let l=i.trackEvents,f=await u(t,l,{events:s},void 0,{keepalive:S});if(P!==n)throw new a("IDENTITY_CHANGED","Event identity changed during delivery");if(f.inserted+f.duplicates+f.rejected+f.skipped!==s.length)throw new a("INVALID_RESPONSE","Incomplete event acknowledgement");d(f.analyticsConfig),p.splice(0,s.length),o-=s.length,q.inserted+=f.inserted,q.duplicates+=f.duplicates,q.rejected+=f.rejected,q.skipped+=f.skipped}return q})();c=O;try{return await O}finally{c===O&&(c=null)}}let R;function k(){if(R||typeof document>"u")return;let S=()=>{document.visibilityState==="hidden"&&e()&&p.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",S),R=()=>document.removeEventListener("visibilitychange",S)}return{rememberConfiguration:d,track(S,P,O={}){return k(),T(S,P,O)},flush:C,reset(){n++,r=void 0,clearTimeout(m),m=void 0,p=[],c=null},detachVisibility(){R?.(),R=void 0}}}function pe(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function ye(t){let e=pe(t),{merchandiseId:n,merchandise:r,...d}=t;return{...d,...e?{merchandise:e}:{}}}function le(t,e,n,r,d){if(d&&r&&(d.scope.projectId!==r.projectId||d.scope.environment!==r.environment))throw new a("SCOPE_MISMATCH","Configuration belongs to another App/environment");let p=0,c=new Set;function m(){if(!e())throw new a("NOT_IDENTIFIED","Call identify before using Features or events")}async function A(h={}){d||m();let T=p,C=!1,R=async()=>{if(C||T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let v=i.getFeatures,y=d?{scope:{projectId:d.scope.projectId,environment:d.scope.environment},payload:await d.features()}:await u(t,v,{});if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");if(r&&(y.scope.projectId!==r.projectId||y.scope.environment!==r.environment))throw new a("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(y.payload.analyticsConfig),y},k=await R(),S=!0,P,O=v=>{try{h.onError?.(v)}catch{}},q=(v,y,b)=>{try{let w=pe(b);n.track(v,y,w?{merchandise:w}:{})}catch(w){O(w)}},o=Y({assertUsable:d?.assertFeatures,scope:k.scope,attributes:h.attributes,onError:h.onError,load:async()=>S?(S=!1,k.payload):(await R()).payload,evaluateRemote:async v=>{if(T!==p)throw new a("IDENTITY_CHANGED","Feature identity changed");let y=i.evaluateFeatures,b=await u(t,y,{...v,attributes:ye(v.attributes)});if(b.scope.projectId!==k.scope.projectId||b.scope.environment!==k.scope.environment)throw new a("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:b.generation,evaluatedAt:b.evaluatedAt,expiresAt:b.expiresAt,features:b.features,...b.merchandiseContext?{merchandiseContext:b.merchandiseContext}:{}}},onExperimentViewed:(v,y,b)=>q("Experiment Viewed",{experimentId:v.key,variationId:y.key},b),onFeatureUsage:(v,y,b)=>q("Feature Evaluated",{feature:v,value:y.value,source:y.source,ruleId:y.ruleId,...y.experimentResult?{variationId:y.experimentResult.key}:{}},b)}),s=o.refresh;function l(){clearTimeout(P),!d&&(C||T!==p||!o.expiresAt||(P=setTimeout(()=>{f().catch(O)},Math.min(2147483647,Math.max(1e3,Date.parse(o.expiresAt)-Date.now()))),typeof P=="object"&&"unref"in P&&P.unref()))}async function f(){try{return await s()}finally{l()}}let g=()=>{C||f().catch(O)},E=o.subscribe(l),N=d?.subscribe(()=>{!C&&d.fresh&&f().catch(O)});function D(){C||(C=!0,clearTimeout(P),typeof window<"u"&&window.removeEventListener("focus",g),E(),N?.(),o.reset(),c.delete(D))}c.add(D);try{await o.init(),(h.attributes?.merchandise||h.attributes?.merchandiseId)&&await o.refreshRemote()}catch(v){throw D(),v}return l(),!d&&typeof window<"u"&&window.addEventListener("focus",g),Object.assign(o,{refresh:f,destroy:D})}return{features:A,reset(h){p++,h();for(let T of c)T()}}}import{z as Ie}from"zod";function fe(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Ie.object({funnelId:L.shape.id,funnelVersionId:L.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new a("INVALID_REQUEST","A valid Funnel source is required");let d=Object.freeze(r.data);function p(c){if("customerId"in c)throw new a("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in c&&c.funnelId!==void 0&&c.funnelId!==d.funnelId||"funnelVersionId"in c&&c.funnelVersionId!==void 0&&c.funnelVersionId!==d.funnelVersionId)throw new a("SCOPE_MISMATCH","The original Funnel source cannot change");return{...c,...d}}return{async claimCoupon(c,m=crypto.randomUUID()){let A=i.grantOffer,h=await u(t,A,p({couponId:c,requestId:m}));return{offer:h.offer,reason:h.reason}},async resolveOffering(c){let m=i.resolveOffering;return u(t,m,p(c))},async resolvePaywall(c){let m=i.resolvePaywall;return u(t,m,p(c))},async previewAttach(c){let m=i.previewAttach;return u(t,m,p(c))}}}function Pt(t){return he(t)}function he(t){let e=K(t),n=e.request,r=X(t.push,e,t.scope??t.configuration?.scope),d=ee(e,()=>{c.reset(p.reset),p.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),p=de(n,d.isIdentified),c=le(n,d.isIdentified,p,t.scope,t.configuration);return{session:e.session,...Z(n,r),...se(n),...ae(n),forFunnel(m){return fe(n,m)},async features(m={}){return c.features(m)},track(m,A,h={}){return p.track(m,A,h)},flush(){return p.flush()},...d.methods}}function Nt(t){if(!j.test(t.customerToken))throw new a("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new a("INVALID_REQUEST","An explicit App and environment scope is required");let e=$({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),d=W({...t,runToken:r.runToken});d.identify(t.customerToken);let p=r.run.instruction?.type==="evaluate_segment"?await d.get():r;return{...r,...p,controller:d}}}}export{Pt as a,he as b,Nt as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./chunk-DSPLGTQI.js";import{b as d}from"./chunk-
|
|
1
|
+
import{a as u}from"./chunk-DSPLGTQI.js";import{b as d}from"./chunk-AWZFL4HE.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as dn,c as mn,d as fn,e as pn}from"./chunk-SBPTOOYB.js";import{$ as Ke,Aa as rn,Ba as on,Ea as an,Fa as sn,Ia as un,M as Ge,Na as ln,O as Je,Oa as cn,P as Be,Pa as te,Q as je,Qa as Q,Y as H,Z as ze,_ as q,aa as Ee,ba as L,ca as Qe,da as Ye,ea as $e,fa as We,ga as Ze,ha as Xe,j as ie,na as ne,oa as en,qa as we,ra as nn,sa as tn}from"./chunk-2HFA34QO.js";import{oa as He,qa as l}from"./chunk-ACF2FBUB.js";import{a as Me,e as ye}from"./chunk-G56XGVMS.js";import{b as ae}from"./chunk-MRN4HP4W.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Ue,h as qe}from"./chunk-XSVQHPQT.js";function Un(e){let n=null,t=null,f=0,u=0,g=!1,c=new Set,r=null,o=null,a=new Set,w=()=>{for(let m of a)try{m()}catch{}},d={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(m,v)=>{!c.has(m)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(m,structuredClone(v),structuredClone(d.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(m,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(m),structuredClone(v),structuredClone(d.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?m=>e.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},C=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function _(m,v=new Set){return c.has(m)?!r||!r.features[m]||["unknownFeature","cyclicPrerequisite"].includes(r.features[m].source):v.has(m)?!1:(v.add(m),(n?.features[m]?.rules??[]).some(S=>[...S.parentConditions??[],...(S.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>_(R.id,v))))}let E=m=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,d.features=n.features),c.has(m)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?C():structuredClone(r.features[m]??C()):e.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!g||_(m)?C():structuredClone(qe(m,d))};async function F(){if(!n||!c.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=u;if(o?.revision===m)return o.loading;let v=f,S=n,R=[...c],P=(async()=>{let T=je.parse(await e.evaluateRemote({attributes:structuredClone(d.attributes),features:R}));if(!(v!==f||m!==u||S!==n)){if(e.assertUsable?.(S.generation),T.generation!==S.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(O=>!Object.hasOwn(T.features,O))||Object.keys(T.features).some(O=>!c.has(O)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=ge.parse({...d.attributes,...T.merchandiseContext}),g=!0}r=structuredClone(T),d.features={...S.features,...Object.fromEntries(Object.entries(r.features).map(([O,k])=>[O,{defaultValue:k.value}]))},w()}})();o={revision:m,loading:P};try{await P}finally{o?.loading===P&&(o=null)}}function i(){F().catch(m=>{try{e.onError?.(m)}catch{}})}async function s(){if(t)return t;let m=f,v=(async()=>{let S=await e.load(),R="remoteFeatures"in S?Je.parse(S):null,P=R??ye.parse(S);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(m!==f)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===P.generation){let{evaluatedAt:O,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=P;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=P.evaluatedAt,n.expiresAt=P.expiresAt,w(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&i(),structuredClone(n)}let T=new Set(R?.remoteFeatures??[]);if([...T].some(O=>Object.hasOwn(P.features,O)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in P&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),n=structuredClone(P),c=T,r=null,o=null,u++,d.features=n.features,d.savedGroups=Ue(n.savedGroups),d.trackedFeatureUsage={},w(),i(),structuredClone(n)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:s,refresh:s,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let v=ge.parse(m);(d.attributes?.merchandise||d.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=v,u++,g=!1,r=null,o=null,d.features=n?.features??{},d.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(m){return E(m).on},isOff(m){return E(m).off},getFeatureValue(m,v){let S=E(m).value;return structuredClone(S===null?v:S)},reset(){f++,u++,t=null,o=null,n=null,r=null,c.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),w()}}}function gn(e){let n,t,f=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw f();let r=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ae).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(r){try{let o=await u;return await t.request(o,{mode:"exclusive"},()=>r(o))}catch(o){throw o instanceof l?o:f()}}function c(r){let o=n.getItem(r);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw f();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw f();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(r,o)=>g(a=>{if(c(a).revision!==r)return null;if(!Number.isSafeInteger(r+1))throw f();return n.setItem(a,JSON.stringify({revision:r+1,entry:o})),r+1})}}async function he(e,n){let t=nn.safeParse(n);if(!t.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return f}async function Ae(e,n,t){if(Number(e.headers.get("content-length"))>n)throw t.error("limit");let f=e.body?.getReader();if(!f)throw t.error("missing");let u=[],g=0;try{for(;;){t.signal?.throwIfAborted();let o=await f.read();if(o.done)break;if(g+=o.value.length,g>n)throw t.error("limit");u.push(o.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let c=new Uint8Array(g),r=0;for(let o of u)c.set(o,r),r+=o.length;return c}async function yn(e,n,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ae(e,n,t))}function Ie(e,n){let t=typeof e=="string"?new TextEncoder().encode(e):e;return t.byteLength===n.byteLength&&Qe(t)===n.sha256}async function ve(e,n){let t=Ze.parse(n),{artifact:f,environmentId:u}=t.content,g=new te(e.baseUrl??ae).origin,c=new te(f.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let r=new AbortController,o=setTimeout(()=>r.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:r.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>f.byteLength)throw new l("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Ae(a,f.byteLength,{signal:r.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ie(w,f))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return Xe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var Fe=(e,n)=>new l(e,n);function rt(e){return sn(e,Fe)}async function Ne(e,n,{predict:t=!0}={}){let f=n.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==f.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(t)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=Tn(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:g},prediction:u}}function Tn(e,n,t){let f=n.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=t.growth,r=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:ye.parse(c)}),o=On(r,t.document,{...n,...f}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function On(e,n,t){return un(e,n,t,Fe)}import{z as B}from"zod";var wn=H.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=B.strictObject({schemaVersion:B.literal(1),scope:Me,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Re=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,t=null,f=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:hn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function r(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&t!==null&&f(w.entry)!==t)throw M();let d=o(w.entry,w.revision);if(Re(w.entry,d)){n=w.revision;return}let C=await e.write(w.revision,d);if(C!==null){if(!Number.isSafeInteger(C)||C<=w.revision)throw M();n=C;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(t!==null&&t!==a)throw M();t=a},async load(){let o=await g();return n=o.revision,t=o.entry?f(o.entry):null,o.entry},retain(o){let a=hn.parse(o),w=a.command;return!w||t!==null&&f(a)!==t?Promise.reject(M()):(t??=f(a),c(()=>r((d,C)=>{if(d&&!Re(f(d),f(a)))throw M();if(!d){if(C!==n&&w.operation!=="close")throw M();return a}if(!d.command)return{...d,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===w.requestId||d.closeCommand&&!Re(d.closeCommand,w))throw M();return{...d,closeCommand:w,closed:!0}}if(!Re(d.command,w))throw M();return d})))},observePurchase(o,a,w){return c(()=>r((d,C)=>{if(!d&&C!==n||d&&f(d)!==f({...o,schemaVersion:1}))throw M();if(d?.purchase&&d.purchase.generation>a.generation)return d;if(d?.purchase&&d.purchase.generation===a.generation&&d.purchase.operationId!==a.operationId)throw M();return w?!d?.purchase||d.purchase.operationId!==a.operationId?d:d.command?{...d,purchase:void 0}:null:{schemaVersion:1,...o,...d,purchase:a}}))},settle(o){return c(()=>r(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function ft(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function se(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((u,g)=>se(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),f=Object.entries(n);return t.length===f.length&&t.every(([u,g])=>Object.hasOwn(n,u)&&se(g,Reflect.get(n,u)))}function vn(e){let n=null,t=0,f=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(r,o="Run identity changed during the request"){if(r!==t||f)throw new l("IDENTITY_CHANGED",o)},assertRun(r){if(n&&(r.id!==n.id||r.source.type!==n.source.type||r.source.id!==n.source.id||r.source.versionId!==n.source.versionId||r.locale!==n.locale||!se(r.parameters,n.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&r.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(r,o,a,w,d){if(!(r.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(r.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!d)return;if(n)for(let C of c)try{C(structuredClone(n))}catch{}}},identify(r){if(!ie.test(r))throw new l("INVALID_TOKEN","Customer credential required");t++,u=r},subscribe(r){return c.add(r),()=>c.delete(r)},reset(){f=!0,t++,u=void 0,n=null,c.clear()}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vt(e,n,t="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!re.test(e))throw new l("INVALID_TOKEN",t)}function Rt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...t}=e;return t}var _n=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rn({options:e,journal:n,state:t,call:f}){let u=null,g=null,c=!1,r={command:null,close:null},o=!1,a,w=null,d=n?n.load().then(i=>{if(t.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();d.catch(()=>{});async function C(i=u){if(n&&await d,!i)throw new l("INVALID_REQUEST","No command is pending");let s=i,m=t.generation;if(n){if(!t.view||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:Y(s)})}if(m!==t.generation||u!==s&&g!==s)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...t.customerToken?{customerToken:t.customerToken}:{}},S=o;o=!0;try{return await f(v,R=>{if(!R.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let P=()=>m!==t.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(P):P()}return!1})}catch(R){throw m===t.generation&&u===s&&!S&&!_n(R)&&(n&&await n.settle(s.requestId),m===t.generation&&u===s&&(u=null,o=!1,w=null)),R}}function _(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return F(s.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original Close");return g??=s,r.close?r.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(r.command)return r.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let m=C(i);r[s]=m;let v=()=>{r[s]===m&&(r[s]=null)};return m.then(v,v),m}async function F(i){let s=await f({operation:"get",settlementRequestId:i,...t.customerToken?{customerToken:t.customerToken}:{}});if(s.settlement?.requestId!==i)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:d,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return r.command},get closeFlight(){return r.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,m,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let S=s.run.paywall,R=S??s.purchase,P=R?.operation,T=s.settlement&&(!S||S.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,O=P?.operationId??R?.quote?.operationId??T?.operationId,k=R?.receiptId??T?.receiptId,G=S?.selectionGeneration??a?.generation??0;if(n&&O&&k&&i.operation!=="review"&&(!t.view||s.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:O,generation:G},J=P?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{t.assertCurrent(m),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:_,executePending:C,settle:F,reset(){u=null,g=null,r.close=null,o=!1,r.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let m=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||m.set(tn,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:m})}}:{},...e.session?{fetch:async(i,s)=>{let m=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};if(!v||typeof v!="object"||Array.isArray(v))throw new l("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:m})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let t=vn(e.funnelId),f=e.session?.subscribeIdentity(()=>{t.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),c=g&&In(g),r=Rn({options:e,journal:c,state:t,call:o});async function o(i,s,m){let v=t.generation,S=()=>t.assertCurrent(v);c&&await r.ready,S();let R=t.view,P=we.parse(await he(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!P.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(S(),P.runToken&&P.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let T=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(T&&P.settlement?.requestId!==T)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(P),t.assertRun(P.run);let O=r.observePurchase(i,P,v,m);if(O&&await O,!P.run.stopped&&["running","waiting"].includes(P.run.status)&&i.operation==="get"&&i.settlementRequestId)return P;let k=s?.(P),G=typeof k=="boolean"?k:k?await k:!1;return S(),["running","waiting"].includes(P.run.status)||r.stop(),t.publish(i,P,R,m,G),P}let a=r.submit,w=null,d=new WeakMap;function C(i){let s=d.get(i);if(s)return s;let m=E(i);return d.set(i,m),m}let _=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;_=!0;let m=t.generation,v=(async()=>{for(let S=0;S<32&&s.run.instruction?.type==="evaluate_segment";S++){if(r.pending||r.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:T}=await Ne(e.configuration,R,{predict:!1});if(m!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return s;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let O=!0;Ne(e.configuration,R).then(({prediction:k})=>{O&&m===t.generation&&!r.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:en(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...T})}finally{O=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let F={get configuration(){return _?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get prediction(){let i=t.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!r.closeRequested?structuredClone(u):null},settle:r.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return ve(e,i)},async pageExperiments(i,s=[]){let m=t.generation;t.assertCurrent(m);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let S=cn.parse(await n.request("funnels",ln.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...t.customerToken?{customerToken:t.customerToken}:{}})));if(t.assertCurrent(m),S.runId!==v||S.scope.projectId!==e.scope?.projectId||S.scope.environment!==e.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return S},review(i){return o({operation:"review",...i?{receiptId:i}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(i,s){c&&await r.ready,s??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let m=t.nextRead();return C(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,m))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?F.settle(i):r.pending?.requestId===i?C(a(r.pending)):C(a({operation:"resume",requestId:i})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(i){return C(a(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?r.executePending(r.closing):r.closeRequested&&r.pending?F.settle(r.pending.requestId):r.inFlight?C(r.inFlight):r.pending?C(a(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(i){t.identify(i),u=null,n.identify(e.runToken)},subscribe:t.subscribe,reset(){f?.(),t.reset(),r.reset(),u=null,n.reset()}};return F}import{ZodError as Dn}from"zod";function Sn(e,n,t,f){try{return e.parse(n)}catch(u){throw f&&u instanceof Dn?new l(t,f):u}}async function Pe(e,n,t,f={},u){let g=typeof f=="function"?{}:f,c=Sn(n.request,t,"INVALID_REQUEST",g.request),r=await e(n.path,c,n.method,u),o=typeof f=="function"?f:f.parseResponse;return o?o(n.response,r):Sn(n.response,r,"INVALID_RESPONSE",g.response)}async function Kt(e,n){if(!ie.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let t=Q(e);if(!e.session)t.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let f=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),u=null,g=!1,c=null,r=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,t.dispose(),u=null,c=null,r=null,o=null});async function d(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,F=await Pe(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),i={paywall:await ve(e,F.paywall)};if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!dn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function C(E){if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let F=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await Pe(t.request,F,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return mn(i.operation,{operationId:c.operationId,currency:f.commerce.currency},"The purchase operation changed"),r=pn(r,i.operation),structuredClone(r)}let _={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},refresh:d,async preview(E){if(!u)throw new l("INVALID_REQUEST","Load the Paywall first");let F=u.document.buttons[E.actionId];if(F?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=Ge(F.product,E.selection,u.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=He(u.document.screen,i,E.selection,u.capabilities),m=ne.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),v=JSON.stringify(m);if(o&&o!==v&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===v){if(a)return a;if(c)return structuredClone(c)}o=v;let S=(async()=>{let R=ne.previewAttach,P=await Pe(t.request,R,m);return fn(P.quote,{productVersionId:i,featureQuantities:s,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=P.quote,r=null,structuredClone(c)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>C("confirm"),cancel:()=>C("cancel"),read:()=>C("read"),destroy(){w?.(),g=!0,t.dispose(),u=null,c=null,r=null,o=null}};return await d(),_}import{z as kn}from"zod";import{z as ce}from"zod";var xn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),bn=2*1048576,Ln=100;function Vn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Cn(e,n){let t=n===void 0?Vn():n,f=Promise.resolve();async function u(c){if(!t)return null;let r;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(c)),new Promise(o=>{r=setTimeout(()=>o(null),Ln)})])}catch{return null}finally{clearTimeout(r)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=bn)return xn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>t?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let r=(await g())[c];return r&&Date.now()>=r.at&&Date.now()-r.at<=q.retentionMs?r.text:void 0},writeArtifact(c,r){t&&(f=f.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:r};let w={},d=2,C=0;for(let[_,E]of Object.entries(o).sort(([,F],[,i])=>i.at-F.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let F=new TextEncoder().encode(JSON.stringify({[_]:E})).byteLength;d+F>bn||C>=128||(w[_]=E,d+=F,C++)}await t.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new l(e,n),$=()=>performance.now(),En=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ir(e){let n=Ke.parse(e.scope),t=new te(e.origin??ae);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(e.assetOrigins??[]).map(y=>{let p=new te(y);if(p.protocol!=="https:"||p.username||p.password||p.search||p.hash||p.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return p.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${t.origin}:${L(n)}`,r=Cn(c,e.storage),o,a=0,w=0,d=!1,C=!1,_=0,E=0,F,i,s,m,v=0,S=new Set,R=new Set,P=new Map,T=new Map,O=0,k=!1;function G(){for(let y of S)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!C&&!d&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Te(y,p){let h=new TextEncoder().encode(p).byteLength;if(!P.has(y)){for(;P.size&&(P.size>=128||O+h>q.maxCacheBytes);){let I=P.entries().next().value;O-=new TextEncoder().encode(I[1]).byteLength,P.delete(I[0])}P.set(y,p),O+=h}}function Oe(y,p,h){return yn(y,p,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _e(y){let p=new te(y,t);if(!f.has(p.origin)||p.username||p.password||p.hash||p.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return p.href}async function Se(y,p,h=!1){let I=await u(_e(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:p,headers:{}});if(I.status===429){let A=I.headers.get("retry-after")??"";v=/^\d+$/.test(A)?Number(A)*1e3:Math.max(0,Date.parse(A)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Fn(y,p,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),A=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,A,D,U].every(Number.isFinite)||A<=I||A-I>q.maxControlAgeMs||I>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(A-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,D-I,0)-($()-p);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+x}function be(){if(clearTimeout(s),clearTimeout(m),C||!S.size)return;J()&&(m=setTimeout(()=>{J()?be():G()},Math.max(1,a-$())),En(m));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{oe().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),En(s)}async function oe(){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let y=_,p=new AbortController;i=p;let h=(async()=>{if(!k){k=!0;try{let pe=await r.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}p.signal.throwIfAborted();let N=o,U=$(),V=await Se(g,p.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Se(g,p.signal));let x=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,p.signal))),{generation:z,...K}=x,X=V.headers.get("etag");if(L(x.scope)!==L(n)||Ye(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=x.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let ke=Fn(V,U,x.policy);if(p.signal.throwIfAborted(),y!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=x,a=ke,w=Date.now()+Math.max(0,ke-$()),d=!1,E=0,v=0,r.writeManifest(L(x)),G(),structuredClone(x)})(),I=setTimeout(()=>p.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),A=new Promise((N,U)=>p.signal.addEventListener("abort",()=>U(p.signal.reason),{once:!0})),D=Promise.race([h,A]).catch(N=>{throw E++,(N instanceof kn.ZodError||N instanceof SyntaxError||N instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,d=!0,G()),N}).finally(()=>{clearTimeout(I),F===D&&(F=void 0),be()});return F=D,D}async function de(y){let p=y.sha256,h=z=>Ie(z,y);_e(y.url);let I=P.get(p);if(I&&h(I))return P.delete(p),P.set(p,I),I;if(T.has(p))return T.get(p);let A=new AbortController;R.add(A);let D=_,N=(async()=>{try{let X=await r.readArtifact(p);if(X&&h(X))return Te(p,X),X}catch{}A.signal.throwIfAborted();let z=await Se(y.url,A.signal,!0),K=await Oe(z,y.byteLength,A.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(C||D!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Te(p,K),r.writeArtifact(p,K),K})(),U=setTimeout(()=>A.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>A.signal.addEventListener("abort",()=>K(A.signal.reason),{once:!0})),x=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(A),T.delete(p)});return T.set(p,x),x}async function me(){return J()||await oe(),Z(),o}async function ue(y){let p,h=new Promise((I,A)=>{p=setTimeout(()=>A(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(p)}}function le(y,p){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(p&&o.funnels[p]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function De(y){let p=y.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Be.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(A=>Object.hasOwn(I.features,A)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return le(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function xe(y,p){let h=await me(),I=h.funnels[y];p&&(!I||I.evaluationMode==="local"&&!I.versions[p])&&(F&&await F,h=await oe()),le(h,y);let A=h.funnels[y];if(A.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let D=p??A.currentVersionId,N=A.versions[D];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(x=>We(JSON.parse(x))),A.evaluationMode==="local"?De(h):void 0]);if(V&&L($e(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return le(h,y),{document:U,growth:V,versionId:D,control:structuredClone(A),manifest:structuredClone(h)}}async function Le(y,p){try{return await xe(y,p)}catch(h){if(!(h instanceof l)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(F&&await F,await oe(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return xe(y,p)}}function Ce(){d=!0,G(),oe().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Nn(y){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(y),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),be()),()=>{S.delete(y),S.size||(clearTimeout(s),clearTimeout(m),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:oe,subscribe:Nn,assertFresh:Z,assertFeatures(y){Z();let p=o.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[p].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return ue(async()=>De(await me()))},pageExperiments:()=>ue(async()=>{let y=await me(),p=y.gb.pageExperiments;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=an.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return le(y),I}),funnel:(y,p)=>ue(()=>Le(y,p)),paywall:(y,p)=>ue(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!p&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let A=p??I.currentVersionId,D=I.versions[A],N=D&&h.artifacts[D.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=ze.parse(JSON.parse(await de(N)));return le(h),{document:U,versionId:A,version:D.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,p){let h=await ue(()=>Le(y,p));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:A,...D}=h.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:D})},assertFunnel(y,p,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Longplay");if(p!==void 0&&I.controlRevision!==p)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!C){C=!0,_++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(m),Ve(),G(),S.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),O=0}}}}function An(e){let n=ie.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let t=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||t.identify(e.apiKey),{async start(f){let u=H.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await he(e,await t.request("funnels",g)));if(!c.success||!c.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let r=c.data;if(r.run.source.id!==g.funnelId||r.run.locale!==(g.locale??"en")||!se(r.run.parameters,g.parameters??{})||(g.customer?!r.customerId||g.customer.type==="id"&&r.customerId!==g.customer.value:r.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}async function hr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(t)!==L(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=re.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=An({...e,scope:t,apiKey:e.credential}),c=r=>{let o=Pn({...e,scope:t,runToken:r,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(r){let o=await g.start({...r,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(r){let o=c(r),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:r,controller:o}}}}export{Pe as a,Un as b,he as c,Fe as d,rt as e,On as f,gn as g,ft as h,se as i,vt as j,Rt as k,Pn as l,Kt as m,ir as n,An as o,hr as p};
|
|
1
|
+
import{b as dn,c as mn,d as fn,e as pn}from"./chunk-SBPTOOYB.js";import{$ as Ke,Aa as rn,Ba as on,Ea as an,Fa as sn,Ia as un,M as Ge,Na as ln,O as Je,Oa as cn,P as Be,Pa as te,Q as je,Qa as Q,Y as H,Z as ze,_ as q,aa as Ee,ba as L,ca as Qe,da as Ye,ea as $e,fa as We,ga as Ze,ha as Xe,j as ie,na as ne,oa as en,qa as we,ra as nn,sa as tn}from"./chunk-WCVK4OMS.js";import{oa as He,qa as l}from"./chunk-ACF2FBUB.js";import{a as Me,e as ye}from"./chunk-G56XGVMS.js";import{b as ae}from"./chunk-AWZFL4HE.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Ue,h as qe}from"./chunk-XSVQHPQT.js";function Un(e){let n=null,t=null,f=0,u=0,g=!1,c=new Set,r=null,o=null,a=new Set,w=()=>{for(let m of a)try{m()}catch{}},d={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(m,v)=>{!c.has(m)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(m,structuredClone(v),structuredClone(d.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(m,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(m),structuredClone(v),structuredClone(d.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?m=>e.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},C=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function _(m,v=new Set){return c.has(m)?!r||!r.features[m]||["unknownFeature","cyclicPrerequisite"].includes(r.features[m].source):v.has(m)?!1:(v.add(m),(n?.features[m]?.rules??[]).some(S=>[...S.parentConditions??[],...(S.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>_(R.id,v))))}let E=m=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,d.features=n.features),c.has(m)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?C():structuredClone(r.features[m]??C()):e.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!g||_(m)?C():structuredClone(qe(m,d))};async function F(){if(!n||!c.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=u;if(o?.revision===m)return o.loading;let v=f,S=n,R=[...c],P=(async()=>{let T=je.parse(await e.evaluateRemote({attributes:structuredClone(d.attributes),features:R}));if(!(v!==f||m!==u||S!==n)){if(e.assertUsable?.(S.generation),T.generation!==S.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(O=>!Object.hasOwn(T.features,O))||Object.keys(T.features).some(O=>!c.has(O)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=ge.parse({...d.attributes,...T.merchandiseContext}),g=!0}r=structuredClone(T),d.features={...S.features,...Object.fromEntries(Object.entries(r.features).map(([O,k])=>[O,{defaultValue:k.value}]))},w()}})();o={revision:m,loading:P};try{await P}finally{o?.loading===P&&(o=null)}}function i(){F().catch(m=>{try{e.onError?.(m)}catch{}})}async function s(){if(t)return t;let m=f,v=(async()=>{let S=await e.load(),R="remoteFeatures"in S?Je.parse(S):null,P=R??ye.parse(S);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(m!==f)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===P.generation){let{evaluatedAt:O,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=P;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=P.evaluatedAt,n.expiresAt=P.expiresAt,w(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&i(),structuredClone(n)}let T=new Set(R?.remoteFeatures??[]);if([...T].some(O=>Object.hasOwn(P.features,O)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in P&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),n=structuredClone(P),c=T,r=null,o=null,u++,d.features=n.features,d.savedGroups=Ue(n.savedGroups),d.trackedFeatureUsage={},w(),i(),structuredClone(n)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:s,refresh:s,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let v=ge.parse(m);(d.attributes?.merchandise||d.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=v,u++,g=!1,r=null,o=null,d.features=n?.features??{},d.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(m){return E(m).on},isOff(m){return E(m).off},getFeatureValue(m,v){let S=E(m).value;return structuredClone(S===null?v:S)},reset(){f++,u++,t=null,o=null,n=null,r=null,c.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),w()}}}function gn(e){let n,t,f=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw f();let r=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ae).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(r){try{let o=await u;return await t.request(o,{mode:"exclusive"},()=>r(o))}catch(o){throw o instanceof l?o:f()}}function c(r){let o=n.getItem(r);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw f();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw f();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(r,o)=>g(a=>{if(c(a).revision!==r)return null;if(!Number.isSafeInteger(r+1))throw f();return n.setItem(a,JSON.stringify({revision:r+1,entry:o})),r+1})}}async function he(e,n){let t=nn.safeParse(n);if(!t.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return f}async function Ae(e,n,t){if(Number(e.headers.get("content-length"))>n)throw t.error("limit");let f=e.body?.getReader();if(!f)throw t.error("missing");let u=[],g=0;try{for(;;){t.signal?.throwIfAborted();let o=await f.read();if(o.done)break;if(g+=o.value.length,g>n)throw t.error("limit");u.push(o.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let c=new Uint8Array(g),r=0;for(let o of u)c.set(o,r),r+=o.length;return c}async function yn(e,n,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ae(e,n,t))}function Ie(e,n){let t=typeof e=="string"?new TextEncoder().encode(e):e;return t.byteLength===n.byteLength&&Qe(t)===n.sha256}async function ve(e,n){let t=Ze.parse(n),{artifact:f,environmentId:u}=t.content,g=new te(e.baseUrl??ae).origin,c=new te(f.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let r=new AbortController,o=setTimeout(()=>r.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:r.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>f.byteLength)throw new l("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Ae(a,f.byteLength,{signal:r.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ie(w,f))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return Xe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var Fe=(e,n)=>new l(e,n);function rt(e){return sn(e,Fe)}async function Ne(e,n,{predict:t=!0}={}){let f=n.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==f.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(t)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=Tn(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:g},prediction:u}}function Tn(e,n,t){let f=n.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=t.growth,r=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:ye.parse(c)}),o=On(r,t.document,{...n,...f}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function On(e,n,t){return un(e,n,t,Fe)}import{z as B}from"zod";var wn=H.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=B.strictObject({schemaVersion:B.literal(1),scope:Me,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Re=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,t=null,f=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:hn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function r(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&t!==null&&f(w.entry)!==t)throw M();let d=o(w.entry,w.revision);if(Re(w.entry,d)){n=w.revision;return}let C=await e.write(w.revision,d);if(C!==null){if(!Number.isSafeInteger(C)||C<=w.revision)throw M();n=C;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(t!==null&&t!==a)throw M();t=a},async load(){let o=await g();return n=o.revision,t=o.entry?f(o.entry):null,o.entry},retain(o){let a=hn.parse(o),w=a.command;return!w||t!==null&&f(a)!==t?Promise.reject(M()):(t??=f(a),c(()=>r((d,C)=>{if(d&&!Re(f(d),f(a)))throw M();if(!d){if(C!==n&&w.operation!=="close")throw M();return a}if(!d.command)return{...d,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===w.requestId||d.closeCommand&&!Re(d.closeCommand,w))throw M();return{...d,closeCommand:w,closed:!0}}if(!Re(d.command,w))throw M();return d})))},observePurchase(o,a,w){return c(()=>r((d,C)=>{if(!d&&C!==n||d&&f(d)!==f({...o,schemaVersion:1}))throw M();if(d?.purchase&&d.purchase.generation>a.generation)return d;if(d?.purchase&&d.purchase.generation===a.generation&&d.purchase.operationId!==a.operationId)throw M();return w?!d?.purchase||d.purchase.operationId!==a.operationId?d:d.command?{...d,purchase:void 0}:null:{schemaVersion:1,...o,...d,purchase:a}}))},settle(o){return c(()=>r(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function ft(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function se(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((u,g)=>se(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),f=Object.entries(n);return t.length===f.length&&t.every(([u,g])=>Object.hasOwn(n,u)&&se(g,Reflect.get(n,u)))}function vn(e){let n=null,t=0,f=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(r,o="Run identity changed during the request"){if(r!==t||f)throw new l("IDENTITY_CHANGED",o)},assertRun(r){if(n&&(r.id!==n.id||r.source.type!==n.source.type||r.source.id!==n.source.id||r.source.versionId!==n.source.versionId||r.locale!==n.locale||!se(r.parameters,n.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&r.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(r,o,a,w,d){if(!(r.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(r.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!d)return;if(n)for(let C of c)try{C(structuredClone(n))}catch{}}},identify(r){if(!ie.test(r))throw new l("INVALID_TOKEN","Customer credential required");t++,u=r},subscribe(r){return c.add(r),()=>c.delete(r)},reset(){f=!0,t++,u=void 0,n=null,c.clear()}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vt(e,n,t="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!re.test(e))throw new l("INVALID_TOKEN",t)}function Rt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...t}=e;return t}var _n=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rn({options:e,journal:n,state:t,call:f}){let u=null,g=null,c=!1,r={command:null,close:null},o=!1,a,w=null,d=n?n.load().then(i=>{if(t.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();d.catch(()=>{});async function C(i=u){if(n&&await d,!i)throw new l("INVALID_REQUEST","No command is pending");let s=i,m=t.generation;if(n){if(!t.view||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:Y(s)})}if(m!==t.generation||u!==s&&g!==s)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...t.customerToken?{customerToken:t.customerToken}:{}},S=o;o=!0;try{return await f(v,R=>{if(!R.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let P=()=>m!==t.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(P):P()}return!1})}catch(R){throw m===t.generation&&u===s&&!S&&!_n(R)&&(n&&await n.settle(s.requestId),m===t.generation&&u===s&&(u=null,o=!1,w=null)),R}}function _(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return F(s.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original Close");return g??=s,r.close?r.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(r.command)return r.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let m=C(i);r[s]=m;let v=()=>{r[s]===m&&(r[s]=null)};return m.then(v,v),m}async function F(i){let s=await f({operation:"get",settlementRequestId:i,...t.customerToken?{customerToken:t.customerToken}:{}});if(s.settlement?.requestId!==i)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:d,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return r.command},get closeFlight(){return r.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,m,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let S=s.run.paywall,R=S??s.purchase,P=R?.operation,T=s.settlement&&(!S||S.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,O=P?.operationId??R?.quote?.operationId??T?.operationId,k=R?.receiptId??T?.receiptId,G=S?.selectionGeneration??a?.generation??0;if(n&&O&&k&&i.operation!=="review"&&(!t.view||s.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:O,generation:G},J=P?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{t.assertCurrent(m),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:_,executePending:C,settle:F,reset(){u=null,g=null,r.close=null,o=!1,r.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let m=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||m.set(tn,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:m})}}:{},...e.session?{fetch:async(i,s)=>{let m=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};if(!v||typeof v!="object"||Array.isArray(v))throw new l("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:m})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let t=vn(e.funnelId),f=e.session?.subscribeIdentity(()=>{t.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),c=g&&In(g),r=Rn({options:e,journal:c,state:t,call:o});async function o(i,s,m){let v=t.generation,S=()=>t.assertCurrent(v);c&&await r.ready,S();let R=t.view,P=we.parse(await he(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!P.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(S(),P.runToken&&P.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let T=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(T&&P.settlement?.requestId!==T)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(P),t.assertRun(P.run);let O=r.observePurchase(i,P,v,m);if(O&&await O,!P.run.stopped&&["running","waiting"].includes(P.run.status)&&i.operation==="get"&&i.settlementRequestId)return P;let k=s?.(P),G=typeof k=="boolean"?k:k?await k:!1;return S(),["running","waiting"].includes(P.run.status)||r.stop(),t.publish(i,P,R,m,G),P}let a=r.submit,w=null,d=new WeakMap;function C(i){let s=d.get(i);if(s)return s;let m=E(i);return d.set(i,m),m}let _=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;_=!0;let m=t.generation,v=(async()=>{for(let S=0;S<32&&s.run.instruction?.type==="evaluate_segment";S++){if(r.pending||r.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:T}=await Ne(e.configuration,R,{predict:!1});if(m!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return s;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let O=!0;Ne(e.configuration,R).then(({prediction:k})=>{O&&m===t.generation&&!r.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:en(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...T})}finally{O=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let F={get configuration(){return _?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get prediction(){let i=t.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!r.closeRequested?structuredClone(u):null},settle:r.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return ve(e,i)},async pageExperiments(i,s=[]){let m=t.generation;t.assertCurrent(m);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let S=cn.parse(await n.request("funnels",ln.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...t.customerToken?{customerToken:t.customerToken}:{}})));if(t.assertCurrent(m),S.runId!==v||S.scope.projectId!==e.scope?.projectId||S.scope.environment!==e.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return S},review(i){return o({operation:"review",...i?{receiptId:i}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(i,s){c&&await r.ready,s??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let m=t.nextRead();return C(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,m))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?F.settle(i):r.pending?.requestId===i?C(a(r.pending)):C(a({operation:"resume",requestId:i})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(i){return C(a(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?r.executePending(r.closing):r.closeRequested&&r.pending?F.settle(r.pending.requestId):r.inFlight?C(r.inFlight):r.pending?C(a(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(i){t.identify(i),u=null,n.identify(e.runToken)},subscribe:t.subscribe,reset(){f?.(),t.reset(),r.reset(),u=null,n.reset()}};return F}import{ZodError as Dn}from"zod";function Sn(e,n,t,f){try{return e.parse(n)}catch(u){throw f&&u instanceof Dn?new l(t,f):u}}async function Pe(e,n,t,f={},u){let g=typeof f=="function"?{}:f,c=Sn(n.request,t,"INVALID_REQUEST",g.request),r=await e(n.path,c,n.method,u),o=typeof f=="function"?f:f.parseResponse;return o?o(n.response,r):Sn(n.response,r,"INVALID_RESPONSE",g.response)}async function Kt(e,n){if(!ie.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let t=Q(e);if(!e.session)t.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let f=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),u=null,g=!1,c=null,r=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,t.dispose(),u=null,c=null,r=null,o=null});async function d(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,F=await Pe(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),i={paywall:await ve(e,F.paywall)};if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!dn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function C(E){if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let F=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await Pe(t.request,F,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return mn(i.operation,{operationId:c.operationId,currency:f.commerce.currency},"The purchase operation changed"),r=pn(r,i.operation),structuredClone(r)}let _={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},refresh:d,async preview(E){if(!u)throw new l("INVALID_REQUEST","Load the Paywall first");let F=u.document.buttons[E.actionId];if(F?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=Ge(F.product,E.selection,u.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=He(u.document.screen,i,E.selection,u.capabilities),m=ne.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),v=JSON.stringify(m);if(o&&o!==v&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===v){if(a)return a;if(c)return structuredClone(c)}o=v;let S=(async()=>{let R=ne.previewAttach,P=await Pe(t.request,R,m);return fn(P.quote,{productVersionId:i,featureQuantities:s,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=P.quote,r=null,structuredClone(c)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>C("confirm"),cancel:()=>C("cancel"),read:()=>C("read"),destroy(){w?.(),g=!0,t.dispose(),u=null,c=null,r=null,o=null}};return await d(),_}import{z as kn}from"zod";import{z as ce}from"zod";var xn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),bn=2*1048576,Ln=100;function Vn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Cn(e,n){let t=n===void 0?Vn():n,f=Promise.resolve();async function u(c){if(!t)return null;let r;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(c)),new Promise(o=>{r=setTimeout(()=>o(null),Ln)})])}catch{return null}finally{clearTimeout(r)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=bn)return xn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>t?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let r=(await g())[c];return r&&Date.now()>=r.at&&Date.now()-r.at<=q.retentionMs?r.text:void 0},writeArtifact(c,r){t&&(f=f.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:r};let w={},d=2,C=0;for(let[_,E]of Object.entries(o).sort(([,F],[,i])=>i.at-F.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let F=new TextEncoder().encode(JSON.stringify({[_]:E})).byteLength;d+F>bn||C>=128||(w[_]=E,d+=F,C++)}await t.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new l(e,n),$=()=>performance.now(),En=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ir(e){let n=Ke.parse(e.scope),t=new te(e.origin??ae);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(e.assetOrigins??[]).map(y=>{let p=new te(y);if(p.protocol!=="https:"||p.username||p.password||p.search||p.hash||p.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return p.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${t.origin}:${L(n)}`,r=Cn(c,e.storage),o,a=0,w=0,d=!1,C=!1,_=0,E=0,F,i,s,m,v=0,S=new Set,R=new Set,P=new Map,T=new Map,O=0,k=!1;function G(){for(let y of S)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!C&&!d&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Te(y,p){let h=new TextEncoder().encode(p).byteLength;if(!P.has(y)){for(;P.size&&(P.size>=128||O+h>q.maxCacheBytes);){let I=P.entries().next().value;O-=new TextEncoder().encode(I[1]).byteLength,P.delete(I[0])}P.set(y,p),O+=h}}function Oe(y,p,h){return yn(y,p,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _e(y){let p=new te(y,t);if(!f.has(p.origin)||p.username||p.password||p.hash||p.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return p.href}async function Se(y,p,h=!1){let I=await u(_e(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:p,headers:{}});if(I.status===429){let A=I.headers.get("retry-after")??"";v=/^\d+$/.test(A)?Number(A)*1e3:Math.max(0,Date.parse(A)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Fn(y,p,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),A=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,A,D,U].every(Number.isFinite)||A<=I||A-I>q.maxControlAgeMs||I>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(A-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,D-I,0)-($()-p);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+x}function be(){if(clearTimeout(s),clearTimeout(m),C||!S.size)return;J()&&(m=setTimeout(()=>{J()?be():G()},Math.max(1,a-$())),En(m));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{oe().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),En(s)}async function oe(){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let y=_,p=new AbortController;i=p;let h=(async()=>{if(!k){k=!0;try{let pe=await r.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}p.signal.throwIfAborted();let N=o,U=$(),V=await Se(g,p.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Se(g,p.signal));let x=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,p.signal))),{generation:z,...K}=x,X=V.headers.get("etag");if(L(x.scope)!==L(n)||Ye(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=x.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let ke=Fn(V,U,x.policy);if(p.signal.throwIfAborted(),y!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=x,a=ke,w=Date.now()+Math.max(0,ke-$()),d=!1,E=0,v=0,r.writeManifest(L(x)),G(),structuredClone(x)})(),I=setTimeout(()=>p.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),A=new Promise((N,U)=>p.signal.addEventListener("abort",()=>U(p.signal.reason),{once:!0})),D=Promise.race([h,A]).catch(N=>{throw E++,(N instanceof kn.ZodError||N instanceof SyntaxError||N instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,d=!0,G()),N}).finally(()=>{clearTimeout(I),F===D&&(F=void 0),be()});return F=D,D}async function de(y){let p=y.sha256,h=z=>Ie(z,y);_e(y.url);let I=P.get(p);if(I&&h(I))return P.delete(p),P.set(p,I),I;if(T.has(p))return T.get(p);let A=new AbortController;R.add(A);let D=_,N=(async()=>{try{let X=await r.readArtifact(p);if(X&&h(X))return Te(p,X),X}catch{}A.signal.throwIfAborted();let z=await Se(y.url,A.signal,!0),K=await Oe(z,y.byteLength,A.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(C||D!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Te(p,K),r.writeArtifact(p,K),K})(),U=setTimeout(()=>A.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>A.signal.addEventListener("abort",()=>K(A.signal.reason),{once:!0})),x=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(A),T.delete(p)});return T.set(p,x),x}async function me(){return J()||await oe(),Z(),o}async function ue(y){let p,h=new Promise((I,A)=>{p=setTimeout(()=>A(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(p)}}function le(y,p){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(p&&o.funnels[p]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function De(y){let p=y.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Be.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(A=>Object.hasOwn(I.features,A)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return le(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function xe(y,p){let h=await me(),I=h.funnels[y];p&&(!I||I.evaluationMode==="local"&&!I.versions[p])&&(F&&await F,h=await oe()),le(h,y);let A=h.funnels[y];if(A.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let D=p??A.currentVersionId,N=A.versions[D];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(x=>We(JSON.parse(x))),A.evaluationMode==="local"?De(h):void 0]);if(V&&L($e(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return le(h,y),{document:U,growth:V,versionId:D,control:structuredClone(A),manifest:structuredClone(h)}}async function Le(y,p){try{return await xe(y,p)}catch(h){if(!(h instanceof l)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(F&&await F,await oe(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return xe(y,p)}}function Ce(){d=!0,G(),oe().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Nn(y){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(y),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),be()),()=>{S.delete(y),S.size||(clearTimeout(s),clearTimeout(m),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:oe,subscribe:Nn,assertFresh:Z,assertFeatures(y){Z();let p=o.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[p].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return ue(async()=>De(await me()))},pageExperiments:()=>ue(async()=>{let y=await me(),p=y.gb.pageExperiments;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=an.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return le(y),I}),funnel:(y,p)=>ue(()=>Le(y,p)),paywall:(y,p)=>ue(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!p&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let A=p??I.currentVersionId,D=I.versions[A],N=D&&h.artifacts[D.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=ze.parse(JSON.parse(await de(N)));return le(h),{document:U,versionId:A,version:D.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,p){let h=await ue(()=>Le(y,p));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:A,...D}=h.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:D})},assertFunnel(y,p,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Longplay");if(p!==void 0&&I.controlRevision!==p)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!C){C=!0,_++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(m),Ve(),G(),S.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),O=0}}}}function An(e){let n=ie.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let t=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||t.identify(e.apiKey),{async start(f){let u=H.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await he(e,await t.request("funnels",g)));if(!c.success||!c.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let r=c.data;if(r.run.source.id!==g.funnelId||r.run.locale!==(g.locale??"en")||!se(r.run.parameters,g.parameters??{})||(g.customer?!r.customerId||g.customer.type==="id"&&r.customerId!==g.customer.value:r.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}async function hr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(t)!==L(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=re.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=An({...e,scope:t,apiKey:e.credential}),c=r=>{let o=Pn({...e,scope:t,runToken:r,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(r){let o=await g.start({...r,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(r){let o=c(r),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:r,controller:o}}}}export{Pe as a,Un as b,he as c,Fe as d,rt as e,On as f,gn as g,ft as h,se as i,vt as j,Rt as k,Pn as l,Kt as m,ir as n,An as o,hr as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as N,c as $,d as Y}from"./chunk-
|
|
1
|
+
import{a as j,b as N,c as $,d as Y}from"./chunk-FXVZRIJ3.js";import{a as D}from"./chunk-DSPLGTQI.js";import{a as O}from"./chunk-AWZFL4HE.js";import{b as U,e as _,g as C}from"./chunk-XSVQHPQT.js";var te=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function re(e,t){let n=e,r=o=>Number.isInteger(o)&&o>=0;return!!n&&typeof n=="object"&&r(n.inserted)&&r(n.duplicates)&&r(n.skipped)&&Array.isArray(n.rejected)&&n.inserted+n.duplicates+n.skipped+n.rejected.length===t}function V(e){let t=[],n,r=(a,i)=>e.log?.(`${e.label} ${a}`,i);function o(a){n===void 0&&t.length&&(n=setTimeout(()=>{u()},a))}async function s(a){let i;try{i=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:a}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(p){return r("not sent",{error:p}),!1}if(i.status===408||i.status===429||i.status>=500)return r("not sent",{status:i.status}),!1;if(!i.ok)return r("rejected",{status:i.status,events:a.length}),!0;let f;try{f=await i.json()}catch{f=void 0}return re(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:i.status}),!1)}function u(){clearTimeout(n),n=void 0;let a=[];for(;t.length&&a.length<20&&(!a.length||te([...a,t[0]].map(i=>i.event))<=65536);)a.push(t.shift());return a.length?s(a.map(i=>i.event)).then(i=>{if(i)return o(1e3);let f=a.filter(p=>++p.attempts<5);f.length<a.length&&r("dropped after retries",{events:a.length-f.length}),t.unshift(...f),o(5e3)}):Promise.resolve()}return{push(a){t.push({event:a,attempts:0}),t.length>=20?u():o(1e3)},flush:u}}async function q(e,t,n,r={}){let o=r.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(o);let u=e.body.getReader(),a=[],i=0,f=!1,p=()=>{},g=new Promise((v,h)=>{p=()=>h(Error(o)),n.addEventListener("abort",p,{once:!0}),n.aborted&&p()});try{for(;;){let m=await Promise.race([u.read(),g]);if(m.done){f=!0;break}if(i+=m.value.byteLength,i>t)throw Error(o);a.push(m.value)}let v=new Uint8Array(i),h=0;for(let m of a)v.set(m,h),h+=m.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(v))}finally{n.removeEventListener("abort",p),f||u.cancel().catch(()=>{}),u.releaseLock()}}async function B(e,t){let n=e?.body;if(!n)return;let r=n.getReader(),o=0,s=!1,u,a=new Promise((p,g)=>{u=setTimeout(()=>g(Error("Exposure response timeout")),2e3)}),i=()=>{},f=new Promise((p,g)=>{i=()=>g(t?.reason),t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i()});try{for(;;){let p=await Promise.race([r.read(),a,f]);if(p.done){s=!0;return}if(o+=p.value.byteLength,o>16384)throw Error("Exposure response budget")}}finally{clearTimeout(u),t?.removeEventListener("abort",i),s||r.cancel().catch(()=>{}),r.releaseLock()}}var fe=2*1024*1024,J=256*1024;async function G(e,t,n,r){let o=()=>{},s=new Promise((u,a)=>{o=()=>a(r.reason),r.addEventListener("abort",o,{once:!0}),r.aborted&&o()});try{let u=e(t,{...n,signal:r});return u.then(a=>{r.aborted&&a.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{r.removeEventListener("abort",o)}}async function pe(e,t,n,r=!1){if(new TextEncoder().encode(n).byteLength>65536)throw Error("Exposure request budget");let o=new URL(t);o.searchParams.set("sdkVersion",O.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let a=await G(e,o.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:n,credentials:"omit",keepalive:r,redirect:"error"},s.signal);await B(a,s.signal)}finally{clearTimeout(u)}}function M(e){let t,n=!1;return{async read(r,o){if(n)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,a=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let i=await G(e,r,{cache:"no-cache",credentials:"omit",redirect:"error"},u),f=await q(i,o,u);return u.throwIfAborted(),f}finally{clearTimeout(a),t===s&&(t=void 0)}},destroy(){n=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}/*!
|
|
2
2
|
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
3
|
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
4
|
*/function ne(e,t){let n,r;try{n=new URL(e),r=new URL(t)}catch{return t}return n.searchParams.forEach((o,s)=>{r.searchParams.has(s)||r.searchParams.set(s,o)}),r.toString()}function oe(e,t){let n=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let s of["source","medium","campaign","term","content"]){let u=r.get(`utm_${s}`);u!==null&&(o[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(n)?"edge":/Chrome/.test(n)?"chrome":/Firefox/.test(n)?"firefox":/Safari/.test(n)?"safari":"unknown",deviceType:/Mobi/.test(n)?"mobile":"desktop",...o}}function ie(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function be(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=$(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),r=M(async(c,d)=>{let l=await n(c,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),o=e.log?(c,d)=>D(e.log,c,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=j(e.deviceIdCookie??"indiana_did"),a=N(),i=null,f={...e.attributes??{}},p="",g=!1,v=!1,h=0,m=0,w=new Map,T=V({endpoint:`${s}/events`,fetch:n,log:o,label:"Exposure"}),P=T.flush,E={trackedExperiments:new Set,log:o,onExperimentViewed:(c,d)=>{e.trackExposures===!1||i?.trackExposures===!1||T.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...a?{sessionId:a}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:c.key,variationKey:d.key})}},H=()=>{E.url=location.href,E.attributes={...oe(u,location),...f}};function Q(c){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return c.variations.some(l=>{if(!l.urlRedirect)return!1;let y=new URL(l.urlRedirect);return y.protocol!==d.protocol||y.host!==d.host})}catch{return!0}}function K(c,d){let l=e.configuration?.snapshot?.generation,y=m,z=location.href;p=c;let W=e.navigate??(x=>location.replace(x)),Z=e.navigateDelay??(e.navigate?0:100),ee=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(x=>setTimeout(x,ee))]),new Promise(x=>setTimeout(x,Z))]).then(()=>{!g&&y===m&&location.href===z&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&W(c)})}function b(){if(!(!i||g||e.configuration&&!e.configuration.fresh)){H();for(let c of i.experiments){if(Q(c)){o?.("Auto experiment blocked",{id:c.key});continue}let d;try{d=C(c,E)}catch(l){o?.("Skipping page experiment",{id:c.key,error:String(l)});continue}if(w.set(c.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=c.persistQueryString?ne(location.href,d.value.urlRedirect):d.value.urlRedirect;U(l,c.urlPatterns??[])?o?.("Skipping redirect because original URL matches redirect URL",{id:c.key}):l!==p&&K(l,P())}break}}}}let R="",F=()=>{location.href!==R&&(m++,R=location.href,p="",b())},A,S;function X(){A??=Y(F),addEventListener("pagehide",L)}let L=()=>{P()};async function k(){if(g)return!1;let c=++h,d;try{d=e.configuration?await e.configuration.pageExperiments():await r.read(s,J)}catch(y){if(g||c!==h)return!1;throw y}if(g||c!==h)return!1;let l=ie(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return i?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),i=l,E.savedGroups=_(l.savedGroups),!0}function I(){g||(S??=e.configuration?.subscribe(()=>{!g&&e.configuration?.fresh&&k().then(c=>{c&&b()}).catch(c=>o?.("Page configuration unavailable",{error:String(c)}))}),X(),R=location.href)}return{async start(){v||g||(v=!0,await k()&&(I(),b()))},async refresh(){await k()&&(m++,v&&I(),p="",b())},setAttributes(c){m++,p="",f={...c},b()},getResults(){return new Map(w)},get generation(){return i?.generation??null},destroy(){g||(g=!0,h++,r.destroy(),S?.(),A?.(),removeEventListener("pagehide",L),i=null,w.clear(),P())}}}export{fe as a,pe as b,M as c,ne as d,oe as e,ie as f,be as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function o(t,e){let a=t.ownerDocument.defaultView;if(typeof t.animate!="function"||a?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n={duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};t.animate(e==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:e==="modal"?[{opacity:0,transform:"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{t.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function i(t,e){t.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0",`background:radial-gradient(circle, ${e.background} 0 15px, color-mix(in srgb, ${e.text} 22%, ${e.background}) 15px 16px, transparent 16.5px)`,`color:${e.text}`,"font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";")}export{o as a,i as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as Ie}from"./chunk-MOWYD2TV.js";import{a as ce,b as ye,c as ge,d as ve,e as he}from"./chunk-SBPTOOYB.js";import{M as me,Y as ue}from"./chunk-WCVK4OMS.js";import{ea as fe,oa as we,qa as w}from"./chunk-ACF2FBUB.js";import{b as be,e as Ee}from"./chunk-EARSGITJ.js";import{d as Ce}from"./chunk-FXVZRIJ3.js";import{a as B}from"./chunk-DSPLGTQI.js";import{b as pe}from"./chunk-XSVQHPQT.js";function Pe(e){let h=e.view;if(!h?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let t=h.paywall.receiptId,P=h.nodeId,y=h.visit,f=h.paywall.resolution,c=f,m="document"in f?f:null;function a(n){if(!ye(n,f))throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let o=h.paywall.quote,R=h.paywall.operation,I=!1,L=new AbortController,p=h.paywall.purchaseRequestId,r=0,d=h.paywall.selectionGeneration??0,k=h.paywall.canReselect===!0,T=null,b=new Map,q=new Map,N=new Map;function O(n){if(n.purchase&&n.purchase.receiptId!==t)throw new w("INVALID_RESPONSE","Purchase receipt changed");let s=n.run.paywall;return n.purchase??(s?.receiptId===t?s:null)}function D(){if(I)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function A(n,s,l){if(D(),s!==r||l!==void 0&&o?.operationId!==l)return!1;let C=d,u=n.run.paywall;if(u?.receiptId===t){if((u.selectionGeneration??0)<d)return!1;d=u.selectionGeneration??0,k=u.canReselect===!0,a(u.resolution)}let v=O(n),g=d>C,S=g?v?.quote??null:v?.quote??o,_=v?.operation??(S?.operationId===o?.operationId?R:null);return S&&_&&ge(_,{operationId:S.operationId},"Purchase operation changed"),u?.receiptId===t&&(c=u.resolution,m="document"in c?c:m?{...c,document:m.document,offering:m.offering,capabilities:ce(c.capabilities,m.capabilities)}:null),(g||S?.operationId!==o?.operationId)&&(r++,u?.receiptId===t&&(p=u.purchaseRequestId)),o=S,R=he(R,_,!0),!0}function j(n,s,l){return new Promise((C,u)=>{let v=!1,g=()=>{clearTimeout(x),L.signal.removeEventListener("abort",M)},S=z=>{v||(v=!0,g(),C(z))},_=z=>{v||(v=!0,g(),u(z))},M=()=>_(new w("IDENTITY_CHANGED","Paywall presentation has closed")),x=setTimeout(()=>_(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l)),Math.max(0,s-Date.now()));L.signal.addEventListener("abort",M,{once:!0}),L.signal.aborted&&M(),n.then(S,_)})}function G(n){return new Promise(s=>{let l=()=>{clearTimeout(C),L.signal.removeEventListener("abort",l),s()},C=setTimeout(l,n);L.signal.addEventListener("abort",l,{once:!0}),L.signal.aborted&&l()})}async function W(n,s,l){D();let C=b.get(n);if(!C){let g=e.pendingCommands?.find(S=>S.requestId===n)??e.pendingCommand;if(g?.operation==="submit"&&g.requestId===n&&g.nodeId===P&&g.visit===y){s.type==="paywall_quote"&&g.input.type==="paywall_quote"&&g.input.predecessor&&!s.predecessor&&(s={...s,predecessor:g.input.predecessor});let S=ue.parse(g),_=ue.parse({...g,input:s});if(_.operation!=="submit"||S.operation!=="submit"||JSON.stringify(_.input)!==JSON.stringify(S.input))throw new w("CONFLICT","A restored purchase request cannot change its input");s=_.input,C=S,b.set(n,C)}}if(C){if(JSON.stringify(C.input)!==JSON.stringify(s))throw new w("CONFLICT","A purchase request cannot change its input")}else{let g=e.view;if(!g||g.nodeId!==P||g.visit!==y||g.paywall?.receiptId!==t)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");C={operation:"submit",requestId:n,nodeId:P,visit:y,revision:g.revision,input:s},b.set(n,C)}let u=Date.now()+3e4,v=await j(e.submit(C),u,n);for(;v.run.pendingRequest?.requestId===n&&Date.now()<u&&!I&&(await G(Math.min(1e3,u-Date.now())),!(I||Date.now()>=u));)v=await j(e.resume(n),u,n);if(I)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(v.run.pendingRequest?.requestId===n)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,n);if(!A(v,l,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed")}async function J(n){if(!o)throw new w("INVALID_REQUEST","A quoted purchase is required");let s=`${n}:${o.operationId}`,l=q.get(s);if(!l){let C=n==="confirm"?"paywall_confirm":"paywall_cancel",u=e.pendingCommands?.find(v=>v.operation==="submit"&&v.input.type===C&&"operationId"in v.input&&v.input.operationId===o.operationId)??e.pendingCommand;l=u?.operation==="submit"&&u.input.type===C&&"operationId"in u.input&&u.input.operationId===o.operationId?u.requestId:crypto.randomUUID(),q.set(s,l)}if(await W(l,{type:n==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.operationId},r),!R)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(R)}return{get view(){return structuredClone(m)},get quote(){return o?structuredClone(o):null},get operation(){return R?structuredClone(R):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return k},async refresh(){D();let n=r,s=await e.get();if(A(s,n),s.run.paywall?.receiptId!==t)throw new w("PRECONDITION_FAILED","Paywall presentation has changed");if(!m){if("document"in c||!e.resolvePaywall)throw new w("INVALID_RESPONSE","Public Paywall reader is unavailable");let l=await e.resolvePaywall(c);D(),a(l),m={...c,document:l.document,offering:l.offering,capabilities:ce(c.capabilities,l.capabilities)}}return structuredClone(m)},preview(n){if(!m)return Promise.reject(new w("PRECONDITION_FAILED","Load the Paywall presentation first"));if(p&&p!==n.requestId&&(T||!k))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));let s=m.document.buttons[n.actionId],l=s?.type==="checkout"?me(s.product,n.selection,m.capabilities):null;if(!l)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let C=we(m.document.screen,l,n.selection,m.capabilities),u=JSON.stringify({actionId:n.actionId,product:l,featureQuantities:C,offerId:n.offerId,nativeOffer:n.nativeOffer});if(N.has(n.requestId)&&N.get(n.requestId)!==u)return Promise.reject(new w("CONFLICT","A purchase request cannot change its quantities or Product"));if(N.set(n.requestId,u),p===n.requestId&&T)return T;let v=p!==n.requestId&&d>0?{operationId:o?.operationId??null,generation:d}:void 0;if(v&&(!k||d<=0))return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));p!==n.requestId&&r++;let g=r;p=n.requestId;let S=(async()=>{if(await W(n.requestId,{type:"paywall_quote",actionId:n.actionId,productVersionId:l,...Object.keys(C).length?{featureQuantities:C}:{},...v?{predecessor:v}:{},...n.offerId?{offerId:n.offerId}:{},...n.nativeOffer?{nativeOffer:n.nativeOffer}:{}},g),!o)throw new w("INVALID_RESPONSE","The accepted quote is missing");return ve(o,{productVersionId:l,featureQuantities:C},"The selected purchase changed"),structuredClone(o)})();return T=S,S.then(()=>{T===S&&(T=null)},_=>{T===S&&(T=null),p===n.requestId&&e.pendingCommand?.requestId!==n.requestId&&_ instanceof w&&_.status!==void 0&&_.status<500&&![401,425].includes(_.status)&&(p=null)}),S},confirm:()=>J("confirm"),cancel:()=>J("cancel"),async read(){if(D(),!o)throw new w("INVALID_REQUEST","A quoted purchase is required");let n=o.operationId,s=r,l=e.pendingCommands?.find(g=>g.operation==="submit"&&(g.input.type==="paywall_confirm"||g.input.type==="paywall_cancel")&&g.input.operationId===n)??e.pendingCommand;l?.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===n&&await e.settle?.(l.requestId);let C=await e.get(void 0,{receiptId:t,operationId:n});D();let u=O(C);if(u?.quote&&u.quote.operationId!==n||u?.operation&&u.operation.operationId!==n)throw new w("INVALID_RESPONSE","Purchase operation changed");let v=A(C,s,n)?R:u?.operation;if(!v)throw new w("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(v)},destroy(){I=!0,L.abort(),b.clear(),q.clear(),N.clear()}}}function Re(e){let h=new Set,t=new Set,P=null;function y(f){if(e.reviewing||h.has(f)||t.has(f)||e.stopped)return;t.add(f);let c=async()=>{if(e.reviewing||e.stopped||e.key!==f){t.delete(f);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{c()},250);return}let m=(async()=>{let o=e.client.view,R=e.expected(),I=R.requestId,L=!1;try{await e.client.submit({operation:"shown",...R})}catch(p){if(!(p instanceof w)||p.code!=="CONFLICT"||p.status!==409||e.client.pendingCommand)throw p;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==f||!r||!o||r.id!==o.id||r.source.versionId!==o.source.versionId||r.nodeId!==R.nodeId||r.visit!==R.visit||r.revision<=R.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw p;let d=e.expected();I=d.requestId,await e.client.submit({operation:"shown",...d})}for(;!e.stopped&&e.key===f&&e.client.pendingCommand?.requestId===I;){if(!e.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(I),L=!0,e.client.pendingCommand?.requestId===I&&await new Promise(p=>setTimeout(p,1500))}e.stopped||e.key!==f||(L&&await e.client.get(),!(e.stopped||e.key!==f)&&h.add(f))})();P=m;let a=()=>{P===m&&(P=null),t.delete(f)};m.then(a,o=>{a(),e.busy||e.fail(o)})};c()}return{report:y,get inFlight(){return P}}}function De(e){let h={},t=new Map;async function P(y){let f=e.client.view,c=f?.screen,m=c?.customerData.nodes[y.nodeId];if(e.stopped||e.busy||!f||!c||!m)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let r=e.document,d=r?fe(r,y.nodeId):null,k=d?.type==="customer_data"?d.data.outputs?.[y.action]:void 0;k&&c.outputs.includes(k)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:k,answers:e.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await e.onIntent?.(y,f);return}let o=y.action.startsWith("sources_")?m.resources.find(r=>r.key===y.value):null;if(y.action.startsWith("sources_")&&!o)throw new w("INVALID_REQUEST","Choose a current resource");let R=`${f.visit}:${y.nodeId}:${o?.key??""}`,I=t.get(R)??[null],p=h[y.nodeId]??{page:1,after:null,filter:"all",...o?{resourceKey:o.key}:{}};if(y.action==="filter"){let r=y.value;if(!r||!(m.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new w("INVALID_REQUEST","Unknown data filter");p={page:1,after:null,filter:r},I.splice(0,I.length,null)}else if(y.action==="next"||y.action==="sources_next"){let r=o?.sources.at(-1),d=o?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:c.dataCursors[y.nodeId];if(!d||!o&&!m.hasNext)return;I[p.page]=d,p={...p,page:p.page+1,after:d}}else if(y.action==="previous"||y.action==="sources_previous"){if(p.page<=1)return;p={...p,page:p.page-1,after:I[p.page-2]??null}}t.set(R,I),h={...h,[y.nodeId]:p},await e.perform(()=>e.client.get({nodeId:f.nodeId,visit:f.visit,revision:f.revision,components:h}))}return{get queries(){return h},intent:P,reset(){h={},t.clear()}}}function Se(e){let{doc:h,holder:t,reviewHolder:P,mountScreenPreview:y}=e,f=!1,c,m=0,a=null,o="",R=new Map,I=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function L(r){if(e.stopped||!e.client.review)return;f||(o=I(e.client.view),R.set(o,structuredClone(e.answers))),f=!0,c=r,t.hidden=!0,e.suspend(!0),P.hidden=!1;let d=++m;try{let k=await e.client.review(r);if(e.stopped||d!==m||!f)return;if(!k.review)throw new w("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,P.replaceChildren();let T=k.run.locale.startsWith("zh"),b=h.createElement("p");b.textContent=T?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(b);for(let[O,D]of k.review.pages.entries()){let A=h.createElement("button");A.type="button",A.textContent=T?`\u7B2C ${O+1} \u9875`:`Page ${O+1}`,A.onclick=()=>{L(D.receiptId)},P.append(A)}if(k.review.page){let O=k.review.page,D=h.createElement("div");if(D.inert=!0,P.append(D),a=y(D,{mode:"live",rendererUrl:e.client.webViewUrl,title:O.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{p()}}),a.update(O.document,k.run.locale,{serverInput:{bindings:O.inputs,answers:O.answers,values:O.values}}),await a.ready,e.stopped||d!==m||!f)return}let q=T?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},N=T?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let O of[...k.review.coupons.map((D,A)=>`${T?"\u4F18\u60E0\u5238":"Coupon"} ${A+1}: ${q[D.status]}`),...k.review.purchases.map((D,A)=>`${T?"\u8D2D\u4E70":"Purchase"} ${A+1}: ${N[D.status]}`)]){let D=h.createElement("p");D.textContent=O,P.append(D)}e.client.view&&await e.enqueue(e.client.view)}catch(k){if(d!==m||e.stopped)return;a?.destroy(),a=null,P.replaceChildren(),e.fail(k)}}async function p(){if(!f||e.stopped||!e.client.review)return;let r=++m;try{if(await e.client.review(),e.stopped||r!==m)return;f=!1,m++,a?.destroy(),a=null,P.replaceChildren(),P.hidden=!0,t.hidden=!1;let d=e.client.view;I(d)!==o?(R.set(o,structuredClone(e.answers)),e.resetScreen()):(R.delete(o),e.suspend(!1)),d&&await e.enqueue(d)}catch(d){if(r!==m||e.stopped)return;a?.destroy(),a=null,P.replaceChildren(),e.fail(d)}}return{get active(){return f},get receipt(){return c},open:L,exit:p,get drafts(){return new Map([...R].map(([r,d])=>[r,structuredClone(d)]))},stop(){f=!1,m++,a?.destroy(),a=null,P.replaceChildren(),P.hidden=!0,t.hidden=!1}}}function Fe(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let h=e.client.pageExperiments.bind(e.client),t=!1,P=!1,y=0,f=!1,c=!1,m,a=new Map,o=new Set,R={},I=new Map,L=be(e.appManifestRelease),p=()=>{for(let q of a.values())q.effect.revert();a.clear();for(let q of I.values())q();I.clear()};function r(q){t||o.has(q)||(o.add(q),h(e.appManifestRelease,[q]).catch(N=>{o.delete(q),B(e.onError,N)}))}async function d(){if(t)return;let q=e.client.view;if(!q||q.stopped||!["running","waiting"].includes(q.status)){y++,p();return}if(f){c=!0;return}f=!0;let N=++y,O=`${q.id}:${q.visit}:${q.revision}`,D=location.href;try{let[A,{applyVisualVariation:j}]=await Promise.all([h(e.appManifestRelease),import("./visual-dom-DQLPBZ2Z.js")]),G=e.client.view;if(t||N!==y||!G||G.stopped||!["running","waiting"].includes(G.status)||`${G.id}:${G.visit}:${G.revision}`!==O||location.href!==D)return;let W=new Set,J=new Set;for(let n of A.assignments){let s=`${A.payload.environmentId}:${n.experimentKey}`;if(J.add(s),I.has(s)||I.set(s,Ee(s,R)),!!n.inExperiment)for(let l of A.payload.experiments){if(l.key!==n.experimentKey||!pe(location.href,l.urlPatterns??[]))continue;let C=l.meta?.findIndex(M=>M.key===n.variationKey)??-1,u=l.variations[C];if(!u?.renderGuard)continue;let v=n.receiptId+":"+l.changeId,g=JSON.stringify([n.variationKey,u]);W.add(v);let S=a.get(v);if(S?.signature===g){S.effect.applied&&r(n.receiptId);continue}a.get(v)?.effect.revert(),a.delete(v);let _=j(u,{requireUniqueTargets:!0,boundVariations:l.variations,allowJs:!1,onApplied:()=>r(n.receiptId),onError:M=>B(e.onError,M)});a.set(v,{signature:g,effect:_}),_.applied&&r(n.receiptId)}}for(let[n,s]of a)W.has(n)||(s.effect.revert(),a.delete(n));for(let[n,s]of I)J.has(n)||(s(),I.delete(n))}catch(A){N===y&&p(),B(e.onError,A)}finally{f=!1,c&&!t&&(c=!1,d())}}let k=e.client.subscribe(()=>{y++,d()}),T=Ce(()=>{y++,p(),d()}),b=async()=>{await d(),t||(m=setTimeout(()=>{b()},15e3))};return{async start(){P||t||(P=!0,await b())},refresh:d,destroy(){t=!0,y++,clearTimeout(m),k(),T(),p(),L.destroy()}}}async function an(e,h){let t=h,{mountScreenPreview:P}=await import("./screen-renderer-NLB3FAQJ.js"),{showPaywall:y}=await import("./paywall-XQG2D3PA.js"),f=t.appManifestRelease?Fe({client:t.client,appManifestRelease:t.appManifestRelease,onError:t.onError}):void 0;f?.start();let c=e.ownerDocument,m=c.activeElement,a=c.createElement("section"),o=c.createElement("div"),R=c.createElement("div"),I=c.createElement("div"),L=c.createElement("button");I.hidden=!0,L.type="button";let p=c.createElement("p"),r=c.createElement("p"),d=c.createElement("button"),k=c.createElement("button"),T=c.createElement("button"),b=c.createElement("dialog"),q;a.dataset.indianaFunnel="",a.setAttribute("aria-busy","false"),a.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",R.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",p.setAttribute("role","status"),r.setAttribute("role","alert"),r.hidden=!0,d.type=k.type=T.type="button",R.append(d,p,r,T,L,k),a.append(o,I,R),e.append(a);let N=null,O=null,D=null,A="",j="",G="",W="",J="",n=!1,s=0,l=!1,C="",u=null,v=Promise.resolve(),g=null,S=null,_=new Set,M={},x=(i,E=null)=>{n||(S=E,r.textContent=i instanceof Error?i.message:"Request failed",r.hidden=!1,T.hidden=t.client.pendingCommand===null,B(t.onError,i))};function z(){let i=t.client.view;if(!i)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:i.nodeId,visit:i.visit,revision:i.revision}}let V=Se({client:t.client,doc:c,holder:o,reviewHolder:I,mountScreenPreview:P,get stopped(){return n},get answers(){return M},suspend(i){O?.setSuspended(i)},resetScreen(){A="",j="",G=""},enqueue:K,fail:x}),Z=Re({client:t.client,expected:z,fail:x,get stopped(){return n},get reviewing(){return V.active},get key(){return A},get busy(){return s}}),te=De({client:t.client,expected:z,perform:Y,onIntent:t.onCustomerDataIntent,get stopped(){return n},get busy(){return s},get document(){return N?.document},get answers(){return M}}),se=i=>i&&(i.screen||i.paywall)?`${i.id}:${i.nodeId}:${i.visit}`:"";function ee(){let i=t.client.view;d.disabled=!V.active&&(s>0||!!t.client.pendingCommand||!i?.canBack||i.stopped||!["running","waiting"].includes(i.status)||!se(i)||j!==se(i))}async function Y(i,E=!1){if(!(s&&!E||n||V.active&&!E)){s++,a.setAttribute("aria-busy","true"),ee(),r.hidden=!0,S=null;try{if(!E&&Z.inFlight){let F=t.client.view;await Z.inFlight;let $=t.client.view;if(!F||!$||$.id!==F.id||$.nodeId!==F.nodeId||$.visit!==F.visit||$.stopped||!["running","waiting"].includes($.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(n)return;let Q=await i();n||await K(t.client.view??Q.run)}catch(Q){x(Q,t.client.pendingCommand?.requestId??null)}finally{s=Math.max(0,s-1),a.setAttribute("aria-busy",String(s>0)),n||(T.hidden=t.client.pendingCommand===null,ee())}}}function ie(){u&&clearTimeout(u),!(n||!D||!["running","waiting"].includes(D.status)&&!t.client.pendingCommand)&&(u=setTimeout(()=>{u=null,de().finally(ie)},D.pendingRequest||t.client.pendingCommand?1500:5e3))}async function de(){if(!(n||l||s)){if(V.active){await V.open(V.receipt);return}l=!0;try{let i=t.client.pendingCommand;i&&t.client.settle&&await t.client.settle(i.requestId);let E=t.client.view,Q=te.queries,F=await t.client.get(E?.screen&&Object.keys(Q).length?{nodeId:E.nodeId,visit:E.visit,revision:E.revision,components:Q}:void 0);!n&&Q===te.queries&&await K(t.client.view??F.run)}catch(i){x(i)}finally{l=!1}}}function Ne(i){let E=i.screen?.presentation;if(!E||E.type==="inline"){b.open&&b.close(),a.parentElement!==e&&e.append(a);return}a.parentElement!==b&&(b.append(a),e.append(b));let Q={sm:420,md:640,lg:900};b.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in E?Q[E.size]+"px":"100vw"}`,b.setAttribute("aria-label",(q?.screen===i.screen?.content.document.name?q?.label:void 0)??N?.document?.name??i.screen?.content.document.name??"Funnel"),b.open||(b.showModal(),Ie(b,E.type))}async function Oe(i){if(n)return;D=i,S&&t.client.pendingCommand?.requestId!==S&&(r.hidden=!0,S=null);let E=i.locale.startsWith("zh");if(L.textContent=E?"\u56DE\u770B":"History",L.hidden=!t.client.review,d.textContent=V.active?E?"\u8FD4\u56DE\u5F53\u524D":"Return to current":E?"\u8FD4\u56DE":"Back",k.textContent=E?"\u5173\u95ED":"Close",T.textContent=E?"\u91CD\u8BD5":"Retry",ee(),T.hidden=t.client.pendingCommand===null,p.textContent=i.pendingRequest?E?"\u6B63\u5728\u5904\u7406":"Processing":i.instruction?.type==="wait"?E?"\u7B49\u5F85\u4E2D":"Waiting":"",C!==`${i.revision}:${i.visit}:${i.status}:${i.stopped}`&&(C=`${i.revision}:${i.visit}:${i.status}:${i.stopped}`,B(t.onState,structuredClone(i))),!i.pendingRequest&&["closed","ineligible","failed"].includes(i.status)){ne();return}if(i.stopped||t.client.configurationReady===!1){V.stop(),N?.destroy(),N=null,O?.destroy(),O=null,o.replaceChildren(),A="",j="",G="",J="",b.open&&b.close(),a.hidden=!0,ie();return}if(a.hidden=!1,V.active){ie();return}let Q=se(i);if(Q!==A&&(j="",N?.destroy(),N=null,O?.destroy(),O=null,o.replaceChildren(),A=Q,G="",J="",M={...i.answers},te.reset()),Ne(i),i.screen){let $=i.screen.content;N||(N=P(o,{mode:"live",rendererUrl:t.client.webViewUrl,title:$.document.name,onAction(U,ae={},le={}){if(V.active)return;M={...M,...le};let Ae=Object.fromEntries((i.screen?.inputs??[]).filter(({variable:oe})=>Object.hasOwn(M,oe)).map(({variable:oe})=>[oe,M[oe]]));Y(()=>t.client.submit({operation:"submit",...z(),input:{type:"screen",output:U,answers:Ae,selection:ae}}))},onAnswers:U=>{V.active||(M={...M,...U})},onCustomerDataIntent:U=>{V.active||te.intent(U).catch(x)},onEscape:()=>{V.active||re()},onError:U=>x(new Error(U)),onRendered:U=>{if(!U)return Z.report(Q);q={screen:$.document.name,label:U},b.open&&b.setAttribute("aria-label",U),Z.report(Q)}}));let H={capabilities:i.screen.capabilities,customerData:i.screen.customerData,parameters:i.parameters,serverInput:{bindings:i.screen.inputs,answers:M,values:i.screen.values}},X=JSON.stringify([$,i.locale,H.parameters,i.screen.inputs,i.screen.values]);if(X!==G)N.update($.document,i.locale,H),G=X,W=JSON.stringify(H.capabilities),J=JSON.stringify(H.customerData);else{let U=JSON.stringify(H.capabilities);U!==W&&(N.updateCapabilities(H.capabilities),W=U),JSON.stringify(H.customerData)!==J&&(N.updateCustomerData(H.customerData),J=JSON.stringify(H.customerData))}await N.ready}else if(i.paywall&&!O){let $=await y(o,{canInteract:()=>!V.active&&!n,start:async()=>Pe(t.client),onPurchase:t.onPurchase,onCheckoutUrl:t.onCheckoutUrl,resolveOfferId:t.resolveOfferId,onEvent:t.onEvent,onOpenUrl:H=>t.onOpenUrl?t.onOpenUrl({receiptId:i.paywall.receiptId,url:H,openIn:"same_window"}):c.defaultView?.location.assign(H),onAction:async H=>{if(V.active)return;let X=await t.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:i.nodeId,visit:i.visit,revision:i.revision,input:{type:"screen",output:H,answers:{}}});await K(t.client.view??X.run)},onError:x,onDismiss:()=>{!V.active&&!n&&t.client.view?.visit===i.visit&&re()}});n?$.host?.destroy():(O=$.host,O?.setSuspended(V.active)),Z.report(Q)}if(n)return;j=Q,ee();let F=i.instruction;if(F&&(F.type==="open_url"||F.type==="event")&&!_.has(F.receiptId)){let $=c.createElement("button");$.type="button",$.textContent=F.type==="open_url"?`${E?"\u524D\u5F80":"Continue to"} ${new URL(F.url).host}`:E?"\u7EE7\u7EED":"Continue",$.onclick=()=>{let H=z(),X=F.type==="open_url"&&!t.onOpenUrl&&F.openIn==="new_window"?ke(F.url):null;Y(async()=>{let U="success";if(F.type==="open_url")if(t.onOpenUrl)try{U=await t.onOpenUrl({receiptId:F.receiptId,url:F.url,openIn:F.openIn})===!1?"failed":"opened"}catch(le){B(t.onError,le),U="failed"}else U=F.openIn==="new_window"&&!X?"failed":"opened";if(F.type==="event"){if(!t.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await t.onEvent(F.event)}if(n||t.client.view?.nodeId!==H.nodeId||t.client.view.visit!==H.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let ae=await t.client.submit({operation:"submit",...H,input:{type:"client_action",receiptId:F.receiptId,outcome:U}});return _.add(F.receiptId),F.type==="open_url"&&!t.onOpenUrl&&F.openIn==="same_window"&&c.defaultView?.location.assign(F.url),ae})},o.replaceChildren($)}!i.pendingRequest&&i.status==="completed"&&!_.has(`complete:${i.id}`)&&(_.add(`complete:${i.id}`),B(t.onComplete,structuredClone(i))),ie()}function ke(i){let E=c.defaultView?.open(i,"_blank")??null;return E&&(E.opener=null),E}function K(i){return ee(),v=v.catch(()=>{}).then(()=>Oe(i)),v}let Te=t.client.subscribe(i=>{t.client.configurationReady===!1&&(a.hidden=!0,N?.destroy(),N=null,O?.destroy(),O=null,o.replaceChildren(),A="",j="",G="",J="",b.open&&b.close()),K(i).catch(x)}),qe=t.client.subscribeError?.(x);function re(){return g||(n?Promise.resolve():t.client.view&&!["running","waiting"].includes(t.client.view.status)?(ne(),Promise.resolve()):(g=Y(()=>t.client.submit({operation:"close",...z()}),!0).then(()=>{t.client.view?.status==="closed"&&ne()}).finally(()=>{g=null}),g))}function ne(){f?.destroy(),!n&&(n=!0,u&&clearTimeout(u),Te(),qe?.(),N?.destroy(),V.stop(),O?.destroy(),b.close(),b.remove(),a.remove(),m instanceof HTMLElement&&m.isConnected&&m.focus(),B(t.onDismiss,D?structuredClone(D):null))}d.onclick=()=>{if(!d.disabled){if(V.active){V.exit();return}Y(()=>t.client.submit({operation:"back",...z()}))}},L.onclick=()=>{V.open()},k.onclick=()=>{re()},T.onclick=()=>{Y(()=>t.client.retry())},b.addEventListener("cancel",i=>{i.preventDefault(),re()});try{let i=await t.client.get();await K(t.client.view??i.run)}catch(i){throw ne(),i}return{destroy:ne,refresh:de,review:V.open,exitReview:V.exit,get unappliedDrafts(){return V.drafts}}}export{Fe as a,an as b};
|