@tinkerlandai/indiana-sdk 0.10.1 → 0.10.2

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +28 -28
  3. package/README.zh-CN.md +22 -22
  4. package/dist/{chunk-ABNSU3ZG.js → chunk-CWHJKWOD.js} +1 -1
  5. package/dist/chunk-EARSGITJ.js +1 -0
  6. package/dist/{chunk-WYZI3TNB.js → chunk-FYGXGMRB.js} +1 -1
  7. package/dist/chunk-GHJ65ILJ.js +1 -0
  8. package/dist/chunk-JPV7F5XI.js +1 -0
  9. package/dist/{chunk-QUWPPZHH.js → chunk-LCLCG2I2.js} +1 -1
  10. package/dist/{chunk-2Y4G5364.js → chunk-Q64VNSPV.js} +3 -3
  11. package/dist/{chunk-CCPNMQHZ.js → chunk-V3RAOCVQ.js} +1 -1
  12. package/dist/{chunk-EDQCH2QS.js → chunk-VZVUZWP2.js} +1 -1
  13. package/dist/{chunk-AHXYGGAA.js → chunk-XO42OH3M.js} +1 -1
  14. package/dist/{configuration-sync-CXe9Zcng.d.ts → configuration-sync-CywDxRkX.d.ts} +1 -1
  15. package/dist/{content-ZRWZ26PF.js → content-QM75T7JO.js} +1 -1
  16. package/dist/{funnel-local-client-BQsdOjQ7.d.ts → funnel-local-client-DXamAj1-.d.ts} +2 -2
  17. package/dist/{funnel-resource-client-Zof1WLgA.d.ts → funnel-resource-client-md62M8Rv.d.ts} +2 -2
  18. package/dist/funnel-runtime-host-BJZUVJAI.js +1 -0
  19. package/dist/index.d.ts +5 -5
  20. package/dist/index.js +1 -1
  21. package/dist/native-shell.js +1 -1
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +2 -2
  24. package/dist/page.js +1 -1
  25. package/dist/{paywall-DR65VN2G.js → paywall-527RPFAX.js} +1 -1
  26. package/dist/react-native.d.ts +5 -5
  27. package/dist/react-native.js +1 -1
  28. package/dist/server.d.ts +5 -5
  29. package/dist/server.js +1 -1
  30. package/dist/visual.js +1 -1
  31. package/package.json +2 -2
  32. package/dist/chunk-6ZZUNGNE.js +0 -1
  33. package/dist/chunk-IWWKVNEX.js +0 -1
  34. package/dist/chunk-Y46ALAKP.js +0 -1
  35. package/dist/funnel-runtime-host-N7TX3LWI.js +0 -1
@@ -1 +1 @@
1
- import{ia as E,ja as M,ka as j,la as O,ma as T}from"./chunk-2Y4G5364.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
+ import{ia as E,ja as M,ka as j,la as O,ma as T}from"./chunk-Q64VNSPV.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-WYZI3TNB.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-2Y4G5364.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-FYGXGMRB.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-Q64VNSPV.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-IWWKVNEX.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
+ import{a as u}from"./chunk-DSPLGTQI.js";import{b as d}from"./chunk-GHJ65ILJ.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};
@@ -90,7 +90,7 @@ type ConfigurationStorage = {
90
90
  };
91
91
 
92
92
  type ConfigurationSyncOptions = {
93
- /** Public configuration origin; defaults to https://api.tinker.cash. */
93
+ /** Public configuration origin; defaults to https://api.longplayai.com. */
94
94
  origin?: string;
95
95
  scope: ConfigurationScope;
96
96
  fetch?: typeof globalThis.fetch;
@@ -1 +1 @@
1
- import{f as _,j as F}from"./chunk-X6BCUINI.js";import{b as q}from"./chunk-SSLZKIIU.js";import{L as U}from"./chunk-2Y4G5364.js";import{Y as P,ca as M,ja as z,ka as N,qa as d}from"./chunk-ACF2FBUB.js";import{a as v}from"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-IWWKVNEX.js";import{a as O}from"./chunk-7DXL3LHT.js";import"./chunk-3PZ4Y6UD.js";import{z as p}from"zod";var V=new WeakMap;function Q(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:O}[r.type];return r.nullable?t.nullable():t}async function ne(r,t){return W(r,t,!1)}async function re(r,t){return W(r,t,!0)}async function W(r,t,w){t.signal?.throwIfAborted();let T=U.parse(t.content),o=T.document;if(V.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),O).parse(t.inputs??{});if(Object.keys(f).length>40)throw new d("INVALID_REQUEST","Too many content inputs");for(let[e,s]of Object.entries(f))z.parse({[e]:s});if(Object.keys(f).some(e=>!Object.hasOwn(o.contract.inputs,e)))throw new d("INVALID_REQUEST","Undeclared content input");for(let[e,s]of Object.entries(o.contract.inputs))if(Object.hasOwn(f,e))Q(s).parse(f[e]);else if(s.required)throw new d("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(o.contract.outputs))if(typeof t.actions[e]!="function")throw new d("INVALID_REQUEST",`Missing host handler for ${e}`);let $=N.parse(t.bindings??[]),a=r.ownerDocument,L,k=o.kind==="popup",n=k?a.createElement("dialog"):null,i=a.createElement("div");if(i.dataset.indianaContent=o.kind,i.setAttribute("aria-label",o.name),i.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",o.name);let e=o.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${P[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(i),r.append(n)}else r.append(i);let c=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||a.defaultView?.innerWidth||800}px`);let B=w?_(n??i):()=>{},H,x,A=new Promise((e,s)=>{H=e,x=s});A.catch(()=>{});let l=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let b;function m(){c||(c=!0,t.signal?.removeEventListener("abort",m),x(new Error("Content preparation cancelled")),b?.destroy(),n?.close(),n?.remove(),i.remove(),V.delete(r),n&&L?.())}let S=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=a.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),e.style.cssText="position:absolute;right:8px;top:8px;width:30px;height:30px;z-index:1",e.addEventListener("click",S),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),S()});async function D(){if(c||!g||C||!l)return;let e=l;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),l=null}catch(s){v(t.onError,s)}finally{C=!1,c||i.removeAttribute("aria-busy")}}function R(){if(c)throw new d("CONFLICT","Content host has been destroyed");g||(L=q(a),B(),w&&!n&&(i.style.width="100%"),n?.showModal(),g=!0)}try{w||R(),b=F(i,{mode:"live",title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||a.defaultView?.innerHeight||800:void 0,onRendered:H,onError:u=>{let I=new Error(u);x(I),v(t.onError,I)},onEscape:k?S:void 0,onAction:(u,I,J)=>{if(c||!g||C||l)return;let h=o.screen.actions.find(y=>y.id===u),j=o.contract.outputs[u];if(!(h?.type!=="event"||!j))try{let y=Q(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);l={requestId:crypto.randomUUID(),contentVersionId:T.id,actionId:u,event:h.event,value:y,selection:I??{},answers:J??{},requestedClose:h.close},D()}catch(y){v(t.onError,y)}}});let e={destroy:m,show:R,get pendingAction(){return l?structuredClone(l):null},retryAction:D,updateCapabilities:u=>b?.updateCapabilities(u)};V.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=M(E,[t.locale,...a.defaultView?.navigator.languages??[]]);if(b.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:$,answers:{},values:f}}),await Promise.race([b.ready,A]),w&&await A,c)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ne as mountContent,re as prepareContent};
1
+ import{f as _,j as F}from"./chunk-X6BCUINI.js";import{b as q}from"./chunk-SSLZKIIU.js";import{L as U}from"./chunk-Q64VNSPV.js";import{Y as P,ca as M,ja as z,ka as N,qa as d}from"./chunk-ACF2FBUB.js";import{a as v}from"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-GHJ65ILJ.js";import{a as O}from"./chunk-7DXL3LHT.js";import"./chunk-3PZ4Y6UD.js";import{z as p}from"zod";var V=new WeakMap;function Q(r){let t={string:p.string(),number:p.number().finite(),boolean:p.boolean(),strings:p.array(p.string()),json:O}[r.type];return r.nullable?t.nullable():t}async function ne(r,t){return W(r,t,!1)}async function re(r,t){return W(r,t,!0)}async function W(r,t,w){t.signal?.throwIfAborted();let T=U.parse(t.content),o=T.document;if(V.has(r))throw new d("CONFLICT","Content is already mounted in this container");let f=p.record(p.string(),O).parse(t.inputs??{});if(Object.keys(f).length>40)throw new d("INVALID_REQUEST","Too many content inputs");for(let[e,s]of Object.entries(f))z.parse({[e]:s});if(Object.keys(f).some(e=>!Object.hasOwn(o.contract.inputs,e)))throw new d("INVALID_REQUEST","Undeclared content input");for(let[e,s]of Object.entries(o.contract.inputs))if(Object.hasOwn(f,e))Q(s).parse(f[e]);else if(s.required)throw new d("INVALID_REQUEST",`Missing content input ${e}`);for(let e of Object.keys(o.contract.outputs))if(typeof t.actions[e]!="function")throw new d("INVALID_REQUEST",`Missing host handler for ${e}`);let $=N.parse(t.bindings??[]),a=r.ownerDocument,L,k=o.kind==="popup",n=k?a.createElement("dialog"):null,i=a.createElement("div");if(i.dataset.indianaContent=o.kind,i.setAttribute("aria-label",o.name),i.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",o.name);let e=o.screen.presentation;n.style.cssText="box-sizing:border-box;padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto",e.type==="modal"||e.type==="sheet"?(n.style.width=`${P[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",n.append(i),r.append(n)}else r.append(i);let c=!1,C=!1,g=!1;w&&!n&&(i.style.width=`${r.getBoundingClientRect().width||a.defaultView?.innerWidth||800}px`);let B=w?_(n??i):()=>{},H,x,A=new Promise((e,s)=>{H=e,x=s});A.catch(()=>{});let l=null,E=structuredClone(o.screen);E.actions=E.actions.map(e=>e.type==="event"?{...e,close:!1}:e);let b;function m(){c||(c=!0,t.signal?.removeEventListener("abort",m),x(new Error("Content preparation cancelled")),b?.destroy(),n?.close(),n?.remove(),i.remove(),V.delete(r),n&&L?.())}let S=()=>{g&&(m(),v(t.onDismiss))};if(n){let e=a.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),e.style.cssText="position:absolute;right:8px;top:8px;width:30px;height:30px;z-index:1",e.addEventListener("click",S),n.prepend(e)}n?.addEventListener("cancel",e=>{e.preventDefault(),S()});async function D(){if(c||!g||C||!l)return;let e=l;C=!0,i.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),l=null}catch(s){v(t.onError,s)}finally{C=!1,c||i.removeAttribute("aria-busy")}}function R(){if(c)throw new d("CONFLICT","Content host has been destroyed");g||(L=q(a),B(),w&&!n&&(i.style.width="100%"),n?.showModal(),g=!0)}try{w||R(),b=F(i,{mode:"live",title:o.name,viewportHeight:o.kind==="page"?r.clientHeight||a.defaultView?.innerHeight||800:void 0,onRendered:H,onError:u=>{let I=new Error(u);x(I),v(t.onError,I)},onEscape:k?S:void 0,onAction:(u,I,J)=>{if(c||!g||C||l)return;let h=o.screen.actions.find(y=>y.id===u),j=o.contract.outputs[u];if(!(h?.type!=="event"||!j))try{let y=Q(j).parse(Object.hasOwn(h.properties,"value")?h.properties.value:h.properties);l={requestId:crypto.randomUUID(),contentVersionId:T.id,actionId:u,event:h.event,value:y,selection:I??{},answers:J??{},requestedClose:h.close},D()}catch(y){v(t.onError,y)}}});let e={destroy:m,show:R,get pendingAction(){return l?structuredClone(l):null},retryAction:D,updateCapabilities:u=>b?.updateCapabilities(u)};V.set(r,e),t.signal?.addEventListener("abort",m,{once:!0}),t.signal?.aborted&&(m(),t.signal.throwIfAborted());let s=M(E,[t.locale,...a.defaultView?.navigator.languages??[]]);if(b.update(E,s,{capabilities:t.capabilities,serverInput:{bindings:$,answers:{},values:f}}),await Promise.race([b.ready,A]),w&&await A,c)throw new Error("Content preparation cancelled");return e}catch(e){throw m(),e}}export{ne as mountContent,re as prepareContent};
@@ -3,7 +3,7 @@ import { z } from 'zod';
3
3
  import { I as InvoiceModeParams, a as InvoiceModeParamsInput, A as ApiInput } from './api-DC44FaTV.js';
4
4
  import { S as StackNode, a as ScreenSelection } from './screen-D81zCpfi.js';
5
5
  import { J as JsonValue, E as EvaluationContext, F as FeatureResult } from './growth-rules-B4YYy64R.js';
6
- import { a as ConfigurationSync } from './configuration-sync-CXe9Zcng.js';
6
+ import { a as ConfigurationSync } from './configuration-sync-CywDxRkX.js';
7
7
 
8
8
  declare const scopeSchema: z.ZodObject<{
9
9
  projectId: z.ZodString;
@@ -12764,7 +12764,7 @@ interface IndianaOptions {
12764
12764
  funnelCommandStorage?: FunnelCommandStorage;
12765
12765
  /** One public GB/Funnel configuration manager shared by this App/environment's consumers. */
12766
12766
  configuration?: ConfigurationSync;
12767
- /** API origin. Defaults to https://api.tinker.cash; override for test/local services. */
12767
+ /** API origin. Defaults to https://api.longplayai.com; override for test/local services. */
12768
12768
  baseUrl?: string;
12769
12769
  fetch?: typeof globalThis.fetch;
12770
12770
  timeoutMs?: number;
@@ -2,8 +2,8 @@ import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
3
  import { S as StackNode } from './screen-D81zCpfi.js';
4
4
  import { I as InvoiceModeParams } from './api-DC44FaTV.js';
5
- import { g as FunnelRuntimeResponse, F as FunnelRunView, h as FunnelMutation, l as FunnelPurchaseRecovery, d as FunnelSegmentPrediction, e as PaywallDelivery, x as PaywallResolution, f as FunnelDataQueries, I as IndianaOptions, j as FeatureClientOptions } from './funnel-local-client-BQsdOjQ7.js';
6
- import { a as ConfigurationSync } from './configuration-sync-CXe9Zcng.js';
5
+ import { g as FunnelRuntimeResponse, F as FunnelRunView, h as FunnelMutation, l as FunnelPurchaseRecovery, d as FunnelSegmentPrediction, e as PaywallDelivery, x as PaywallResolution, f as FunnelDataQueries, I as IndianaOptions, j as FeatureClientOptions } from './funnel-local-client-DXamAj1-.js';
6
+ import { a as ConfigurationSync } from './configuration-sync-CywDxRkX.js';
7
7
 
8
8
  /** The store supplies the intent hint. Only verified provider facts prove ownership. */
9
9
  declare const nativeRestoreCommandSchema: z.ZodUnion<readonly [z.ZodObject<{
@@ -0,0 +1 @@
1
+ import{b as a}from"./chunk-LCLCG2I2.js";import"./chunk-SBPTOOYB.js";import"./chunk-Q64VNSPV.js";import"./chunk-ACF2FBUB.js";import"./chunk-EARSGITJ.js";import"./chunk-XO42OH3M.js";import"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-GHJ65ILJ.js";import"./chunk-7DXL3LHT.js";import"./chunk-3PZ4Y6UD.js";export{a as showFunnelRun};
package/dist/index.d.ts CHANGED
@@ -3,16 +3,16 @@ import { z } from 'zod';
3
3
  import { S as ScreenAnswers, s as screenInputBindingsSchema, a as SurfaceData, C as CustomerDataIntent } from './customer-page-km5f1PJZ.js';
4
4
  import { J as JsonValue, F as FeatureResult } from './growth-rules-B4YYy64R.js';
5
5
  import { S as StackNode, a as ScreenSelection } from './screen-D81zCpfi.js';
6
- import { P as PaywallSession, S as SubscriptionOperation, F as FunnelRunView, I as IndianaOptions, C as CustomerSession, R as RemoteFeatureResult, a as PushAddressObservation, b as FunnelCommandStorage, c as FunnelStartInput, d as FunnelSegmentPrediction, e as PaywallDelivery, f as FunnelDataQueries, g as FunnelRuntimeResponse, h as FunnelMutation } from './funnel-local-client-BQsdOjQ7.js';
7
- export { i as FeatureClient, j as FeatureClientOptions, k as FunnelPendingEntry, l as FunnelPurchaseRecovery, m as IndianaError, L as LocalFunnelClient, n as LocalFunnelClientOptions, o as PaywallPurchaseInput, p as PaywallStartInput, q as PushHost, r as PushJournal, s as SessionCredentials, t as createFeatureClient, u as createLocalFunnelClient, v as createPaywallSession } from './funnel-local-client-BQsdOjQ7.js';
8
- import { F as FunnelRunController, a as FunnelResourceSource, I as IndianaFeatureOptions, N as NativeRestoreCommand } from './funnel-resource-client-Zof1WLgA.js';
9
- export { b as FunnelControllerResponse, c as createFunnelRunController } from './funnel-resource-client-Zof1WLgA.js';
6
+ import { P as PaywallSession, S as SubscriptionOperation, F as FunnelRunView, I as IndianaOptions, C as CustomerSession, R as RemoteFeatureResult, a as PushAddressObservation, b as FunnelCommandStorage, c as FunnelStartInput, d as FunnelSegmentPrediction, e as PaywallDelivery, f as FunnelDataQueries, g as FunnelRuntimeResponse, h as FunnelMutation } from './funnel-local-client-DXamAj1-.js';
7
+ export { i as FeatureClient, j as FeatureClientOptions, k as FunnelPendingEntry, l as FunnelPurchaseRecovery, m as IndianaError, L as LocalFunnelClient, n as LocalFunnelClientOptions, o as PaywallPurchaseInput, p as PaywallStartInput, q as PushHost, r as PushJournal, s as SessionCredentials, t as createFeatureClient, u as createLocalFunnelClient, v as createPaywallSession } from './funnel-local-client-DXamAj1-.js';
8
+ import { F as FunnelRunController, a as FunnelResourceSource, I as IndianaFeatureOptions, N as NativeRestoreCommand } from './funnel-resource-client-md62M8Rv.js';
9
+ export { b as FunnelControllerResponse, c as createFunnelRunController } from './funnel-resource-client-md62M8Rv.js';
10
10
  import { C as CouponInput, O as Offer } from './coupon-fA1QujHt.js';
11
11
  export { a as OfferUnavailableReason } from './coupon-fA1QujHt.js';
12
12
  import { M as MerchantBridgeManifest } from './funnel-node-evaluation-P5B4fPfJ.js';
13
13
  export { F as FunnelNodeEvaluationContext, e as evaluateFunnelNode } from './funnel-node-evaluation-P5B4fPfJ.js';
14
14
  import { A as ApiInput, O as OfferingItem, I as InvoiceModeParams } from './api-DC44FaTV.js';
15
- export { C as ConfigurationStorage, a as ConfigurationSync, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-CXe9Zcng.js';
15
+ export { C as ConfigurationStorage, a as ConfigurationSync, b as ConfigurationSyncOptions, c as createConfigurationSync } from './configuration-sync-CywDxRkX.js';
16
16
  import 'zod/v4';
17
17
 
18
18
  /** Currency always comes from business data; locale only controls notation. No currency conversion. */
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as ke,b as be}from"./chunk-QUWPPZHH.js";import{a as Oe,c as He}from"./chunk-EDQCH2QS.js";import{a as Fe}from"./chunk-Y46ALAKP.js";import{b as De,g as Pe,l as z,m as xe,n as Be,p as Le}from"./chunk-WYZI3TNB.js";import"./chunk-SBPTOOYB.js";import{F as Me,G as Ne,H as Te,Ka as ge,La as we,Ma as Ee,Qa as ve,i as oe,k as q,l as ae,m as ie,n as se,o as ce,p as de,q as ue,qa as ye,r as le,s as me,t as fe,u as pe,w as $,x as he,y as Ie}from"./chunk-2Y4G5364.js";import{qa as P}from"./chunk-ACF2FBUB.js";import{c as _e}from"./chunk-CLXORAOK.js";import"./chunk-6ZZUNGNE.js";import{c as Se,d as Re}from"./chunk-AHXYGGAA.js";import{a as G}from"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-IWWKVNEX.js";import"./chunk-7DXL3LHT.js";import"./chunk-3PZ4Y6UD.js";import{z as U}from"zod";var r=class extends Error{constructor(u,x=0,h=!1,m="fix_request"){super(u);this.code=u;this.status=x;this.retryable=h;this.recovery=m;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function Ge(n,_){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");let u=n.body?.getReader();if(!u)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");let x=()=>{u.cancel().catch(()=>{})};_.addEventListener("abort",x,{once:!0});let h=0,m="",a=new TextDecoder("utf-8",{fatal:!0});try{for(_.throwIfAborted();;){let d=await u.read();if(_.throwIfAborted(),d.done)break;if(h+=d.value.byteLength,h>262144)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");m+=a.decode(d.value,{stream:!0})}return m+=a.decode(),JSON.parse(m)}catch(d){throw _.throwIfAborted(),d instanceof r?d:new r("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{_.removeEventListener("abort",x),await u.cancel().catch(()=>{}),u.releaseLock()}}function Ue(n){let _=ce.parse(n.origin),u=de.parse(n.manifest),x={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let o of["projectId","environmentId","environment"])if(u[o]!==n.scope[o])throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");let h=n.customerId===void 0?null:U.uuid().parse(n.customerId),m=0,a=null,d=null,B=new AbortController,H=n.fetch??globalThis.fetch;async function M(o,t,i,y,N){if(!u.capabilities.includes(o))throw new r("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let E=se[o];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(E.authority))throw new r("MERCHANT_BRIDGE_FORBIDDEN",403);let T=m,O=AbortSignal.any([B.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...y?[y]:[]]);O.throwIfAborted();let v=new Headers(await n.headers?.());if(O.throwIfAborted(),T!==m)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(v.get("authorization")??"")||v.has("X-Indiana-Bridge-Signature")||v.has("X-Indiana-Bridge-Key-Id"))throw new r("MERCHANT_BRIDGE_FORBIDDEN",403);v.set(ie,String(q)),v.set("Accept","application/json");let S=crypto.randomUUID();v.set("X-Request-Id",S),v.set("Content-Type","application/json");let f=await H(_+ae,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:v,signal:O,body:JSON.stringify({bridgeVersion:q,requestId:S,command:E.command,scope:x,data:N??(i===void 0?{}:{operationId:i})})}),D=await Ge(f,O);if(O.throwIfAborted(),T!==m)throw new DOMException("Merchant identity changed","AbortError");if(!f.ok){let g=Ie.safeParse(D);throw!g.success||g.data.scope.projectId!==n.scope.projectId||g.data.scope.environment!==n.scope.environment||g.data.scope.environmentId!==n.scope.environmentId||g.data.requestId!==S||g.data.command!==E.command?new r("MERCHANT_BRIDGE_INVALID_RESPONSE",f.status):new r(g.data.error.code,f.status,g.data.error.retryable,g.data.error.recovery)}let R=ue(U.unknown()).safeParse(D);if(!R.success||R.data.scope.projectId!==n.scope.projectId||R.data.scope.environment!==n.scope.environment||R.data.scope.environmentId!==n.scope.environmentId||R.data.requestId!==S||R.data.command!==E.command)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE",f.status);let I=t.safeParse(R.data.data);if(!I.success)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE",f.status);return I.data}function w(){if(!h)throw new r("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return h}async function F(o,t,i,y){let N=w(),E=pe.parse({operationId:i,customerId:N}),T=await M(o,t,E.operationId,y,E);if(T.customerId!==N||T.operationId!==E.operationId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return T}return{async readPresentation(o){let t=await M("presentation",me,void 0,o);if(d!==null&&d!==t.nativeUserId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t.presentation&&h!==null&&t.presentation.customerId!==h)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return d=t.nativeUserId,a=t.presentation,t},async createSession(o){let t=await M("session",le,void 0,o);if(d!==null&&d!==t.nativeUserId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(h!==null&&h!==t.session.customerId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(a&&a.customerId!==t.session.customerId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return h=t.session.customerId,d=t.nativeUserId,t.session},async reportPresentation(o,t){let i=w(),y=fe.parse(o);if(!a||a.customerId!==i||a.decisionId!==y.decisionId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return M("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,t,y)},async readCustomerCommerce(o){let t=w(),i=await M("customer_commerce",he,void 0,o);if(i.customerId!==t)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i},async executePurchase(o,t){let i=await F("purchases",$,o,t);if(i.type!=="purchase")throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");return i},readOperation:(o,t)=>F("operation_status",oe,o,t),async executeSubscriptionChange(o,t){let i=await F("subscription_changes",$,o,t);if(i.type!=="subscription_change")throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");return i},reset(){m++,B.abort(),B=new AbortController,h=null,a=null,d=null}}}function je(n){let _=Se(n.baseUrl),u=n.scope,x=ve(n),h=n.fetch??globalThis.fetch.bind(globalThis),m,a=!1,d=!1,B=0,H=0,M="",w=0,F=0,o=0,t,i=!1,y,N=!0,E,T,O,v,S,f,D=e=>{f===e&&(f=void 0)},R=new Set,I=(e,l)=>G(n.onStatus,e,l);function g(){let e=S;S=void 0,e?.host.destroy(),e?.client.reset()}let K=()=>Date.now()<F&&performance.now()<o;function J(e){if(e.target.release!==n.appManifestRelease||!K())return!1;try{return _e(e.target.render,document,location.pathname,()=>{})}catch{return I("incompatible",e.id),!1}}function j(e){return!a&&e.epoch===w&&e.visit===H&&document.visibilityState!=="hidden"}async function X(e){if(f||S){I("in_progress",e.id);return}if(!n.session.peek()){I("identity_required",e.id);return}let l={command:we.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:crypto.randomUUID(),locale:document.documentElement.lang||"en"}),epoch:w,visit:H};f=l,await Z(l)}async function Z(e){if(e.dispatching)return;e.dispatching=!0;let l,b=!1;async function p(s){if(e.epoch!==w)return;let c=s.view;c&&["running","waiting"].includes(c.status)&&await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:c.nodeId,visit:c.visit,revision:c.revision})}try{I("starting",e.command.entryId);let s=await x.request("funnels",e.command),c=Ee.safeParse(s);if(c.success){if(c.data.scope.projectId!==u.projectId||c.data.scope.environment!==u.environment)throw new P("SCOPE_MISMATCH","Entry scope changed");e.epoch===w&&I(c.data.reason,e.command.entryId),D(e);return}let C=ye.parse(s);if(!C.runToken||C.scope.projectId!==u.projectId||C.scope.environment!==u.environment||C.run.source.type!=="funnel"||C.run.source.id!==e.command.funnelId||C.run.source.versionId!==e.command.versionId)throw new P("INVALID_RESPONSE","Invalid entry Run");if(e.epoch!==w){D(e),I("identity_changed",e.command.entryId);return}let A=z({...n,runToken:C.runToken,funnelId:e.command.funnelId});l=A,await A.get();let k=A.view;if(!k||k.id!==C.run.id||k.source.type!=="funnel"||k.source.id!==e.command.funnelId||k.source.versionId!==e.command.versionId)throw new P("INVALID_RESPONSE","Entry Run version changed");if(!j(e)){await p(A),I("left_screen",e.command.entryId),D(e);return}let ne=!1,te=!1,re=await be(n.container,{...n.host,client:A,appManifestRelease:n.appManifestRelease,onDismiss(V){ne=!0,S?.client===A&&(S=void 0,A.reset()),G(n.host?.onDismiss,V)},onComplete(V){te=!0,S?.client===A&&g(),G(n.host?.onComplete,V)}});if(!j(e)||ne||te){re.destroy(),j(e)||await p(A),D(e);return}S={host:re,client:A},b=!0,D(e),I("started",e.command.entryId)}catch(s){!l&&s instanceof P&&s.status!==void 0&&s.status>=400&&s.status<500&&!s.retryable&&D(e),e.epoch===w&&!a&&(I("start_failed",e.command.entryId),G(n.host?.onError,s))}finally{b||l?.reset(),e.dispatching=!1}}function Ce(){if(i=!1,!(a||!d||!K()||document.visibilityState==="hidden")){N=!1;for(let e of m?.entries??[])if(!(e.event!=="screen_enter"||R.has(`${e.funnelId}:${e.id}`)||!J(e))){if(!n.session.peek()){I("identity_required",e.id);continue}R.add(`${e.funnelId}:${e.id}`),X(e);break}}}let L=()=>{!i&&!a&&(i=!0,queueMicrotask(Ce))};function Ae(){let e=location.origin+location.pathname;e!==M&&(M=e,H++,N=!0,R.clear(),L())}function Y(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let l=e.target;if(!(l instanceof Element)||l.closest("[data-indiana-funnel]"))return;let b=l.closest("button,a,input");if(!(!b||b.matches(":disabled,[aria-disabled='true']")||b.closest("[hidden],[inert],[aria-hidden='true']")))for(let p of m?.entries??[]){let s=p.target.button;if(p.event!=="button_click"||!s||!J(p))continue;let c=document.querySelectorAll(s.selector);if(!(c.length!==1||c[0]!==b)){X(p);break}}}async function Q(){if(a)return;if(y)return y;let e=++B;E=new AbortController;let l=(async()=>{let b=await h(`${_}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",signal:E.signal});if(!b.ok)throw new P("SERVICE_UNAVAILABLE","Funnel entries unavailable",b.status);let p=ge.parse(await b.json()),s=Date.parse(p.validatedAt),c=Date.parse(p.validUntil);if(p.scope.projectId!==u.projectId||p.scope.environment!==u.environment||p.scope.environmentId!==n.environmentId||p.release!==n.appManifestRelease||c<=Date.now()||s>Date.now()+5e3||c-s>6e4||c<=s)throw new P("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(a||e!==B)return;let C=m===void 0;m=p,F=c,o=performance.now()+Math.min(c-Date.now(),6e4),(C||N)&&L()})();y=l;try{await l}finally{y===l&&(y=void 0)}}async function W(){try{await Q()}catch{I("configuration_unavailable")}a||(t=setTimeout(()=>{W()},15e3))}let ee=()=>L();return{async start(){d||a||(d=!0,M=location.origin+location.pathname,T=Re(Ae),O=n.session.subscribeIdentity(()=>{w++,N=!0,f=void 0,R.clear(),g(),L()}),v=new MutationObserver(L),v.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id"]}),document.addEventListener("click",Y,!0),document.addEventListener("visibilitychange",ee),await W())},refresh:Q,async retry(){f&&!a&&f.epoch===w&&await Z(f)},destroy(){a=!0,B++,clearTimeout(t),E?.abort(),v?.disconnect(),T?.(),O?.(),document.removeEventListener("click",Y,!0),document.removeEventListener("visibilitychange",ee),g(),m=void 0}}}async function nn(...n){return(await import("./paywall-DR65VN2G.js")).showPaywall(...n)}async function tn(...n){return(await import("./funnel-runtime-host-N7TX3LWI.js")).showFunnelRun(...n)}async function rn(...n){return(await import("./content-ZRWZ26PF.js")).mountContent(...n)}async function on(...n){return(await import("./content-ZRWZ26PF.js")).prepareContent(...n)}export{P as IndianaError,r as MerchantBridgeError,Pe as createBrowserFunnelCommandStorage,Be as createConfigurationSync,De as createFeatureClient,He as createFunnelClient,ke as createFunnelPageExperiments,z as createFunnelRunController,je as createIamFunnelEntries,Oe as createIndiana,Le as createLocalFunnelClient,Ue as createMerchantBridge,xe as createPaywallSession,Fe as evaluateFunnelNode,Ne as formatCouponDiscount,Me as formatCouponMoney,Te as formatCouponTerms,rn as mountContent,on as prepareContent,tn as showFunnelRun,nn as showPaywall};
1
+ import{a as ke,b as be}from"./chunk-LCLCG2I2.js";import{a as Oe,c as He}from"./chunk-VZVUZWP2.js";import{a as Fe}from"./chunk-JPV7F5XI.js";import{b as De,g as Pe,l as z,m as xe,n as Be,p as Le}from"./chunk-FYGXGMRB.js";import"./chunk-SBPTOOYB.js";import{F as Me,G as Ne,H as Te,Ka as Ee,La as ge,Ma as we,Qa as ve,i as oe,k as q,l as ae,m as ie,n as se,o as ce,p as de,q as ue,qa as ye,r as le,s as me,t as fe,u as pe,w as $,x as he,y as Ie}from"./chunk-Q64VNSPV.js";import{qa as P}from"./chunk-ACF2FBUB.js";import{c as _e}from"./chunk-CLXORAOK.js";import"./chunk-EARSGITJ.js";import{c as Se,d as Re}from"./chunk-XO42OH3M.js";import{a as L}from"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-GHJ65ILJ.js";import"./chunk-7DXL3LHT.js";import"./chunk-3PZ4Y6UD.js";import{z as j}from"zod";var r=class extends Error{constructor(u,B=0,I=!1,f="fix_request"){super(u);this.code=u;this.status=B;this.retryable=I;this.recovery=f;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function Ge(n,_){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");let u=n.body?.getReader();if(!u)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");let B=()=>{u.cancel().catch(()=>{})};_.addEventListener("abort",B,{once:!0});let I=0,f="",a=new TextDecoder("utf-8",{fatal:!0});try{for(_.throwIfAborted();;){let d=await u.read();if(_.throwIfAborted(),d.done)break;if(I+=d.value.byteLength,I>262144)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");f+=a.decode(d.value,{stream:!0})}return f+=a.decode(),JSON.parse(f)}catch(d){throw _.throwIfAborted(),d instanceof r?d:new r("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{_.removeEventListener("abort",B),await u.cancel().catch(()=>{}),u.releaseLock()}}function Ue(n){let _=ce.parse(n.origin),u=de.parse(n.manifest),B={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let o of["projectId","environmentId","environment"])if(u[o]!==n.scope[o])throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");let I=n.customerId===void 0?null:j.uuid().parse(n.customerId),f=0,a=null,d=null,F=new AbortController,k=n.fetch??globalThis.fetch;async function M(o,t,i,E,N){if(!u.capabilities.includes(o))throw new r("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let v=se[o];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(v.authority))throw new r("MERCHANT_BRIDGE_FORBIDDEN",403);let T=f,x=AbortSignal.any([F.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...E?[E]:[]]);x.throwIfAborted();let S=new Headers(await n.headers?.());if(x.throwIfAborted(),T!==f)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(S.get("authorization")??"")||S.has("X-Indiana-Bridge-Signature")||S.has("X-Indiana-Bridge-Key-Id"))throw new r("MERCHANT_BRIDGE_FORBIDDEN",403);S.set(ie,String(q)),S.set("Accept","application/json");let g=crypto.randomUUID();S.set("X-Request-Id",g),S.set("Content-Type","application/json");let p=await k(_+ae,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:S,signal:x,body:JSON.stringify({bridgeVersion:q,requestId:g,command:v.command,scope:B,data:N??(i===void 0?{}:{operationId:i})})}),D=await Ge(p,x);if(x.throwIfAborted(),T!==f)throw new DOMException("Merchant identity changed","AbortError");if(!p.ok){let y=Ie.safeParse(D);throw!y.success||y.data.scope.projectId!==n.scope.projectId||y.data.scope.environment!==n.scope.environment||y.data.scope.environmentId!==n.scope.environmentId||y.data.requestId!==g||y.data.command!==v.command?new r("MERCHANT_BRIDGE_INVALID_RESPONSE",p.status):new r(y.data.error.code,p.status,y.data.error.retryable,y.data.error.recovery)}let R=ue(j.unknown()).safeParse(D);if(!R.success||R.data.scope.projectId!==n.scope.projectId||R.data.scope.environment!==n.scope.environment||R.data.scope.environmentId!==n.scope.environmentId||R.data.requestId!==g||R.data.command!==v.command)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE",p.status);let l=t.safeParse(R.data.data);if(!l.success)throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE",p.status);return l.data}function w(){if(!I)throw new r("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return I}async function H(o,t,i,E){let N=w(),v=pe.parse({operationId:i,customerId:N}),T=await M(o,t,v.operationId,E,v);if(T.customerId!==N||T.operationId!==v.operationId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return T}return{async readPresentation(o){let t=await M("presentation",me,void 0,o);if(d!==null&&d!==t.nativeUserId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t.presentation&&I!==null&&t.presentation.customerId!==I)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return d=t.nativeUserId,a=t.presentation,t},async createSession(o){let t=await M("session",le,void 0,o);if(d!==null&&d!==t.nativeUserId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(I!==null&&I!==t.session.customerId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(a&&a.customerId!==t.session.customerId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return I=t.session.customerId,d=t.nativeUserId,t.session},async reportPresentation(o,t){let i=w(),E=fe.parse(o);if(!a||a.customerId!==i||a.decisionId!==E.decisionId)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return M("presentation_events",j.strictObject({queued:j.literal(!0)}),void 0,t,E)},async readCustomerCommerce(o){let t=w(),i=await M("customer_commerce",he,void 0,o);if(i.customerId!==t)throw new r("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i},async executePurchase(o,t){let i=await H("purchases",$,o,t);if(i.type!=="purchase")throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");return i},readOperation:(o,t)=>H("operation_status",oe,o,t),async executeSubscriptionChange(o,t){let i=await H("subscription_changes",$,o,t);if(i.type!=="subscription_change")throw new r("MERCHANT_BRIDGE_INVALID_RESPONSE");return i},reset(){f++,F.abort(),F=new AbortController,I=null,a=null,d=null}}}function je(n){let _=Se(n.baseUrl),u=n.scope,B=ve(n),I=n.fetch??globalThis.fetch.bind(globalThis),f,a=!1,d=!1,F=0,k=0,M="",w=0,H=0,o=0,t,i=!1,E,N=!0,v,T,x,S,g,p,D=e=>{p===e&&(p=void 0)},R=new Set,l=(e,m)=>L(n.onStatus,e,m);function y(){let e=g;g=void 0,e?.host.destroy(),e?.client.reset()}let K=()=>Date.now()<H&&performance.now()<o;function J(e){if(e.target.release!==n.appManifestRelease||!K())return!1;try{return _e(e.target.render,document,location.pathname,()=>{})}catch{return l("incompatible",e.id),!1}}function V(e){return!a&&e.epoch===w&&e.visit===k&&document.visibilityState!=="hidden"}async function X(e){if(p||g){l("in_progress",e.id);return}if(!n.session.peek()){l("identity_required",e.id);return}let m={command:ge.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:crypto.randomUUID(),locale:document.documentElement.lang||"en"}),epoch:w,visit:k};p=m,await Z(m)}async function Z(e){if(e.dispatching)return;e.dispatching=!0;let m,b=!1;async function h(s){if(e.epoch!==w)return;let c=s.view;c&&["running","waiting"].includes(c.status)&&await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:c.nodeId,visit:c.visit,revision:c.revision})}try{l("starting",e.command.entryId);let s=await B.request("funnels",e.command),c=we.safeParse(s);if(c.success){if(c.data.scope.projectId!==u.projectId||c.data.scope.environment!==u.environment)throw new P("SCOPE_MISMATCH","Entry scope changed");e.epoch===w&&l(c.data.reason,e.command.entryId),D(e);return}let A=ye.parse(s);if(!A.runToken||A.scope.projectId!==u.projectId||A.scope.environment!==u.environment||A.run.source.type!=="funnel"||A.run.source.id!==e.command.funnelId||A.run.source.versionId!==e.command.versionId)throw new P("INVALID_RESPONSE","Invalid entry Run");if(e.epoch!==w){D(e),l("identity_changed",e.command.entryId);return}let C=z({...n,runToken:A.runToken,funnelId:e.command.funnelId});m=C,await C.get();let U=C.view;if(!U||U.id!==A.run.id||U.source.type!=="funnel"||U.source.id!==e.command.funnelId||U.source.versionId!==e.command.versionId)throw new P("INVALID_RESPONSE","Entry Run version changed");if(!V(e)){await h(C),l("left_screen",e.command.entryId),D(e);return}let ne=!1,te=!1,re=await be(n.container,{...n.host,client:C,appManifestRelease:n.appManifestRelease,onDismiss(O){ne=!0,g?.client===C&&(g=void 0,C.reset(),O&&O.status!=="completed"&&l("run_ended",e.command.entryId)),L(n.host?.onDismiss,O)},onComplete(O){te=!0,g?.client===C&&y(),L(n.host?.onComplete,O)},onError(O){L(n.host?.onError,O),g?.client===C&&O instanceof P&&O.code==="FORBIDDEN"&&(y(),l("run_ended",e.command.entryId))}});if(!V(e)||ne||te){re.destroy(),V(e)||await h(C),D(e);return}g={host:re,client:C},b=!0,D(e),l("started",e.command.entryId)}catch(s){!m&&s instanceof P&&s.status!==void 0&&s.status>=400&&s.status<500&&!s.retryable&&D(e),e.epoch===w&&!a&&(l("start_failed",e.command.entryId),L(n.host?.onError,s))}finally{b||m?.reset(),e.dispatching=!1}}function Ce(){if(i=!1,!(a||!d||!K()||document.visibilityState==="hidden")){N=!1;for(let e of f?.entries??[])if(!(e.event!=="screen_enter"||R.has(`${e.funnelId}:${e.id}`)||!J(e))){if(!n.session.peek()){l("identity_required",e.id);continue}R.add(`${e.funnelId}:${e.id}`),X(e);break}}}let G=()=>{!i&&!a&&(i=!0,queueMicrotask(Ce))};function Ae(){let e=location.origin+location.pathname;e!==M&&(M=e,k++,N=!0,R.clear(),G())}function Y(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let m=e.target;if(!(m instanceof Element)||m.closest("[data-indiana-funnel]"))return;let b=m.closest("button,a,input");if(!(!b||b.matches(":disabled,[aria-disabled='true']")||b.closest("[hidden],[inert],[aria-hidden='true']")))for(let h of f?.entries??[]){let s=h.target.button;if(h.event!=="button_click"||!s||!J(h))continue;let c=document.querySelectorAll(s.selector);if(!(c.length!==1||c[0]!==b)){X(h);break}}}async function Q(){if(a)return;if(E)return E;let e=++F;v=new AbortController;let m=(async()=>{let b=await I(`${_}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",signal:v.signal});if(!b.ok)throw new P("SERVICE_UNAVAILABLE","Funnel entries unavailable",b.status);let h=Ee.parse(await b.json()),s=Date.parse(h.validatedAt),c=Date.parse(h.validUntil);if(h.scope.projectId!==u.projectId||h.scope.environment!==u.environment||h.scope.environmentId!==n.environmentId||h.release!==n.appManifestRelease||c<=Date.now()||s>Date.now()+5e3||c-s>6e4||c<=s)throw new P("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(a||e!==F)return;let A=f===void 0;f=h,H=c,o=performance.now()+Math.min(c-Date.now(),6e4),(A||N)&&G()})();E=m;try{await m}finally{E===m&&(E=void 0)}}async function W(){try{await Q()}catch{l("configuration_unavailable")}a||(t=setTimeout(()=>{W()},15e3))}let ee=()=>G();return{async start(){d||a||(d=!0,M=location.origin+location.pathname,T=Re(Ae),x=n.session.subscribeIdentity(()=>{w++,N=!0,p=void 0,R.clear(),y(),G()}),S=new MutationObserver(G),S.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id"]}),document.addEventListener("click",Y,!0),document.addEventListener("visibilitychange",ee),await W())},refresh:Q,async retry(){p&&!a&&p.epoch===w&&await Z(p)},destroy(){a=!0,F++,clearTimeout(t),v?.abort(),S?.disconnect(),T?.(),x?.(),document.removeEventListener("click",Y,!0),document.removeEventListener("visibilitychange",ee),y(),f=void 0}}}async function nn(...n){return(await import("./paywall-527RPFAX.js")).showPaywall(...n)}async function tn(...n){return(await import("./funnel-runtime-host-BJZUVJAI.js")).showFunnelRun(...n)}async function rn(...n){return(await import("./content-QM75T7JO.js")).mountContent(...n)}async function on(...n){return(await import("./content-QM75T7JO.js")).prepareContent(...n)}export{P as IndianaError,r as MerchantBridgeError,Pe as createBrowserFunnelCommandStorage,Be as createConfigurationSync,De as createFeatureClient,He as createFunnelClient,ke as createFunnelPageExperiments,z as createFunnelRunController,je as createIamFunnelEntries,Oe as createIndiana,Le as createLocalFunnelClient,Ue as createMerchantBridge,xe as createPaywallSession,Fe as evaluateFunnelNode,Ne as formatCouponDiscount,Me as formatCouponMoney,Te as formatCouponTerms,rn as mountContent,on as prepareContent,tn as showFunnelRun,nn as showPaywall};