@tinkerlandai/longplay-sdk 0.10.41 → 0.10.43

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 (94) hide show
  1. package/CHANGELOG.md +16 -3
  2. package/README.md +1 -0
  3. package/dist/check-response-OIBVUP72.js +1 -0
  4. package/dist/{chunk-P6XQC7GG.js → chunk-22LQSRYH.js} +1 -1
  5. package/dist/{chunk-OEONV3JY.js → chunk-2PVQUPBN.js} +1 -1
  6. package/dist/{chunk-EECTJHI6.js → chunk-3SXPCVIP.js} +1 -1
  7. package/dist/chunk-3XMBILUJ.js +1 -0
  8. package/dist/{chunk-MYDMOAKX.js → chunk-5JRBCW6V.js} +1 -1
  9. package/dist/{chunk-VJHURKRY.js → chunk-5TJISOWN.js} +1 -1
  10. package/dist/{chunk-S4P4UUUF.js → chunk-6XRXHFM6.js} +1 -1
  11. package/dist/{chunk-KINNES62.js → chunk-7MYS52FL.js} +1 -1
  12. package/dist/{chunk-2RUJXZCO.js → chunk-7X65GNKZ.js} +1 -1
  13. package/dist/{chunk-W35FZWGG.js → chunk-AQONMY2H.js} +1 -1
  14. package/dist/{chunk-5PNH2FPI.js → chunk-ASL7TJFU.js} +1 -1
  15. package/dist/{chunk-H26F3IOI.js → chunk-AV2WZSII.js} +1 -1
  16. package/dist/chunk-B4AELNLE.js +1 -0
  17. package/dist/{chunk-CQRSMCCG.js → chunk-C4NG6RVA.js} +1 -1
  18. package/dist/{chunk-NFY7DKVJ.js → chunk-CALDEF4M.js} +1 -1
  19. package/dist/{chunk-24Z3THUR.js → chunk-CSLTAXC7.js} +1 -1
  20. package/dist/{chunk-HGH2X6QM.js → chunk-CWD36SJO.js} +1 -1
  21. package/dist/{chunk-OAAS5LJY.js → chunk-DCZWNTG2.js} +1 -1
  22. package/dist/{chunk-GXADA7OV.js → chunk-DGZCD3AY.js} +1 -1
  23. package/dist/chunk-DPVYEOD6.js +1 -0
  24. package/dist/{chunk-VWRQBQZD.js → chunk-FMSHIKMI.js} +1 -1
  25. package/dist/{chunk-SYHMHKFQ.js → chunk-FTGRTYBL.js} +1 -1
  26. package/dist/{chunk-EOPKOAR5.js → chunk-HLCDAU5A.js} +1 -1
  27. package/dist/{chunk-EJSDOSP5.js → chunk-HTXB2WVI.js} +1 -1
  28. package/dist/chunk-IT5DIE6G.js +1 -0
  29. package/dist/{chunk-7IVLNV5H.js → chunk-KP4QI4RX.js} +1 -1
  30. package/dist/{chunk-26UXCYBP.js → chunk-LSVTH3TS.js} +1 -1
  31. package/dist/{chunk-DPEMW2FO.js → chunk-LZ3OJYBY.js} +1 -1
  32. package/dist/{chunk-QJMM37CB.js → chunk-MEDW4N3F.js} +1 -1
  33. package/dist/{chunk-2LERKK7O.js → chunk-MPD3UIY4.js} +1 -1
  34. package/dist/{chunk-Y2HXKANG.js → chunk-MWICFZUF.js} +1 -1
  35. package/dist/{chunk-EON4IKWR.js → chunk-NVF54BDR.js} +1 -1
  36. package/dist/{chunk-AQQJPP3P.js → chunk-P6TNBX2S.js} +1 -1
  37. package/dist/{chunk-6EBS6MLW.js → chunk-PBZSOTKZ.js} +1 -1
  38. package/dist/{chunk-2XF34Q6D.js → chunk-PG5UESZB.js} +1 -1
  39. package/dist/{chunk-756SIMZF.js → chunk-Q23JDNYJ.js} +1 -1
  40. package/dist/{chunk-RQTYIUWP.js → chunk-RDUKCMST.js} +1 -1
  41. package/dist/{chunk-6STWY5GX.js → chunk-RJY5CUTB.js} +1 -1
  42. package/dist/{chunk-FTVNGN6Z.js → chunk-RMRZSF5C.js} +1 -1
  43. package/dist/chunk-S7A3IBAF.js +10 -0
  44. package/dist/chunk-SSRQGIGB.js +1 -0
  45. package/dist/{chunk-2LUVO7GM.js → chunk-T43HTIQX.js} +1 -1
  46. package/dist/{chunk-G6CWZBT5.js → chunk-TL67SYPH.js} +1 -1
  47. package/dist/{chunk-O3HLNU6T.js → chunk-UJMP7AMY.js} +1 -1
  48. package/dist/{chunk-TGPZJ5A7.js → chunk-V65FSNYO.js} +1 -1
  49. package/dist/{chunk-2P2YSNYU.js → chunk-X4UTTXOU.js} +1 -1
  50. package/dist/{chunk-W3J2SIPY.js → chunk-XZEZFWFD.js} +1 -1
  51. package/dist/chunk-YVAQLTHJ.js +1 -0
  52. package/dist/{content-XYUJFGY2.js → content-FZOT5NDI.js} +1 -1
  53. package/dist/funnel-host-purchase-6GV67OIA.js +1 -0
  54. package/dist/funnel-paywall-prerender-OA3QN2VI.js +1 -0
  55. package/dist/funnel-route-prediction-XGCMCIKA.js +1 -0
  56. package/dist/funnel-route-source-O76QSUYU.js +1 -0
  57. package/dist/funnel-runtime-host-NU36AKUF.js +1 -0
  58. package/dist/index.js +1 -1
  59. package/dist/merchant-bridge-contracts-FB63H7NE.js +1 -0
  60. package/dist/native-shell.js +1 -1
  61. package/dist/openrouter.js +1 -1
  62. package/dist/operation-contracts-YSFIINLK.js +1 -0
  63. package/dist/page.js +1 -1
  64. package/dist/paywall-GLXO4HN7.js +1 -0
  65. package/dist/paywall-content-IF2LKXDF.js +1 -0
  66. package/dist/paywall-session-YDG3FDOP.js +1 -0
  67. package/dist/popup.js +1 -1
  68. package/dist/react-native.js +1 -1
  69. package/dist/screen-renderer-RDXKWHYE.js +1 -0
  70. package/dist/server.js +1 -1
  71. package/dist/{visual-dom-7YYJQ2ZI.js → visual-dom-IN6DRNX3.js} +1 -1
  72. package/dist/visual.js +1 -1
  73. package/package.json +1 -1
  74. package/dist/check-response-SR3PDVGE.js +0 -1
  75. package/dist/chunk-4B4RB36N.js +0 -1
  76. package/dist/chunk-6OVMC5BT.js +0 -1
  77. package/dist/chunk-ANXK3B5B.js +0 -1
  78. package/dist/chunk-BWRRZ2NW.js +0 -1
  79. package/dist/chunk-H7AHDGVU.js +0 -10
  80. package/dist/chunk-PYLX3WF6.js +0 -1
  81. package/dist/funnel-host-purchase-BNS3242X.js +0 -1
  82. package/dist/funnel-paywall-prerender-DDQI3GAZ.js +0 -1
  83. package/dist/funnel-route-prediction-BT5ZWU54.js +0 -1
  84. package/dist/funnel-route-source-7ZJMZRID.js +0 -1
  85. package/dist/funnel-runtime-host-3SSDNG24.js +0 -1
  86. package/dist/merchant-bridge-contracts-YU53UKUN.js +0 -1
  87. package/dist/operation-contracts-GEIGP23I.js +0 -1
  88. package/dist/paywall-YZAEI7TF.js +0 -1
  89. package/dist/paywall-content-QBSB5NA7.js +0 -1
  90. package/dist/paywall-session-MHBAZLS7.js +0 -1
  91. package/dist/screen-renderer-SEJG7A2C.js +0 -1
  92. /package/dist/{chunk-2ULWP26K.js → chunk-GPJF3T43.js} +0 -0
  93. /package/dist/{chunk-4PGYQ2TI.js → chunk-RA7GZ67U.js} +0 -0
  94. /package/dist/{chunk-PBBREFS5.js → chunk-WPFTSHP2.js} +0 -0
@@ -1 +1 @@
1
- import{a as E,b as M,c as j,d as O,e as T}from"./chunk-SYHMHKFQ.js";import{a as u}from"./chunk-G6CWZBT5.js";import{j as w}from"./chunk-S4P4UUUF.js";import{b as t}from"./chunk-2ULWP26K.js";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 Z(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,Z as d};
1
+ import{a as E,b as M,c as j,d as O,e as T}from"./chunk-FTGRTYBL.js";import{a as u}from"./chunk-TL67SYPH.js";import{j as w}from"./chunk-6XRXHFM6.js";import{b as t}from"./chunk-GPJF3T43.js";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 Z(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,Z as d};
@@ -1 +1 @@
1
- import{a as n}from"./chunk-G6CWZBT5.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
1
+ import{a as n}from"./chunk-TL67SYPH.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
@@ -1 +1 @@
1
- import{b as d}from"./chunk-2LUVO7GM.js";import{a as u}from"./chunk-DSPLGTQI.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{b as d}from"./chunk-T43HTIQX.js";import{a as u}from"./chunk-DSPLGTQI.js";function m(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function y(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function g(e=d){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var o=new Set,s;function S(e){let t=()=>e();if(o.add(t),!s){let i=!0,a=history.pushState,p=history.replaceState,r=()=>{if(i)for(let n of[...o])o.has(n)&&u(n)},c=function(...n){a.apply(this,n),r()},h=function(...n){p.apply(this,n),r()};history.pushState=c,history.replaceState=h,addEventListener("popstate",r),addEventListener("hashchange",r),s=()=>{i=!1,history.pushState===c&&(history.pushState=a),history.replaceState===h&&(history.replaceState=p),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{o.delete(t)&&(o.size||(s?.(),s=void 0))}}export{m as a,y as b,g as c,S as d};
@@ -1 +1 @@
1
- import{b as _e}from"./chunk-6STWY5GX.js";import{a as M}from"./chunk-TGPZJ5A7.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-4B4RB36N.js";import{a as Se,b as Ce,c as ve}from"./chunk-EON4IKWR.js";import{K as x}from"./chunk-OAAS5LJY.js";import{a as te}from"./chunk-PYLX3WF6.js";import{i as ne}from"./chunk-W35FZWGG.js";import{A as X,C as Z,E as Pe}from"./chunk-7IVLNV5H.js";import{w as de}from"./chunk-VJHURKRY.js";import{b as Oe}from"./chunk-2XF34Q6D.js";import{a as l}from"./chunk-G6CWZBT5.js";import{h as W}from"./chunk-S4P4UUUF.js";import{b as be}from"./chunk-2LUVO7GM.js";import{b as n}from"./chunk-2ULWP26K.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-QBSB5NA7.js"),import("./check-response-SR3PDVGE.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
1
+ import{b as _e}from"./chunk-RJY5CUTB.js";import{a as M}from"./chunk-V65FSNYO.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-DPVYEOD6.js";import{a as Se,b as Ce,c as ve}from"./chunk-NVF54BDR.js";import{K as x}from"./chunk-DCZWNTG2.js";import{a as te}from"./chunk-B4AELNLE.js";import{i as ne}from"./chunk-AQONMY2H.js";import{A as X,C as Z,E as Pe}from"./chunk-KP4QI4RX.js";import{w as de}from"./chunk-5TJISOWN.js";import{b as Oe}from"./chunk-PG5UESZB.js";import{a as l}from"./chunk-TL67SYPH.js";import{h as W}from"./chunk-6XRXHFM6.js";import{b as be}from"./chunk-T43HTIQX.js";import{b as n}from"./chunk-GPJF3T43.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-IF2LKXDF.js"),import("./check-response-OIBVUP72.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
@@ -0,0 +1 @@
1
+ import{b as Zn}from"./chunk-SSRQGIGB.js";import{a as Jn,b as jn,c as pn,d as fn,e as Me,f as zn,h as Bn,i as Wn,j as Yn,k as Xn}from"./chunk-HTXB2WVI.js";import{b as An,c as Kn}from"./chunk-FMSHIKMI.js";import{a as Un}from"./chunk-W32FI2A2.js";import{c as Mn,e as $n,f as xn,h as Gn,i as _e,j as nn,k as Qn,l as tn}from"./chunk-P6TNBX2S.js";import{b as Sn}from"./chunk-IT5DIE6G.js";import{K as en}from"./chunk-DCZWNTG2.js";import{a as Ue,d as Fn}from"./chunk-B4AELNLE.js";import{c as Nn,e as On,f as _n,g as Ln,h as Hn,i as Vn}from"./chunk-AQONMY2H.js";import{b as kn}from"./chunk-RDUKCMST.js";import{B as cn}from"./chunk-KP4QI4RX.js";import{w as qn}from"./chunk-5TJISOWN.js";import{t as Tn}from"./chunk-7MYS52FL.js";import{C as Dn}from"./chunk-MWICFZUF.js";import{a as y}from"./chunk-TL67SYPH.js";import{a as Ee}from"./chunk-DSPLGTQI.js";async function mn(t){let{session:C,load:R}=ut(t);try{return await R(),C}catch(n){throw C.destroy(),n}}function ut(t){let C=t.view;if(!C?.paywall)throw new y("INVALID_REQUEST","The current node is not a Paywall");let R=C.paywall.receiptId,n=C.nodeId,v=C.visit,A=C.paywall.resolution,o=C.paywall,_="document"in A?{document:A.document,offering:A.offering,capabilities:A.capabilities}:null;function u(){let i=o.resolution;return"document"in i?i:_&&{...i,document:_.document,offering:_.offering,capabilities:Nn(i.capabilities,_.capabilities)}}function P(i){if(!On(i,A))throw new y("INVALID_RESPONSE","The pinned Paywall binding changed")}let E=!1,$=new Set,te=null;function w(){let i=u();if(i&&!E)for(let a of $)Ee(a,structuredClone(i))}async function L(){b();let i=u();if(i)return structuredClone(i);if(!te){let a=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new y("INVALID_RESPONSE","Public Paywall reader is unavailable");let D=await An(t,o.resolution);return b(),P(D),_={document:D.document,offering:D.offering,capabilities:D.capabilities},w(),u()})();te=a;let s=()=>{te===a&&(te=null)};a.then(s,s)}return te.then(a=>structuredClone(a))}let l=new AbortController,q=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===v&&i.input.type==="paywall_quote")?.requestId??C.paywall.purchaseRequestId,S=0,ie=null,U=new Set,H=null,Q=new Map;function G(i){if(i.purchase&&i.purchase.receiptId!==R)throw new y("INVALID_RESPONSE","Purchase receipt changed");let a=i.run.paywall;return i.purchase??(a?.receiptId===R?a:null)}function b(){if(E)throw new y("IDENTITY_CHANGED","Paywall presentation has closed")}function X(i,a,s){if(b(),a!==S||s!==void 0&&o.quote?.operationId!==s)return!1;let D=o.selectionGeneration??0,f=i.run.paywall;if(f?.receiptId===R){if((f.selectionGeneration??0)<(o.selectionGeneration??0))return!1;P(f.resolution)}let c=G(i),N=f?.receiptId===R&&(f.selectionGeneration??0)>D,h=N?c?.quote??null:c?.quote??o.quote,B=c?.operation??(h?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&h&&Hn(o.quote,h),h&&B&&_n(B,{operationId:h.operationId,membershipId:cn(h)?h.membershipId:null,...cn(h)?{featureQuantities:h.featureQuantities??{}}:{}},"Purchase operation changed"),(N||h?.operationId!==o.quote?.operationId)&&(S++,f?.receiptId===R&&(q=f.purchaseRequestId)),f?.canReselect===!0&&f.purchaseRequestId===H&&!(t.pendingCommands??[t.pendingCommand]).some(W=>W?.requestId===H)&&(H=null),o={...o,...f?.receiptId===R?f:{},...s!==void 0&&!N&&c?.canReselect!==void 0?{canReselect:c.canReselect}:{},quote:h,operation:Vn(o.operation,B,!0)},w(),!0}function O(i,a,s){return new Promise((D,f)=>{let c=!1,N=()=>{clearTimeout(j),l.signal.removeEventListener("abort",W)},h=ge=>{c||(c=!0,N(),D(ge))},B=ge=>{c||(c=!0,N(),f(ge))},W=()=>B(new y("IDENTITY_CHANGED","Paywall presentation has closed")),j=setTimeout(()=>B(new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,a-Date.now()));l.signal.addEventListener("abort",W,{once:!0}),l.signal.aborted&&W(),i.then(h,B)})}function qe(i){return new Promise(a=>{let s=()=>{clearTimeout(D),l.signal.removeEventListener("abort",s),a()},D=setTimeout(s,i);l.signal.addEventListener("abort",s,{once:!0}),l.signal.aborted&&s()})}function he(i,a){b();let s=Q.get(i)??t.pendingCommands?.find(c=>c.requestId===i)??t.pendingCommand;if(s?.operation==="submit"&&s.requestId===i&&s.nodeId===n&&s.visit===v){a.type==="paywall_quote"&&s.input.type==="paywall_quote"&&s.input.predecessor&&!a.predecessor&&(a={...a,predecessor:s.input.predecessor});let c=en.parse(s),N=en.parse({...s,input:a});if(c.operation!=="submit"||N.operation!=="submit"||JSON.stringify(c.input)!==JSON.stringify(N.input))throw new y("CONFLICT","A purchase request cannot change its input");return Q.set(i,c),c}let D=t.view;if(!D||D.nodeId!==n||D.visit!==v||D.paywall?.receiptId!==R)throw new y("PRECONDITION_FAILED","The Paywall visit has changed");let f=en.parse({operation:"submit",requestId:i,nodeId:n,visit:v,revision:D.revision,input:structuredClone(a)});if(f.operation!=="submit")throw new y("INVALID_REQUEST","A purchase submission is required");return Q.set(i,f),f}async function me(i,a){b();let{requestId:s,input:D}=i,f=Date.now()+3e4;U.add(s);try{let c=await O(t.submit(i),f,s);for(;c.run.pendingRequest?.requestId===s&&Date.now()<f&&!E&&(await qe(Math.min(1e3,f-Date.now())),!(E||Date.now()>=f));)c=await O(t.resume(s),f,s);if(E)throw new y("IDENTITY_CHANGED","Paywall presentation has closed");if(c.run.pendingRequest?.requestId===s)throw new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s);if(!X(c,a,D.type==="paywall_confirm"||D.type==="paywall_cancel"?D.operationId:void 0))throw new y("PRECONDITION_FAILED","The purchase selection has changed");H===s&&(H=null)}catch(c){if(H=s,D.type==="paywall_quote"&&t.settle&&!E&&c instanceof y&&c.status!==void 0&&![401,425].includes(c.status)&&!c.retryable&&c.recovery!=="recover_operation")try{if((await O(t.settle(s),f,s)).settlement?.state==="settled"){let h=await O(t.get(),f,s);X(h,a)&&h.run.paywall?.purchaseRequestId===s&&o.canReselect===!0&&Q.delete(s)}}catch{}throw c instanceof y&&c.code==="COMMAND_PENDING"&&c.status===void 0&&Q.delete(s),c}finally{U.delete(s)}}async function z(i){if(!o.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let a=i==="confirm"?"paywall_confirm":"paywall_cancel",s=[...Q.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(f=>f.operation==="submit"&&f.input.type===a&&"operationId"in f.input&&f.input.operationId===o.quote.operationId),D=s?.operation==="submit"&&s.input.type===a&&"operationId"in s.input&&s.input.operationId===o.quote.operationId?s.requestId:crypto.randomUUID();if(await me(he(D,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:qn(o.quote.merchantTerms)}:{}}),S),!o.operation)throw new y("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let se={get view(){return structuredClone(u())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??C.locale},get canReselect(){return o.canReselect===!0&&H===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),a=t.pendingPurchase;if(a&&(a.receiptId!==R||a.operationId!==o.quote?.operationId))return{type:"recover",operationId:a.operationId,requestId:i[0]?.requestId??null};let s=Ue({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??H??q,pending:U.size>0||i.length>0||H!==null,destroyed:E,canReselect:o.canReselect});return s.type==="recover"&&s.requestId===null&&!E&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!a&&!i.length&&!U.size&&!q?{type:"native",operationId:null}:s},get pendingCancellation(){return!E&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===n&&i.visit===v&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return E?()=>{}:($.add(i),()=>$.delete(i))},async refresh(){b();let i=S,a=await t.get();if(X(a,i),a.run.paywall?.receiptId!==R)throw new y("PRECONDITION_FAILED","Paywall presentation has changed");return L()},preview(i){let a=u();if(!a)return Promise.reject(new y("PRECONDITION_FAILED","Load the Paywall presentation first"));if(q&&q!==i.requestId&&(ie||o.canReselect!==!0))return Promise.reject(new y("COMMAND_PENDING","Retry the original purchase before starting another"));let s=a.document.buttons[i.actionId],D=s?.type==="checkout"?kn(s.product,i.selection,a.capabilities):null;if(!D)return Promise.reject(new y("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let f=Tn(a.document.screen,D,i.selection,a.capabilities),c=q!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,N=t.view?.parameters.commerce;if(N&&typeof N=="object"&&!Array.isArray(N)&&N.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new y("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new y("INVALID_REQUEST","A web membership change cannot include a store offer"));if(c&&o.canReselect!==!0)return Promise.reject(new y("COMMAND_PENDING","Original purchase requires authoritative termination"));let h;try{h=he(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:D,...Object.keys(f).length?{featureQuantities:f}:{},...c?{predecessor:c}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(j){return Promise.reject(j)}if(q===i.requestId&&ie)return ie;q!==i.requestId&&S++;let B=S;q=i.requestId;let W=(async()=>{if(await me(h,B),!o.quote)throw new y("INVALID_RESPONSE","The accepted quote is missing");return Ln(o.quote,{productVersionId:D,featureQuantities:f,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return ie=W,W.then(()=>{ie===W&&(ie=null)},j=>{ie===W&&(ie=null),q===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&j instanceof y&&j.status!==void 0&&j.status<500&&![401,425].includes(j.status)&&(q=null)}),W},confirm:()=>z("confirm"),cancel:()=>z("cancel"),async read(){if(b(),!o.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,a=S,s=t.pendingCommands?.find(h=>h.operation==="submit"&&(h.input.type==="paywall_confirm"||h.input.type==="paywall_cancel")&&h.input.operationId===i)??t.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===i&&await t.settle?.(s.requestId);let D=await t.get(void 0,{receiptId:R,operationId:i});b();let f=G(D);if(f?.quote&&f.quote.operationId!==i||f?.operation&&f.operation.operationId!==i)throw new y("INVALID_RESPONSE","Purchase operation changed");let c=X(D,a,i),N=c?o.operation:f?.operation;if(!N)throw new y("INVALID_RESPONSE","The current purchase result is missing");return c&&U.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(H=null),structuredClone(N)},destroy(){E=!0,F(),$.clear(),l.abort(),Q.clear()}},F=t.subscribe(i=>{E||i.nodeId!==n||i.visit!==v||i.paywall?.receiptId!==R||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(P(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:se,load:L}}function et(t){let C=new Set,R=new Set,n=null;async function v(u,P){let E=!1;for(;!t.stopped&&t.key===u&&t.client.pendingCommand?.requestId===P;){if(!t.client.settle)throw new y("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(P),E=!0,t.client.pendingCommand?.requestId===P&&await new Promise($=>setTimeout($,1500))}t.stopped||t.key!==u||(E&&await t.client.get(),!(t.stopped||t.key!==u)&&C.add(u))}function A(u,P){n=P;let E=()=>{n===P&&(n=null),R.delete(u)};return P.then(E,$=>{E(),t.busy||t.fail($)}),P}function o(u){if(t.reviewing||C.has(u)||R.has(u)||t.stopped)return;R.add(u);let P=async()=>{if(t.reviewing||t.stopped||t.key!==u||C.has(u)){R.delete(u);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{P()},250);return}let E=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==u)return;if(t.client.pendingCommand){setTimeout(()=>{P()},250);return}}let $=t.client.view,te=t.expected(),w=te.requestId;try{await t.client.submit({operation:"shown",...te})}catch(L){if(!(L instanceof y)||L.code!=="CONFLICT"||L.status!==409||t.client.pendingCommand)throw L;await t.client.get();let l=t.client.view;if(t.stopped||t.reviewing||t.key!==u||!l||!$||l.id!==$.id||l.source.versionId!==$.source.versionId||l.nodeId!==te.nodeId||l.visit!==te.visit||l.revision<=te.revision||l.stopped||!l.screen&&(!l.paywall||l.paywall.receiptId!==$.paywall?.receiptId)||!["running","waiting"].includes(l.status)||t.client.pendingCommand)throw L;let d=t.expected();w=d.requestId,await t.client.submit({operation:"shown",...d})}await v(u,w)})();A(u,E)};P()}function _(){if(n)return n;let u=t.client.pendingCommand;if(u?.operation!=="shown")return null;let P=t.key;return R.add(P),A(P,(async()=>{await t.client.retry(),await v(P,u.requestId)})())}return{report:o,settled:_,get inFlight(){return n}}}function nt(t){let C={},R=new Map;async function n(v){let A=t.client.view,o=A?.screen,_=o?.customerData.nodes[v.nodeId];if(t.stopped||t.busy||!A||!o||!_)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(v.action)){let L=t.document,l=L?Dn(L,v.nodeId):null,d=l?.type==="customer_data"?l.data.outputs?.[v.action]:void 0;d&&o.outputs.includes(d)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:d,answers:t.answers,selection:v.value?{[v.nodeId]:v.value}:{}}})):await t.onIntent?.(v,A);return}let P=v.action.startsWith("sources_")?_.resources.find(L=>L.key===v.value):null;if(v.action.startsWith("sources_")&&!P)throw new y("INVALID_REQUEST","Choose a current resource");let E=`${A.visit}:${v.nodeId}:${P?.key??""}`,$=R.get(E)??[null],w=C[v.nodeId]??{page:1,after:null,filter:"all",...P?{resourceKey:P.key}:{}};if(v.action==="filter"){let L=v.value;if(!L||!(_.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(L))throw new y("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:L},$.splice(0,$.length,null)}else if(v.action==="next"||v.action==="sources_next"){let L=P?.sources.at(-1),l=P?L?{kind:"ledger",cursor:{at:L.detail[0],id:L.id,type:"source"}}:null:o.dataCursors[v.nodeId];if(!l||!P&&!_.hasNext)return;$[w.page]=l,w={...w,page:w.page+1,after:l}}else if(v.action==="previous"||v.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:$[w.page-2]??null}}R.set(E,$),C={...C,[v.nodeId]:w},await t.perform(()=>t.client.get({nodeId:A.nodeId,visit:A.visit,revision:A.revision,components:C}))}return{get queries(){return C},intent:n,reset(){C={},R.clear()}}}function tt(t){let{doc:C,holder:R,reviewHolder:n,mountScreenPreview:v}=t,A=!1,o,_=0,u=null,P="",E,$=new Map,te=l=>l?`${l.id}:${l.nodeId}:${l.visit}:${l.revision}:${l.paywall?.quote?.operationId??""}`:"";async function w(l){if(t.stopped||!t.client.review||A&&l===o&&E?.active)return;let d=!A||l!==o;A||(P=te(t.client.view),$.set(P,structuredClone(t.answers))),A=!0,o=l,R.hidden=!0,t.suspend(!0),n.hidden=!1;let q=++_;d&&(E?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),E=nn(n,t.loadingOptions,"funnel",()=>{L()}));let S=d?E:void 0;try{if(S?.start(!1,t.client.view?.locale),q!==_||t.stopped)return;let ie=t.client.review(l),U=await(S?.wait(ie,_e)??ie);if(t.stopped||q!==_||!A)return;if(!U.review)throw new y("INVALID_RESPONSE","Historical projection is missing");u?.destroy(),u=null,S||n.replaceChildren();let H=C.createElement("div"),Q=S?tn(H,n):()=>{};n.append(H);let G=U.run.locale.startsWith("zh"),b=t.chrome;H.style.cssText=b.history;let X=C.createElement("p");X.textContent=G?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",X.style.cssText=b.historyTitle,H.append(X);let O=C.createElement("p");O.style.cssText=b.historyNote,O.textContent=U.review.pages.length?G?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":G?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",H.append(O);let qe=U.review.page?.receiptId,he=C.createElement("div");he.style.cssText=b.historyPages;for(let[se,F]of U.review.pages.entries()){let i=C.createElement("button");i.type="button",i.textContent=G?`\u7B2C ${se+1} \u9875`:`Page ${se+1}`;let a=qe!==void 0&&F.receiptId===qe;i.style.cssText=a?b.primary:b.secondary,a&&i.setAttribute("aria-current","page"),Me(i,()=>t.chrome.focus),i.onclick=()=>{w(F.receiptId)},he.append(i)}if(he.childElementCount&&H.append(he),U.review.page){let se=U.review.page,F=C.createElement("div");F.inert=!0,F.style.cssText=b.historyPage,H.append(F),u=v(F,{mode:"live",rendererUrl:t.client.webViewUrl,title:se.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{q===_&&!t.stopped&&S?.present(Q)},onError:a=>{if(q!==_||t.stopped)return;let s=new Error(a);S?.finish("error",s),u?.destroy(),u=null,H.remove(),t.fail(s)},onEscape:()=>{L()}});let i=u;if(i.update(se.document,U.run.locale,{serverInput:{bindings:se.inputs,answers:se.answers,values:se.values}}),await i.ready,t.stopped||q!==_||!A)return}let me=G?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},z=C.createElement("div");z.style.cssText=b.historyRecords;for(let se of[...U.review.coupons.map((F,i)=>`${G?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${me[F.status]}`),...U.review.purchases.map((F,i)=>`${G?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Xn(F.status,G)}`)]){let F=C.createElement("p");F.textContent=se,F.style.margin="0",z.append(F)}z.childElementCount&&H.append(z),U.review.page||S?.present(Q),t.client.view&&await t.enqueue(t.client.view)}catch(ie){if(q!==_||t.stopped)return;S?.finish("error",ie),u?.destroy(),u=null,n.replaceChildren(),t.fail(ie)}}async function L(){if(!A||t.stopped||!t.client.review)return;let l=++_;E?.finish("dismissed");try{if(await t.client.review(),t.stopped||l!==_)return;A=!1,_++,E?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),n.hidden=!0,R.hidden=!1;let d=t.client.view;te(d)!==P?($.set(P,structuredClone(t.answers)),t.resetScreen()):($.delete(P),t.suspend(!1)),d&&await t.enqueue(d)}catch(d){if(l!==_||t.stopped)return;u?.destroy(),u=null,n.replaceChildren(),t.fail(d)}}return{get active(){return A},get receipt(){return o},open:w,exit:L,get drafts(){return new Map([...$].map(([l,d])=>[l,structuredClone(d)]))},stop(){A=!1,_++,E?.finish("dismissed"),u?.destroy(),u=null,n.replaceChildren(),n.hidden=!0,R.hidden=!1}}}var wn=5e3;async function dt(t,C,R){let n=C,v=n.prepared&&Zn(n.prepared),A=()=>{};function o(){n.prepared&&n.prepared.state!=="adopted"&&v?.release()}let _=()=>n.prepared?.state==="shown"&&!!v?.modal,u=n.client.identitySignal,P;try{P=await Promise.all([import("./screen-renderer-RDXKWHYE.js"),import("./paywall-GLXO4HN7.js")]),n.signal?.throwIfAborted(),u?.throwIfAborted()}catch(e){throw o(),e}let[{mountScreenPreview:E},{showPaywall:$}]=P,te=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&n.appManifestRelease?Kn({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;te?.start();let w=t.ownerDocument,L=Gn(w),l=!1,d=w.createElement("section"),q=w.createElement("div"),S=w.createElement("div"),ie=w.createElement("div"),U=w.createElement("button");ie.hidden=!0,U.type="button";let H=w.createElement("p"),Q=w.createElement("p"),G=w.createElement("button"),b=w.createElement("button"),X=w.createElement("button"),O=w.createElement("dialog"),qe,he=!1;d.dataset.indianaFunnel="",d.dataset.longplayCloseOwner="sdk",d.setAttribute("aria-busy","false"),H.setAttribute("role","status"),Q.setAttribute("role","alert"),Q.hidden=!0,G.type=b.type=X.type="button",S.append(G,U,H,Q,X,b),d.append(q,ie,S),t.append(d);let me=jn,z=pn(me),se="",F=(w.documentElement.lang||"").startsWith("zh"),i,a="",s;for(let e of[G,U,X,b])Me(e,()=>z.focus);function D(){let e=F?"\u5173\u95ED":"Close";b.parentElement===O?(b.textContent="\xD7",b.setAttribute("aria-label",e),xn(b,me)):(b.textContent=e,b.removeAttribute("aria-label"),b.style.cssText=z.link+";margin-inline-start:auto")}function f(e){let r=e?.screen?.content.document.theme??me,m=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,b.parentElement===O]);if(m===se)return;se=m,me=r;let V=b.parentElement===O;z=pn(me,V),d.style.cssText=z.root+";min-width:0"+(V?";display:flex;flex-direction:column;min-height:100%":""),S.style.cssText=z.bar+(V?";margin-top:auto":""),S.hidden&&(S.style.display="none"),G.style.cssText=U.style.cssText=z.secondary,X.style.cssText=z.primary,H.style.cssText=z.status,Q.style.cssText=z.alert,D(),fn(G)}function c(){S.hidden=G.hidden&&U.hidden&&X.hidden&&Q.hidden&&!H.textContent&&(b.hidden||b.parentElement!==S),S.style.display=S.hidden?"none":"flex",i?.responsive&&s!==void 0&&i.setContentHeight(s+S.getBoundingClientRect().height)}f();let N=null,h=null,B=null,W="",j="",ge=!1,$e="",rn="",xe="",g=!1,de=0,Ge=!1,yn="",on=null,sn=Promise.resolve(),hn=!n.client.view,J=R,Ae,Le,Qe="",Je,ce=!1,De=null,ve=!1,je=()=>n.client.pendingCommand?.operation==="close",pe=null,Z=null,gn=Un({document:w,run:async()=>{(!h?.observing||n.client.pendingCommand)&&await ln()},delay:()=>{if(!fe.pending&&!(g||!B||!["running","waiting"].includes(B.status)&&!n.client.pendingCommand)&&!(h?.observing&&!n.client.pendingCommand))return B.pendingRequest||n.client.pendingCommand?1500:wn},hiddenDelay:()=>!g&&!fe.pending&&n.client.pendingCommand?15e3:void 0}),ee=null;function an(){return Z&&n.client.hasDurableJournal===!0&&ee?.acknowledged===!0&&ee.operationId===Z.operationId&&n.client.view?.id===ee.runId&&n.client.view?.status==="closed"&&n.client.view.revision===ee.revision+1&&!(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0))&&!n.client.pendingPurchase?Z:null}function vn(e){let r=e.run.paywall;if(ee&&e.settlement?.requestId===ee.requestId&&e.settlement.state==="settled"&&e.settlement.operationId===null&&e.run.id===ee.runId&&e.run.status==="closed"&&!e.run.pendingRequest&&e.run.revision===ee.revision+1&&e.run.nodeId===ee.nodeId&&e.run.visit===ee.visit&&r?.receiptId===ee.receiptId&&r.selectionGeneration===ee.selectionGeneration&&(r.quote?.operationId??null)===ee.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===ee.operationId){let m=ee.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,V=Ue({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(m||r.canReselect===!0&&V.type==="native")&&(ee.acknowledged=!0)}}let ke=null,ze=new Set,Ie={},Se=!1,le=(e,r=null)=>{g||(ke=r,Se=!1,Q.textContent=zn(e,F),Q.hidden=!1,X.hidden=n.client.pendingCommand===null,c(),Ee(n.onError,e))},fe=Sn({client:n.client,document:w,conceal(){g||(be(),J?.finish("dismissed"),d.hidden=!0,l||(l=!0,L()))},async receive(e){g||await we(n.client.view??e.run)},failed(e){if(!g){if(!fe.pending){ve=!1;let r=n.client.view;r&&we(r).then(()=>le(e),le);return}Xe(),d.parentElement!==t&&t.append(d),d.hidden=!1,G.hidden=U.hidden=b.hidden=!0,H.textContent="",f(),le(e,n.client.pendingCommand?.requestId??null)}}}),In=()=>{g||(ke=null,Q.textContent=Wn(F),Q.hidden=!1,X.hidden=!0,c())};function Te(){let e=n.client.view;if(!e)throw new y("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}let T=tt({client:n.client,doc:w,holder:q,reviewHolder:ie,mountScreenPreview:E,loadingOptions:n,get chrome(){return z},get stopped(){return g},get answers(){return Ie},suspend(e){h?.setSuspended(e)},resetScreen(){W="",j="",$e=""},enqueue:we,fail:le}),He=et({client:n.client,expected:Te,fail:le,get stopped(){return g},get reviewing(){return T.active},get key(){return W},get busy(){return de},get staleRead(){return on}}),Be=nt({client:n.client,expected:Te,perform:Ne,onIntent:n.onCustomerDataIntent,get stopped(){return g},get busy(){return de},get document(){return N?.document},get answers(){return Ie}}),We=e=>`${e.id}:${e.nodeId}:${e.visit}`,Fe=e=>e&&(e.screen||e.paywall)?We(e):"";function Pe(){let e=n.client.view;G.disabled=!T.active&&(de>0||!!n.client.pendingCommand||!e?.canBack||e.stopped||!["running","waiting"].includes(e.status)||!Fe(e)||j!==Fe(e)),G.hidden=!T.active&&!e?.canBack,fn(G);let r=!!h&&!T.active;b.hidden=r&&!J?.active||he&&!T.active,U.hidden=!n.client.review||!T.active&&!e?.canBack,r&&(H.textContent=""),c()}async function bn(e){if(!e)return;let r=n.client.view;await e;let m=n.client.view;if(!r||!m||m.id!==r.id||m.nodeId!==r.nodeId||m.visit!==r.visit||m.stopped||!["running","waiting"].includes(m.status))throw new y("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(e,r=!1,m){if(!((de||ve||pe||Z)&&!r||g||T.active&&!r)){de++,d.setAttribute("aria-busy","true"),Q.hidden=!0,ke=null,Se=!1,Pe();try{if(r||await bn(He.inFlight),g)return;let V=await e();g||await we(n.client.view??V.run)}catch(V){m?.(V)&&n.client.pendingCommand===null?In():fe.pending||le(V,n.client.pendingCommand?.requestId??null)}finally{de=Math.max(0,de-1),d.setAttribute("aria-busy",String(de>0)),g||(X.hidden=n.client.pendingCommand===null,Pe())}}}function Ve(){gn.schedule()}async function ln(){if(!(g||Ge||de)&&!fe.pending){if(T.active){await T.open(T.receipt);return}Ge=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let r=n.client.view,m=Be.queries,V=await n.client.get(r?.screen&&Object.keys(m).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:m}:void 0);Se&&!g&&(Se=!1,Q.hidden=!0,c()),!g&&m===Be.queries&&await we(n.client.view??V.run)}catch(e){le(e),Se=!g}finally{Ge=!1}}}function Ye(e,r,m){if(J?.active){let ue=J;return ue.setDismissHandler(()=>Cn(ue)),ue}let V=nn(t,n,"funnel",()=>Cn(V),Jn);return J=V,V.start(e,r,m),V}function Cn(e){g||ce||(ce=!0,e.finish("dismissed"),be(),d.hidden=!0,n.client.view?Re().finally(re):re())}function un(){clearTimeout(Je?.timeout),Je=void 0}function be(){he=!1,un(),Ae?.abort(),Ae=void 0,N?.destroy(),N=null,h?.destroy(),h=null,Le?.(),Le=void 0,O.open&&O.close(),q.replaceChildren(),q.style.cssText="",s=void 0,W="",j="",ge=!1,$e="",xe=""}function Pn(){let e=w.defaultView;i?.responsive&&e&&N?.resizeViewport?.(e.innerHeight,e.innerWidth)}function Xe(){i?.destroy(),i=void 0,a=""}function Ze(e){let r=e.screen?.presentation;if(!r||r.type==="inline"){O.open&&O.close(),Xe(),b.parentElement!==S&&S.append(b),d.parentElement!==t&&t.append(d);for(let ue of["flex","display","flex-direction","justify-content"])q.style.removeProperty(ue);f(e),c();return}d.parentElement!==O&&(O.append(b,d),t.append(O)),q.style.flex="1 0 auto",q.style.display="flex",q.style.flexDirection="column",q.style.justifyContent="center",f(e);let m=e.screen.content.document,V=JSON.stringify([r,se]);if(V!==a){Xe(),a=V;let ue={sm:420,md:640,lg:900},Ce="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";O.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${me.background};color:${me.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ue[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${Ce};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),i=Mn(O,{presentation:r,theme:m.theme,pages:m.pages},Pn),i.latch()}c(),O.setAttribute("aria-label",(qe?.screen===e.screen?.content.document.name?qe?.label:void 0)??N?.document?.name??e.screen?.content.document.name??"Funnel")}async function it(e){if(g||ce)return;if(fe.observe(),fe.pending){B=e;return}if(ve&&(je()||["running","waiting"].includes(e.status))||(B=e,ke&&n.client.pendingCommand?.requestId!==ke&&(Q.hidden=!0,ke=null),F=e.locale.startsWith("zh"),U.textContent=F?"\u56DE\u770B":"History",G.textContent=T.active?F?"\u8FD4\u56DE\u5F53\u524D":"Return to current":F?"\u8FD4\u56DE":"Back",D(),X.textContent=F?"\u91CD\u8BD5":"Retry",X.hidden=n.client.pendingCommand===null,H.textContent=e.pendingRequest?F?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?F?"\u7B49\u5F85\u4E2D":"Waiting":"",Pe(),yn!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(yn=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,Ee(n.onState,structuredClone(e))),g||ce))return;if((!e.pendingRequest||ve&&e.status==="closed")&&["closed","ineligible","failed"].includes(e.status)){re();return}if(e.stopped&&_()){re();return}if(e.stopped||n.client.configurationReady===!1){T.stop(),o(),be(),J?.finish("skipped"),d.hidden=!0,Ve();return}if(d.hidden=!1,T.active){Ve();return}let r=Fe(e),m=n.client.view;if(m&&m.revision>e.revision&&Fe(m)!==r)return;let V=!e.instruction&&!e.pendingRequest&&e.nodeType==="screen"&&["running","waiting"].includes(e.status);r!==W&&(W&&J?.finish("dismissed"),be(),W=r,Ie={...e.answers},Be.reset());let ue=We(e);if(Qe===ue){d.hidden=!0;return}if(V&&!r){d.hidden=!0;let M=n.prepared?.state==="shown"?null:Ye(!0,e.locale);!g&&!ce&&Je?.key!==ue&&(un(),Je={key:ue,timeout:setTimeout(()=>{let I=n.client.view;if(g||!M?.active&&n.prepared?.state!=="shown"||!I||We(I)!==ue)return;Qe=ue;let Y=new Error("Funnel screen preparation timed out");M?.finish("error",Y),o(),be(),le(Y)},_e)}),Ve();return}un();let K=M=>{let I=n.client.view;return!g&&!ce&&!De&&!M.aborted&&n.client.configurationReady!==!1&&!!I&&!I.stopped&&!["closed","ineligible","failed"].includes(I.status)&&Fe(I)===r},Ce=(M,I)=>{K(I)&&(Qe=r,J?.finish("error",M),be(),d.hidden=!0,le(M))};if(r||((e.instruction&&e.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(e.status))&&o(),Ze(e),e.instruction?.type!=="event"&&e.instruction?.type!=="open_url"&&J?.finish("skipped")),e.screen){o();let M=e.screen.content;if(!N){let x=e.screen.presentation.type!=="inline",oe=Ye(x,e.locale);if(g||ce)return;let ne=(Ae=new AbortController).signal;Ze(e),Le=x?Qn(O):tn(d,t),N=E(q,{mode:"live",closeActions:Array.from(new Set([...n.closeActions??[],...M.document.actions.filter(p=>p.type==="event"&&p.close).map(p=>p.id)])),onAuthoredClose(p){K(ne)&&(he=p,Pe())},rendererUrl:n.client.webViewUrl,title:M.document.name,...x?{hostPresentation:()=>i?.type??e.screen.presentation.type}:{},onResize:p=>{s=p,i?.responsive&&i.setContentHeight(p+S.getBoundingClientRect().height)},onAction(p,ye={},lt={}){if(T.active||!K(ne)||j!==r)return;Ie={...Ie,...lt};let dn=e.screen?.inputs??[],En=Object.fromEntries(dn.filter(({variable:Oe})=>Object.hasOwn(Ie,Oe)).map(({variable:Oe})=>[Oe,Ie[Oe]]));if(Yn(dn,En).length){In();return}Ne(()=>n.client.submit({operation:"submit",...Te(),input:{type:"screen",output:p,answers:En,selection:ye}}),!1,Oe=>Bn(Oe,dn))},onAnswers:p=>{T.active||!K(ne)||j!==r||(Ie={...Ie,...p})},onCustomerDataIntent:p=>{T.active||!K(ne)||j!==r||Be.intent(p).catch(le)},onEscape:()=>{!K(ne)||j!==r||T.active||pe||Z||Re()},onError:p=>{let ye=new Error(p);j===r?le(ye):Ce(ye,ne)},onRendered:p=>{if(!(!K(ne)||j===r))try{oe.present(ye=>{Le?.(),Le=void 0,p&&(qe={screen:M.document.name,label:p},O.setAttribute("aria-label",p)),x&&(O.showModal(),l=!1,i?.responsive&&O.focus({preventScroll:!0}),!ye&&n.loading!=="host"&&$n(O,i?.type??e.screen.presentation.type,i?.responsive)),j=r,ge=x,Pe()}),K(ne)&&He.report(r)}catch(ye){Ce(ye,ne)}}}),Pn()}let I={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:Ie,values:e.screen.values}},Y=JSON.stringify([M,e.locale,I.parameters,e.screen.inputs,e.screen.values]);if(Y!==$e)N.update(M.document,e.locale,I),$e=Y,rn=JSON.stringify(I.capabilities),xe=JSON.stringify(I.customerData);else{let x=JSON.stringify(I.capabilities);x!==rn&&(N.updateCapabilities(I.capabilities),rn=x),JSON.stringify(I.customerData)!==xe&&(N.updateCustomerData(I.customerData),xe=JSON.stringify(I.customerData))}let ae=N;if(ae)try{await(J?.wait(ae.ready)??ae.ready)}catch(x){Ae&&Ce(x,Ae.signal)}}else if(e.paywall&&!h){let M=e.paywall.resolution,I="document"in M?M.document:null,Y=v,ae=null,x=(Ae=new AbortController).signal,oe={loading:"host",signal:x,canInteract:()=>K(x)&&!T.active&&!pe&&!Z,beforeAction:async()=>{de++;try{await bn(He.settled()),Q.hidden=!0,ke=null,Se=!1,c()}finally{de=Math.max(0,de-1)}},start:()=>mn(n.client),onObservationChange:Ve,onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resumeCheckout:n.resumeCheckout,allowNewPurchase:n.allowNewPurchase,checkoutNavigation:n.checkoutNavigation,terminateCheckout:n.terminateCheckout,confirmOnHostedCheckout:n.confirmOnHostedCheckout,resolveOfferId:n.resolveOfferId,resolveSubscriptionChange:n.resolveSubscriptionChange,claimCoupon:n.claimCoupon,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p,openIn:"same_window"}):w.defaultView?.location.assign(p),onAction:async p=>{if(T.active)return;let ye=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:p,answers:{}}});await we(n.client.view??ye.run)},onError:p=>{j===r?le(p):Ce(p,x)}},ne={quoteError:p=>Ee(n.onError,p),present(p){K(x)&&(ae?.present(()=>{p(),j=r,ge=!!q.querySelector("dialog[open]"),ge&&(l=!1),Pe()}),K(x)&&He.report(r))},async closeAction(p){g||T.active||await fe.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:n.client.view?.revision??e.revision,input:{type:"screen",output:p,answers:{}}})},async dismiss(){if(!(g||x.aborted||T.active||pe||Z||!ve&&!K(x))){if(ve=!0,(n.resumeCheckout||n.terminateCheckout)&&at()){B=n.client.view,re();return}await Re()}}};if(Y){let p=await Y.adopt(e,{options:oe,handoff:ne,start:()=>mn(n.client)});p&&K(x)&&!g?(Ze(e),h=p,J?.active&&J.present(()=>{}),j=r,ge=Y.modal,ge&&(l=!1),Pe(),He.report(r),T.active&&h.setSuspended(!0)):(p?.destroy(),o())}if(g||ce)return;if(!h){if(ae=Ye(!0,e.locale,I),g||ce)return;Ze(e);let p=await $(q,oe,ne).catch(ye=>(Ce(ye,x),null));!K(x)&&!(ve&&!g&&!x.aborted)?p?.host?.destroy():p&&(h=p.host,h?.setSuspended(T.active))}}if(g||ce)return;Pe();let k=e.instruction;if(k&&(k.type==="open_url"||k.type==="event")&&!ze.has(k.receiptId)){let M=w.createElement("button");M.type="button",M.style.cssText=z.primary,Me(M,()=>z.focus),q.style.cssText=z.stage,M.textContent=k.type==="open_url"?`${F?"\u524D\u5F80":"Continue to"} ${new URL(k.url).host}`:F?"\u7EE7\u7EED":"Continue",M.onclick=()=>{let I=Te(),Y=k.type==="open_url"&&!n.onOpenUrl&&k.openIn==="new_window"?rt(k.url):null;Ne(async()=>{let ae="success";if(k.type==="open_url")if(n.onOpenUrl)try{ae=await n.onOpenUrl({receiptId:k.receiptId,url:k.url,openIn:k.openIn})===!1?"failed":"opened"}catch(oe){Ee(n.onError,oe),ae="failed"}else ae=k.openIn==="new_window"&&!Y?"failed":"opened";if(k.type==="event"){if(!n.onEvent)throw new y("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(k.event)}if(g||n.client.view?.nodeId!==I.nodeId||n.client.view.visit!==I.visit)throw new y("PRECONDITION_FAILED","The client action visit changed");let x=await n.client.submit({operation:"submit",...I,input:{type:"client_action",receiptId:k.receiptId,outcome:ae}});return ze.add(k.receiptId),k.type==="open_url"&&!n.onOpenUrl&&k.openIn==="same_window"&&w.defaultView?.location.assign(k.url),x})},J?.active?J.present(()=>q.replaceChildren(M)):q.replaceChildren(M)}!e.pendingRequest&&e.status==="completed"&&!ze.has(`complete:${e.id}`)&&(ze.add(`complete:${e.id}`),Ee(n.onComplete,structuredClone(e))),Ve()}function rt(e){let r=w.defaultView?.open(e,"_blank")??null;return r&&(r.opener=null),r}function we(e){return Pe(),sn=sn.catch(()=>{}).then(async()=>{try{await it(e)}catch(r){throw J?.active&&(Qe=We(e),J.finish("error",r),be(),d.hidden=!0),r}}),sn}let ot=n.client.subscribe(e=>{if(!hn){if(e.stopped&&(ge||_())&&!ve){B=e,re();return}!ve&&(e.stopped||n.client.configurationReady===!1||W&&j!==W&&(Fe(e)!==W||["closed","ineligible","failed"].includes(e.status)))&&(be(),J?.finish("dismissed"),d.hidden=!0),we(e).catch(le)}}),st=n.client.subscribeError?.(e=>{fe.pending||le(e)});function at(){let e=n.client.view,r=e?.paywall;return!!r?.operation&&!!e&&["running","waiting"].includes(e.status)&&Fn(Ue({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Re(e){if(De)return De;if(g||!e&&(pe||Z))return Promise.resolve();let r=!e&&je();return!r&&n.client.view&&!["running","waiting"].includes(n.client.view.status)?(B=n.client.view,re(),Promise.resolve()):(De=Ne(async()=>{let m=r?await n.client.retry():await(e?n.client.submit.bind(n.client):fe.submit)({operation:"close",...e??Te()});return e&&vn(m),m},!0).then(()=>{let m=n.client.view;m?.status==="closed"&&!je()&&(B=m,re())}).finally(()=>{De=null}),De)}function re(){te?.destroy(),!g&&(g=!0,fe.destroy(),A(),o(),n.signal?.removeEventListener("abort",re),u?.removeEventListener("abort",re),J?.finish("dismissed"),gn.destroy(),ot(),st?.(),be(),Xe(),T.stop(),O.remove(),d.remove(),l||L(),Ee(n.onDismiss,B?structuredClone(B):null))}G.onclick=()=>{if(!G.disabled){if(T.active){T.exit();return}Ne(()=>n.client.submit({operation:"back",...Te()}))}},U.onclick=()=>{T.open()},b.onclick=()=>{J?.active?J.dismiss():pe||Re()},X.onclick=()=>{fe.pending?fe.retry().catch(()=>{}):je()?Re():Ne(()=>n.client.retry())},O.addEventListener("cancel",e=>{e.preventDefault(),J?.active?J.dismiss():pe||Re()}),n.signal?.addEventListener("abort",re,{once:!0}),u?.addEventListener("abort",re,{once:!0});let Ke=!1;v&&(A=v.onClose(()=>{g||ce||(ce=!0,J?.finish("dismissed"),be(),d.hidden=!0,n.client.view?Re().finally(re):Ke=!0)}));let Rn={destroy:re,refresh:ln,get recovery(){let e=an();if(e)return e;if(!g&&!de&&!ve&&!pe&&h){let r=h.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??Z?.operationId??null,requestId:n.client.pendingCommand?.requestId??null}},prepareFallback(){if(pe)return pe;let e=an();if(e)return Promise.resolve(e);let r=n.client.pendingPurchase?.operationId??n.client.view?.paywall?.quote?.operationId??Z?.operationId??null,m=()=>({type:"recover",operationId:r,requestId:n.client.pendingCommand?.requestId??null});if(n.client.hasDurableJournal!==!0){let k=h?.recovery;return Promise.resolve(k&&k.type!=="native"&&k.type!=="cancel"?k:m())}let V=(n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[])).some(k=>k.operation==="close");if(g&&!(V||Z&&n.client.view?.status==="closed")||de||Ge||De||T.active||!h&&!Z&&!V)return Promise.resolve(m());let ue=h,K=(async()=>{try{if(!Z&&V){let I=await n.client.retry();return await we(n.client.view??I.run),m()}if(!Z){let I=await ue.prepareFallback();if(I.type!=="native")return I;if(n.client.hasDurableJournal!==!0)return m();Z=I}let k=n.client.pendingCommands??(n.client.pendingCommand?[n.client.pendingCommand]:[]);if(k.length){let I=k.find(ae=>ae.operation==="close");if(!I||!ee||I.requestId!==ee.requestId)return m();let Y=await n.client.retry();vn(Y),await we(n.client.view??Y.run)}else{let I=n.client.view,Y=I?.paywall;if(!I||!Y||Y.selectionGeneration===void 0||(Y.quote?.operationId??null)!==Z.operationId||Z.operationId!==null&&Y.canReselect!==!0)return m();let ae=Y.selectionGeneration,x=await n.client.get();await we(n.client.view??x.run);let oe=n.client.view,ne=oe?.paywall;if(!oe||!ne||!["running","waiting"].includes(oe.status)||oe.stopped||oe.id!==I.id||oe.nodeId!==I.nodeId||oe.visit!==I.visit||ne.receiptId!==Y.receiptId||ne.selectionGeneration!==ae||(ne.quote?.operationId??null)!==Z.operationId||Z.operationId!==null&&ne.canReselect!==!0||n.client.pendingPurchase||(n.client.pendingCommands?.length??(n.client.pendingCommand?1:0)))return m();let p=Te();ee={runId:oe.id,operationId:Z.operationId,revision:p.revision,requestId:p.requestId,nodeId:oe.nodeId,visit:oe.visit,receiptId:ne.receiptId,selectionGeneration:ae,acknowledged:!1},await Re(p)}let M=an();return M?(re(),M):m()}catch(k){return le(k),m()}})();pe=K;let Ce=()=>{pe===K&&(pe=null)};return K.then(Ce,Ce),K},review:T.open,exitReview:T.exit,get unappliedDrafts(){return T.drafts}};try{let e=n.client.view;if(e)((n.client.viewAgeMs??wn)>=wn||e.instruction?.type==="evaluate_segment")&&(on=ln().finally(()=>{on=null})),await we(e);else{if(d.hidden=!0,g)throw new DOMException("Presentation cancelled","AbortError");let r=Ke||n.prepared?.state==="shown"?null:Ye(n.client.view?.screen?.presentation.type!=="inline",n.client.view?.locale);if(g||ce&&!Ke)throw new DOMException("Presentation cancelled","AbortError");let m=n.client.get(),V=await(r?r.wait(m,_e):ct(m,_e));if(hn=!1,Ke)return g||await Re().finally(re),Rn;await we(n.client.view??V.run)}}catch(e){throw J?.finish("error",e),re(),e}return Rn}function ct(t,C){let R;return Promise.race([t,new Promise((n,v)=>{R=setTimeout(()=>v(new Error("Presentation data timed out")),C)})]).finally(()=>clearTimeout(R))}function Zt(t,C,R){return dt(t,C,R)}export{dt as a,Zt as b};
@@ -1 +1 @@
1
- import{i as ie}from"./chunk-H7AHDGVU.js";import{a as Z,c as ee,e as te,f as ne,h as N,j as re,k as oe,l as se}from"./chunk-AQQJPP3P.js";import{b as X}from"./chunk-DPEMW2FO.js";import{r as V}from"./chunk-EOPKOAR5.js";import"./chunk-OAAS5LJY.js";import"./chunk-5PNH2FPI.js";import"./chunk-RQTYIUWP.js";import"./chunk-7IVLNV5H.js";import"./chunk-VJHURKRY.js";import"./chunk-VILB5M4X.js";import"./chunk-2XF34Q6D.js";import"./chunk-26UXCYBP.js";import{o as Y,p as K}from"./chunk-KINNES62.js";import{A as G}from"./chunk-Y2HXKANG.js";import"./chunk-HGH2X6QM.js";import"./chunk-MYDMOAKX.js";import{c as $,d as R}from"./chunk-EECTJHI6.js";import{a as p}from"./chunk-G6CWZBT5.js";import"./chunk-S4P4UUUF.js";import"./chunk-2LUVO7GM.js";import{b as u}from"./chunk-2ULWP26K.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";var z=new WeakMap;function ce(s){let t={string:u.string(),number:u.number().finite(),boolean:u.boolean(),strings:u.array(u.string()),json:R}[s.type];return s.nullable?t.nullable():t}function ae(s,t){let f=u.record(u.string(),R).parse(s);if(Object.keys(f).length>40)throw new p("INVALID_REQUEST","Too many content inputs");for(let[m,r]of Object.entries(f))Y.parse({[m]:r});if(Object.keys(f).some(m=>!Object.hasOwn(t.inputs,m)))throw new p("INVALID_REQUEST","Undeclared content input");for(let[m,r]of Object.entries(t.inputs))if(Object.hasOwn(f,m))ce(r).parse(f[m]);else if(r.required)throw new p("INVALID_REQUEST",`Missing content input ${m}`);return f}async function Ae(s,t){return le(s,t,!1)}async function Se(s,t){return le(s,t,!0)}async function le(s,t,f){t.signal?.throwIfAborted();let m=X.parse(t.content),r=m.document;if(t.closeControl==="content"&&!r.screen.actions.some(e=>e.type==="event"&&e.close))throw new p("INVALID_REQUEST","An authored Close control requires a declared Close action");if(z.has(s))throw new p("CONFLICT","Content is already mounted in this container");let y=ae(t.inputs??{},r.contract),T=new Set(u.array(u.string()).max(40).parse(t.mutableInputs??[]));if(T.size!==(t.mutableInputs?.length??0)||[...T].some(e=>!Object.hasOwn(r.contract.inputs,e)))throw new p("INVALID_REQUEST","Mutable content inputs must name unique declared inputs");for(let e of Object.keys(r.contract.outputs))if(typeof t.actions[e]!="function")throw new p("INVALID_REQUEST",`Missing host handler for ${e}`);let M=K.parse(t.bindings??[]),d=s.ownerDocument,ue=s.clientHeight||d.defaultView?.innerHeight||800,P,w,a,_,x=r.kind==="popup",n=x?d.createElement("dialog"):null,c=d.createElement("div");if(c.dataset.indianaContent=r.kind,c.setAttribute("aria-label",r.name),c.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",r.name);let e=r.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=`${$[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",a=ee(n,r.screen,()=>{w?.resizeViewport(d.defaultView?.innerHeight||800,d.defaultView?.innerWidth||1024)}),n.append(c),s.append(n)}else s.append(c);let i=!1,A=!1,E=!1,S=!1,de=n?oe(n):se(c,s),D=re(s,t,r.kind,()=>{k()&&(b(),h(t.onDismiss))}),q,H,L=new Promise((e,o)=>{q=e,H=o});L.catch(()=>{});let g=null,I=structuredClone(r.screen),W=G(I,[t.locale,...d.defaultView?.navigator.languages??[]]),j=t.capabilities;I.actions=I.actions.map(e=>e.type==="event"?{...e,close:!1}:e);function b(){i||(i=!0,t.signal?.removeEventListener("abort",b),D.finish("dismissed"),H(new Error("Content preparation cancelled")),a?.destroy(),_?.(),w?.destroy(),n?.close(),n?.remove(),c.remove(),z.delete(s),n&&P?.())}let v=()=>{!E||!k()||(b(),h(t.onDismiss))};function k(){try{return t.canDismiss?.()!==!1}catch(e){return h(t.onError,e),!1}}if(n&&t.closeControl!=="content"){let e=d.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),ne(e,r.screen.theme),e.addEventListener("click",v),n.prepend(e)}n&&a?.responsive&&(_=Z(n,v,k,t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),n.addEventListener("click",e=>{if(e.target!==n)return;let o=n.getBoundingClientRect();(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)&&v()})),n?.addEventListener("cancel",e=>{e.preventDefault(),v()}),n?.addEventListener("keydown",e=>{e.key==="Escape"&&(e.preventDefault(),v())});async function F(){if(i||!E||A||!g)return;let e=g;A=!0,c.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),g=null}catch(o){i||h(t.onError,o)}finally{A=!1,i||c.removeAttribute("aria-busy")}}function J(){if(i)throw new p("CONFLICT","Content host has been destroyed");E||!S||(P??=N(d),D.present(e=>{de(),n&&(a?.latch(),n.showModal(),a?.responsive&&n.focus({preventScroll:!0}),!e&&t.loading!=="host"&&te(n,a?.type??r.screen.presentation.type,a?.responsive)),E=!0}))}function U(e){D.finish("error",e),H(e instanceof Error?e:new Error(String(e))),b()}let Q={destroy:b,show:J,get pendingAction(){return g?structuredClone(g):null},retryAction:F,updateInputs(e){if(i)throw new p("CONFLICT","Content host has been destroyed");let o=u.record(u.string(),R).parse(e),C=ae({...y,...o},r.contract);for(let l of Object.keys(o))if(!T.has(l)&&(!Object.hasOwn(y,l)||V(y[l])!==V(C[l])))throw new p("PRECONDITION_FAILED","This content input is frozen; prepare a new presentation");V(y)!==V(C)&&(w?.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:C}}),y=C)},updateCapabilities(e){if(i)return;let o=structuredClone(e);w?.updateCapabilities(o),j=o}};z.set(s,Q),t.signal?.addEventListener("abort",b,{once:!0});try{if(t.signal?.throwIfAborted(),f||(P=N(d),D.start(x,t.locale??r.screen.strings.defaultLocale),i&&await L),w=ie(c,{mode:"live",rendererUrl:t.rendererUrl,title:r.name,viewportHeight:r.kind==="page"?ue:a?.responsive?d.defaultView?.innerHeight||800:void 0,...a?.responsive?{viewportWidth:d.defaultView?.innerWidth||1024,hostPresentation:()=>a.type}:{},onResize:e=>{i||a?.responsive&&(c.style.height=`${e}px`,c.style.overflow="clip",a.setContentHeight(e))},onRendered:e=>{if(!i&&(e&&n?.setAttribute("aria-label",e),!S))try{S=!0,f||J(),q()}catch(o){U(o),h(t.onError,o)}},onError:e=>{if(i)return;let o=new Error(e);S||U(o),h(t.onError,o)},onEscape:x?v:void 0,onAction:(e,o,C)=>{if(i||!E||A||g)return;let l=r.screen.actions.find(O=>O.id===e),B=r.contract.outputs[e];if(!(l?.type!=="event"||!B)&&!(l.close&&!k()))try{let O=ce(B).parse(Object.hasOwn(l.properties,"value")?l.properties.value:l.properties);g=structuredClone({requestId:crypto.randomUUID(),contentVersionId:m.id,actionId:e,event:l.event,value:O,selection:o??{},answers:C??{},requestedClose:l.close}),F()}catch(O){h(t.onError,O)}}}),w.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:y}}),await Promise.race([w.ready,L]),f&&await L,i)throw new Error("Content preparation cancelled");return Q}catch(e){throw U(e),e}}export{Ae as mountContent,Se as prepareContent};
1
+ import{i as ie}from"./chunk-S7A3IBAF.js";import{a as Z,c as ee,e as te,f as ne,h as N,j as re,k as oe,l as se}from"./chunk-P6TNBX2S.js";import{b as X}from"./chunk-LZ3OJYBY.js";import{r as V}from"./chunk-HLCDAU5A.js";import"./chunk-DCZWNTG2.js";import"./chunk-ASL7TJFU.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import{o as Y,p as K}from"./chunk-7MYS52FL.js";import{A as G}from"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import{c as $,d as R}from"./chunk-3SXPCVIP.js";import{a as p}from"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-T43HTIQX.js";import{b as u}from"./chunk-GPJF3T43.js";import{a as h}from"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var z=new WeakMap;function ce(s){let t={string:u.string(),number:u.number().finite(),boolean:u.boolean(),strings:u.array(u.string()),json:R}[s.type];return s.nullable?t.nullable():t}function ae(s,t){let f=u.record(u.string(),R).parse(s);if(Object.keys(f).length>40)throw new p("INVALID_REQUEST","Too many content inputs");for(let[m,r]of Object.entries(f))Y.parse({[m]:r});if(Object.keys(f).some(m=>!Object.hasOwn(t.inputs,m)))throw new p("INVALID_REQUEST","Undeclared content input");for(let[m,r]of Object.entries(t.inputs))if(Object.hasOwn(f,m))ce(r).parse(f[m]);else if(r.required)throw new p("INVALID_REQUEST",`Missing content input ${m}`);return f}async function Ae(s,t){return le(s,t,!1)}async function Se(s,t){return le(s,t,!0)}async function le(s,t,f){t.signal?.throwIfAborted();let m=X.parse(t.content),r=m.document;if(t.closeControl==="content"&&!r.screen.actions.some(e=>e.type==="event"&&e.close))throw new p("INVALID_REQUEST","An authored Close control requires a declared Close action");if(z.has(s))throw new p("CONFLICT","Content is already mounted in this container");let y=ae(t.inputs??{},r.contract),T=new Set(u.array(u.string()).max(40).parse(t.mutableInputs??[]));if(T.size!==(t.mutableInputs?.length??0)||[...T].some(e=>!Object.hasOwn(r.contract.inputs,e)))throw new p("INVALID_REQUEST","Mutable content inputs must name unique declared inputs");for(let e of Object.keys(r.contract.outputs))if(typeof t.actions[e]!="function")throw new p("INVALID_REQUEST",`Missing host handler for ${e}`);let M=K.parse(t.bindings??[]),d=s.ownerDocument,ue=s.clientHeight||d.defaultView?.innerHeight||800,P,w,a,_,x=r.kind==="popup",n=x?d.createElement("dialog"):null,c=d.createElement("div");if(c.dataset.indianaContent=r.kind,c.setAttribute("aria-label",r.name),c.style.cssText="width:100%;min-width:0",n){n.setAttribute("aria-label",r.name);let e=r.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=`${$[e.size]}px`,e.type==="sheet"&&(n.style.margin="auto auto 0")):n.style.width="100vw",a=ee(n,r.screen,()=>{w?.resizeViewport(d.defaultView?.innerHeight||800,d.defaultView?.innerWidth||1024)}),n.append(c),s.append(n)}else s.append(c);let i=!1,A=!1,E=!1,S=!1,de=n?oe(n):se(c,s),D=re(s,t,r.kind,()=>{k()&&(b(),h(t.onDismiss))}),q,H,L=new Promise((e,o)=>{q=e,H=o});L.catch(()=>{});let g=null,I=structuredClone(r.screen),W=G(I,[t.locale,...d.defaultView?.navigator.languages??[]]),j=t.capabilities;I.actions=I.actions.map(e=>e.type==="event"?{...e,close:!1}:e);function b(){i||(i=!0,t.signal?.removeEventListener("abort",b),D.finish("dismissed"),H(new Error("Content preparation cancelled")),a?.destroy(),_?.(),w?.destroy(),n?.close(),n?.remove(),c.remove(),z.delete(s),n&&P?.())}let v=()=>{!E||!k()||(b(),h(t.onDismiss))};function k(){try{return t.canDismiss?.()!==!1}catch(e){return h(t.onError,e),!1}}if(n&&t.closeControl!=="content"){let e=d.createElement("button");e.type="button",e.textContent="\xD7",e.setAttribute("aria-label",t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),ne(e,r.screen.theme),e.addEventListener("click",v),n.prepend(e)}n&&a?.responsive&&(_=Z(n,v,k,t.locale?.startsWith("zh")?"\u5173\u95ED":"Close"),n.addEventListener("click",e=>{if(e.target!==n)return;let o=n.getBoundingClientRect();(e.clientX<o.left||e.clientX>o.right||e.clientY<o.top||e.clientY>o.bottom)&&v()})),n?.addEventListener("cancel",e=>{e.preventDefault(),v()}),n?.addEventListener("keydown",e=>{e.key==="Escape"&&(e.preventDefault(),v())});async function F(){if(i||!E||A||!g)return;let e=g;A=!0,c.setAttribute("aria-busy","true");try{await t.actions[e.actionId](structuredClone(e)),g=null}catch(o){i||h(t.onError,o)}finally{A=!1,i||c.removeAttribute("aria-busy")}}function J(){if(i)throw new p("CONFLICT","Content host has been destroyed");E||!S||(P??=N(d),D.present(e=>{de(),n&&(a?.latch(),n.showModal(),a?.responsive&&n.focus({preventScroll:!0}),!e&&t.loading!=="host"&&te(n,a?.type??r.screen.presentation.type,a?.responsive)),E=!0}))}function U(e){D.finish("error",e),H(e instanceof Error?e:new Error(String(e))),b()}let Q={destroy:b,show:J,get pendingAction(){return g?structuredClone(g):null},retryAction:F,updateInputs(e){if(i)throw new p("CONFLICT","Content host has been destroyed");let o=u.record(u.string(),R).parse(e),C=ae({...y,...o},r.contract);for(let l of Object.keys(o))if(!T.has(l)&&(!Object.hasOwn(y,l)||V(y[l])!==V(C[l])))throw new p("PRECONDITION_FAILED","This content input is frozen; prepare a new presentation");V(y)!==V(C)&&(w?.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:C}}),y=C)},updateCapabilities(e){if(i)return;let o=structuredClone(e);w?.updateCapabilities(o),j=o}};z.set(s,Q),t.signal?.addEventListener("abort",b,{once:!0});try{if(t.signal?.throwIfAborted(),f||(P=N(d),D.start(x,t.locale??r.screen.strings.defaultLocale),i&&await L),w=ie(c,{mode:"live",rendererUrl:t.rendererUrl,title:r.name,viewportHeight:r.kind==="page"?ue:a?.responsive?d.defaultView?.innerHeight||800:void 0,...a?.responsive?{viewportWidth:d.defaultView?.innerWidth||1024,hostPresentation:()=>a.type}:{},onResize:e=>{i||a?.responsive&&(c.style.height=`${e}px`,c.style.overflow="clip",a.setContentHeight(e))},onRendered:e=>{if(!i&&(e&&n?.setAttribute("aria-label",e),!S))try{S=!0,f||J(),q()}catch(o){U(o),h(t.onError,o)}},onError:e=>{if(i)return;let o=new Error(e);S||U(o),h(t.onError,o)},onEscape:x?v:void 0,onAction:(e,o,C)=>{if(i||!E||A||g)return;let l=r.screen.actions.find(O=>O.id===e),B=r.contract.outputs[e];if(!(l?.type!=="event"||!B)&&!(l.close&&!k()))try{let O=ce(B).parse(Object.hasOwn(l.properties,"value")?l.properties.value:l.properties);g=structuredClone({requestId:crypto.randomUUID(),contentVersionId:m.id,actionId:e,event:l.event,value:O,selection:o??{},answers:C??{},requestedClose:l.close}),F()}catch(O){h(t.onError,O)}}}),w.update(I,W,{capabilities:j,serverInput:{bindings:M,answers:{},values:y}}),await Promise.race([w.ready,L]),f&&await L,i)throw new Error("Content preparation cancelled");return Q}catch(e){throw U(e),e}}export{Ae as mountContent,Se as prepareContent};
@@ -0,0 +1 @@
1
+ import{b as Q}from"./chunk-YVAQLTHJ.js";import{b as N}from"./chunk-SSRQGIGB.js";import"./chunk-CSLTAXC7.js";import"./chunk-DGZCD3AY.js";import{a as K}from"./chunk-HTXB2WVI.js";import{b as B}from"./chunk-XZEZFWFD.js";import"./chunk-FMSHIKMI.js";import"./chunk-W32FI2A2.js";import{i as R,j as J}from"./chunk-P6TNBX2S.js";import"./chunk-RJY5CUTB.js";import"./chunk-V65FSNYO.js";import"./chunk-DPVYEOD6.js";import"./chunk-IT5DIE6G.js";import"./chunk-NVF54BDR.js";import"./chunk-7X65GNKZ.js";import"./chunk-PBZSOTKZ.js";import"./chunk-HLCDAU5A.js";import"./chunk-DCZWNTG2.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import"./chunk-B4AELNLE.js";import"./chunk-AQONMY2H.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import{a as f}from"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-SLUA7ABW.js";import"./chunk-X4UTTXOU.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import"./chunk-GPJF3T43.js";import{a as u}from"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var b=new WeakMap,C=new WeakMap,H=new WeakSet;function ie(E,e){let s=e.prepared,T=()=>{s&&!H.has(s)&&N(s)?.release()},U=b.get(e.client);if(U)return T(),U;let _=r=>({...r,requestId:r.requestId??crypto.randomUUID()}),p=e.allowNewPurchase!==!1&&e.start instanceof Promise?e.start:void 0,c=e.allowNewPurchase===!1||!e.start||e.start instanceof Promise?void 0:_(e.start);c&&s?.state==="ready"&&s.matches(c)&&s.open();let i=s&&(c&&(s.state==="preparing"||["shown","closed"].includes(s.state)&&s.matches(c))||p&&["preparing","ready"].includes(s.state))?s:void 0;i?H.add(i):T();let d=i&&N(i);d?.claim();let v=Promise.resolve().then(async()=>{let r=!1,y,A,L=!1,q=()=>{},M=()=>{},I,x=!1,O=!1,h,G=!1,n=e.signal?AbortSignal.any([e.signal,e.client.identitySignal]):e.client.identitySignal,m=()=>{b.get(e.client)===v&&b.delete(e.client),n.removeEventListener("abort",F),q(),M(),i&&H.delete(i),d?.release()};function V(){if(h)return h;let a=new Promise(w=>h=w);return C.set(e.client,a),a.then(()=>{C.get(e.client)===a&&C.delete(e.client)}),b.get(e.client)===v&&b.delete(e.client),h}let o=J(E,e,"funnel",()=>S(),K);function F(){S()}function S(a=!1){if(!r){if(r=!0,o.finish("dismissed"),y){y.destroy();return}if(a&&I){let w=V();G=!0,I.then(async P=>{P.mode==="run"&&P.status!=="blocked"&&e.client.controller&&e.client.attempt?.requestId===c?.requestId&&await e.client.close()}).catch(()=>{}).finally(()=>{w(),u(e.onDismiss,null)}),m();return}m(),u(e.onDismiss,null)}}n.addEventListener("abort",F,{once:!0}),d&&(M=d.onClose(()=>{x?r||V():S(!0)}));try{let k=function(){!r&&!n.aborted&&!L&&A&&e.client.recovery.status==="complete"&&(L=!0,u(e.onComplete,structuredClone(A)))},D=function(t){if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");return e.onCheckoutUrl?e.onCheckoutUrl(t):E.ownerDocument.defaultView?.location.assign(t)};var X=k,Y=D;n.throwIfAborted();let a=e.client.controller?.view?.paywall?.resolution,w=a&&"document"in a?a.document:e.loadingDocument;o.start(!0,c?.locale??e.client.attempt?.locale??w?.screen.strings.defaultLocale,w??null);let P=p?o.wait(p.then(t=>t?_(t):null,()=>null),R):Promise.resolve(c??null);P.catch(()=>{}),i?.state==="shown"?(O=!0,o.present(()=>{})):i&&["preparing","ready"].includes(i.state)&&Promise.all([i.ready,P.catch(()=>null)]).then(([t,l])=>{if(t){if(r||!o.active||!l||!i.matches(l)||!d?.revealable)return d?.release();o.present(()=>{i.open()==="shown"?O=!0:d.release()})}});let W=C.get(e.client);if(W&&await o.wait(W),r)return null;if(n.throwIfAborted(),p){let t=await P;if(r)return null;if(n.throwIfAborted(),!t)return o.finish("skipped"),m(),null;c=t}I=c?e.client.start(c):e.client.refresh();let j=await o.wait(I,R);if(r)return null;n.throwIfAborted();let z=e.client.controller;return j.mode!=="run"||j.status==="blocked"||!z?(o.finish("skipped"),m(),O&&u(e.onDismiss,null),null):(n.removeEventListener("abort",F),x=!0,q=e.client.subscribe(k),y=await Q(E,{...e,prepared:i,client:z,signal:n,checkoutNavigation:"after_confirmation",resumeCheckout:t=>e.client.continueCheckout(D,t),terminateCheckout:e.allowNewPurchase===!1?void 0:t=>e.client.terminateCheckout(t),async onCheckoutUrl(t){if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");let l=e.client.recovery;if((!l.actions.includes("continue_checkout")||!l.purchases.some(g=>g.type==="checkout"&&g.checkoutUrl===t))&&(l=await e.client.refresh(),n.throwIfAborted(),r))throw new DOMException("Presentation dismissed","AbortError");if(B(l)!==t)throw new f("PURCHASE_PENDING","Checkout differs from the original recovery proof");return D(t)},async resolveOfferId(t){if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");let l=e.client.attempt;if(!l)throw new f("PURCHASE_PENDING","Read the original Start before selecting an offer");let g=await e.resolveOfferId?.(t,l);if(n.throwIfAborted(),r)throw new DOMException("Presentation dismissed","AbortError");if(e.client.attempt?.requestId!==l.requestId)throw new f("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting an offer");return g},async resolveSubscriptionChange(t){n.throwIfAborted();let l=e.client.attempt;if(r||!l)throw new f("PURCHASE_PENDING","Read the original Start before selecting a membership");let g=await e.resolveSubscriptionChange?.(t);if(n.throwIfAborted(),r||e.client.attempt?.requestId!==l.requestId)throw new f("PURCHASE_STORAGE_CONFLICT","The original purchase changed while selecting a membership");return g},onComplete(t){A=t,k()},onError(t){u(e.onError,t),t instanceof f&&t.status===401&&!n.aborted&&e.client.refresh().catch(l=>u(e.onError,l))},onDismiss(t){r=!0,m(),h?.(),u(e.onDismiss,t)}},o),r||n.aborted?(y.destroy(),null):y)}catch(a){if(G||h?.(),r)return null;throw o.finish("error",a),m(),u(e.onError,a),a}});return b.set(e.client,v),v}export{ie as showFunnelPurchase};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-SSRQGIGB.js";import"./chunk-CSLTAXC7.js";import"./chunk-DGZCD3AY.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import"./chunk-AQONMY2H.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-LSVTH3TS.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as PRERENDER_MAX_AGE_MS,b as preparedInternals,c as prerenderFunnelPurchase};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-CSLTAXC7.js";import"./chunk-DGZCD3AY.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import"./chunk-VILB5M4X.js";import"./chunk-3SXPCVIP.js";import"./chunk-GPJF3T43.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as predictFunnelStart,c as predictedPaywallLoadingDocument,b as predictionRefusal};
@@ -0,0 +1 @@
1
+ import{a as e,b as o,c as n}from"./chunk-DGZCD3AY.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import"./chunk-VILB5M4X.js";import"./chunk-3SXPCVIP.js";import"./chunk-GPJF3T43.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{e as FUNNEL_ROUTE_LIMITS,o as funnelRouteSchema,n as projectFunnelRoute};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-YVAQLTHJ.js";import"./chunk-SSRQGIGB.js";import"./chunk-CSLTAXC7.js";import"./chunk-DGZCD3AY.js";import"./chunk-HTXB2WVI.js";import"./chunk-FMSHIKMI.js";import"./chunk-W32FI2A2.js";import"./chunk-P6TNBX2S.js";import"./chunk-IT5DIE6G.js";import"./chunk-DCZWNTG2.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import"./chunk-B4AELNLE.js";import"./chunk-AQONMY2H.js";import"./chunk-RDUKCMST.js";import"./chunk-KP4QI4RX.js";import"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-SLUA7ABW.js";import"./chunk-X4UTTXOU.js";import"./chunk-T43HTIQX.js";import"./chunk-GPJF3T43.js";import"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as showFunnelRun,b as showObservedFunnelRun};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as En,c as bn}from"./chunk-W3J2SIPY.js";import{a as We,c as Rn}from"./chunk-VWRQBQZD.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-FTVNGN6Z.js";import"./chunk-6STWY5GX.js";import{a as In}from"./chunk-ANXK3B5B.js";import"./chunk-TGPZJ5A7.js";import{h as mn,i as vn,k as Pn}from"./chunk-P6XQC7GG.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-4B4RB36N.js";import{a as ze}from"./chunk-EON4IKWR.js";import"./chunk-H26F3IOI.js";import"./chunk-2LERKK7O.js";import"./chunk-2RUJXZCO.js";import"./chunk-6EBS6MLW.js";import"./chunk-EOPKOAR5.js";import{K as Ke}from"./chunk-OAAS5LJY.js";import"./chunk-NFY7DKVJ.js";import"./chunk-5PNH2FPI.js";import{c as hn,e as gn}from"./chunk-PYLX3WF6.js";import"./chunk-W35FZWGG.js";import"./chunk-RQTYIUWP.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-7IVLNV5H.js";import{A as Be,C as He,E as qe,F as Ue,H as Ve,I as je,J as Ge,K as Je,L as Te,M as $e,y as _e,z as Le}from"./chunk-VJHURKRY.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-2XF34Q6D.js";import"./chunk-26UXCYBP.js";import"./chunk-KINNES62.js";import"./chunk-Y2HXKANG.js";import"./chunk-HGH2X6QM.js";import"./chunk-MYDMOAKX.js";import"./chunk-EECTJHI6.js";import{a as G}from"./chunk-G6CWZBT5.js";import"./chunk-S4P4UUUF.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-2P2YSNYU.js";import"./chunk-3VUPVXAV.js";import"./chunk-2LUVO7GM.js";import{b as U}from"./chunk-2ULWP26K.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-CQRSMCCG.js";import"./chunk-PBBREFS5.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let N=$e.safeParse(J);throw!N.success||N.data.scope.projectId!==n.scope.projectId||N.data.scope.environment!==n.scope.environment||N.data.scope.environmentId!==n.scope.environmentId||N.data.requestId!==g||N.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(N.data.error.code,M.status,N.data.error.retryable,N.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-YU53UKUN.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(N.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),N=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await F(A);return}let v=crypto.randomUUID(),K=N.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await F(j)}async function F(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=N.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(N.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-3SSDNG24.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Fe=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Fe=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Fe||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,F(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Ne=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),N.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Ne.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await F(g)},destroy(){t=!0,u++,$.cancel(),N.release(g?.deliveryTicket),Ne.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function N(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-3SSDNG24.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let F=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){F.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:F,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!N(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&N(r)&&b?.entries.some(F=>F.id===r.id&&F.funnelId===r.funnelId&&F.versionId===r.versionId&&F.event===r.event&&JSON.stringify(F.target)===JSON.stringify(r.target)&&JSON.stringify(F.delivery)===JSON.stringify(r.delivery))===!0,()=>{let F=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(F===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:F};l=X,te(X)}catch(X){c.release(F),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&N(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!N(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let F=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(F),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-YZAEI7TF.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-YZAEI7TF.js"),import("./screen-renderer-SEJG7A2C.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-MHBAZLS7.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-SEJG7A2C.js").catch(()=>{}),import("./paywall-YZAEI7TF.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-3SSDNG24.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-DDQI3GAZ.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-SEJG7A2C.js").catch(()=>{}),import("./paywall-YZAEI7TF.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-BNS3242X.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-BNS3242X.js").catch(()=>{}),import("./screen-renderer-SEJG7A2C.js").catch(()=>{}),(await import("./funnel-paywall-prerender-DDQI3GAZ.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-DDQI3GAZ.js"),import("./funnel-host-purchase-BNS3242X.js"),import("./paywall-YZAEI7TF.js"),import("./screen-renderer-SEJG7A2C.js"),import("./paywall-content-QBSB5NA7.js"),import("./check-response-SR3PDVGE.js"),import("./operation-contracts-GEIGP23I.js")])}async function yt(...n){return(await import("./funnel-route-prediction-BT5ZWU54.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-BT5ZWU54.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./content-XYUJFGY2.js")).mountContent(...n)}async function vt(...n){return(await import("./content-XYUJFGY2.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,gt as mountContent,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,vt as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
1
+ import{a as En,c as bn}from"./chunk-XZEZFWFD.js";import{a as We,c as Rn}from"./chunk-FMSHIKMI.js";import{a as Ie}from"./chunk-W32FI2A2.js";import{a as pn,c as wn,d as Sn}from"./chunk-RMRZSF5C.js";import"./chunk-RJY5CUTB.js";import{a as In}from"./chunk-3XMBILUJ.js";import"./chunk-V65FSNYO.js";import{h as mn,i as vn,k as Pn}from"./chunk-22LQSRYH.js";import{E as Ae,d as Xe,f as Qe,g as ge,h as ve,i as Ye,w as yn}from"./chunk-DPVYEOD6.js";import"./chunk-IT5DIE6G.js";import{a as ze}from"./chunk-NVF54BDR.js";import"./chunk-AV2WZSII.js";import"./chunk-MPD3UIY4.js";import"./chunk-7X65GNKZ.js";import"./chunk-PBZSOTKZ.js";import"./chunk-HLCDAU5A.js";import{K as Ke}from"./chunk-DCZWNTG2.js";import"./chunk-CALDEF4M.js";import"./chunk-ASL7TJFU.js";import{c as hn,e as gn}from"./chunk-B4AELNLE.js";import"./chunk-AQONMY2H.js";import"./chunk-RDUKCMST.js";import{B as dn,C as ln,D as un,E as fn,c as an,d as sn,e as cn}from"./chunk-KP4QI4RX.js";import{A as Be,C as He,E as qe,F as Ue,H as Ve,I as je,J as Ge,K as Je,L as Te,M as $e,y as _e,z as Le}from"./chunk-5TJISOWN.js";import"./chunk-VILB5M4X.js";import{b as Ce}from"./chunk-PG5UESZB.js";import"./chunk-LSVTH3TS.js";import"./chunk-7MYS52FL.js";import"./chunk-MWICFZUF.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-3SXPCVIP.js";import{a as G}from"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import{a as be,c as de}from"./chunk-J6KIN4RH.js";import"./chunk-SLUA7ABW.js";import{c as we,d as Ee}from"./chunk-X4UTTXOU.js";import"./chunk-3VUPVXAV.js";import"./chunk-T43HTIQX.js";import{b as U}from"./chunk-GPJF3T43.js";import{a as Z}from"./chunk-DSPLGTQI.js";import"./chunk-C4NG6RVA.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";var I=class extends Error{constructor(f,b=0,w=!1,h="fix_request"){super(f);this.code=f;this.status=b;this.retryable=w;this.recovery=h;this.name="MerchantBridgeError"}code;status;retryable;recovery};async function _n(n,d){if(!n.headers.get("content-type")?.split(";",1)[0].trim().match(/^application\/(?:json|[a-z0-9.+-]+\+json)$/i))throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let f=n.body?.getReader();if(!f)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");let b=()=>{f.cancel().catch(()=>{})};d.addEventListener("abort",b,{once:!0});let w=0,h="",t=new TextDecoder("utf-8",{fatal:!0});try{for(d.throwIfAborted();;){let i=await f.read();if(d.throwIfAborted(),i.done)break;if(w+=i.value.byteLength,w>262144)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");h+=t.decode(i.value,{stream:!0})}return h+=t.decode(),JSON.parse(h)}catch(i){throw d.throwIfAborted(),i instanceof I?i:new I("MERCHANT_BRIDGE_INVALID_RESPONSE")}finally{d.removeEventListener("abort",b),await f.cancel().catch(()=>{}),f.releaseLock()}}function Tn(n){let d=qe.parse(n.origin),f=Ue.parse(n.manifest),b={projectId:n.scope.projectId,environmentId:n.scope.environmentId,environment:n.scope.environment};for(let m of["projectId","environmentId","environment"])if(f[m]!==n.scope[m])throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");let w=n.customerId===void 0?null:U.uuid().parse(n.customerId),h=0,t=null,i=null,u=new AbortController,y=n.fetch??globalThis.fetch;async function P(m,s,E,_,O){if(!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=He[m];if(["merchant_catalog_reader","merchant_refund_authority","indiana_server_key"].includes(S.authority))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);let l=h,o=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],..._?[_]:[]]);o.throwIfAborted();let T=new Headers(await n.headers?.());if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(/\bgg_(?:sk|ct|rt)_/.test(T.get("authorization")??"")||T.has("X-Indiana-Bridge-Signature")||T.has("X-Indiana-Bridge-Key-Id"))throw new I("MERCHANT_BRIDGE_FORBIDDEN",403);T.set(Be,String(_e)),T.set("Accept","application/json");let g=crypto.randomUUID();T.set("X-Request-Id",g),T.set("Content-Type","application/json");let M=await y(d+Le,{method:"POST",credentials:"include",redirect:"error",cache:"no-store",headers:T,signal:o,body:JSON.stringify({bridgeVersion:_e,requestId:g,command:S.command,scope:b,data:O??(E===void 0?{}:{operationId:E})})}),J=await _n(M,o);if(o.throwIfAborted(),l!==h)throw new DOMException("Merchant identity changed","AbortError");if(!M.ok){let N=$e.safeParse(J);throw!N.success||N.data.scope.projectId!==n.scope.projectId||N.data.scope.environment!==n.scope.environment||N.data.scope.environmentId!==n.scope.environmentId||N.data.requestId!==g||N.data.command!==S.command?new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status):new I(N.data.error.code,M.status,N.data.error.retryable,N.data.error.recovery)}let c=Ve(U.unknown()).safeParse(J);if(!c.success||c.data.scope.projectId!==n.scope.projectId||c.data.scope.environment!==n.scope.environment||c.data.scope.environmentId!==n.scope.environmentId||c.data.requestId!==g||c.data.command!==S.command)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);let $=s.safeParse(c.data.data);if(!$.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE",M.status);return $.data}function R(){if(!w)throw new I("MERCHANT_BRIDGE_UNAUTHENTICATED",401);return w}async function B(m,s,E,_){let O=R();if(_!==void 0&&Te.parse({operationId:_,customerId:O}),!f.capabilities.includes(m))throw new I("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let S=h,l=AbortSignal.any([u.signal,AbortSignal.timeout(Math.min(3e4,Math.max(1e3,n.timeoutMs??1e4))),...n.signal?[n.signal]:[],...s?[s]:[]]);l.throwIfAborted();let o,T=new Promise((g,M)=>{o=()=>M(l.reason),l.addEventListener("abort",o,{once:!0})});try{let M=E(async()=>{let c=await import("./merchant-bridge-contracts-FB63H7NE.js");if(l.throwIfAborted(),S!==h||w!==O)throw new DOMException("Merchant identity changed","AbortError");return c},l),J=await Promise.race([M,T]);return l.throwIfAborted(),J}finally{l.removeEventListener("abort",o)}}async function z(m,s,E,_){let O=R(),S=Te.parse({operationId:E,customerId:O}),l=await P(m,s,S.operationId,_,S);if(l.customerId!==O||l.operationId!==S.operationId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return l}return{async readPresentation(m){let s=await P("presentation",Ge,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(s.presentation&&w!==null&&s.presentation.customerId!==w)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return i=s.nativeUserId,t=s.presentation,s},async createSession(m){let s=await P("session",je,void 0,m);if(i!==null&&i!==s.nativeUserId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(w!==null&&w!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");if(t&&t.customerId!==s.session.customerId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return w=s.session.customerId,i=s.nativeUserId,s.session},async reportPresentation(m,s){let E=R(),_=Je.parse(m);if(!t||t.customerId!==E||t.decisionId!==_.decisionId)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return P("presentation_events",U.strictObject({queued:U.literal(!0)}),void 0,s,_)},async readCustomerCommerce(m){let s=R(),E=await B("customer_commerce",m,async(_,O)=>{let[S,l]=await Promise.all([_(),P("customer_commerce",U.unknown(),void 0,O)]),o=S.merchantBridgeCommerceSchema.safeParse(l);if(!o.success)throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return o.data});if(E.customerId!==s)throw new I("MERCHANT_BRIDGE_SCOPE_MISMATCH");return E},async executePurchase(m,s){let E=await B("purchases",s,async(_,O)=>z("purchases",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="purchase")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},readOperation:(m,s)=>B("operation_status",s,async(E,_)=>z("operation_status",(await E()).merchantOperationLookupSchema,m,_),m),async executeSubscriptionChange(m,s){let E=await B("subscription_changes",s,async(_,O)=>z("subscription_changes",(await _()).merchantBridgeOperationSchema,m,O),m);if(E.type!=="subscription_change")throw new I("MERCHANT_BRIDGE_INVALID_RESPONSE");return E},reset(){h++,u.abort(),u=new AbortController,w=null,t=null,i=null}}}var en=U.strictObject({command:ve,target:Qe,runId:U.uuid().optional(),expiresAt:U.iso.datetime({offset:!0}).optional(),deliveryLimit:U.number().int().min(1).max(100).optional()}).refine(n=>n.command.release===n.target.release),Ze=U.strictObject({schemaVersion:U.literal(1),entries:U.array(en).max(4e3)});function nn(n){let d=!1,f=()=>{d||n.unavailable(),d=!0};function b(){return n.storage===!1?void 0:n.storage??globalThis.sessionStorage}function w(t){let i=b()?.getItem(t);if(!i)return[];if(i.length>1048576)throw Error("Entry recovery is too large");return Ze.parse(JSON.parse(i)).entries}function h(t,i){let u=b();if(!u)return;if(!i.length)return u.removeItem(t);let y=JSON.stringify(Ze.parse({schemaVersion:1,entries:i}));if(y.length>1048576)throw Error("Entry recovery is too large");u.setItem(t,y)}return{load(){try{let t=n.binding();if(!t||n.storage===!1)return;let i="indiana.funnel.entries.v1."+JSON.stringify(t);return{key:i,entries:w(i)}}catch{f();return}},retain(t,i){if(t)try{let u=en.parse(i);h(t,[...w(t).filter(y=>y.command.funnelId!==u.command.funnelId),u])}catch{f()}},forget(t,i){if(t)try{h(t,w(t).filter(u=>u.command.requestId!==i))}catch{f()}}}}var tn=U.strictObject({version:U.literal(1),runs:U.array(U.uuid()).max(100)}),De=new WeakMap,Oe=new WeakMap;function Se(n){let d=!1;function f(){d||n.unavailable(),d=!0}function b(t){let i=t.storage.getItem(t.key);if(!i)return[];if(i.length>8192)throw Error("Invalid entry delivery record");return tn.parse(JSON.parse(i)).runs}function w(t){let i=De.get(t.storage);i||De.set(t.storage,i=new Map);let u=i.get(t.key);return u||i.set(t.key,u=new Set),u}function h(t){if(!t)return;let i=De.get(t.storage),u=i?.get(t.key);u?.delete(t.requestId),u?.size===0&&i?.delete(t.key)}return{claim(t,i,u,y,P=!1){if(u!==void 0)try{let R=n.binding();if(!R)throw Error("Entry delivery identity is unavailable");let B={storage:n.storage??globalThis.sessionStorage,key:"indiana.funnel.delivery.v1."+JSON.stringify([...R,i,t]),requestId:y},z=b(B);if(Oe.get(B.storage)?.has(B.key))throw Error("Entry delivery storage is unavailable");B.storage.setItem(B.key,JSON.stringify({version:1,runs:z}));let m=w(B);return!P&&!m.has(y)&&z.length+m.size>=u?!1:(m.add(y),B)}catch{return f(),!1}},accept(t,i){if(t)try{let u=b(t);u.includes(i)||t.storage.setItem(t.key,JSON.stringify(tn.parse({version:1,runs:[...u,i].slice(-100)})))}catch{let u=Oe.get(t.storage);u||Oe.set(t.storage,u=new Set),u.add(t.key),f()}finally{h(t)}},release:h}}function Pe(){let n,d,f=()=>{clearTimeout(n),n=void 0;let b=d;d=void 0,b?.cancelled()};return{get active(){return d!==void 0},start(b,w,h,t){if(d)return;if(b===0){w()?h():t();return}let i={valid:w,cancelled:t};d=i,n=setTimeout(()=>{d===i&&(d=void 0,n=void 0,w()?h():t())},b*1e3)},recheck(){d&&!d.valid()&&f()},cancel:f}}var Re=n=>["running","waiting"].includes(n.status)&&!n.pendingRequest&&(n.stopped||!n.screen&&!n.paywall&&n.instruction?.type==="wait"&&n.instruction.kind!=="operation");function Cn(n){let d=we(n.baseUrl),f=n.scope,b=Ce(n),w=n.fetch??globalThis.fetch.bind(globalThis),h,t=!1,i=!1,u=0,y=0,P="",R=0,B=0,z=0,m=!1,s,E=!0,_,O,S,l,o,T=-1,g,M=e=>{g===e&&(N.release(e.deliveryTicket),g=void 0,x())},J=new Set,c=(e,a)=>Z(n.onStatus,e,a),$=Pe(),N=Se({storage:n.deliveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,"customer",e]:void 0},unavailable:()=>c("delivery_unavailable")}),ee=new Set,te=nn({storage:n.recoveryStorage,binding:()=>{let e=n.session.snapshot()?.customerId;return e?[d,f.projectId,f.environment,n.environmentId,n.appManifestRelease,e]:void 0},unavailable:()=>c("recovery_unavailable")}),Y=e=>te.forget(e.storageKey,e.command.requestId);function Q(e,a){a&&(e.runId=a.id,e.expiresAt=a.runExpiresAt),te.retain(e.storageKey,{command:e.command,target:e.target,...e.runId&&{runId:e.runId},...e.expiresAt&&{expiresAt:e.expiresAt},...e.deliveryLimit!==void 0&&{deliveryLimit:e.deliveryLimit}})}function re(){let e=o;o=void 0,e?.host.destroy(),e?.slot.remove(),e?.client.reset(),x()}let le=()=>$.active||g!==void 0||o!==void 0&&!o.background;function me(e,a){if(o?.client!==e)return;Q(o.recovery,a);let p=Re(a);o.slot.hidden=p,p!==o.background&&(o.background=p,p?c("run_background",o.entryId):T=y,x())}function pe(e,a,p){let v=e.client.view;if(!a||e.background||!v?.screen||v.paywall||v.pendingRequest||v.stopped||v.status!=="waiting")return;let K=Ke.parse({operation:"close",requestId:crypto.randomUUID(),nodeId:v.nodeId,visit:v.visit,revision:v.revision,customerToken:a}),j=Ce({...n,session:void 0});j.requestWithCredential("funnels",K,e.runToken,{keepalive:p}).then(()=>Y(e.recovery)).catch(()=>{}).finally(()=>j.dispose())}let ae=()=>{o&&pe(o,n.session.peek(),!0)},r=()=>Date.now()<B&&performance.now()<z;function C(e){if(e.target.release!==n.appManifestRelease||!r())return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return c("incompatible",e.id),!1}}function H(e){if(t||e.epoch!==R||e.visit!==y||document.visibilityState==="hidden")return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function W(e){if(le()){c("in_progress",e.id);return}let a=R,p=y;$.start(e.delivery?.delaySeconds??0,()=>!t&&a===R&&p===y&&document.visibilityState!=="hidden"&&C(e)&&h?.entries.some(v=>v.id===e.id&&v.funnelId===e.funnelId&&v.versionId===e.versionId&&v.event===e.event&&JSON.stringify(v.target)===JSON.stringify(e.target)&&JSON.stringify(v.delivery)===JSON.stringify(e.delivery))===!0,()=>{V(e)},()=>{J.delete(`${e.funnelId}:${e.id}`)})}async function V(e){if(le()){c("in_progress",e.id);return}if(!n.session.peek()){c("identity_required",e.id);return}let a=te.load(),p=a?.entries.find(A=>A.command.funnelId===e.funnelId&&(!A.expiresAt||Date.parse(A.expiresAt)>Date.now()));if(p){if(!X(p)){c("recovery_pending",e.id);return}let A={...p,storageKey:a.key,epoch:R,visit:y};ee.add(A.command.requestId),g=A,await F(A);return}let v=crypto.randomUUID(),K=N.claim(e.id,e.funnelId,e.delivery?.maxPerSession,v);if(K===!1){c("frequency",e.id),x();return}let j={freshStart:!0,deliveryLimit:e.delivery?.maxPerSession,deliveryTicket:K,command:ve.parse({operation:"entry_start",entryId:e.id,funnelId:e.funnelId,versionId:e.versionId,release:n.appManifestRelease,requestId:v,locale:document.documentElement.lang||"en"}),epoch:R,visit:y,target:e.target,storageKey:a?.key};ee.add(j.command.requestId),g=j,await F(j)}async function F(e){if(e.dispatching)return;e.dispatching=!0;let a=e.freshStart===!0;e.freshStart=!1;let p,v=!1,K=!1;async function j(A){if(e.epoch!==R)return;let D=A.view;if(!(e.storageKey&&D&&(Re(D)||D.paywall||D.pendingRequest))&&D&&["running","waiting"].includes(D.status))try{await A.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:D.nodeId,visit:D.visit,revision:D.revision}),Y(e)}catch(k){if(!(k instanceof G&&k.code==="FORBIDDEN"))throw k}}try{if(!e.deliveryTicket&&e.deliveryLimit!==void 0){let q=N.claim(e.command.entryId,e.command.funnelId,e.deliveryLimit,e.command.requestId,!0);q!==!1&&(e.deliveryTicket=q)}Q(e),c("starting",e.command.entryId);let A=await b.request("funnels",e.command),D=Ye.safeParse(A);if(D.success){if(D.data.scope.projectId!==f.projectId||D.data.scope.environment!==f.environment)throw new G("SCOPE_MISMATCH","Entry scope changed");e.epoch===R&&c(D.data.reason,e.command.entryId),Y(e),M(e);return}let k=Xe.parse(A);if(!k.runToken||k.scope.projectId!==f.projectId||k.scope.environment!==f.environment||k.run.source.type!=="funnel"||k.run.source.id!==e.command.funnelId||k.run.source.versionId!==e.command.versionId||e.runId!==void 0&&k.run.id!==e.runId)throw new G("INVALID_RESPONSE","Invalid entry Run");if(N.accept(e.deliveryTicket,k.run.id),e.epoch!==R){M(e),c("identity_changed",e.command.entryId);return}Q(e,k.run);let L=Ae({...n,runToken:k.runToken,funnelId:e.command.funnelId,initialResponse:a?A:void 0});p=L,K=!0,await L.get(),K=!1;let ne=L.view;if(!ne||ne.id!==k.run.id||ne.source.type!=="funnel"||ne.source.id!==e.command.funnelId||ne.source.versionId!==e.command.versionId)throw new G("INVALID_RESPONSE","Entry Run version changed");if(!["running","waiting"].includes(ne.status)){Y(e),M(e),c("run_ended",e.command.entryId);return}let{showFunnelRun:fe}=await import("./funnel-runtime-host-NU36AKUF.js");if(!H(e)){await j(L),c("left_screen",e.command.entryId),M(e);return}let Fe=!1,xe=!1;if(o&&!o.background){await j(L),c("in_progress",e.command.entryId),M(e);return}o&&re();let ie=document.createElement("div");ie.hidden=Re(ne),n.container.append(ie);let ke=await fe(ie,{...n.host,client:L,appManifestRelease:n.appManifestRelease,onState(q){me(L,q),Z(n.host?.onState,q)},onDismiss(q){Fe=!0,ie.remove(),q&&!["running","waiting"].includes(q.status)&&Y(e),o?.client===L&&(o=void 0,L.reset(),x(),q&&q.status!=="completed"&&c("run_ended",e.command.entryId)),Z(n.host?.onDismiss,q)},onComplete(q){xe=!0,Y(e),o?.client===L&&re(),Z(n.host?.onComplete,q)},onError(q){Z(n.host?.onError,q),o?.client===L&&q instanceof G&&q.code==="FORBIDDEN"&&(Y(e),re(),c("run_ended",e.command.entryId))}}).catch(q=>{throw ie.remove(),q});if(!H(e)||Fe||xe){ke.destroy(),ie.remove(),H(e)||await j(L),M(e);return}let he=Re(L.view??ne);ie.hidden=he,o={host:ke,client:L,slot:ie,entryId:e.command.entryId,background:he,runToken:k.runToken,owner:n.session.peek(),recovery:e},he||(T=e.visit),v=!0,M(e),c("started",e.command.entryId),he&&c("run_background",e.command.entryId)}catch(A){A instanceof G&&(!p||K&&A.code==="FORBIDDEN")&&A.status!==void 0&&A.status>=400&&A.status<500&&!A.retryable&&(Y(e),M(e)),e.epoch===R&&!t&&(c("start_failed",e.command.entryId),Z(n.host?.onError,A))}finally{v||p?.reset(),e.dispatching=!1}}function X(e){if(e.command.release!==n.appManifestRelease||e.target.release!==n.appManifestRelease)return!1;try{return de(e.target.render,document,location.pathname,()=>{})}catch{return!1}}function ye(){if(le())return!1;let e=te.load();for(let a of e?.entries??[]){if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now()){te.forget(e.key,a.command.requestId);continue}if(a.command.requestId===o?.recovery.command.requestId||ee.has(a.command.requestId)||!X(a))continue;ee.add(a.command.requestId);let p={...a,storageKey:e.key,epoch:R,visit:y};return g=p,F(p),!0}return!1}function ue(){if(m=!1,$.recheck(),t||!i||document.visibilityState==="hidden")return;se();let e=o!==void 0&&!o.background;if(e&&(T=y),!ye()){if(!r()){E=!0;return}E=!1;for(let a of h?.entries??[]){let p=`${a.funnelId}:${a.id}`;if(!(a.event!=="screen_enter"||J.has(p)||!C(a))){if(!n.session.peek()){c("identity_required",a.id);continue}if(T===y){J.add(p),e&&c("in_progress",a.id);continue}if(g||$.active){c("in_progress",a.id);return}J.add(p),W(a);break}}}}let x=()=>{!m&&!t&&(m=!0,queueMicrotask(ue))};function se(){let e=location.origin+location.pathname;return e===P?!1:(P=e,y++,$.cancel(),E=!0,J.clear(),ee.clear(),!0)}function oe(){se()&&x()}function ce(e){if(!e.isTrusted||e.button!==0||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||document.visibilityState==="hidden")return;let a=e.target;if(!(a instanceof Element)||a.closest("[data-indiana-funnel]"))return;let p=a.closest("button,a,input");if(!(!p||p.matches(":disabled,[aria-disabled='true']")||p.closest("[hidden],[inert],[aria-hidden='true']")))for(let v of h?.entries??[]){let K=v.target.button;if(!(v.event!=="button_click"||!K||!C(v))){try{let j=be(document);if(!p.matches(K.selector)||j(K.selector,p)!==1)continue}catch{c("incompatible",v.id);continue}W(v);break}}}async function Me(){if(t)return;if(s)return s;let e=++u,a=new AbortController;_=a;let p,v=new Promise((A,D)=>{p=()=>D(new G("TIMEOUT","Funnel entry configuration read cancelled or timed out")),a.signal.addEventListener("abort",p,{once:!0})}),K=setTimeout(()=>a.abort(),n.timeoutMs??5e3),j=(async()=>{let A=async()=>{let fe=await w(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:a.signal});if(!fe.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",fe.status);return ge.parse(await fe.json())},D=await Promise.race([A(),v]),k=Date.parse(D.validatedAt),L=Date.parse(D.validUntil);if(D.scope.projectId!==f.projectId||D.scope.environment!==f.environment||D.scope.environmentId!==n.environmentId||D.release!==n.appManifestRelease||L<=Date.now()||k>Date.now()+5e3||L-k>6e4||L<=k)throw new G("INVALID_RESPONSE","Entry configuration scope or deadline changed");if(t||e!==u)return;let ne=h===void 0;h=D,B=L,z=performance.now()+Math.min(L-Date.now(),6e4),$.recheck(),(ne||E)&&x()})();s=j;try{await j}finally{clearTimeout(K),a.signal.removeEventListener("abort",p),s===j&&(s=void 0)}}async function on(){if(!(!i||t)){try{await Me()}catch{t||c("configuration_unavailable")}x()}}let Ne=Ie({document,run:on,delay:()=>i&&!t?15e3:void 0});return{async start(){i||t||(i=!0,P=location.origin+location.pathname,O=Ee(oe),S=n.session.subscribeIdentity(()=>{R++,$.cancel(),N.release(g?.deliveryTicket),E=!0,g=void 0,J.clear(),T=-1,ee.clear(),o&&pe(o,o.owner,!1),re(),x()}),l=new MutationObserver(x),l.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",ce,!0),document.addEventListener("visibilitychange",x),addEventListener("pagehide",ae),await Ne.refresh())},refresh:Me,async retry(){g&&!t&&g.epoch===R&&await F(g)},destroy(){t=!0,u++,$.cancel(),N.release(g?.deliveryTicket),Ne.destroy(),_?.abort(),l?.disconnect(),O?.(),S?.(),document.removeEventListener("click",ce,!0),document.removeEventListener("visibilitychange",x),removeEventListener("pagehide",ae),ae(),re(),b.dispose(),h=void 0}}}function An(n){let d=we(n.baseUrl),f=n.fetch??globalThis.fetch.bind(globalThis),b,w=0,h=0,t=!1,i=!1,u=!1,y=0,P=0,R=-1,B=!1,z="",m,s,E,_,O=new Set,S,l,o,T=(r,C)=>Z(n.onStatus,r,C),g=Pe(),M=()=>{try{return n.deliveryIdentity?.()}catch{return}},J=()=>JSON.stringify(M()),c=Se({storage:n.deliveryStorage,binding:()=>{let r=M();return r?.id?[d,n.scope.projectId,n.scope.environment,n.environmentId,r.type,r.id]:void 0},unavailable:()=>T("delivery_unavailable")}),$=()=>Date.now()<w&&performance.now()<h;function N(r){try{return $()&&r.target.release===n.appManifestRelease&&de(r.target.render,document,location.pathname,()=>{})}catch{return T("incompatible",r.id),!1}}function ee(){let r=o;o=void 0,r?.host.destroy(),r?.slot.remove()}async function te(r){if(r.dispatching)return;r.dispatching=!0;let C=y;try{let H=await r.process.open({operation:"entry_start",funnelId:r.entry.funnelId,versionId:r.entry.versionId,entryId:r.entry.id,release:n.appManifestRelease,locale:n.locale??"en"});c.accept(r.deliveryTicket,H.run.id);let{showFunnelRun:W}=await import("./funnel-runtime-host-NU36AKUF.js");if(t||C!==y||l!==r)return;let V=document.createElement("div");n.container.append(V),R=P;let F=await W(V,{...n.host,client:H.controller,appManifestRelease:n.appManifestRelease,onDismiss(X){o?.process===r.process&&(o=void 0,V.remove()),Z(n.host?.onDismiss,X)}});if(t||C!==y||l!==r){F.destroy(),V.remove();return}o={entry:r.entry,process:r.process,host:F,slot:V,deliveryTicket:r.deliveryTicket},l=void 0,T("run_presented",r.entry.id)}catch(H){if(t||C!==y||l!==r)return;H instanceof G&&"result"in H?(c.release(r.deliveryTicket),l=void 0,r.process.destroy(),T("suppressed",r.entry.id),Q()):T("entry_unavailable",r.entry.id)}finally{r.dispatching=!1}}function Y(r){if(t||i||l||o||S||g.active||R===P||!N(r))return;let C=`${P}:${r.id}`;if(O.has(C))return;O.add(C);let H=P,W=y,V=J();g.start(r.delivery?.delaySeconds??0,()=>!t&&y===W&&P===H&&J()===V&&document.visibilityState!=="hidden"&&N(r)&&b?.entries.some(F=>F.id===r.id&&F.funnelId===r.funnelId&&F.versionId===r.versionId&&F.event===r.event&&JSON.stringify(F.target)===JSON.stringify(r.target)&&JSON.stringify(F.delivery)===JSON.stringify(r.delivery))===!0,()=>{let F=c.claim(r.id,r.funnelId,r.delivery?.maxPerSession,crypto.randomUUID());if(F===!1){T("frequency",r.id),Q();return}try{let X={entry:r,process:n.createProcess(r),visit:P,deliveryTicket:F};l=X,te(X)}catch(X){c.release(F),T("entry_unavailable",r.id),Z(n.host?.onError,X)}},()=>{O.delete(C)})}function Q(){B||t||(B=!0,queueMicrotask(()=>{if(B=!1,g.recheck(),!(t||i||document.visibilityState==="hidden"||!$()||l||o||S||g.active||R===P)){for(let r of b?.entries??[])if(r.event==="screen_enter"&&!O.has(`${P}:${r.id}`)&&N(r)){Y(r);break}}}))}function re(r){if(!r.isTrusted||r.defaultPrevented||!(r.target instanceof Element)||l||o||S||R===P)return;let C=be(document,()=>{});for(let H of b?.entries??[]){let W=H.target.button;if(H.event!=="button_click"||!W||!N(H))continue;let V=r.target.closest(W.selector);if(!(!V||V.tagName.toLowerCase()!==W.tag||C(W.selector)!==1||V.matches(":disabled")||V.closest('[inert],[hidden],[aria-hidden="true"]'))){Y(H);break}}}let le=()=>{let r=location.origin+location.pathname;r!==z&&(z=r,P++,g.cancel(),O.clear(),Q())};async function me(){if(t)return;if(s)return s;let r=y,C=new AbortController;m=C;let H,W=new Promise((ye,ue)=>{H=ue}),V=()=>H(new G("TIMEOUT","Funnel entry read cancelled"));C.signal.addEventListener("abort",V,{once:!0});let F=setTimeout(()=>C.abort(),n.timeoutMs??5e3),X=(async()=>{let ye=encodeURIComponent(JSON.stringify(["funnel-process/1"])),ue=async()=>{let ce=await f(`${d}/api/v1/funnel-entries/${n.environmentId}?iam=${n.appManifestRelease}&executionContracts=${ye}`,{credentials:"omit",cache:"no-store",redirect:"error",signal:C.signal});if(!ce.ok)throw new G("SERVICE_UNAVAILABLE","Funnel entries unavailable",ce.status);return ge.parse(await ce.json())},x=await Promise.race([ue(),W]),se=Date.parse(x.validatedAt),oe=Date.parse(x.validUntil);if(x.scope.projectId!==n.scope.projectId||x.scope.environment!==n.scope.environment||x.scope.environmentId!==n.environmentId||x.release!==n.appManifestRelease||oe<=Date.now()||se>Date.now()+5e3||oe<=se||oe-se>6e4)throw new G("INVALID_RESPONSE","Entry scope or deadline changed");t||r!==y||(b=x,w=oe,h=performance.now()+Math.min(oe-Date.now(),6e4),g.recheck(),Q())})();s=X;try{await X}finally{clearTimeout(F),C.signal.removeEventListener("abort",V),s===X&&(s=void 0)}}async function pe(){if(!(!u||t))try{await me()}catch{t||T("configuration_unavailable")}}let ae=Ie({document,run:pe,delay:()=>u&&!t?15e3:void 0});return{async start(){u||t||(u=!0,z=location.origin+location.pathname,E=Ee(le),_=new MutationObserver(Q),_.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["hidden","inert","aria-hidden","data-indiana-id","id","style","data-testid","data-test","data-qa"]}),document.addEventListener("click",re,!0),document.addEventListener("visibilitychange",Q),await ae.refresh())},refresh:me,async retry(){l&&!t&&await te(l)},async syncIdentity(){g.cancel();let r=o??l??S;if(!r){i=!1,Q();return}try{let C=await r.process.syncIdentity();return i=!1,S===r&&(l={...r,visit:P},S=void 0,await te(l)),C}catch(C){throw r.process.view||(S={...r,visit:P},l=void 0,ee()),C}},async detach(){i=!0,y++,g.cancel(),m?.abort();let r=o??l??S;r&&(S={...r,visit:P}),l=void 0,ee(),r&&await r.process.detach()},destroy(){t=!0,y++,g.cancel(),ae.destroy(),m?.abort(),_?.disconnect(),E?.(),document.removeEventListener("click",re,!0),document.removeEventListener("visibilitychange",Q);let r=o??l??S;c.release(r?.deliveryTicket),l=void 0,S=void 0,ee(),r?.process.destroy(),b=void 0}}}async function Dn(n,d){return(await import("./paywall-GLXO4HN7.js")).showPaywall(n,d)}async function dt(){return await Promise.all([import("./paywall-GLXO4HN7.js"),import("./screen-renderer-RDXKWHYE.js")]),Dn}async function lt(...n){return n[1]=ze(n[1]),(await import("./paywall-session-YDG3FDOP.js")).createPaywallSession(...n)}async function ut(...n){let d=n[1].signal?.aborted?void 0:We(n[1].client);try{return import("./screen-renderer-RDXKWHYE.js").catch(()=>{}),import("./paywall-GLXO4HN7.js").catch(()=>{}),await(await rn(()=>import("./funnel-runtime-host-NU36AKUF.js"),n[1].prepared)).showFunnelRun(...n)}finally{d?.()}}async function rn(n,d){try{return await n()}catch(f){throw d&&d.state!=="adopted"&&await import("./funnel-paywall-prerender-OA3QN2VI.js").then(b=>b.preparedInternals(d)?.release(),()=>{}),f}}async function ft(...n){return import("./screen-renderer-RDXKWHYE.js").catch(()=>{}),import("./paywall-GLXO4HN7.js").catch(()=>{}),(await rn(()=>import("./funnel-host-purchase-6GV67OIA.js"),n[1].prepared)).showFunnelPurchase(...n)}async function mt(...n){return import("./funnel-host-purchase-6GV67OIA.js").catch(()=>{}),import("./screen-renderer-RDXKWHYE.js").catch(()=>{}),(await import("./funnel-paywall-prerender-OA3QN2VI.js")).prerenderFunnelPurchase(...n)}async function pt(){await Promise.all([import("./funnel-paywall-prerender-OA3QN2VI.js"),import("./funnel-host-purchase-6GV67OIA.js"),import("./paywall-GLXO4HN7.js"),import("./screen-renderer-RDXKWHYE.js"),import("./paywall-content-IF2LKXDF.js"),import("./check-response-OIBVUP72.js"),import("./operation-contracts-YSFIINLK.js")])}async function yt(...n){return(await import("./funnel-route-prediction-XGCMCIKA.js")).predictFunnelStart(...n)}async function ht(...n){return(await import("./funnel-route-prediction-XGCMCIKA.js")).predictedPaywallLoadingDocument(...n)}async function gt(...n){return(await import("./content-FZOT5NDI.js")).mountContent(...n)}async function vt(...n){return(await import("./content-FZOT5NDI.js")).prepareContent(...n)}export{G as LongplayError,I as MerchantBridgeError,yn as createBrowserFunnelCommandStorage,En as createBrowserFunnelPurchaseStorage,vn as createConfigurationSync,mn as createFeatureClient,wn as createFunnelClient,Rn as createFunnelPageExperiments,Sn as createFunnelProcess,bn as createFunnelPurchaseClient,Ae as createFunnelRunController,Cn as createIamFunnelEntries,An as createIamFunnelProcessEntries,Pn as createLocalFunnelClient,pn as createLongplay,Tn as createMerchantBridge,lt as createPaywallSession,In as evaluateFunnelNode,sn as formatCouponDiscount,an as formatCouponMoney,cn as formatCouponTerms,hn as getPaywallRecovery,un as isPaywallOperationComplete,fn as isPaywallOperationPending,ln as isPaywallUpdateOperation,dn as isPaywallUpdateQuote,gt as mountContent,yt as predictFunnelStart,ht as predictedPaywallLoadingDocument,pt as preloadFunnelPurchase,dt as preloadPaywall,vt as prepareContent,gn as preparePaywallFallback,mt as prerenderFunnelPurchase,ft as showFunnelPurchase,ut as showFunnelRun,Dn as showPaywall};
@@ -0,0 +1 @@
1
+ import{O as r,P as m,i as e}from"./chunk-5TJISOWN.js";import"./chunk-LSVTH3TS.js";import"./chunk-5JRBCW6V.js";import"./chunk-6XRXHFM6.js";import"./chunk-GPJF3T43.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{m as merchantBridgeCommerceSchema,r as merchantBridgeOperationSchema,e as merchantOperationLookupSchema};